【问题标题】:How can we control the play/pause of the bootstrap carousel with single button我们如何用单个按钮控制引导轮播的播放/暂停
【发布时间】:2014-11-26 07:09:49
【问题描述】:
我浏览了“添加播放/暂停按钮以引导轮播”博客,很好。在那个博客中,它为我们提供了两个按钮(播放和暂停),但我需要通过一个按钮来控制它。这样我就可以在点击播放时添加暂停图标,反之亦然。
$(function () {
$('#carousel').carousel({
interval: 2000,
pause: "false"
});
$('#playButton').click(function () {
$('#carousel').carousel('cycle');
});
$('#pauseButton').click(function () {
$('#carousel').carousel('pause');
});
});
我刚刚添加了这个脚本。
【问题讨论】:
标签:
javascript
twitter-bootstrap
carousel
【解决方案1】:
您可以执行一些操作,例如在单击时添加一个指定状态的类。最终可能想整理一下,但现在应该可以了
$(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>
【解决方案2】:
我不知道引用的是什么博客文章,因为没有链接,但是 vernak2539 的解决方案对我来说似乎真的很啰嗦。
为什么不将播放和暂停按钮保留在 DOM 中,并在视觉上切换它们。
在css中:
#playButton{display:none;}
在 js 中,在现有的 play/pause.onclick 函数中添加 toggle() 行:
$('#playButton').click(function(){
$('#playButton,#pauseButton').toggle();
$('#homeCarousel').carousel('cycle');
});
$('#pauseButton').click(function(){
$('#playButton,#pauseButton').toggle();
$('#homeCarousel').carousel('pause');
});