为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

呼如林 2021-12-02 15:19:00
我想要的是在 div 中添加一个类,例如,在视口顶部的 100 像素处。所以不是在滚动 100 像素之后,而是当它在视口顶部下方 100 像素时。有人可以帮我解决这个问题吗?<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 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

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


查看完整回答
反对 回复 2021-12-02
  • 1 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信