【问题标题】:Slide animation using jQuery only works in one direction使用 jQuery 的幻灯片动画只在一个方向上起作用
【发布时间】:2023-03-19 07:30:01
【问题描述】:

http://jsfiddle.net/WEBk2/1/

我有一组块元素,我在点击时附加了一个幻灯片动画。目标是让元素继续顺畅地来回滑动。

<section class="stretch">
    <div class="block blue"></div><div class="block red"></div><div class="block green"></div><div class="block orange"></div><div class="block silver"></div><div class="block teal"></div><div class="block salmon"></div>
</section>
<button class="button-left">Left</button>
<button class="button-right">Right</button>

还有 jQuery:

function moveRight() {
        var lastBlock = $(".stretch .block:last-child");
        lastBlock.remove();
        $(".stretch .block:first-child").before(lastBlock);
        $(".stretch .block").each(function(){
            $(this).css("left","0").css("right","0");
            $(this).animate({"left": "+=250px"}, "5000");
        });
    };

    function moveLeft() {
        var firstBlock = $(".stretch .block:first-child");
        firstBlock.remove();
        $(".stretch .block:last-child").after(firstBlock);
        $(".stretch .block").each(function(){
            $(this).css("right","0").css("left","0");
            $(this).animate({"right": "+=250px"}, "5000");
        });
    };
$(".button-right").click(function(){
        moveLeft();
    });

    $(".button-left").click(function(){
        moveRight();
    });

我得到的结果是只有一个移动功能是用动画(moveRight)滑动。我不明白为什么它不能用 moveLeft 函数制作动画。

【问题讨论】:

    标签: javascript jquery jquery-animate


    【解决方案1】:

    Fiddle

    moveRight()更改为

    function moveRight() {
        if ($('.stretch .block:animated').length == 0) {
            var lastBlock = $(".stretch .block:last-child");
            var cloned = lastBlock.clone()
            cloned.width(1);
            $(".stretch .block:first-child").before(cloned);
            cloned.animate({
                'width': "250"
            }, "5000", function () {
                lastBlock.remove()
            });
        }
    };
    

    还有moveLeft()

    function moveLeft() {
        if ($('.stretch .block:animated').length == 0) {
            var firstBlock = $(".stretch .block:first-child");
            var cloned = firstBlock.clone()
            cloned.width(250);
            $(".stretch .block:last-child").after(cloned);
            firstBlock.animate({
                'width': "0"
            }, "5000", function () {
                firstBlock.remove()
            });
        }
    };
    

    这至少可以实现您的视觉效果。如果您没有足够的元素来填充容器,而右侧缺少一个元素,则克隆是必要的。

    检查是否有任何元素被动画化将防止多个克隆由同一个元素组成。

    【讨论】:

    • 还有moveLeft函数也有问题,它负责右移按钮动作,时不时会出问题,因为你在做之前要删除first-child元素动画。这会导致它跳过一个元素,从而将第一个元素删除到最后一个元素,然后向左滑动(跳过 2 个元素)。
    • 哈哈,.clone() 也是我的第一个猜测!干得好!
    • 这是完美的。我需要查看它并准确了解您在这里做什么以及它为什么起作用,但是我将其插入并且它运行良好。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    相关资源
    最近更新 更多