我使用的脚本在下一个div的左击或右击上具有动画效果。它目前可以正常工作,但我想为其添加两个功能。如果单击它,我需要它重复返回到第一张幻灯片,如果通过第一张幻灯片,请单击它返回到最后一张幻灯片。另外,我有兴趣让它在页面加载时自动启动。

我尝试将点击包装在函数中并设置setTimeout,但似乎没有用。该动画当前使用CSS。

这是当前的JS:

<script>
jQuery(document).ready(function() {
var boxes = jQuery(".box").get(),
    current = 0;

jQuery('.right').click(function () {
    if (current == (-boxes.length + 1)){
        } else {
        current--;
    updateBoxes();
    }
console.log(-boxes.length + 1);
    console.log(current);
});

jQuery('.left').click(function () {
    if (current === 0){
    } else{
    current++;
    updateBoxes();
    }
});

function updateBoxes() {
    for (var i = current; i < (boxes.length + current); i++) {
        boxes[i - current].style.left = (i * 100 + 50) + "%";
    }

}
});
</script>


让我知道是否需要jsfiddle以获得更好的表示。到目前为止,我认为该代码非常易于点击动画。

谢谢。

最佳答案

尝试

jQuery(document).ready(function () {
    var boxes = jQuery(".box").get(),
        current = 0,
        timer;

    jQuery('.right').click(function () {
        if (current == (-boxes.length + 1)) {
            current = 0;
        } else {
            current--;
        }
        updateBoxes();
    }).click(); //initialize the view

    jQuery('.left').click(function () {
        if (current === 0) {
            current = -boxes.length + 1;
        } else {
            current++;
        }
        updateBoxes();
    });

    function updateBoxes() {
        //custom implementation for testing
        console.log('show', current)
        $(boxes).hide().eq(-current).show();

        autoPlay();
    }

    function autoPlay() {
        clearTimeout(timer);
        //auto play
        timer = setTimeout(function () {
            jQuery('.right').click();
        }, 2500)
    }

});


演示:Fiddle

07-26 06:43