active偽類在PC端的作用為鼠標點擊到放開時給元素添加樣式用,呈現目標被點擊的激活狀態。
寫法也很簡單
/** 將a標簽點擊時的背景色改為紅色 **/
a:active{
background-color: red;
}
但是直接在移動端這么寫會發現沒有效果。查找一番,在mozilla開發社區找到了結果。
<code>[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>.</code>
需要在按鈕元素或body/html上綁定一個touchstart事件才能激活:active狀態。
document.body.addEventListener('touchstart', function (){}); //...空函數即可
將上述事件監聽代碼加上后,Safari Mobile上就可以看到按鈕按下后的切換效果了。
參考文章:https://developer.mozilla.org/en-US/docs/Web/CSS/:active