2011-12-29 128 views
11

我想显示复选框作为切换按钮。但我无法将自定义图片应用于CCS - 仍然绘制复选框。如何完成这项任务?复选框的自定义图片?

我的CSS:

input[type=checkbox]#settingsbutton { 
    border-style: none; 
    background-color: transparent; 
    width: 42px; 
    height: 40px; 
    display: block; 
} 

input[type=checkbox].button-settings { 
    background-image: url("images/button-settings-normal.png"); 
} 

input[type=checkbox].button-settings:active { 
    background-image: url("images/button-settings-normal.png"); 
} 

input[type=checkbox].button-settings:hover { 
    background-image: url("images/button-settings-hover.png"); 
} 

input[type=checkbox].button-settings:active { 
    background-image: url("images/button-settings-pressed.png"); 
} 

我的HTML:

<body> 

<input type="checkbox" id="settingsbutton" class="button-settings"/> 

</body> 

回答

15

如果你想它是用纯css的解决方案,那么你必须在你的标记添加label。这是一个trick &写艾克这样的:

input[type=checkbox]{ 
    display:none; 
} 
input[type=checkbox] + label{ 
    height: 40px; 
     width: 42px; 
} 
body:not(#foo) input[type=checkbox]:checked + label{ 
    background-image: url("images/button-settings-normal.png"); 
} 

body:not(#foo) input[type=checkbox] + label{ 
    background-position:0 -46px; /* as per your requirement*/ 
    height: 40px; 
} 

HTML

<body> 

<input type="checkbox" id="settingsbutton" class="button-settings"/> 
<label for="settingsbutton"></label> 

</body> 

阅读这些文章:

http://www.thecssninja.com/css/custom-inputs-using-css

http://www.wufoo.com/2011/06/13/custom-radio-buttons-and-checkboxes/

但它不工作,IE8 &下面

+0

的联系是非常有用的,但我不明白为什么你使用'显示:上的复选框none'?如果没有显示,你不能点击它?您的链接建议将不透明度设置为零。 – Mikaveli 2013-06-03 14:33:58

+2

您可以点击将激活复选框的标签 – Prodikl 2014-01-19 09:02:12

0

尝试这种解决方案,如果你有一些标签文字

input[type=checkbox]{ 
    display:none; 
} 
input[type=checkbox] + label:before{ 
    height: 42px; 
    width: 42px; 
    content: url("../img/chk.jpg"); 
} 
body input[type=checkbox]:checked + label:before{ 
    content: url("../img/chk_checked.jpg"); 
}