FED实验室 - 专注WEB端开发和用户体验

Safari :active伪类失效问题

CSS(3) JAVASCRIPT 煦涵 2233℃ 0评论

:active伪类,参见CSS2.1 Selector Spec,如果在PC端开发中会经常遇到,当然在某些初级或入门级的面试中也会问到A锚链接元素的几种状态,也许你可能会弄混,:link,:visited,:hover,:active, 常用缩写"LVHA", 或者更好记忆为"LOVE HATE"即"爱与恨",好像是某个歌手的专辑名称,自行百度,这样记起来就比较容易记住了.摘录其中的一段描述:

Note that the A:hover must be placed after the A:link and A:visited rules, since otherwise the cascading rules will hide the 'color' property of the A:hover rule. Similarly, because A:active is placed after A:hover, the active color (lime) will apply when the user both activates and hovers over the A element.

这里是分割线!!!!!!!!!!!!!!!!!!!!

本文想说下在iOS 系统Safari浏览器中:active伪类失效的原因以及解决方案.

1. 失效原因
我们可以从Safari Developer Library中找到答案,描述如下:

You can also use the -webkit-tap-highlight-color CSS property in combination with setting a touch event to configure buttons to behave similar to the desktop. On iOS, mouse events are sent so quickly that the down or active state is never received. Therefore, the :active pseudo state is triggered only when there is a touch event set on the HTML element—for example, when ontouchstart is set on the element as follows:

<button class="action" ontouchstart="" style="-webkit-tap-highlight-color: rgba(0,0,0,0);">Testing Touch on iOS</button>

Now when the button is tapped and held on iOS, the button changes to the specified color without the surrounding transparent gray color appearing.

其中的描述,在iOS上,鼠标事件是太快了,按钮及active状态无法触发,因此,:active状态只能在设置了touch 事件的元素上触发,具体可详见上文中标红色部分. 参考链接::active pseudo-class doesn't work in mobile safari

2. 解决方案
1) 像上面那样:

<button ontouchstart="" >Testing Touch on iOS</button>

2) 另一种就是在docuemnt上绑定touchstart事件

document.addEventListener("touchstart", function() {
   // do nothing
},false);

小知识点,以作备忘!

下面是「FED实验室」的微信公众号二维码,欢迎扫描关注:

FED实验室

行文不易,如有帮助,欢迎打赏!

赞赏支持 喜欢 (5)
捐赠共勉
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址