自动播放Javascript轮播直到按钮单击

时间:2017-12-08 00:08:57

标签: javascript html css gsap

所以我有一个整洁的小旋转木马,通过点击左箭头或右箭头起作用。

的Javascript

unitWidth = 760;
unitTotal = 4;
unitCtr = 1;

onLeftArrow = function(e) {
    //alert("Left");
    disableArrows();
    if (unitCtr<=unitTotal) {
        unitCtr++;
        TweenLite.to(productImg, 0.6, {x: "-="+unitWidth, onComplete:enableArrows });
    }
    hideArrows();
}

onRightArrow = function(e) {
    //alert("Right");
    disableArrows();
    if (unitCtr>1) {
        unitCtr--;
        TweenLite.to(productImg, 0.6, {x: "+="+unitWidth, onComplete:enableArrows });
    }
    hideArrows();
}

function hideArrows() {
    //alert(unitCtr)
    if (unitCtr <= 1) {
        arrowRight.style.visibility = "hidden";
        arrowLeft.style.visibility = "visible";
    }
    if (unitCtr >= unitTotal) {
        arrowRight.style.visibility = "visible";
        arrowLeft.style.visibility = "hidden";
    }
    if (unitCtr>1 && unitCtr<unitTotal) {
        arrowRight.style.visibility = "visible";
        arrowLeft.style.visibility = "visible";
    }
}

function disableArrows() { //ADDED NEW FUNCTION TO DISABLE ARROWS
    arrowLeft.removeEventListener('click', onLeftArrow, false);
    arrowRight.removeEventListener('click', onRightArrow, false);
}

function enableArrows() { //ADDED NEW FUNCTION TO RE-ENABLE ARROWS
    arrowLeft.addEventListener('click', onLeftArrow, false);
    arrowRight.addEventListener('click', onRightArrow, false);
}

HTML

<div id="arrowL">
    <img src="arrow_click.png" width="100" height="415" />
</div>

<div id="arrowR">
    <img src="arrow_click.png" width="100" height="415" />
</div>

<div id="product_img">
    <div class="img_container" id="product1">
        <img src="panel1.jpg" class="product" />
    </div>
    <div class="img_container" id="product2">
        <img src="panel2.jpg" class="product" />
    </div>
    <div class="img_container" id="product3">
        <img src="panel3.jpg" class="product" />
    </div>
    <div class="img_container" id="product4">
        <img src="panel4.jpg" class="product" />
    </div>
</div>

我希望旋转木马一直自动播放一次,直到它到达终点或有人点击箭头。有关最佳方法的建议吗? (我使用GSAP处理实际动作)

1 个答案:

答案 0 :(得分:0)

尝试使用部分代码来处理转换为模块,以便更容易调用/使用它们。

请注意:我没有对它进行测试,但它会让您了解旋转木马应如何作为自动播放以及如何停止它。 (您也可以添加其余的代码,这只是新的或更新的部分。)

<强>的javascript

var unitWidth = 760,
    unitTotal = 4,
    unitCtr = 1,
    interval;

onLeftArrow = function(e) {
    disableArrows();
    transition_forward();
    hideArrows();
}

function transition_forward(){
    if (unitCtr<=unitTotal) {
        unitCtr++;
        TweenLite.to(productImg, 0.6, {x: "-="+unitWidth, onComplete:enableArrows });
    }
}

function auto_play(){
    interval = setInterval(function(){
        transition_forward();
    }, 2500);
}

auto_play();

clearIV = function(){
    clearInterVal(interval );
}

arrowLeft.addEventListener('click', clearIV, false);
arrowRight.addEventListener('click', clearIV, false);