移动端网页解决CSS的active伪类无效的方法

2020-05-02 08:15:53易采站长站整理

}     
.slotbtn:active, .slotbtn:focus{     
    background-image: url(../images/sbtn_active.png);     
}    

html代码:

XML/HTML Code复制内容到剪贴板

<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状态。

CSS Code复制内容到剪贴板

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

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