Javascript 当div为视口顶部的x个像素时添加一个类

Javascript 当div为视口顶部的x个像素时添加一个类,javascript,jquery,Javascript,Jquery,我想要的是,当一个div是视口顶部的100像素时,向它添加一个类。因此,不是在滚动100px后,而是在视口顶部下方100px时。有人能帮我吗 <script> jQuery(function() { //caches a jQuery object containing the header element var header = jQuery('#v0'); jQuery(window).scroll(function() { var sc

我想要的是,当一个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>

jQuery(函数(){
//缓存包含header元素的jQuery对象
var header=jQuery(“#v0”);
jQuery(窗口).滚动(函数(){
var scroll=jQuery(window.scrollTop();
如果(滚动>=2939){
header.addClass('fixed1');
}
否则{
header.removeClass('fixed1');
}
});
});

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

$(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');
    }
  });
});
更新代码:

您使用完整的
jQuery
限定符而不是使用速记
$
有什么原因吗?
fixed1
是否作为css类存在?您可以使用Window.innerHeight获取视口的高度(),然后使用Element.getBoundingClientRect()将其与div的顶部位置进行比较是的,我使用jQuery是因为我的CMS要求…fixed1将excist作为一个类,这是正确的。嗨,Orkun,谢谢你的代码。但我想我还不够清楚。如果你进入这个页面:你向下滚动到某一点,你会看到一部电影在滚动条上播放。我希望页面的那部分停在页眉下面。收割台的高度为90px。如果我使用我的原始代码,它在我的屏幕上运行良好,但在其他屏幕上则不同。希望我足够清楚…非常感谢你的帮助。但它似乎不起作用。你的例子在这里也不起作用。。。我希望我没有占用你的时间。我也尝试过isScrolledintoView,但我不知道如何使用removeClass。我认为这是我的错。jsbin代码现在应该可以工作了。请记住,为了使代码适合您,它应该适合您的html。例如添加一个视频容器div,或者如果有,使用它自己的类名等。