代码之家  ›  专栏  ›  技术社区  ›  Alex C

纯CSS复选框图像替换

  •  75
  • Alex C  · 技术社区  · 16 年前

     <tr><td><input type="checkbox" class="custom_image" value="1" id="CB1" /><label for='CB1'>&nbsp;</label></td></tr>
     <tr><td><input type="checkbox" class="custom_image" value="2" id="CB2" /><label for='CB2'>&nbsp;</label></td></tr>
     <tr><td><input type="checkbox" class="custom_image" value="3" id="CB3" /><label for='CB3'>&nbsp;</label></td></tr>
     <tr><td><input type="checkbox" class="custom_image" value="4" id="CB4" /><label for='CB4'>&nbsp;</label></td></tr>
    

    我想用一对自定义的开/关图像替换复选框图像,我想知道是否有人对如何使用CSS有更好的理解?

    我发现了这个“CSS忍者”教程,但我不得不承认我觉得它有点复杂。 http://www.thecssninja.com/css/custom-inputs-using-css

    据我所知,你可以使用伪类

     td:not(#foo) > input[type=checkbox] + label
     {
         background: url('/images/off.png') 0 0px no-repeat;
         height: 16px;
         padding: 0 0 0 0px;
     }
    

    我的期望是,通过添加上面的CSS,复选框至少会默认为在关闭状态下显示图像,然后我会添加以下内容来打开

     td:not(#foo) > input[type=checkbox]:checked + label {
         background: url('/images/on.png') 0 0px no-repeat;
     }
    

    不幸的是,我好像错过了关键的一步。我已经尝试使用自定义CSS3选择器语法来匹配我当前的设置-但是肯定缺少一些东西(如果有必要的话,图像的大小是16x16)

    http://www.w3.org/TR/css3-selectors/#checked

    编辑: 我在教程中遗漏了一些东西,他将图像更改应用于标签,而不是输入本身。我仍然没有得到预期的交换图像的复选框结果页上,但认为我更接近。

    3 回复  |  直到 7 年前
        1
  •  124
  •   raveren    12 年前

    input[checkbox] + label

    完整代码: http://gist.github.com/592332

    J中间: http://jsfiddle.net/4huzr/

        2
  •  41
  •   Mo Valipour    14 年前

    通过使用 :before 选择器,您可以在两行CSS中执行此操作。(不涉及脚本)。

    <label> 标签和工作,即使它是失踪的。

    注意:在不支持CSS3的浏览器中,复选框看起来很正常。(向后兼容)。

    input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
    input[type=checkbox]:checked:before { background:green; }​
    

    您可以在此处看到演示: http://jsfiddle.net/hqZt6/1/

    http://jsfiddle.net/hqZt6/6/

        3
  •  2
  •   ahajib Shaun McHugh    10 年前

    如果你还在寻找更多的定制,

    查看以下库: https://lokesh-coder.github.io/pretty-checkbox/

    谢谢