如果用户通过触摸设备访问我们的网站,我想忽略所有:hover CSS声明。因为:hover CSS没有意义,如果平板电脑在点击/点击时触发它,它甚至会令人不安,因为它可能会一直停留到元素失去焦点。说实话,我不知道为什么触屏设备觉得有必要触发:悬停在第一位——但这是现实,所以这个问题也是现实。
a:hover {
color:blue;
border-color:green;
/* etc. > ignore all at once for touch devices */
}
所以,(如何)我可以删除/忽略所有CSS:悬停声明在一次(而不必知道每一个)有他们声明后触摸设备?
这也是一个可能的解决方案,但你必须通过你的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>
源
附注:但是我们应该记住,市场上有越来越多的触摸设备,它们同时也支持鼠标输入。
悬停CSS媒体功能来拯救!仅使用CSS,当设备没有悬停功能时,您可以覆盖样式。
下面的演示由现代触摸设备支持。
/* hover query styles */
a {
color: red;
font-size: 3em;
}
a:hover {
color: blue;
}
@media (hover: none) {
a:link,
a:visited {
color: blue;
text-decoration: none;
border: 0.1em solid currentColor;
padding: 0 0.1em;
}
}
/* used to show if demo browser has hover capabilities */
.detection:before {
content: 'UNKNOWN';
color: red;
}
@media(hover) {
.detection:before {
content: 'YES';
color: green;
}
}
@media (hover: none) {
.detection:before {
content: 'NO';
}
}
<p>Hoverable pointer detected: <span class="detection"></span></p>
<h3>Experiences between device hover capabilities</h3>
<p>If the device has a hover capability, the link below:</p>
<ul>
<li>should be red</li>
<li>should be blue when hovered</li>
</ul>
<p>If the device does not have a hover capability, the link below:</p>
<ul>
<li>should always be blue</li>
<li>should be surrounded by a blue border</li>
</ul>
<p><a href="https://www.google.com">Link</a></p>
注意:请记住,由于Surface PC的主要输入(功能)是鼠标,它最终将是一个蓝色链接,即使它是一个分离的(平板电脑)屏幕。浏览器将(应该)总是默认使用最精确的输入功能。
试试这个(我在这个例子中使用background和background-color):
var ClickEventType = ((document.ontouchstart !== null) ? 'click' : 'touchstart');
if (ClickEventType == 'touchstart') {
$('a').each(function() { // save original..
var back_color = $(this).css('background-color');
var background = $(this).css('background');
$(this).attr('data-back_color', back_color);
$(this).attr('data-background', background);
});
$('a').on('touchend', function(e) { // overwrite with original style..
var background = $(this).attr('data-background');
var back_color = $(this).attr('data-back_color');
if (back_color != undefined) {
$(this).css({'background-color': back_color});
}
if (background != undefined) {
$(this).css({'background': background});
}
}).on('touchstart', function(e) { // clear added stlye="" elements..
$(this).css({'background': '', 'background-color': ''});
});
}
css:
a {
-webkit-touch-callout: none;
-webkit-tap-highlight-color: transparent;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}