CSS實現點擊改變元素背景色

來源:互聯網
上載者:User

標籤:鍵盤事件   style   顏色   使用者輸入   ack   logs   選擇   dex   接收   

可通過使用css偽類實現點擊元素變色的效果,兩個偽類是:active, :focus

:active

:active選取器用於選擇活動連結。當在一個連結上點擊時,它就會成為活動的(啟用的),:active選取器適用於所有元素,不僅限於連結a元素

:focus

:focus 選取器用於選取獲得焦點的元素。僅接收鍵盤事件或其他使用者輸入的元素允許 :focus 選取器。

 

由於上面的特性,如果想實現點擊時變色效果,有以下兩種方法,兩者區別在

:active,元素被點擊時變色,但顏色在點擊後消失

:focus, 元素被點擊後變色,且顏色在點擊後不消失

    button:active{      background:olive;    }    button:focus{      background:olive;    }

 線上執行個體:http://jsfiddle.net/vt1bzpsq/

由於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;}

線上執行個體:http://jsfiddle.net/mwbbcyja/

 

CSS實現點擊改變元素背景色

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.