CSS hover not being ignored on touch-screen device

2020-02-28 10:48发布

问题:

I've appended a div with a html button:

$('.nav').append('<button class="restart">Restart</button>');

The button has css properties for hover. My problem is that when tapping the button on a touch-screen device, the button retains its hover state until another element is tapped.

Is there any way that the hover property can be ignored when browsing with a touch-screen device?

回答1:

I came across this exact problem recently, iOS seems to consider the hover psuedo as an additional click, so links will needs clicking twice etc.

If you use modernizr you can apply your :hover psuedos through the .no-touch class which is applied to the html tag.

so:

html a { color:#222; }

html.no-touch a:hover { color:#111; }


回答2:

Not an ideal solution, but thanks @dualed for the headstart!

@media screen and (min-device-width:768px) and (max-device-width:1024px) /*catch touch screen devices */
{
    button.restart:hover
    {
        /* replicate 'up' state of element */
    }
}


回答3:

You can specify the media type in your CSS rules.

@media handheld {
  button.restart:hover {
    /* undo hover styling */
  }
}

However, note that hand held devices do not necessarily have a touch screen.

(Btw. this is CSS not jQuery)



回答4:

Maybe that's not what you want, but you can specify different css stylesheets depending on the media :

 <link rel="stylesheet" media="screen,projection,tv" href="main.css" type="text/css">
 <link rel="stylesheet" media="print" href="print.css" type="text/css">
 <link rel="stylesheet" media="handheld" href="smallscreen.css" type="text/css">

in above example, main.css will be used for computer screens but for a handeld device, it will be smallscreen.css



回答5:

One nice and easy way is using Modernizr.

When Modernizr runs, it will add an entry in the class attribute of the HTML tag for every feature it detects, prefixing the feature with no- if the browser doesn’t support it.

Now add following lines to your css stylesheet

.touch *:hover {
    display: none;
}

And freely use :hover as many times as you like. When your site is viewed in touch screens hover effect of all elements will be disabled.