![](/img/trans.png)
[英]Console Error: Uncaught TypeError: Cannot read property 'top' of undefined
[英]jQuery Console Error: Cannot read property 'top' of undefined
此脚本平滑滚动我的 #anchor 链接并由于高度不同的固定标题创建适当的偏移量。
经过几个小时的故障排除/研究后,我无法弄清楚为什么 'top' 未定义。 一切都按预期工作,但是当我从另一个页面单击导航 (a.anchorlink) 时,总是会发生此错误。 就在页面加载之前,控制台中会弹出此错误。 当页面加载时,这个错误消失了。
jQuery:
jQuery(document).ready(function($){
var $root = $('html, body');
function getFixedOffset($) {
if($(window).scrollTop() === 0) {
return 100;
}
else {
return 55;
}
}
$('a.anchorlink').click(function() {
var href = $.attr(this, 'href');
var targetID = href.substr(href.indexOf("#") + 1);
if (targetID.length) {
var lengthID = $("#" + targetID).offset().top;
$root.animate({
scrollTop: lengthID - getFixedOffset($)
}, 850, function() {
window.location.hash = lengthID;
});
return false;
}
});
})
HTML:
<ul class="menu">
<li"><a href="/about#mission" class="anchorlink">Sub-link 1</a></li>
<li"><a href="/about#history" class="anchorlink">Sub-link 2</a></li>
</ul>
<!-- All other pages don't have hashes and will spit the error before load -->
如您所见,为了请求 top 属性,我已确保 targetID 存在(不为零)。 是否有我可以采取的其他步骤,或者您是否需要有关吐出错误的页面的更多信息?
我建议你做下一个,因为你的元素目标可能不存在:
if (targetID.length && $("#" + targetID).length > 0) {...
您只是在验证 href 的内容,而不是验证 DOM 中的元素是否存在。 因此,通过这种双重检查,您可以确保尝试对不存在的元素执行某些操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.