简体   繁体   中英

How can we control the play/pause of the bootstrap carousel with single button

I went through the "Add Play/Pause button to bootstrap carousel" blog, its fine. In that blog it has provided us with two button (play and pause), but I need to control it through one button. So that I can add pause icon on the click of play and vice-versa.

 $(function () { $('#carousel').carousel({ interval: 2000, pause: "false" }); $('#playButton').click(function () { $('#carousel').carousel('cycle'); }); $('#pauseButton').click(function () { $('#carousel').carousel('pause'); }); }); 

I just added this script.

You could do something like adding a class designating state when clicked. Might want to tidy up eventually, but that should get it at the moment

 $(function() { $('#carousel').carousel({ interval: 2000, pause: "false" }); $(document).on('click', '#playPauseBtn', function() { var $el = $(this); var isPlaying = $el.hasClass('isPlaying'); var isPaused = $el.hasClass('isPaused'); if (isPaused) { // we know it's paused, so play it $('#carousel').carousel('cycle'); $el.removeClass('isPaused'); $el.addClass('isPlaying'); } else if (isPlaying) { // we know it's playing, so pause it $('#carousel').carousel('pause'); $el.removeClass('isPlaying'); $el.addClass('isPaused'); } }); }); 
 <div id="playPauseBtn" class="isPaused"></div> 

I don't know what blog post is being referenced, because there is no link, but vernak2539's solution seems really long-winded to me. Why not keep the play and pause buttons in the DOM and just toggle them visually.

In the css:

#playButton{display:none;}

In the js, add toggle() lines inside existing play/pause.onclick functions:

$('#playButton').click(function(){
    $('#playButton,#pauseButton').toggle();
    $('#homeCarousel').carousel('cycle');
});
$('#pauseButton').click(function(){
    $('#playButton,#pauseButton').toggle();
    $('#homeCarousel').carousel('pause');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM