簡體   English   中英

滾動添加和刪除類

[英]Adding and removing class on scroll

用戶滾動后,我要向div添加一個類。 這可以正常工作,但是由於某些原因,當用戶再次向后滾動時,它不會刪除此類。 控制台中沒有錯誤。 我要去哪里錯了?

 var scrolled = $('body').offset().top - 800; $(window).on('resize scroll', function() { if ($(window).scrollTop() > scrolled) { $('#one').addClass('in'); } else { $('#one').removeClass('in'); } }); 
 section.bg-red { background: red; } section.bg-blue { background: blue; } section { min-height: 100vh; } section p { color: red; text-align: center; position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } section.in p { color: #fff; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="bg-red" id="one"> <p>Well done you scrolled</p> </section> <section class="bg-blue"> ddd </section> 

在Codepen上查看

問題是您要從實體的偏移頂部減去800 ,這將產生負數。 窗口的滾動頂部永遠不會是負數,因此永遠不會刪除該類。

 section.bg-red { background: red; } section.bg-blue { background: blue; } section { min-height: 100vh; } section p { color: red; text-align: center; position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); } section.in p { color: #fff; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="bg-red" id="one"> <p>Well done you scrolled</p> </section> <section class="bg-blue"> ddd </section> <script> var scrolled = $('body').offset().top; $(window).on('resize scroll', function() { if ($(window).scrollTop() > scrolled) { $('#one').addClass('in'); } else { $('#one').removeClass('in'); } }); </script> 

我找到了使用Waypoints.js的解決方案,該解決方案可以按需執行。 所需要做的就是將waypoints.js包含到項目中,並在下面編寫以下Javascript。

            var $elone = $('.element-one');
            $elone.waypoint(function(direction) {
                if (direction == 'down') {
                    $elone.addClass('in');
                }
                else {
                    $elone.removeClass('in');
                }
            }, {offset: '50%'});

這使您可以使用百分比而不是像素,這對於響應式網站效果更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM