【问题标题】:CSS Toggle Switch without classes / id没有类 / id 的 CSS 切换开关
【发布时间】:2016-09-06 15:41:46
【问题描述】:

我现在正在为我大学的网络工程课程做一个项目。我们必须创建某种学校管理网站,并且现在只允许使用纯 HTML 和 CSS,但我们在没有类和 id 的 CSS 中工作的限制是,只允许使用选择器。

现在我想在我们的页面上添加一个切换按钮,我找到了这个网站 (https://proto.io/freebies/onoff/),您可以在其中创建自己的切换按钮。但是您收到的代码适用于我不允许使用的类,所以我尝试更改代码以便它只使用选择器但它不起作用。 也许有人可以在这里帮助我理解我的错误(除了复制代码 sn-p 而不是解决问题)。

div:last-of-type {
  position: relative;
  width: 67px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}
input[type="checkbox"] {
  display: none;
}
label {
  display: block;
  overflow: hidden;
  cursor: pointer;
  height: 22px;
  padding: 0;
  line-height: 22px;
  border: 2px solid #CCCCCC;
  border-radius: 22px;
  background-color: #FA1212;
  transition: background-color 0.3s ease-in;
}
label:before {
  content: "";
  display: block;
  width: 22px;
  margin: 0px;
  background: #FFFFFF;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 43px;
  border: 2px solid #CCCCCC;
  border-radius: 22px;
  transition: all 0.3s ease-in 0s;
}
input[type="checkbox"]:checked + label {
  background-color: #28CF25;
}
input[type="checkbox"]:checked + label,
input[type="checkbox"]:checked +label:before {
  border-color: #28CF25;
}
input[type="checkbox"]:checked + label:before {
  right: 0px;
}
<div>
  <input type="checkbox" name="onoffswitch" checked>
  <label for="myonoffswitch"></label>
</div>

【问题讨论】:

    标签: html css checkbox toggle


    【解决方案1】:

    你不需要使用类,只要标签有一个for="...",它与输入的id="..."相同,并且标签出现在输入标签之后是正确的.

    标签元素上的for 属性链接到输入元素上的id 属性,其余的由浏览器完成。

    下面的快速演示演示了这一点:

    html{background:rgba(0,0,0,0.4);text-align:center;font-size:2em;}
    input:checked + label {
      background: lime;
    }
    input:checked + label {
      color: red;
    }
    input + label {
      display: inline-block;
      height: 40px;
      border-radius: 25px;
      width: 100px;
      background: tomato;
      position: relative;
      transition: all 0.4s;
      cursor: pointer;
      border: 5px solid lightgray;
      box-shadow: inset 2px 2px 5px black, 2px 2px 5px black;
    }
    input[type="checkbox"] {
      display: none;
    }
    input + label:before {
      content: "";
      position: absolute;
      background: white;
      height: 30px;
      width: 30px;
      top: 5px;
      transition: all 0.4s;
      left: calc(100% - 35px);
      border-radius: 50%;
      box-shadow: 2px 2px 5px black;
    }
    input:checked + label:before {
      left: 5px;
    }
    Click My toggle Checkbox
    <br/><br/>
    <div>
      <input type="checkbox" id="myonoffswitch" />
      <label for="myonoffswitch"></label>
    </div>

    【讨论】:

    • 感谢您的帮助,将 id 包含在输入标签中,它现在可以工作了。使用属性选择器是否更好,例如input[type="checkbox"]:checked 而不是 input:checked 或者它没有任何区别,因为只有复选框可以被“选中”?
    • 如果您使用单选按钮,那么该属性将是有益的。否则,:checked 就足够了
    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 2020-03-21
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 2013-12-06
    相关资源
    最近更新 更多