Javascript - How to add a pause button in carousel

2019-08-08 16:53发布

I have found this script in Magento which is rotating images from a certain directory. This is working fine. But I need to add a "pause" button after the "1-6". I am not an expert on javascript so not sure how to do this. Can someone please help me with this?

The code:

<?php
$speed = 5000;//miliseconds
?>


<script type="text/javascript">
var timeoutID;

homeTileCount = 1;
$$('.home-tile-container img').each(function(e){
    $(e).writeAttribute('id','home-tile-' + homeTileCount);
    $(e).addClassName('home-tile');
    homeTileCount++;
});

homeTileCount--;

var homeTileRemote = $$('.home-tile-remote')[0];
for (i=homeTileCount;i>=1;i--)
    homeTileRemote.insert('<div id="home-tile-remote-'+i+'" class="overflow"><a href="#" onclick="switchTile('+i+');return false">'+i+'</a></div>');

function switchTile(n)
{
    //console.log(n);
    clearTimeout(timeoutID);
    $$('.home-tile-container img').each(function(e){
        e.removeClassName('home-tile-active');
    });

    $$('.home-tile-remote > div').each(function(e){
        e.removeClassName('home-tile-remote-active');
    });

    $('home-tile-remote-'+n).addClassName('home-tile-remote-active');
    $('home-tile-'+n).addClassName('home-tile-active');
    next = n+1;
    if (next > homeTileCount)
        next = 1;
    timeoutID = setTimeout('switchTile('+next+')', <?=$speed?>);
}

switchTile(1);
setTimeout('switchTile(2)', <?=$speed?>);
</script>

And this is how the carousel looks: enter image description here

1条回答
Evening l夕情丶
2楼-- · 2019-08-08 17:20

Maybe this:

<?php
$speed = 5000;//miliseconds
?>


<script type="text/javascript">
var paused=false;
var timeoutID;

homeTileCount = 1;
$$('.home-tile-container img').each(function(e){
$(e).writeAttribute('id','home-tile-' + homeTileCount);
$(e).addClassName('home-tile');
homeTileCount++;
});

homeTileCount--;

var homeTileRemote = $$('.home-tile-remote')[0];
for (i=homeTileCount;i>=1;i--)
    homeTileRemote.insert('<div id="home-tile-remote-'+i+'" class="overflow"><a href="#" onclick="switchTile('+i+');return false">'+i+'</a></div>');

function switchTile(n)
{
if (!paused) {
    //console.log(n);
    clearTimeout(timeoutID);
    $$('.home-tile-container img').each(function(e){
        e.removeClassName('home-tile-active');
    });

    $$('.home-tile-remote > div').each(function(e){
        e.removeClassName('home-tile-remote-active');
    });

    $('home-tile-remote-'+n).addClassName('home-tile-remote-active');
    $('home-tile-'+n).addClassName('home-tile-active');
    next = n+1;
    if (next > homeTileCount)
        next = 1;
    timeoutID = setTimeout('switchTile('+next+')', <?=$speed?>);
    }
    }

switchTile(1);
setTimeout('switchTile(2)', <?=$speed?>);
</script>
<button type="button" onclick="paused=true;">Pause</button>
查看更多
登录 后发表回答