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

我想要的是在 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>


呼如林
浏览 125回答 1
1回答

开心每一天1111

不确定这是否正是您想要实现的,但这是代码。如果标题距窗口顶部的距离超过 100 像素(这不是很常见,因为标题顶部应该有一些东西),那么新类将添加到标题中。$(function() {&nbsp;&nbsp;&nbsp; var $header = $('#v0');&nbsp; $(window).scroll(function () {&nbsp;&nbsp; &nbsp; if ($header.offset().top - $(this).scrollTop() > 100) {&nbsp; &nbsp; &nbsp; $header.addClass('blabla');&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; $header.removeClass('blabla');&nbsp; &nbsp; }&nbsp; });});更新:根据您的反馈,这是我想到的第一个解决方案。我认为这就是你需要的行为。希望对你有用:$(function() {&nbsp;&nbsp;&nbsp; var $header = $('header');&nbsp; var $video = $('#v0');&nbsp; var $videoContainer = $('.videoContainer');&nbsp; $(window).scroll(function () {&nbsp; &nbsp; // Here we check if video field touches the header, and add 'fixed' class&nbsp; &nbsp; if ((($header.offset().top + $header.height()) - $video.offset().top) >= 0) {&nbsp; &nbsp; &nbsp; $video.addClass('fixed')&nbsp; &nbsp; }&nbsp; &nbsp; // Since both video and header is fixed now I needed some other&nbsp; &nbsp; // element to check if we are again getting away from the header&nbsp; &nbsp; // (scrolling up again) That's why I added the $videoContainer element&nbsp;&nbsp; &nbsp; // to be able to remove the 'fixed' class.&nbsp; &nbsp; if ($videoContainer.offset().top > ($header.offset().top + $header.height())) {&nbsp; &nbsp; &nbsp; $video.removeClass('fixed');&nbsp; &nbsp; }&nbsp; });});更新代码:https : //jsbin.com/foyoyus/6/edit?html,css,js,output
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript