0

我想知道是否有人可以使用 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);

};
});
4

1 回答 1

0

Well you are calling each() so you perform a scroll to each h2 per click. Keep track which element you passed scrolled to and only scroll to the next one, e.g.:

 $(document).ready(function(){
     var next = 0;
     $('#down').click(function(){
        $("#wrap").scrollTo($("#container h2").eq(next), 800, { axis:'y' });
        next++;
     });
 });

Update:

You have to make sure that the counter does not increase or decrease to much. I changed it also a little to not always use the selector to find all the h2 elements. It is sufficient to get them once. The counter check should also fix the problem when you are at the last element and click down (resp. when you are at the first element and click 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' });
        }
     });
 });
于 2010-06-18T17:03:23.880 回答