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

时间:2019-10-24 09:53:00

标签: 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 scroll = jQuery(window).scrollTop();

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

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

1 个答案:

答案 0 :(得分:0)

不确定这是否确实要实现,但这是代码。如果标题距窗口顶部的距离超过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