为什么 href 的 scrollY 没有转到我想要的位置?
why doesn't scrollY for href go to my desired position?
我正在尝试 link 到页面中的 div,我要求 window.scrollTo(0, $(this.hash));
转到 div 所在的位置。
当我 console.log 它时,它是正确的,但是当我在 window.scrollTo 中使用它时,它会转到页面顶部。为什么它不能到达正确的位置?
$(document).ready(function() {
$('a').on('click', function(e){
e.preventDefault();
// console.log(this.hash);
console.log(e.currentTarget.href.indexOf('#'));
console.log($(this.hash));
console.log(window.pageYOffset);
console.log(window.location.hash);
if(e.currentTarget.href.indexOf('#') != -1){
// console.log(window.location);
window.scrollTo(0, $(this.hash)); //the scrollY should be the hash location
console.log($(this.hash));
}
return false;
});
});
我认为您误解了 window.scrollTo
的作用。您可以在此处找到文档:http://www.w3schools.com/jsref/met_win_scrollto.asp
它基本上接受 xPos 和 yPos 作为参数。因此,您可以执行类似 window.scrollTo(0, $(this.hash).offset().top)
的操作,或者您可以执行 $(window).animate({scrollTop: $(this.hash).offset().top})
如果有帮助请告诉我!
我正在尝试 link 到页面中的 div,我要求 window.scrollTo(0, $(this.hash));
转到 div 所在的位置。
当我 console.log 它时,它是正确的,但是当我在 window.scrollTo 中使用它时,它会转到页面顶部。为什么它不能到达正确的位置?
$(document).ready(function() {
$('a').on('click', function(e){
e.preventDefault();
// console.log(this.hash);
console.log(e.currentTarget.href.indexOf('#'));
console.log($(this.hash));
console.log(window.pageYOffset);
console.log(window.location.hash);
if(e.currentTarget.href.indexOf('#') != -1){
// console.log(window.location);
window.scrollTo(0, $(this.hash)); //the scrollY should be the hash location
console.log($(this.hash));
}
return false;
});
});
我认为您误解了 window.scrollTo
的作用。您可以在此处找到文档:http://www.w3schools.com/jsref/met_win_scrollto.asp
它基本上接受 xPos 和 yPos 作为参数。因此,您可以执行类似 window.scrollTo(0, $(this.hash).offset().top)
的操作,或者您可以执行 $(window).animate({scrollTop: $(this.hash).offset().top})
如果有帮助请告诉我!