当前位置 : 首页 » 编程语言 » 正文

让bootstrap的carousel支持滑动滚屏的实现代码

分类 : 编程语言 | 发布时间 : 2018-04-21 09:06:21 | 浏览 : 0

原始的轮播组件,并不支持滑动滚屏:

代码如下:

<span style="white-space:pre">  </span><div class="row"> 
    <div id="carousel-generic" class="carousel slide" 
      data-ride="carousel"> 
      <ol class="carousel-indicators"> 
        <li data-target="#carousel-generic" data-slide-to="0" 
          class="active"></li> 
        <li data-target="#carousel-generic" data-slide-to="1"></li> 
        <li data-target="#carousel-generic" data-slide-to="2"></li> 
      </ol> 
 
      <div class="carousel-inner" style="text-align: center"> 
        <div class="item active"> 
          <img alt="First slide" src="img/slide/1.png"></img> 
        </div> 
        <div class="item"> 
          <img alt="Second slide" src="img/slide/2.png"></img> 
        </div> 
        <div class="item"> 
          <img alt="Third slide" src="img/slide/3.png"></img> 
        </div> 
      </div> 
 
      <a class="left carousel-control" href="#carousel-generic" rel="external nofollow" rel="external nofollow"  
        data-slide="prev"> <span 
        class="glyphicon glyphicon-chevron-left"></span> 
      </a> <a class="right carousel-control" href="#carousel-generic" rel="external nofollow" rel="external nofollow"  
        data-slide="next"> <span 
        class="glyphicon glyphicon-chevron-right"></span> 
      </a> 
    </div> 
  </div> 

上面的方式,可以通过点击左右两边的箭头触发切换,但无法滑动切换。当然,自动切换还是可以的。

解决上述问题,方法其实也较多,比较方便的是使用hammer。

在此之前,需要下载hammer.min.js,jquery.hammer.js.。

下载不了的可以在我的资源里下载hammer.zip

代码如下:

<--! js顺序 --> 
<script type="text/javascript" src="js/jquery.js"></script> 
<script type="text/javascript" src="js/bootstrap.min.js"></script> 
<script type="text/javascript" src="js/hammer/hammer.min.js"></script> 
<script type="text/javascript" src="js/hammer/jquery.hammer.js"></script> 
[javascript] view plain copy
//有需求的可以把左右箭头注释掉 
$('#carousel-generic').hammer().on('swipeleft', function(){ 
  $(this).carousel('next'); 
}); 
$('#carousel-generic').hammer().on('swiperight', function(){ 
  $(this).carousel('prev'); 
}); 

总结

相关阅读:

Remove duplicates from an array of objects in JavaScript

Can I call jquery click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

Check whether a string matches a regex in JS

jQuery event to trigger action when a div is made visible

Check if user is using IE with jQuery

Resize HTML5 canvas to fit window

How do I replace a character at a particular index in JavaScript?

JavaScript file upload size validation

Converting a string to a date in JavaScript

How to get the data-id attribute?