如何实现视口宽度<680px时修改滚动触发的scrollTop阈值?
解决方案
你可以通过动态判断视口宽度来设置对应的scrollTop阈值,修改后的代码如下:
$(window).scroll(function(){ // 根据视口宽度设置阈值 const threshold = $(window).width() < 680 ? 28 : 44; if ($(this).scrollTop() > threshold) { $('body').addClass('fixed-header'); } else { $('body').removeClass('fixed-header'); } });
如果需要处理窗口大小改变的情况(比如用户拖动窗口调整宽度后,阈值能自动更新),可以把逻辑封装成一个函数,同时绑定scroll和resize事件:
function updateHeaderState() { const threshold = $(window).width() < 680 ? 28 : 44; if ($(window).scrollTop() > threshold) { $('body').addClass('fixed-header'); } else { $('body').removeClass('fixed-header'); } } // 绑定滚动和窗口 resize 事件 $(window).on('scroll resize', updateHeaderState); updateHeaderState(); // 页面加载时先执行一次,确保初始状态正确
这样不管是滚动页面还是调整窗口大小,都会根据当前视口宽度使用对应的阈值来控制header的固定状态。
内容的提问来源于stack exchange,提问作者fourroses
相关产品推荐
相关产品推荐

