开发者

scrolling h2 elements with scrollTo in jquery

I was wondering if anyone can help me with this scrolling problem using the scrollTo plugin for jquery.I want to be able to scroll one h2 element at a time with one click...in my script it scrolls across all h2 elements with one click..Help me please guys!!

 $(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' });
     });
    });
 jQ开发者_运维问答uery.fn.reverse = function() {

  return this.pushStack(this.get().reverse(), arguments);

};
});


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' });
        }
     });
 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜