如何在幻灯片结束时停止Bootstrap 3 Carousel Cycling

时间:2014-11-19 00:27:25

标签: jquery twitter-bootstrap twitter-bootstrap-3

请你看看this demo,让我知道当滑块在开始时捕捉lat项目或左控制时我如何禁用控件。我已经尝试过这段代码了

$('#myCarousel').carousel('pause')
$('#myCarousel').on('slide.bs.carousel', function () {
    var $this = $(this);

  if($('.carousel-inner .item:first').hasClass('active')) {
    $this.children('.left.carousel-control').hide();
  } else if($('.carousel-inner .item:last').hasClass('active')) {
    $this.children('.right.carousel-control').hide();
  } else {
    $this.children('.carousel-control').show();
  }
})

但这不能正常运作。感谢

1 个答案:

答案 0 :(得分:3)

你有4张幻灯片,只有3个指标,这可能无助于混乱。 @Schmalzy在data-target上的指标也很好。

我建议挂钩slid.bs.carousel事件而不是slide,因为这样可以让你知道你现在在哪张幻灯片上,就像你刚刚来的那样。< / p>

由于bootstrap使用数据属性的方式知道哪个指标链接到哪个幻灯片,我们可以使用这些索引来了解我们在与slid事件结合时所处的幻灯片。

$('#myCarousel').carousel('pause');
$('#myCarousel').find('.carousel-control.left').hide(); // hide initial left control
var slideCount = $('#myCarousel').find('.carousel-indicators li').length; // get number of slides
$('#myCarousel').on('slid.bs.carousel', function () {
  var index = $(this).find('.carousel-indicators .active').data('slide-to'); // get the index of the slide we are NOW on
  if(index == 0){ // is first slide
    $(this).find('.carousel-control.right').show(); // add this in here in case only 2 slides
    $(this).find('.carousel-control.left').hide();
  }else if(index == slideCount - 1){ // is last slide
    $(this).find('.carousel-control.left').show(); // add this in here in case only 2 slides
    $(this).find('.carousel-control.right').hide();
  }else{ // is not first or last slide
    $(this).find('.carousel-control').show();
  }
})

<强> Demo

PS。可以说在开始时将这些频繁的.find调用作为变量存储以帮助优化。即:

var $myCarousel = $('#myCarousel');
var $myCarouselControls = $myCarousel.find('.carousel-control');
var $myCarouselControlsLeft = $myCarouselControls.filter('.left');
var $myCarouselControlsRight = $myCarouselControls.filter('.right');
var $myCarouselIndicators = $myCarousel.find('.carousel-indicators li');
$myCarousel.carousel('pause');
$myCarouselControlsLeft.hide();
var slideCount = $myCarouselIndicators.length;
$myCarousel.on('slid.bs.carousel', function () {
  var index = $myCarouselIndicators.filter('.active').data('slide-to');
  if(index == 0){ // is first slide
    $myCarouselControlsRight.show();
    $myCarouselControlsLeft.hide();
  }else if(index == slideCount - 1){ // is last slide
    $myCarouselControlsLeft.show();
    $myCarouselControlsRight.hide();
  }else{ // is not first or last slide
    $myCarouselControls.show();
  }
})

<强> Optimised Demo