方法:1、使用“:active”偽類,配合“:focus”偽類,只需要將“:active”偽類和“:focus”偽類設(shè)置相同背景顏色即可實(shí)現(xiàn)效果;2、使用tabindex屬性控制次序,配合“:focus”偽類實(shí)現(xiàn)點(diǎn)擊后變色,且不消失效果。
本教程操作環(huán)境:windows7系統(tǒng)、CSS3&&HTML5版、Dell G3電腦。
可通過使用css偽類實(shí)現(xiàn)點(diǎn)擊元素變色的效果,兩個偽類是:active, :focus
1、:active:用于選擇活動鏈接。當(dāng)在一個鏈接上點(diǎn)擊時,它就會成為活動的(激活的),:active選擇器適用于所有元素,不僅限于鏈接a元素
:focus:用于選取獲得焦點(diǎn)的元素。僅接收鍵盤事件或其他用戶輸入的元素允許 :focus 選擇器。
由于上面的特性,如果想實(shí)現(xiàn)點(diǎn)擊時變色效果,有以下兩種方法,兩者區(qū)別在
:active,元素被點(diǎn)擊時變色,但顏色在點(diǎn)擊后消失
:focus, 元素被點(diǎn)擊后變色,且顏色在點(diǎn)擊后不消失
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>document</title> <style> button:active{ background:olive; } button:focus{ background:olive; } </style> </head> <body bgcolor="#ccc"> <button>cmcc</button> </body> </html>
效果:
2、由于div等元素?zé)o法接受鍵盤或其他用戶事件,即不支持:focus偽類,可通過增加tabIndex屬性使其支持:focus
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>document</title> <style> div{ background: #fff; border:1px solid rgb(59, 59, 59); border-radius: 5px; margin: 10px 0; } div:focus { background-color:red; } </style> </head> <body bgcolor="#ccc"> <div tabindex="1"> Section 1 </div> <div tabindex="2"> Section 2 </div> <div tabindex="3"> Section 3 </div> </body> </html>
效果:
推薦學(xué)習(xí):css視頻教程