javascript 如何在 100vh 滚动后切换类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26729776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to toggle class after 100vh scroll
提问by Kevin Brandao da Graca
How to make this function add the class after scrolling 100vh
?
Currently it adds the class after 850px
.
如何让这个函数在滚动后添加类100vh
?
目前它在850px
.
$("document").ready(function($){
var nav = $('#verschwinden');
$(window).scroll(function () {
if ($(this).scrollTop() > 850) {
nav.addClass("doch");
} else {
nav.removeClass("doch");
}
});
});
回答by Roko C. Buljan
100vh
in jQuery is simple as $(window).height()
while in pure JavaScript is window.innerHeight
or a bit more longer.
100vh
在 jQuery 中很简单,$(window).height()
而在纯 JavaScript 中则是window.innerHeight
或更长一些。
jQuery(function($) {
var $nav = $('#verschwinden');
var $win = $(window);
var winH = $win.height(); // Get the window height.
$win.on("scroll", function () {
if ($(this).scrollTop() > winH ) {
$nav.addClass("doch");
} else {
$nav.removeClass("doch");
}
}).on("resize", function(){ // If the user resizes the window
winH = $(this).height(); // you'll need the new height value
});
});
you can also make the if
part a bit shorter by simply using:
您还可以if
通过简单地使用以下方法使部分更短:
$nav.toggleClass("doch", $(this).scrollTop() > winH );