jQuery animate中scrollTop用变量替代固定值的优化方案咨询
规范实现方案
完全不需要借助eval,直接动态获取顶部固定div的实时高度来计算滚动偏移量即可,具体实现如下:
- 实时获取固定div高度
给顶部固定div添加一个类名(比如.fixed-top-bar),每次计算滚动位置前,用outerHeight()获取它的当前高度(该方法会包含元素的padding和border,若需要包含margin则用outerHeight(true)):
const fixedBarHeight = $('.fixed-top-bar').outerHeight();
- 计算并执行滚动对齐
直接将动态获取的高度代入scrollTop的计算逻辑,无需字符串拼接或eval:
$('html, body').animate({ scrollTop: $('#sectionid').offset().top - fixedBarHeight }, 0);
- 适配窗口resize场景
如果需要在窗口尺寸变化时,依然保持section顶部与固定div底部对齐,可以监听resize事件,实时调整滚动位置:
$(window).on('resize', function() { const fixedBarHeight = $('.fixed-top-bar').outerHeight(); // 若当前已滚动到目标section区域,重新校准位置 const targetScrollTop = $('#sectionid').offset().top - fixedBarHeight; if ($(window).scrollTop() >= targetScrollTop - 10 && $(window).scrollTop() <= targetScrollTop + 10) { $('html, body').scrollTop(targetScrollTop); } });
关于之前直接用变量无效的原因
大概率是myPageTop变量没有实时更新固定div的高度,或者变量的作用域存在问题。直接用outerHeight()实时获取高度,能避免缓存过期导致的计算错误,是更可靠的写法。
内容的提问来源于stack exchange,提问作者hashcakes
相关产品推荐
相关产品推荐

