jquery:动画滚动左

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6875054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:30:26  来源:igfitidea点击:

jquery: animate scrollLeft

jqueryjquery-selectors

提问by bswinnerton

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)

我对 jquery 很陌生,似乎无法弄清楚为什么我的代码不起作用。我有一个水平布局,想使用 scrollLeft() 函数(与此代码完美配合)

$("#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 时向左滚动功能有很好的动画效果

$("#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?

但无济于事。我究竟做错了什么?

回答by ayyp

You'll want something like this:

你会想要这样的东西:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
我相信这应该有效,它是从一个scrollTopscrollTop函数中采用的。

回答by Colin

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

首先,我应该指出,如果你经常这样做,css 动画可能效果最好,但我最终通过将 .scrollLeft 包裹在 .animate 中来获得所需的效果

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

第二个参数是速度,如果您使用某种平滑滚动,您还可以添加第三个参数。