【问题标题】:jQuery click event just for touch, for all others hoverjQuery单击事件仅用于触摸,其他所有悬停
【发布时间】:2014-04-06 17:49:35
【问题描述】:

我尝试修改我的 jQuery 代码,在默认桌面设备上使用“悬停”事件,并在触摸设备上使用“点击”功能。原因在于,将它们分开会带来更好的可用性。

我在这个 Fiddle 中发布了我的整个代码:http://jsfiddle.net/syZC6/

 $(document).ready(function(e){
              $("header").hover(function() {   
                  if ($('#expandMenu').is(':visible'))
                  {
                      $('#menubar').removeClass('menu-active');
                      $('#switcher').removeClasse'switcherOpen');
                  }
                  else
                  {
                      $('#menubar').addClass('menu-active');
                      $('#switcher').addClass('switcherOpen');
                  }

                  $('#expandMenu').slideToggle( "fast");
               });          
                });

也许有一个解决方案,就像我以前做过的那样:

$(window).width() < 900 ? "true" : "false",

但它只是检测窗口加载时的当前宽度,而不是设备类型……

非常感谢您的帮助!

【问题讨论】:

    标签: jquery touch detection


    【解决方案1】:

    您可以根据自己的条件声明事件

    演示http://jsfiddle.net/e2fc7/

       var touchscreen;
       if (window.matchMedia("(max-width: 300px)").matches) {
           touchscreen = true;
       } else {
           touchscreen = false;
       }
    
       var evt = touchscreen ? 'touchstart' : 'mouseenter';
    
       $("header").bind(evt, function () {
           if ($('#expandMenu').is(':visible')) {
               $('#menubar').removeClass('menu-active');
               $('#switcher').removeClasse 'switcherOpen');
       } else {
           $('#menubar').addClass('menu-active');
           $('#switcher').addClass('switcherOpen');
       }
       $('#expandMenu').slideToggle("fast");
       });
    

    【讨论】:

    • 谢谢,它看起来不错,但你确定它有效吗?我将您的代码复制到 jsfiddle 中,没有更多操作...
    • 抱歉刚刚检查和编辑。我将hover 替换为mouseenter,将on 替换为bind。我现在按预期工作。
    • @Vector 什么是“(max-width: 300px)”,为什么是 300px?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多