【问题标题】:How to toggle class after 100vh scroll100vh滚动后如何切换类
【发布时间】:2014-12-31 00:37:45
【问题描述】:

如何让这个函数在滚动后添加类100vh
目前它在850px之后添加类。

$("document").ready(function($){
    var nav = $('#verschwinden');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 850) {
            nav.addClass("doch");
        } else {
            nav.removeClass("doch");
        }
    });
});

【问题讨论】:

  • 不应该是$(document)吗?甚至更短:jQuery(function($){
  • 我不知道,这是我在互联网上找到的,它有效。

标签: javascript scroll height viewport


【解决方案1】:

100vh 在 jQuery 中很简单,就像 $(window).height(),而在纯 JavaScript 中是 window.innerHeight or a bit more longer

jsFiddle demo

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
    });

});

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

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

demo

【讨论】:

  • 很好用!但我忘记了导航也花了 6vh,有没有办法从窗口高度中删除导航的高度?
  • 6 视口高度为 6% sry
猜你喜欢
  • 1970-01-01
  • 2020-08-05
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多