我想知道是否有人可以使用jquery的scrollTo插件帮助我解决这个滚动问题。我希望能够一次滚动一个h2元素一次点击...在我的脚本中滚动所有h2元素只需点击一下......请大家帮帮我!!
$(document).ready(function(){
$('#down').click(function(){
$("#container h2").each(function(i,h2){
$("#wrap").scrollTo(h2, 800, { axis:'y' });
});
});
$('#up').click(function(){
$("#container h2").reverse().each(function(i,h2){
$("#wrap").scrollTo(h2, 800, { axis:'y' });
});
});
jQuery.fn.reverse = function() {
return this.pushStack(this.get().reverse(), arguments);
};
});
答案 0 :(得分:0)
您正在呼叫each()
,因此您每次点击都会对每个h2
执行滚动操作。跟踪您传递的元素滚动到哪一个,只滚动到下一个元素,例如:
$(document).ready(function(){
var next = 0;
$('#down').click(function(){
$("#wrap").scrollTo($("#container h2").eq(next), 800, { axis:'y' });
next++;
});
});
<强>更新强>
您必须确保计数器不会增加或减少太多。我也改变了一点,并不总是使用选择器来查找所有h2
元素。一次就足够了。当你在最后一个元素并点击down
时(当你在第一个元素并点击up
时),计数器检查也应该解决问题:
$(document).ready(function(){
var elements = $("#container h2");
var next = 0;
var max = elements.length;
$('#down').click(function(){
if(next+1 < max) {
next++;
$("#wrap").scrollTo(elements[next], 800, { axis:'y' });
}
});
$('#up').click(function(){
if(next-1 > -1) {
next--;
$("#wrap").scrollTo(elements[next], 800, { axis:'y' });
}
});
});