【问题标题】:Add a class when div is x amount pixels of top of viewport当 div 为视口顶部的 x 个像素时添加一个类
【发布时间】:2019-10-24 21:36:15
【问题描述】:

我想有的是给一个div添加一个类的时候,例如,视口顶部的100像素。所以不是在滚动 100px 之后而是在视口顶部下方 100px 时。有人可以帮我吗?

<script>
jQuery(function() {
    //caches a jQuery object containing the header element
    var header = jQuery('#v0');
    jQuery(window).scroll(function() {
        var scroll = jQuery(window).scrollTop();

        if (scroll >= 2939) {
            header.addClass('fixed1');
 }

    else {
            header.removeClass('fixed1');
        }
    });
});
</script>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

不确定这是否正是您想要实现的,但这是代码。如果标题距离窗口顶部超过 100 像素(这不是很常见,因为标题顶部应该有一些东西),那么新类将添加到标题中。

$(function() {  
  var $header = $('#v0');
  $(window).scroll(function () { 
    if ($header.offset().top - $(this).scrollTop() > 100) {
      $header.addClass('blabla');
    } else {
      $header.removeClass('blabla');
    }
  });
});

更新: 根据您的反馈,这是我想到的第一个解决方案。我认为这是你需要的行为。希望对你有用:

$(function() {  
  var $header = $('header');
  var $video = $('#v0');
  var $videoContainer = $('.videoContainer');

  $(window).scroll(function () {
    // Here we check if video field touches the header, and add 'fixed' class
    if ((($header.offset().top + $header.height()) - $video.offset().top) >= 0) {
      $video.addClass('fixed')
    }
    // Since both video and header is fixed now I needed some other
    // element to check if we are again getting away from the header
    // (scrolling up again) That's why I added the $videoContainer element 
    // to be able to remove the 'fixed' class.
    if ($videoContainer.offset().top > ($header.offset().top + $header.height())) {
      $video.removeClass('fixed');
    }
  });
});

更新代码: https://jsbin.com/foyoyus/6/edit?html,css,js,output

【讨论】:

  • 您好 Orkun,感谢您的代码。但我想我还不够清楚。如果您转到此页面:publivision.mooke.nl/page/1886/vormgeving 并向下滚动,而不是在某个点看到滚动播放的电影。我希望页面的那部分在标题下方停止。标题的高度为 90 像素。如果我使用我的原始代码,它在我的屏幕上可以正常工作,但在其他屏幕上会有所不同。希望我足够清楚......
  • 非常感谢您的帮助。但这似乎不起作用。此外,您的示例在这里不起作用...我希望我不会抢您的时间。我也试过 isScrolledintoView 但我不知道如何使用 removeClass。
  • 我认为这是我的错。 jsbin 代码现在应该可以工作了。请记住,为了使代码适合您,它应该适应您的 html。例如添加一个视频容器 div 或者如果有,使用它自己的类名等。
猜你喜欢
  • 1970-01-01
  • 2013-10-08
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多