巧用CSS3偽類別選取器自訂checkbox和radio的樣式

來源:互聯網
上載者:User

標籤:line   其他   content   log   點擊   ima   htm   適應   this   

由於原生的checkbox和radio的樣式太簡陋了,在設計頁面的時候,設計師往往會設計自己的checkbox和radio樣式。一半情況下,為了適應各個瀏覽器的相容性,我們都會用其他的元素替代原生的checkbox和radio,然後用js實現選中和未選中時候的樣式,用來類比checkbox和radio。

例如這種:

用其他元素類比(以checkbox為例):

<div class=‘checkbox‘></div>
$(‘.checkbox‘).click(function(){    if($(this).hasClass("checked")){              $(this).removeClass("checked");    }else{             $(this).addClass("checked");    }});

運用JS添加點擊事件,切換選中和未選中的狀態。

那麼,能僅僅只用樣式,改變原生的checkbox的樣式呢?

 

使用CSS實現:


在表單元素中,為了擴大checkbox的點擊範圍,我們經常用label和checkbox相連,現在也可以運用這個關係,把樣式加在label上,隱藏checkbox(設定透明度,不能display:none,否則關聯會失效)。

html結構:

<input type="checkbox" id="mycheck" /><lable for="mycheck">check me</label>

 

css樣式:

input[type="checkbox"] + label::before {content: ‘\a0‘; /* non-break space */display: inline-block;vertical-align: .2em;width: .8em;height: .8em;margin-right: .2em;border-radius: .2em;background: silver;text-indent: .15em;line-height: .65;}

 

利用虛擬元素::before給label添加樣式,利用CSS3的偽類別選取器:checked,:hover,:focus,:disabled設定不用狀態的樣式

 

input[type="checkbox"]:checked + label::before {content: ‘\2713‘;background: yellowgreen;}

 

input[type="checkbox"]:focus + label::before {box-shadow: 0 0 .1em .1em #58a;}input[type="checkbox"]:disabled + label::before {background: gray;box-shadow: none;color: #555;}

 

 

這樣,僅僅使用樣式就能顯示不同狀態下的checkbox樣式了。

 

巧用CSS3偽類別選取器自訂checkbox和radio的樣式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.