Uncaught TypeError:无法读取未定义的offset()的属性"top". [英] Uncaught TypeError: Cannot read property 'top' of undefined offset().top
本文介绍了Uncaught TypeError:无法读取未定义的offset()的属性"top".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,这里有此消息: 未捕获的TypeError:无法读取未定义的属性"top"
Hi there got this message here: Uncaught TypeError: Cannot read property 'top' of undefined
'scrollTop': $target.offset().top - 60
代码块:
$('.btn-circle-cover').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 60
}, 2200, 'swing', function () {
window.location.hash = target;
});
});
推荐答案
this.hash
无效,因为this
将代表<button>
,而不会包含href
.而是使用.parentNode
遍历到具有href
属性的父元素,然后使用.hash
获取href
的哈希值.
this.hash
is not a valid because this
will represent the <button>
which will not have the href
. Instead traverse to the parent element which has the href
attribute using .parentNode
and use .hash
to get the hash of the href
.
示例:
$('.btn-circle-cover').on('click', function(e) {
e.preventDefault();
var target = this,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - 60
}, 2200, 'swing', function() {
console.log('hash is: ', e.currentTarget.parentNode.hash)
window.location.hash = e.currentTarget.parentNode.hash;
});
});
body {
height: 4000px;
}
button {
margin-top: 3000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Scroll Down</p>
<a href="#hdsf">
<button class="btn-circle-cover">Click here</button>
</a>
这篇关于Uncaught TypeError:无法读取未定义的offset()的属性"top".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文