【问题标题】:Replacing a checkbox element with icons用图标替换复选框元素
【发布时间】:2020-02-20 15:14:43
【问题描述】:

我想自定义浏览器复选框。选中状态时,应显示图标 checked.svg 而不是复选框,否则应显示图标 unchecked.svg

这是我的代码。 HTML:

<div class="checkbox-custom">
   <input type="checkbox"/>
      <div class="checkmark">
          <img src="@/assets/images/icons/checkbox/unchecked.svg" class="unchecked"/>
          <img src="@/assets/images/icons/checkbox/checked.svg" class="checked"/>
    </div>
</div>

SASS:

.checkbox-custom {
    position: absolute;
    width: 28px;
    height: 28px;
    left: 0;
    top: 0;

    // Hide default browser checkbox
    input[type=checkbox] {
                display: none;
            }

   input[type=checkbox] + .checkmark {
        position: absolute;
        left: 3.5px;
        top: 3.5px;
        right: 3.5px;
        bottom: 3.5px;

        display: inline-block;
        cursor: pointer;

        img {
            width: 21px;
            height: 21px;
        }

        .checked {
            display: none;
        }
    }    

    input[type=checkbox]:checked + .checkmark {
        .checked {
            display: block;
        }

        .unchecked {
            display: none;
        }
    }
 }

当我点击复选框时,没有任何反应。可能是什么错误?

【问题讨论】:

标签: html css checkbox sass


【解决方案1】:

这可以在没有任何 javascript 的情况下完成。单击标签元素会切换其中的复选框,因此通过一些巧妙的 css,我们可以根据输入的选中状态更改显示。

input[type=checkbox] {
  display: none;
}
.label {
  border: 1px solid #000;
  display: inline-block;
  padding: 3px;
  /* background: url("unchecked.png") no-repeat left center; */ 
  /* padding-left: 15px; */
}
input[type=checkbox]:checked + .label {
  background: #f00;
  color: #fff;
  /* background-image: url("checked.png"); */
}
&lt;label&gt;&lt;input type="checkbox"&gt;&lt;span class="label"&gt;Check me&lt;/span&gt;&lt;/label&gt;

更改 .label 样式以使用您选择的背景图像(并将其放置在文本的左侧)。

【讨论】:

    【解决方案2】:

    http://jsfiddle.net/pKM3x/

    CSS:

    .checkbox{
        width: 23px;
        height: 21px;
         background: transparent url(http://i.stack.imgur.com/S4p2R.png ) no-repeat 0 50%
    }
    .checked{
        background: transparent url(http://i.stack.imgur.com/S4p2R.png ) no-repeat 80% 50%
    }
    

    HTML:

    <div class="checkbox">
    </div>
    

    JQUERY:

    $(".checkbox").click(function(){
        $(this).toggleClass('checked')
    });
    

    这也可以用纯 JS 来做。

    【讨论】:

    • 它有效,但在表单中,您应该在发送表单时使用输入标签来获取值。
    猜你喜欢
    • 2015-09-29
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2015-03-20
    • 2013-04-04
    • 2014-01-21
    相关资源
    最近更新 更多