仅用于触摸屏的jQuery Mobile滑动手势,而不适用于鼠标

时间:2016-03-30 19:11:31

标签: jquery-mobile touch

我正在使用jQuery Mobile允许触摸屏用户在网站中来回导航,左键滑动并向右滑动手势。问题是swipeleft和swiperight事件也是用普通鼠标触发的,这非常烦人,因为它发生在用户用鼠标选择一些文本时。

您可以在网站上看到问题(http://laetitia-stucki.ch/)和下面的JavaScript代码段。

您是否知道如何仅使用触摸设备触发滑动事件而不使用常规鼠标?

"use strict";
$( document ).ready( function() {
  ( function() {
    $( "body" ).on( "swiperight", function( e ) { navigate_prev_page(); });
    $( "body" ).on( "swipeleft",  function( e ) { navigate_next_page(); });
    function navigate_next_page() {
      var target_page = $( ".button-next" ).first().attr( "href" );
      window.location.href = target_page;
    }
    function navigate_prev_page() {
      var target_page = $( ".button-prev" ).first().attr( "href" );
      window.location.href = target_page;
    }
  })();
});

1 个答案:

答案 0 :(得分:1)

谢谢Gjermund Dahl的回答。我按照你的链接找到了另一个有趣的链接http://www.stucox.com/blog/you-cant-detect-a-touchscreen/,最终设法找到了解决方案。我们的想法是在触发swipe事件时禁用mousedown事件,并在触发touchstart事件时再次启用它。我在下面发布我的解决方案如您所见,jQuery MobileMousetrap库可以协同工作。

"use strict";
$( document ).ready( function() {
  ( function() {

    var navigate_to_page = function( e, button_class ) {
      var target_page = $( button_class ).first().attr( 'href' );
      window.location.href = target_page;
    }

    Mousetrap.bind( 'left',       function( e ) { navigate_to_page( e, '.bouton-prec'    ); });
    Mousetrap.bind( 'esc',        function( e ) { navigate_to_page( e, '.bouton-accueil' ); });
    Mousetrap.bind( 'right',      function( e ) { navigate_to_page( e, '.bouton-suiv'    ); });

    $( 'body' ).on( 'mousedown',  function( e ) { disable_swipe( e ); });
    $( 'body' ).on( 'touchstart', function( e ) { enable_swipe( e );  });

    function disable_swipe( e ) {
      $( 'body' ).off( 'swiperight swipeleft' );
    }
    function enable_swipe( e ) {
      $( 'body' ).on( 'swiperight', function( e ) { navigate_to_page( e, '.bouton-prec' ); });
      $( 'body' ).on( 'swipeleft',  function( e ) { navigate_to_page( e, '.bouton-suiv' ); });
    }
  })();
});
相关问题