動畫scrollTop屬性是否呈現不準確。 請檢查我在jsbin中創建的這段代碼http://jsbin.com/ewulum/2/edit動畫jQuery scrollTop無法正常工作
我想要做的是點擊鏈接時會自動向下滾動到相應的部分。但我無法弄清楚代碼中出現了什麼問題,爲什麼不能正確地向下滾動到相應的部分。點擊前兩個鏈接似乎工作正常。
在此先感謝。
動畫scrollTop屬性是否呈現不準確。 請檢查我在jsbin中創建的這段代碼http://jsbin.com/ewulum/2/edit動畫jQuery scrollTop無法正常工作
我想要做的是點擊鏈接時會自動向下滾動到相應的部分。但我無法弄清楚代碼中出現了什麼問題,爲什麼不能正確地向下滾動到相應的部分。點擊前兩個鏈接似乎工作正常。
在此先感謝。
其實它的工作和動畫jQuery的scrollTop工作正常。只需將height:2000px
添加到body
css即可。當你點擊第3,第4或第5個鏈接時,它會向下滾動,因爲第5部分沒有空格,所以滾動停止。在它下面添加一些空間或在容器上添加高度應該可以解決您的問題。
一切對我來說都很好。滾動到特定元素的最相關代碼是:
$('html, body').animate({ scrollTop: $('#box').offset().top }, 2000);
可以根據需要添加額外的像素以完美定位它。
$('html, body').animate({ scrollTop: $('#box').offset().top + 10 }, 2000);
我走進你的http://jsbin.com/ewulum/2/edit,並提出了一些變化: 「點擊前兩個環節似乎做工精細」
.wrapper {
width: 90%;
margin: 0 auto;
background:#ececec;
overflow: auto;
height: 250px;
}
JS文件
//event delegation
$("#nav-wrapper").on("click", "a", function(e){
var cur_el_href = $(this).attr("href"),
cur_el_top =$(cur_el_href).offset().top;
e.preventDefault();
console.log("The current elem's href value is " + cur_el_href);
console.log("The target section's offset top is " + cur_el_top);
$(".wrapper").animate({
scrollTop:cur_el_top
},
800, function(){
//this callback is for demonstration only so as not to back to top when testing other links
$(this).animate({scrollTop:0}, 1000);
});
});
我想知道爲回調函數設置一個定時器有什麼意義? 順便說一句,感謝您的回覆。 – chanHXC
錯別字錯誤.....我拿出來了。 –
是的,因爲有*空間*可供頁面滾動。點擊時請注意滾動條「鏈接5」。它觸底。可能的解決方案:[add white space](http://jsbin.com/ewulum/3/edit)。 – jensgram
謝謝,我會看看代碼 – chanHXC
是否有任何解決方法,而不是添加任意空白? 我希望有另一種方法來解決這個問題。 – chanHXC