简体   繁体   English

向左/向右滚动带有动画的图像

[英]Scroll left / right an image with animation

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: 我尝试使用animate功能,但没有成功:

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. 我正在Windows 8的触摸屏桌面上的IE 10上进行测试,因此它也必须在滑动/点击事件中起作用。

Any help would be appreciated! 任何帮助,将不胜感激!

DEMO 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 . 您需要设置jQuery对象scrollerscrollLeft属性的动画,而不是HTMLObject scroller动画 ,因为前者具有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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM