可通過使用css偽類實現點擊元素變色的效果,兩個偽類是:active, :focus
:active
:active選擇器用於選擇活動鏈接。當在一個鏈接上點擊時,它就會成為活動的(激活的),:active選擇器適用於所有元素,不僅限於鏈接a元素
:focus
:focus 選擇器用於選取獲得焦點的元素。僅接收鍵盤事件或其他用戶輸入的元素允許 :focus 選擇器。
由於上面的特性,如果想實現點擊時變色效果,有以下兩種方法,兩者區別在
:active,元素被點擊時變色,但顏色在點擊后消失
:focus, 元素被點擊后變色,且顏色在點擊后不消失
button:active{
background:olive;
}
button:focus{
background:olive;
}
由於div等元素無法接受鍵盤或其他用戶事件,即不支持:focus偽類,可通過增加tabIndex屬性使其支持:focus。
<div tabindex="1">
Section 1
</div>
<div tabindex="2">
Section 2
</div>
<div tabindex="3">
Section 3
</div>
div:focus {
background-color:red;
outline: none;
}

