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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:24:19  来源:igfitidea点击:

How to toggle class after 100vh scroll

javascriptscrollheightviewport

提问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

100vhin jQuery is simple as $(window).height()while in pure JavaScript is window.innerHeightor a bit more longer.

100vh在 jQuery 中很简单,$(window).height()而在纯 JavaScript 中则是window.innerHeight更长一些

jsFiddle demo

jsFiddle 演示

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 ifpart a bit shorter by simply using:

您还可以if通过简单地使用以下方法使部分更短:

$nav.toggleClass("doch", $(this).scrollTop() > winH );

demo

演示