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

jQuery实现锚点滚动偏移时跳转首段报Cannot read properties of undefined (reading 'top')错误

错误原因
  • 报错本质是$(target).offset()返回undefined,说明通过target值无法匹配到页面对应DOM元素,常见触发场景:
    • 导航中存在href="#"的空锚点链接,#作为选择器无法匹配任何元素
    • 链接锚点值和页面对应区域的id拼写不一致
  • 代码存在隐藏问题:animate回调函数声明的target形参会覆盖外层的target变量,导致hash赋值异常
修复后代码
$(document).ready(function(){
  var headerHeight = $("header#navigation-items").height();
  // 仅匹配当前页非空锚点链接
  $('a[href^="#"]').not('a[href="#"]').on("click", function(e) {
    e.preventDefault();
    var target = $(this).attr("href");
    // 提前判断目标元素是否存在,避免报错
    if ($(target).length > 0) {
      var scrollToPosition = $(target).offset().top - headerHeight;
      // 同时指定html、body兼容不同浏览器的滚动逻辑
      $('html, body').animate({
        scrollTop: scrollToPosition
      }, 300, function() {
        window.location.hash = target;
      })
    }
  })
});
修改说明
  • 选择器调整为a[href^="#"],过滤掉跳转到其他页面附带锚点的链接,避免匹配到当前页不存在的元素
  • 新增$(target).length判断,元素不存在时直接跳过逻辑,不会抛出错误
  • 移除animate回调的target形参,避免变量覆盖
  • 用on替代已被jQuery废弃的bind方法,兼容性更好
  • 动画对象新增body,兼容部分低版本浏览器的滚动行为差异
  • 如果需要支持href="#"的回到顶部功能,可移除.not('a[href="#"]')过滤规则,在逻辑中新增分支判断:
    let scrollToPosition = 0;
    if (target !== '#' && $(target).length > 0) {
      scrollToPosition = $(target).offset().top - headerHeight;
    }
    

内容的提问来源于stack exchange,提问作者Kumar_Maddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:27:01