我試圖用「向上移動」和「向下移動」按鈕創建單個頁面,這會將窗口滾動到下一個或上一個部分(div)。我使用的方法很簡單。例如,我有5個元素帶有特殊的ID。我使用jquery創建一個名爲「pos」的數組,我擁有所有元素的位置。點擊「向上移動」和「向下移動」按鈕我檢查這個數組,如果它包含具有較低或較高值的位置 - 窗口滾動。
我創建jfiddle,所以你可以點擊這裏這個例子 - http://jsfiddle.net/YbqAB/
它適用於jfiddle網站,但我的網頁上「下移」按鈕不能滾動窗口時$(窗口).scrollTop()值等於到當前位置,即使存在下一個位置。這個問題並不是一成不變的 - 我反覆瀏覽頁面(CTRL + F5)很多次,有時我會看到這個問題,有時候不會。
因此,例如,如果我有4個div,位置爲:0px,300px,500px,800px,當我點擊「向下移動」按鈕時,窗口成功滾動到300px的div。但是當我點擊「向下移動」按鈕再次移動到下一個500px的位置 - 沒有任何反應。如果我用鼠標滾輪滾動窗口,只需要幾個像素,「向下移動」按鈕再次運行良好,並將窗口滾動到500px的div。
我做錯了什麼?或者也許有人知道更簡單的解決方案謝謝。Jquery ScrollTop動畫問題
HTML:
<div id="buttons">
<div id="top-button"> up </div>
<div id="bottom-button"> down </div>
</div>
<div id="position1"> First block </div>
<div id="position2"> Second block </div>
<div id="position3"> Third block </div>
<div id="position4"> Fourth block </div>
<div id="position5"> Fifth block </div>
CSS:
#buttons{
position: fixed;
right: 10px;
top: 50%;
}
#top-button,
#bottom-button{
width: 40px;
height: 40px;
background: orange;
margin-bottom: 10px;
font-size: 11px;
text-align: center;
line-height: 40px;
color: yellow;
}
#position1,
#position2,
#position3,
#position4,
#position5{
width: 100%;
height: 400px;
color: white;
text-align: center;
background: green;
border-bottom: 5px solid yellow;
padding-top: 20px;
}
的Jquery:
var pos = [
0,
$("#position2").offset().top,
$("#position3").offset().top,
$("#position4").offset().top,
$("#position5").offset().top
];
var $root = $('html, body');
var current;
$("#buttons #top-button").click(function() {
$.each(pos, function(i,v){
if(v < $(window).scrollTop()){
current = v;
}
});
$root.stop(true,true).animate({scrollTop:current},500);
});
$("#buttons #bottom-button").click(function() {
$.each(pos, function(i,v){
if($(window).scrollTop() < v ){
$root.stop(true,true).animate({scrollTop: v}, 500);
return false;
}
});
});
它在我看來像你做的一切正確......在Chrome中工作得很好。 –