Scroll left / right an image with animation

2019-07-26 05:52发布

问题:

Please take a look at this DEMO.

By using the code from this post I've managed to make the image to move horizontally by clicking the left or right links.

What I'd like to achieve is to make the image jumps smoother somehow.

Here's my code:

<script>
    var scrollDiv = function(dir, px) {
        var scroller = document.getElementById('scroller');
        if (dir == 'l'){
            scroller.scrollLeft -= px;
        }
        else if (dir == 'r'){
            scroller.scrollLeft += px;
        }
    }
</script>

<a class="tArrowL" href="javascript: void(0);" onclick="scrollDiv('l', 80); return false;">« left</a>
<a class="tArrowR" href="javascript: void(0);" onclick="scrollDiv('r', 80); return false;">right »</a>
<div class="wrapOut">
    <div id="scroller" class="wrapIn">
        <img id="" src="http://lorempixel.com/output/nature-q-c-1044-480-2.jpg" />
    </div>
</div>

I tried to use the animate function, but with no success:

var scrollDiv = function(dir, px) {
    var scroller = document.getElementById('scroller');
    if (dir == 'l'){
        scroller.animate( { scrollLeft: '-= px' }, 1000);
    }
    else if (dir == 'r'){
        scroller.animate( { scrollLeft: '+= px' }, 1000);
    }
}

I'm testing on IE 10 on windows 8 on touchscreen desktop, so it has to work on swipe / tap events too.

Any help would be appreciated!

回答1:

DEMO

You need to animate the scrollLeft property of the jQuery object scroller, and not the HTMLObject scroller, because it's the former which has the method animate.

var scrollDiv = function (dir, px) {
    var scroller = document.getElementById('scroller'), // HTMLObject
        go;   // holds '+=' or '-='

    if (dir == 'l') go = '-=';
     else go = '+=';     // no need for else-if here

    // `$(HTMLObject)` ---> `jQuery Object`
    $(scroller).animate({
        scrollLeft: go + px  // becomes '-=int' or '+=int' 
    }, 500); // duration
}