【问题标题】:Repeating horizontal auto scroll bar重复水平自动滚动条
【发布时间】:2017-08-25 23:12:58
【问题描述】:

我有一个自动滚动条脚本,可以使图像向右滚动。我想让它在到达终点后重复。请帮忙!

<div class="scrolls">
    <div>
        <img src="img1" height="200"/>
        <img src="img2" height="200"/>
        <img src="img3" height="200"/>
    </div>          
</div>

<script>
    $(document).ready(function() {
        var sL = 4000;
        $('.scrolls').animate({
            scrollLeft : sL
        },100000, 'linear');

        $(".scrolls").on("click",function(){
                $(this).stop(true,false);
        });

        $(".scrolls").on("mouseenter",function(){
            $(this).stop(true,false);
        });

        $(".scrolls").on("mouseleave",function(){
            $(this).animate({
            scrollLeft : sL
            },100000, 'linear');
        });
    })
    </script>

【问题讨论】:

    标签: javascript scroll


    【解决方案1】:

    使用 listitems 获取一个无序列表(html 标记)

    <div class="scrolls">
        <ul>
            <li><img src="img1" height="200"/></li>
            <li><img src="img2" height="200"/></li>
            <li><img src="img3" height="200"/></li>
        </ul>
    </div>
    

    复制此列表项,以便将整个水平空间填满两次。现在将 div 向右滚动,每次图像离开 div 时,将其从开头移动到结尾。

    // create as many copys as needed for filling the whole harizontal space twice
    var dummyClones = $('.scrolls > ul > li').clone(true);
    while($('.scrolls > ul').width() < 2*$('.scrolls').width())
      $('.scrolls > ul').append(dummyClones.clone(true));
    

    动画本身是通过window.requestAnimationFrame解决的:

    var animationSpeedInMiliseconds = 10000; // 10 seconds for 1000px
    function step(timestamp) {
        if(!step.startTimestamp) step.startTimestamp = timestamp;
        if(!step.stopped) {
            let delta = timestamp - step.startTimestamp;
            let pixelCountToShift = (delta / animationSpeedInMiliseconds) * 1000;
            if($('.scrolls').scrollLeft()+pixelCountToShift > $('.scrolls > ul > li:eq(0)').width()) {
                $('.scrolls > ul').append($('.scrolls > ul > li:eq(0)'));
                $('.scrolls').scrollLeft($('.scrolls').scrollLeft()+pixelCountToShift-$('.scrolls > ul > li:eq(0)').width());
            } else {
                $('.scrolls').scrollLeft($('.scrolls').scrollLeft()+pixelCountToShift);
            }
        }
        step.startTimestamp = timestamp;
        window.requestAnimationFrame(step);
    }
    

    注意:它并不完美。这是我在 4 分钟内创建的示例,旨在被理解为概念验证。不是用于生产用途的脚本。

    jsfiddle:https://jsfiddle.net/Kasalop/tktfr4rz/2/

    【讨论】:

    • 请尝试使用 Snippets 是可能的。
    • @Keith 不是 sn-ps 的粉丝(我的浏览器安全策略无论如何都会阻止它们),但我保证将来我会继续忙于 sn-ps。
    猜你喜欢
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    相关资源
    最近更新 更多