简体   繁体   English

JQuery 悬停、点击和触摸组合

[英]JQuery hover, click and touch combination

I would like to show and hide an element using hover, click and touch events.我想使用悬停、点击和触摸事件来显示和隐藏元素。 The idea behind this is that you will be able to use the same element for touch devices, devices that use a mouse and combination devices, like laptops that have touch.这背后的想法是,您将能够为触摸设备、使用鼠标的设备和组合设备(如具有触摸功能的笔记本电脑)使用相同的元素。 So I would need to combine mouse and touch input .所以我需要结合 mouse 和 touch input The problem is that the events influence eachother and multiple events are fired when I use touch causing the element to be shown and hidden over and over again.问题是事件会相互影响,并且当我使用触摸导致元素一遍又一遍地显示和隐藏时会触发多个事件。

How can I get the behaviour I want;我怎样才能得到我想要的行为;

  • toggle on click and touch切换点击和触摸
  • show on mouseenter在鼠标输入上显示
  • hide on mouseout鼠标移开时隐藏

I have tried multiple implementations such as the following and none seem to be stable.我尝试了多种实现,例如以下,但似乎没有一个是稳定的。

 $("#showMe").hide();
 $(document).on('touchstart click mouseenter mouseout', '#thingToTrigger', function (event) {
    event.stopPropagation();
    if (event.handled !== true) {
        $("#showMe").toggle(1000);
        event.handled = true;
    } else {
        return false;
    }
});

Here is the JSFiddle http://jsfiddle.net/9305f9d7/这是JSFiddle http://jsfiddle.net/9305f9d7/

The main thing you want to achieve is to disable default behaviour.您想要实现的主要目标是禁用默认行为。

You can add listeners for the various events, and prevent the others at the beginning of the event listeners.您可以为各种事件添加侦听器,并在事件侦听器的开头阻止其他事件。 eg:例如:

$(document).on('touchstart click', '#thingToTrigger', function (event) {
    event.preventDefault();
    //Do Touch specific stuff, e.g. toggle()
});

$(document).on('mouseenter', '#thingToTrigger', function (event) {
    event.preventDefault();
    //Do Mouseenter specific stuff, e.g. show()
});

$(document).on('mouseout', '#thingToTrigger', function (event) {
    event.preventDefault();
    //Do Mouseout specific stuff, e.g. hide()
});

You can add class on click of that element.您可以在单击该元素时添加类。

e.g. #div1 and #div2

$("#div1").click(function(){
    $(this).toggleClass("clicked");
    $("#div2").show();
});

$("#div1").on("mouseenter",function(){
    $("#div2").show();
});

$("#div1").on("mouseout",function(){
    if($(this).hasClass("clicked")==false) $("#div2").hide();
});

Hope this help.希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM