bxSlider:禁用桌面浏览器的touchEnabled

时间:2017-07-18 10:55:22

标签: javascript jquery html bxslider

如果用户有桌面浏览器,我试图禁用bxSlider库的touchEnabled选项。

if(navigator.userAgent.match(/Chrome|Mozilla|Safari/)){
     $('.theSlider').bxSlider({
          touchEnabled: false
     });
}

//Html slider
<ul class="theSlider">

在Chrome中的开发人员工具控制台中调试时,我尝试将其设置为false时未定义touchEnabled。我做错了什么?

2 个答案:

答案 0 :(得分:2)

感谢您的回复,这是我设法解决的问题。我将默认的var touchDevice设置为false。如果用户正在使用移动设备,则会检测并将touchDevice设置为true。当我初始化bxSlider时,它将采用任何touchDevice设置,并将touchEnabled设置为该结果。

// Enable touch events for Mobile Browsers
var touchDevice = false;
if (navigator.userAgent.match(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/)) {
      touchDevice = true;
}

$('.theSlider').bxSlider({
      touchEnabled: touchDevice
});

答案 1 :(得分:0)

  1. 在窗口对象上侦听touchstart event。如果应用加载在桌面上,很可能它不会触发触摸事件。反过来,移动设备会在正常使用时触发touchstart事件。
  2. 接下来,如果touchstart触发,则bx方法.reloadSlider()会运行并传递存储新选项的对象(cfg2
  3. 最后一项任务是删除侦听器,因为每个会话只需要一次这样的目的。
  4. 详情在演示

    中发表

    演示

    &#13;
    &#13;
    // Initial Configuration
    var cfg1 = {
      touchEnabled: false
    }
    // Alternate Configuration
    var cfg2 = {
      touchEnabled: true,
      oneToOneTouch: true,
      swipeThreshold: 25,
      preventDefaultSwipeX: false,
      preventDefaultSwipeY: false
    }
    
    /* Store the instant in a variable.
    || Pass the cfg1 option 
    */
    var bx = $('.bx').bxSlider(cfg1);
    
    /* Delegate the touchstart event on window object
    || which basically will only detects a touchstart
    || event if the device can actually use touch events.
    || So when using a laptop, desktop, etc., the 
    || touchstart will never be triggered.
    */
    /* Now if this loads on a mobile device, it will detect
    || touchstart event and then reload bxSlider with a new
    || configuration (cfg2) which among its options is the
    || touchEnabled: true / property: value
    || Once that is done, it will remove the event listener
    || with .off() method.
    */
    $(window).on('touchstart', enableTouch);
    
    function enableTouch(e) {
    
      bx.reloadSlider(cfg2);
    
      $(window).off('touchstart', enableTouch);
    }
    &#13;
    img {
      display: block;
      margin: 0 auto;
    }
    &#13;
    <link href="https://cdn.jsdelivr.net/bxslider/4.2.12/jquery.bxslider.css" rel="stylesheet">
    
    <ul class='bx'>
      <li><img src='http://imgh.us/1one.png'></li>
      <li><img src='http://imgh.us/2two.png'></li>
      <li><img src='http://imgh.us/3three.png'></li>
      <li><img src='http://imgh.us/4four.png'></li>
      <li><img src='http://imgh.us/5five.png'></li>
      <li><img src='http://imgh.us/6six.png'></li>
    </ul>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src='https://cdn.jsdelivr.net/bxslider/4.2.12/jquery.bxslider.min.js'></script>
    &#13;
    &#13;
    &#13;