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

后端 未结 14 2067
旧巷少年郎
旧巷少年郎 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:23

    OK, I've worked it out! It involves changing the CSS slightly and adding some JS.

    Using jQuery to make it easy:

    $(document).ready(function() {
        $('.hover').on('touchstart touchend', function(e) {
            e.preventDefault();
            $(this).toggleClass('hover_effect');
        });
    });
    

    In english: when you start or end a touch, turn the class hover_effect on or off.

    Then, in your HTML, add a class hover to anything you want this to work with. In your CSS, replace any instance of:

    element:hover {
        rule:properties;
    }
    

    with

    element:hover, element.hover_effect {
        rule:properties;
    }
    

    And just for added usefulness, add this to your CSS as well:

    .hover {
    -webkit-user-select: none;
    -webkit-touch-callout: none;        
    }
    

    To stop the browser asking you to copy/save/select the image or whatever.

    Easy!

提交回复
热议问题