You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现视口宽度<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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 17:13:15