Problem:
When touch devices visit websites, the :hover CSS style triggers on clicks or taps. This can be distracting or even render interactive elements inaccessible.
Objective:
Remove or ignore all :hover CSS declarations for touch devices without knowing each declaration's selector.
Solutions:
Remove all CSS rules containing :hover using JavaScript.
<code class="javascript">if (hasTouch()) { for (var si in document.styleSheets) { for (var ri = styleSheet.rules.length - 1; ri >= 0; ri--) { if (styleSheet.rules[ri].selectorText.match(':hover')) { styleSheet.deleteRule(ri); } } } }</code>
Pros:
Use @media blocks to contain :hover rules.
<code class="css">@media (hover: hover) { a:hover { color: blue; } }</code>
Pros:
Detect touch events using JavaScript and conditionally add a CSS class.
<code class="js">if (!hasTouch()) document.body.className += ' hasHover'</code>
<code class="css">body.hasHover a:hover { color: blue; }</code>
Pros:
Enable or disable hover styles based on mouse cursor and touch events.
<code class="js">function watchForHover() { document.addEventListener('touchstart', updateLastTouchTime, true) document.addEventListener('touchstart', disableHover, true) document.addEventListener('mousemove', enableHover, true) }</code>
Pros:
The above is the detailed content of How to Effectively Disable :hover Styles on Touch Devices: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!