Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery: animate scrollLeft

I'm quite new to jquery and can't seem to figure out why my code isn't working. I have a horizontal layout and want to use the scrollLeft() function (which works perfect with this code)

$("#next").click(function() {
    currentElement = currentElement.next();
    scrollTo(currentElement);    
});

function scrollTo(element) {
    $(window).scrollLeft(element.position().left);
}

But ideally, I would like to animate this so that when #next is clicked there is a nice animated effect to the scroll left function

$("#next").click(function() {
    currentElement = currentElement.next();
    scrollTo(currentElement);    
});

function scrollTo(element) {
    $(window).animate({scrollLeft: element.position().left}, 750);
}

But to no avail. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...