bxSlider:为桌面浏览器禁用 touchEnabled

bxSlider: Disabling touchEnabled for desktop browsers

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

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

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

在 Chrome 中的开发人员工具控制台中进行调试时,我在尝试将其设置为 false 时得到 touchEnabled is not defined 。我做错了什么?

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

详情在演示中评论

演示

// 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);
}
img {
  display: block;
  margin: 0 auto;
}
<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>

感谢您的回复,这是我设法解决的问题。我将默认的 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
});