繁体   English   中英

当 div 是视口顶部的 x 数量像素时,添加 class

[英]Add a class when div is x amount pixels of top of viewport

我想要的是在一个 div 中添加一个 class ,例如,视口顶部的 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>

我已经使用此代码将导航栏固定在滚动事件的顶部。 您可以使用此代码修复 div

$(document).ready(function() {

      $(window).scroll(function () { 
          console.log($(window).scrollTop())
        if ($(window).scrollTop() > 280) {
          $('#nav_bar').addClass('navbar-fixed');
        }
        if ($(window).scrollTop() < 281) {
          $('#nav_bar').removeClass('navbar-fixed');
        }
      });
    });

css

.navbar-fixed {
        top: 0;
        z-index: 100;
      position: fixed;
        width: 100%;
    }

不确定这是否正是您想要实现的,但这是代码。 If the header is more than 100px away from the top (which is not very usual because then there should be something on top of the header) of the window, then the new class is added to the header.

$(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,ZF78E6228D689

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM