在URL調整錨點位置,使它看起來接近屏幕
http://www.site.com/xxx.php#aaaa
使用錨中間將會跳轉到錨是
<a name="aaaa"></a>
但是,這是正確的在屏幕上方。
無論如何要抵消這個輕微下降,以適應中間?如果它是一個靜態頁面,我想我可以插入更高一點的錨點。但我有一個動態生成的列表。
在URL調整錨點位置,使它看起來接近屏幕
http://www.site.com/xxx.php#aaaa
使用錨中間將會跳轉到錨是
<a name="aaaa"></a>
但是,這是正確的在屏幕上方。
無論如何要抵消這個輕微下降,以適應中間?如果它是一個靜態頁面,我想我可以插入更高一點的錨點。但我有一個動態生成的列表。
您可以使用以下調用輕鬆地通過儘可能多的滾動你的頁面,只要你想:
window.scrollBy(0, 100)
的缺點是,如果你試圖在你的document.ready()事件這樣做,它贏得了」因爲瀏覽器只有在整個頁面被加載後才能滾動到所需的元素(包括任何javascript)。那麼,該怎麼辦?
下面是一些註釋代碼,以幫助您瞭解正在發生的事情:
$(function() {
var hash = window.location.hash.substring(1);
if(hash.length > 0 && $('#'+ hash).size() > 0){
// Binds a function to the page scroll to be executed
// only once at the first scroll.
$(document).one('scroll', function(){
// when the browser finishes loading the page, it will
// scroll right to our element.
var elemTop = $('#'+ hash).offset().top; // Retrieve element's offset top
var docTop = $(document).scrollTop(); // Retrieve page's offset
// if our element is right at the top of the page, we
// want to scroll down a bit.
if(elemTop == docTop) {
//Adjust the amount of scrolling to the middle of the screen
window.scrollBy(0, window.outerHeight/2);
}
});
}
});
如何找出需要移動的像素數量?我想我需要知道那是正確的?看,錨釋放我知道... – Hao
@Jusfeel - 你滾動窗口的一半outerHeight。自滾動開始以來,這將始終將您的錨定在中間位置,您的錨點位於最上方。我在調整滾動量的代碼中的評論只是因爲滾動到頁面中間可能看起來不太好。您可能只想滾動100px。 – Chandranshu
您指出的缺點對我來說似乎不是問題。它正在工作。至少在Firefox上。 – Hao
你介意使用JavaScript通過儘可能多的像素作爲要滾動頁面下面? – Chandranshu
不,如果很簡單。 – Hao
請參閱下面的答案。我不能保證它會很容易,但我已儘可能多地註釋。 – Chandranshu