您的位置:首页 > 移动开发

移动端:active伪类无效的解决方法

2016-01-10 13:16 246 查看

:active伪类常用于设定点击状态下或其他被激活状态下一个链接的样式。最常用于锚点<a href="#">这种情况,一般主流浏览器下也支持其他元素,如button等。在多按键的鼠标系统中,:active只适用于主按键,目前的大部分情况都是左键即主键。

该伪类下定义的CSS样式只在按下鼠标按钮与释放鼠标按钮之间的短暂瞬间被触发显示。使用键盘的tab键也可以触发:active状态。

说到:active伪类就不得不提到:link,:visited,:hover,:active这个四个,最常用的是用于a链接,设定鼠标交互时不同的链接颜色。如下示例:

[css]
view plaincopyprint?





a:link { /* Essentially means a[href], or that the link actually goes somewhere */ color: blue; } a:visited { color: purple; } a:hover { color: green; } a:active { color: red; }

a:link { /* Essentially means a[href], or that the link actually goes somewhere */
color: blue;
}
a:visited {
color: purple;
}
a:hover {
color: green;
}
a:active {
color: red;
}


上述代码中,将 :visited放到最后,则会导致以下结果:若链接已经被访问过,a:visited会覆盖:active和:hover的样式声明,链接将总是呈现为紫色,无论鼠标悬停还是按下激活,链接都将保持为紫色。

基于此原因,上述代码必须按照顺序定义,一般称为LVHA-order: :link — :visited — :hover — :active,为方便记忆,可记为“LOVE HATE”

L :link

O

V :visited

E

H :hover

A :active

T

E

浏览器兼容性:

ChromeSafariFirefoxOperaIEAndroidiOS
Yep2.0.4+any4+4+TBDTBD
项目中是移动端页面要做一个按钮状态切换的效果,在PC上测试没有问题,到了手机端发现安卓的正常,iOS则没有效果。

源码:

[css]
view plaincopyprint?





.slotbtn{ width: 5.5rem; height: 4rem; background: url(../images/sbtn.png) no-repeat 0 0; -webkit-background-size: 100% auto; background-size: 100% auto; overflow: hidden; cursor: pointer; -webkit-tap-highlight-color:transparent; -webkit-user-select:none; } .slotbtn:active, .slotbtn:focus{ background-image: url(../images/sbtn_active.png); }

.slotbtn{
width: 5.5rem;
height: 4rem;
background: url(../images/sbtn.png) no-repeat 0 0;
-webkit-background-size: 100% auto;
background-size: 100% auto;
overflow: hidden;
cursor: pointer;
-webkit-tap-highlight-color:transparent;
-webkit-user-select:none;
}
.slotbtn:active, .slotbtn:focus{
background-image: url(../images/sbtn_active.png);
}


html代码:

[html]
view plaincopyprint?





<div class="row tc row-sbtn"><span id="slotbtn" class="slotbtn"></span></div>
<div class="row tc row-sbtn"><span id="slotbtn" class="slotbtn"></span></div>


页面截图:



虽然知道jQuery Mobile框架中常会用操作class的方法来进行按钮状态切换,不过觉得非常繁琐,性能不好。而且我们有:active的天然定制属性,为何不用而舍近求远呢??

经过一番查找,之后在mozilla开发社区找到了:active不起作用的答案:

[1] By default, Safari Mobile does not use the :active state unless there is a touchstart event handler on the relevant element or on the <body>.

看来在iOS系统的移动设备中,需要在按钮元素或body/html上绑定一个touchstart事件才能激活:active状态。

[html]
view plaincopyprint?





document.body.addEventListener('touchstart', function () { //...空函数即可});

document.body.addEventListener('touchstart', function () { //...空函数即可});


将上述事件监听代码加上后,Safari Mobile上就可以看到按钮按下后的切换效果了。

参考文章:https://developer.mozilla.org/en-US/docs/Web/CSS/:active

转载请注明来自freshlover的CSDN博客《移动端:active伪类无效的解决方法》/article/2626490.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: