How do I simulate a hover with a touch in touch enabled browsers?

后端 未结 14 2060
旧巷少年郎
旧巷少年郎 2020-11-22 17:04

With some HTML like this:

Some Text

Then some CSS like this:

p {
  color:black;
}

p:hover {
  color:red         


        
14条回答
  •  春和景丽
    2020-11-22 17:16

    To answer your main question: “How do I simulate a hover with a touch in touch enabled browsers?”

    Simply allow ‘clicking’ the element (by tapping the screen), and then trigger the hover event using JavaScript.

    var p = document.getElementsByTagName('p')[0];
    p.onclick = function() {
     // Trigger the `hover` event on the paragraph
     p.onhover.call(p);
    };
    

    This should work, as long as there’s a hover event on your device (even though it normally isn’t used).

    Update: I just tested this technique on my iPhone and it seems to work fine. Try it out here: http://jsfiddle.net/mathias/YS7ft/show/light/

    If you want to use a ‘long touch’ to trigger hover instead, you can use the above code snippet as a starting point and have fun with timers and stuff ;)

提交回复
热议问题