Overcoming Sticky Hover Effects on Buttons in Touch Environments
When designing a user interface with touch devices in mind, managing hover effects on buttons can be a challenge. This seemingly straightforward task becomes complicated due to the persistent hover state that occurs on touchscreens, where the hover effect remains activated after touch, resulting in a perpetually blue button.
Inefficient Solutions
While solutions exist, such as adding a no-hover class ontouchend or using a touch class with documentElement, these methods have drawbacks. They can degrade performance and fail to handle devices with both touchscreen and mouse capabilities.
An Elusive Solution
The ideal solution would involve removing the hover state upon touchend, but direct manipulation of the hover state seems elusive. Focusing elsewhere fails to remove the hover effect, and the manual act of tapping another element appears to deactivate it, yet programmatic triggering of this action remains a mystery.
A Breakthrough
The arrival of CSS Media Queries Level 4 in 2018 brought a revolutionary solution to this dilemma:
@media (hover: hover) { button:hover { background-color: blue; } }
This declaration essentially states: "If the browser supports true hovering (e.g., a mouse-like input device), apply the hover style when buttons are hovered over."
For browsers that lack this feature, a polyfill can come to the rescue. Utilizing this polyfill, the futuristic CSS above can be transformed into:
html.my-true-hover button:hover { background-color: blue; }
Client-side JavaScript from the polyfill then detects hover support and toggles the presence of the my-true-hover class accordingly, providing an elegant solution to the sticky hover effects on touch devices.
The above is the detailed content of How Can We Prevent Sticky Hover Effects on Buttons in Touch Environments?. For more information, please follow other related articles on the PHP Chinese website!