首页 > 解决方案 > 未捕获的类型错误:通过导航栏导航到 html 页面的最顶部部分时,无法读取未定义的属性(读取“顶部”)

问题描述

我正在尝试使用 jquery 代码创建一个偏移函数,以防止标题隐藏在粘性导航栏后面。尽管该功能在通过导航栏链接导航到页面的其他部分时工作正常,但当我尝试导航到我的 html 页面的第一部分时,它会抛出错误“无法读取未定义的属性(读取'顶部')”。谁能告诉我问题是什么以及我应该如何解决它。下面是我的代码。我正在使用 jquery 3.4.1。

$(document).ready(function(){
  
var headerHeight = $("header#navigation-items").height();

$('a[href*="#"]').bind("click", function(e) {

    e.preventDefault();

    var target = $(this).attr("href"); //Get the target
    var scrollToPosition = $(target).offset().top - (headerHeight);

    $('html').animate({
      'scrollTop': scrollToPosition
    }, 300, function(target) {
      window.location.hash = target;

    })

  })
});

标签: jquery

解决方案


我能够找出这个问题。我在为我的主页选项卡定义 id 时添加了一个 # 符号,即 id= "#home" 。因此,导航链接无法识别此 id 并返回空集合并导致错误。在更改 id ="home" 时,我能够解决此问题。


推荐阅读