最近ytkah在學習用bootstrap搭建網站,Bootstrap能自適應pc端和手機端,并且移動設備優先,適合現如今移動營銷。bootstrap是封裝好的框架,需要某些功能只需調用相應的組件就可以,但有些還是沒加入,比如幻燈輪播觸屏左右滑動手勢就不支持,大家用的設備基本是觸屏的了,能用滑動交互在小屏幕上體驗會更好,那么如何實現呢?一個比較簡單的方法是增加一個滑動手勢js插件:hammer.js,網上有很多cdn調用地址,像//cdn.bootcss.com/hammer.js/2.0.8/hammer.min.js,我們在head中加載一下然后再通過javascript把swipe功能調用出來就可以了。下面是幻燈片的原始html代碼
<div data-ride="carousel" class="carousel slide" id="carousel-example-generic"><ol class="carousel-indicators"><li class="" data-slide-to="0" data-target="#carousel-example-generic"></li><li data-slide-to="1" data-target="#carousel-example-generic" class="active"></li><li data-slide-to="2" data-target="#carousel-example-generic" class=""></li></ol><div role="listbox" class="carousel-inner"><div class="item"><img alt="First slide" src="http://ibootstrap-file.b0.upaiyun.com/lorempixel.com/1600/500/sports/1/default.jpg" data-holder-rendered="true"></div><div class="item active"><img alt="Second slide [1140x500]" src="http://ibootstrap-file.b0.upaiyun.com/lorempixel.com/1600/500/sports/2/default.jpg" data-holder-rendered="true"></div><div class="item"><img alt="Third slide [1140x500]" src="http://ibootstrap-file.b0.upaiyun.com/lorempixel.com/1600/500/sports/3/default.jpg" data-holder-rendered="true"></div></div><a data-slide="prev" role="button" href="#carousel-example-generic" class="left carousel-control"><span aria-hidden="true" class="glyphicon glyphicon-chevron-left"></span><span class="sr-only">Previous</span></a><a data-slide="next" role="button" href="#carousel-example-generic" class="right carousel-control"><span aria-hidden="true" class="glyphicon glyphicon-chevron-right"></span><span class="sr-only">Next</span></a></div>
關鍵的步驟來了,我們需要寫一個javascript命令調用hammer.js中的swipe功能
<script>$(function(){var myElement= document.getElementById('carousel-example-generic')var hm=new Hammer(myElement);hm.on("swipeleft",function(){$('#carousel-example-generic').carousel('next')})hm.on("swiperight",function(){$('#carousel-example-generic').carousel('prev')})})</script>div的id一定要對應,上面是carousel-example-generic,javascript中也要這個,否則不能實現。
需要注意的是,jquery版本最好是1.9版本的jquery-1.9.1.min.js,否則可能在電腦上可以實現手勢滑動,而在手機上無法觸摸滑動
javascript命令這個是關鍵,不會寫不會改就不好玩了。做個標記,方便日后查詢
以上所述是小編給大家介紹的Bootstrap幻燈片輪播圖支持觸屏左右手勢滑動的實現方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答