使用背景图像复选框

时间:2016-06-02 04:55:54

标签: html css checkbox

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

<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 example中看到的那样,图标尺寸正确,但它永远不会像应该的那样设置背景图像。有什么建议吗?

3 个答案:

答案 0 :(得分:7)

你可以用标签

来做
   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/

答案 1 :(得分:2)

您实际上不应该尝试直接更改复选框;某些浏览器将始终显示默认复选框。通常如何通过为链接到输入id字段的复选框添加标签。例如:

<input type='checkbox' id='x' name='fordCheckBox'>
<label for='x'></label>

然后将复选框设置为display: none,然后将实际的css应用于标签。您的选择器应如下所示:input[type=checkbox]:checked + label

我发现这篇文章将有助于解释所有内容并逐步引导您完成:

http://webdesign.tutsplus.com/tutorials/quick-tip-easy-css3-checkboxes-and-radio-buttons--webdesign-8953

答案 2 :(得分: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”。

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

相关问题