1. 程式人生 > 其它 >Bootstrap幻燈輪播如何支援觸屏左右滑動手勢?

Bootstrap幻燈輪播如何支援觸屏左右滑動手勢?

  最近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命令這個是關鍵,不會寫不會改就不好玩了。做個標記,方便日後查詢