【问题标题】:CSS Checkboxes, how to deal with requiredCSS Checkboxes,需要怎么处理
【发布时间】:2017-06-22 08:45:57
【问题描述】:

我正在使用此 HTML 将浏览器复选框换成我自己的

input[type="checkbox"] {
  display: none;
  width: 30px;
  &+label {
    width: 30px;
    &::before {
      display: inline-block;
      width: 30px;
      height: 26px;
      margin: 0px;
      vertical-align: middle;
      background: url(../images/tick.png) -30px top no-repeat;
      cursor: pointer;
      content: "";
    }
  }
  &:checked+label::before {
    background: url(../images/tick.png) left top no-repeat;
  }
}
<input required type="checkbox" id="acceptance" name="acceptance" value="yes"><label for="acceptance"></label>

【问题讨论】:

  • 不明白你的意思,表单不勾选才会提交
  • 你的意思是如何直观地显示复选框是必需的?喜欢放一个红色星号或类似的东西?
  • 我需要提供视觉反馈。表单不会提交,但与普通复选框不同,标签元素没有 HTML5 反馈。
  • @mikepa88 是后备位置,但我宁愿直接指出是此复选框导致提交被禁用
  • 你可以在 :after 后面加上一些文字表明它必须被检查。

标签: css checkbox required-field


【解决方案1】:

您不需要label。您可以将:before 元素直接添加到复选框输入中(请务必进行跨浏览器检查。不确定兼容性)。

任何兼容 html5 的浏览器都会弹出提示该元素是必需的:

由于我没有图片,我将未选中的颜色更改为红色,将选中的颜色更改为蓝色:

input[type="checkbox"] {
  width: 30px;
}

input[type="checkbox"]::before {
  display: inline-block;
  width: 30px;
  height: 26px;
  margin: 0px;
  vertical-align: middle;
  background: url(../images/tick.png) -30px top no-repeat red;
  cursor: pointer;
  content: "";
}

input[type="checkbox"]:checked::before {
  background: url(../images/tick.png) left top no-repeat blue;
}
<form>
<input required type="checkbox" id="acceptance" name="acceptance" value="yes">
<input type="submit" />
</form>

【讨论】:

    【解决方案2】:

    您正在使用:before 向标签显示刻度/十字图像,具体取决于复选框:checked 设置。对:after 执行相同操作:

    input[type="checkbox"] {
        &[required] + label:after {
            content: "*";
            color: red;
        }
    }
    

    【讨论】:

      【解决方案3】:

      由于我也遇到这种问题,找到了更新的解决方案,我会在这里分享一下

      https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Using_built-in_form_validation

      现在我们有了:valid:invalid 伪类

      例如:

      input[type=checkbox]:invalid + label {
         color: red;
      }
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多