滚动时为body添加/移除sticky类脚本调整:延迟添加与无交互自动隐藏
实现需求的完整可运行代码
<!DOCTYPE html> <html lang="en" class="dont-sticky2"> <head> <style> body { background: white; } body.sticky { background: grey; } .test { width: 150px; height :150px; top: auto; position: relative; background: #ccc; } body.sticky .test { top: 0; position: sticky; background: yellow; } </style> </head> <body style="height:5000px;"> <h1>Scroll Test 1 (working)</h1> <div class="test">Testing.</div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { // 存储定时器ID let addStickyTimer = null; let hideStickyTimer = null; // 重置无交互隐藏定时器 function resetHideTimer() { if (hideStickyTimer) { clearTimeout(hideStickyTimer); } // 2秒无交互移除sticky类 hideStickyTimer = setTimeout(() => { $('body').removeClass('sticky'); }, 2000); } // 绑定.test元素的交互事件,触发时重置隐藏倒计时 $('.test').on('mouseenter click', function() { if ($('body').hasClass('sticky')) { resetHideTimer(); } }); function stickyCheck(){ if ( $(window).width() >= 991 && $(window).scrollTop() >= 250 && !$('html').hasClass('dont-sticky') ) { // 先清空之前的添加定时器,避免滚动频繁触发重复任务 if (addStickyTimer) { clearTimeout(addStickyTimer); } // 延迟1秒添加sticky类 addStickyTimer = setTimeout(() => { $('body').addClass('sticky'); // 启动无交互隐藏倒计时 resetHideTimer(); }, 1000); } else { // 不满足触发条件时清空所有定时器,移除类 if (addStickyTimer) { clearTimeout(addStickyTimer); addStickyTimer = null; } if (hideStickyTimer) { clearTimeout(hideStickyTimer); hideStickyTimer = null; } $('body').removeClass('sticky'); } } stickyCheck(); $(window).scroll(function() { stickyCheck(); }); }); </script> </body> </html>
功能说明
- 满足需求a:sticky类添加操作延迟1秒执行,滚动过程中触发的重复添加任务会被自动清理,不会出现叠加触发问题
- 满足需求b:sticky类生效后,只要用户在.test元素上有鼠标移入、点击操作就会重置2秒倒计时,连续交互不会自动隐藏;2秒内无任何交互自动移除sticky类,下次页面滚动满足条件会重新触发添加逻辑,循环生效
- 修复了你之前写法中定时器没有存储ID、clearTimeout用法错误的问题
内容的提问来源于stack exchange,提问作者user3643520
相关产品推荐
相关产品推荐

