我知道這個問題很可能被問及解決了一千次,但我需要關於我的具體案例的建議。獲取window.scrollTo(0,0);去工作
我在我的網站上設置了幾個錨,我使用jquery在它們之間平滑滾動。我一直在使用一個#top
錨點滾動到頁面的頂部,它的工作原理。但問題是,如果我讓按鈕滾動到#top,它將不會滾動到頁面的絕對頂部(因爲我無法在網頁上設置足夠高的錨點)。
我試圖讓它與window.scrollTo(0, 0);
命令一起工作,但我不知道如何讓它工作,同時仍然有可能滾動到錨點。
我用下面的jQuery的錨滾動:
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function() {
window.location.hash = target;
});
});
});
有了這個HTML:
<a href="#top">
<img alt="" heigth="60" onmouseout="this.src='http://i.imgur.com/0JvWWER.png'" onmouseover="this.src='http://i.imgur.com/Ow7CVn0.png'" src="http://i.imgur.com/0JvWWER.png" width="60" />
</a>
現在,我怎麼了window.scrollTo(0,0);
工作,我該如何實現它在html正文?
在此先感謝。
給了''
,一個'ID = 「頂」'和嘗試? –'var $ target = target ==='#top'? 0:$(target).offset()。top;'會爲你解決這個問題,你甚至不需要錨點。 – somethinghere
謝謝,完美無缺:) –