问题
Hi there got this message here: Uncaught TypeError: Cannot read property 'top' of undefined
'scrollTop': $target.offset().top - 60
Code block:
$('.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;
});
});
回答1:
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
.
Example:
$('.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>
来源:https://stackoverflow.com/questions/40098804/uncaught-typeerror-cannot-read-property-top-of-undefined-offset-top