如果用户通过触摸设备访问我们的网站,我想忽略所有:hover CSS声明。因为:hover CSS没有意义,如果平板电脑在点击/点击时触发它,它甚至会令人不安,因为它可能会一直停留到元素失去焦点。说实话,我不知道为什么触屏设备觉得有必要触发:悬停在第一位——但这是现实,所以这个问题也是现实。

a:hover {
  color:blue;
  border-color:green;
  /* etc. > ignore all at once for touch devices */
}

所以,(如何)我可以删除/忽略所有CSS:悬停声明在一次(而不必知道每一个)有他们声明后触摸设备?


当前回答

要使当前的答案也在IE11中工作(如果你仍然支持它的话):

@media (hover: hover) and (pointer: fine), only screen and (-ms-high-对比度:active), (-ms-high-对比度:none) { A:悬停{颜色:红色;} } <a href="#" >Some Link</a>

其他回答

要使当前的答案也在IE11中工作(如果你仍然支持它的话):

@media (hover: hover) and (pointer: fine), only screen and (-ms-high-对比度:active), (-ms-high-对比度:none) { A:悬停{颜色:红色;} } <a href="#" >Some Link</a>

2020解决方案- CSS只-没有Javascript

使用带有媒体指针的媒体悬停将帮助您解决此问题。在chrome Web和android手机上测试。我知道这个老问题,但我没有找到像这样的答案。

@media (hover: hover) and(指针:fine) { A:悬停{颜色:红色;} } <a href="#" >Some Link</a>

它对我很有帮助:链接

function hoverTouchUnstick() {
    // Check if the device supports touch events
    if('ontouchstart' in document.documentElement) {
        // Loop through each stylesheet
        for(var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
            var sheet = document.styleSheets[sheetI];
            // Verify if cssRules exists in sheet
            if(sheet.cssRules) {
                // Loop through each rule in sheet
                for(var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
                    var rule = sheet.cssRules[ruleI];
                    // Verify rule has selector text
                    if(rule.selectorText) {
                        // Replace hover psuedo-class with active psuedo-class
                        rule.selectorText = rule.selectorText.replace(":hover", ":active");
                    }
                }
            }
        }
    }
}

这也是一个可能的解决方案,但你必须通过你的css和添加一个.no-touch类在你的悬停样式。

Javascript:

if (!("ontouchstart" in document.documentElement)) {
document.documentElement.className += " no-touch";
}

CSS例子:

<style>
p span {
    display: none;
}

.no-touch p:hover span {
    display: inline;
}
</style>
<p><a href="/">Tap me</a><span>You tapped!</span></p>

附注:但是我们应该记住,市场上有越来越多的触摸设备,它们同时也支持鼠标输入。

肮脏的方式…这并不优雅,但却是最简单的方法。

删除任何特征悬停。

.your-class:hover:before {
  color: blue;
  background: linear-gradient(to bottom, rgba(231,56,39,0) 0%, #aaaaaa 100%);
}

@media all and (min-width:320px) and (max-width: 960px) {
    .your-class:hover:before {
    color: black;
    background: transparent;
  }
}