Twitter Bootstrap轮播:获取幻灯片的方向

Wil*_*iam 8 jquery carousel twitter-bootstrap

如何确定旋转木马是向左还是向右滑动?我查看了滑动和滑动事件的文档,但都没有提供有关幻灯片方向的任何相关信息.

我还检查了传递给slid事件的事件处理程序的事件对象,但我似乎也找不到任何有用的线索.

任何帮助,将不胜感激!

haj*_*poj 7

所以据我所知,twitter bootstrap不会通过事件对象暴露旋转木马的移动方向.但是,它会为幻灯片中涉及的元素添加"右"或"左"类.

所以基本上我看到2个选项.在事件对象中公开方向或在元素上查找右侧或左侧类.

选项1:

您将不得不修改bootstrap轮播代码.在轮播中,滑动功能改变:

e = $.Event('slide')
Run Code Online (Sandbox Code Playgroud)

e = $.Event('slide', {direction: direction})
Run Code Online (Sandbox Code Playgroud)

(在bootstrap.js正常版本中的337-340行左右)

然后你可以得到这样的方向:

var $carousel = $('.carousel');
$carousel.carousel();

$carousel.bind('slide', function(e) {
  console.log("e.direction = " + e.direction);
});
Run Code Online (Sandbox Code Playgroud)

选项2:

等待一段时间将css"left"或"right"类添加到元素中,然后检查该类是否存在.

var $carousel = $('.carousel');
$carousel.carousel();

$carousel.bind('slide', function(e) {

  setTimeout( function(){
    var left = $carousel.find('.item.active.left');
    var right = $carousel.find('.item.active.right');
    if(left.length > 0) {
      console.log('left');
    }
    else if(right.length > 0) {
      console.log('right');
    }
  }, 500);
});
Run Code Online (Sandbox Code Playgroud)

需要超时,因为在触发事件和设置左右类之间存在竞争条件.显然这是一个hackyer解决方案,但您不必修改引导代码.可能还有其他选择,但我觉得选项1是最好的.

编辑:在最新版本的bootstrap css(2.1.1)中,选项1的行更改为:

(第340行)来自:

, e = $.Event('slide', {
  relatedTarget: $next[0]
})
Run Code Online (Sandbox Code Playgroud)

至:

, e = $.Event('slide', {
  relatedTarget: $next[0],
  direction: direction
});
Run Code Online (Sandbox Code Playgroud)


小智 7

从3.0.0-rc1开始,以下工作方式可以从索引,索引和幻灯片方向访问活动元素,下一个元素.您可以根据需要随意降低选择器的特异性.

carousel.on('slide.bs.carousel', function (event) {

  var active = $(event.target).find('.carousel-inner > .item.active');
  var from = active.index();
  var next = $(event.relatedTarget);
  var to = next.index();
  var direction = event.direction;

});
Run Code Online (Sandbox Code Playgroud)


pau*_*dru 5

对于twitter bootstrap 3:

$('#myCarousel').on('slide.bs.carousel', function (event) {
    alert(event.direction);
});
Run Code Online (Sandbox Code Playgroud)