为复选框使用背景图像

新手上路,请多包涵

我正在尝试设置一些复选框,以便在未选中时使用我已有的一张图像,然后在选中时使用另一张图像。这是我当前的复选框:

 <input type="checkbox" name="fordCheckBox" value="Ford">

我还使用以下 CSS 为每个复选框设置背景图像。

 input[type=checkbox][name=fordCheckBox] {
        background:url("https://pbs.twimg.com/profile_images/550291079719698432/LbybHjIh.jpeg") no-repeat;
        height: 25px;
        width: 25px;
        background-size: 50%;
    }

    input[type=checkbox][name=fordCheckBox]:checked {
        background:url("http://contentservice.mc.reyrey.net/image_v1.0.0/2267461") no-repeat;
        height: 25px;
        width: 25px;
        background-size: 50%;
    }

正如您在我的 JSFiddle 示例 中看到的那样,图标大小正确,但它从未像应有的那样设置背景图像。有什么建议么?

原文由 pallasmedia 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 478
2 个回答

你可以用标签来做

   input[type=checkbox] {
    display:none;
}

input[type=checkbox] + label {
    display:inline-block;
    padding: 0 0 0 0px;
    background:url("https://pbs.twimg.com/profile_images/550291079719698432/LbybHjIh.jpeg") no-repeat;
    height: 125px;
    width: 125px;;
    background-size: 50%;
}

input[type=checkbox]:checked + label {
    background:url("http://contentservice.mc.reyrey.net/image_v1.0.0/2267461") no-repeat;
    height: 125px;
    width: 125px;
    display:inline-block;
    background-size: 50%;
}

HTML

 <input type="checkbox" name="fordCheckBox" id="Ford" value="Ford">
<label for="Ford"></label>

请检查更新的 jsfiddle https://jsfiddle.net/s4nr6q3d/

原文由 Malith 发布,翻译遵循 CC BY-SA 4.0 许可协议

我使用了这个 CSS。在这个 CSS 中,当复选框被选中时,它会在复选框上放置一个勾号图像。它还默认更改复选框的大小、颜色和边框。

     input[type='checkbox'] {
        -webkit-appearance: none;
        width: 30px;
        height: 30px;
        background: white;
        border-radius: 5px;
        border: 2px solid #555;
        vertical-align:middle;
    }

    input[type='checkbox']:checked {
        background-image: url("Images/tick-sm.png");
        background-size: 90%;
        background-position: right center;
        background-repeat: no-repeat;
   }

将“Images/tick-sm.png”替换为您自己的图片。

如果您也想要未选中状态的不同背景,请将第二个块的相同内容添加到第一个块并替换图像。

原文由 Saadat 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题