2016-03-30 2 views
1

jQuery Mobileを使用して、タッチスクリーンユーザーは、スワイプした右ジェスチャーでWebサイトを前後にナビゲートできます。問題は、swipeleftイベントとswiperightイベントも通常のマウスでトリガされ、ユーザがマウスでテキストを選択したときに発生するため、非常に面倒です。jQueryタッチスクリーンのみのためのモバイルスワイプジェスチャー

この問題は、Webサイト自体(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; 
    } 
    })(); 
}); 
+0

スワイプイベントは、マウスの動きとタッチジェスチャで機能します。最初にデバイスを特定し、タッチスクリーンにのみスワイプイベントを適用する必要があります。このトレッドを確認してください:http://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device-in-jquery –

答えて

1

あなたの答えはGjermund Dahlです。私はあなたのリンクをたどり、別の興味深いリンクhttp://www.stucox.com/blog/you-cant-detect-a-touchscreen/を見つけて、最後に解決策を見つけました。考え方は、mousedownイベントがトリガされたときにswipeイベントを無効にし、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'); }); 
    } 
    })(); 
}); 
関連する問題