我现在正在为我大学的网络工程课程做一个项目。我们必须创建某种学校管理网站,现在只允许使用纯HTML和CSS,但有一个限制,即我们在没有类和id的CSS中工作,只允许使用选择器。
现在我想在我们的页面上添加一个切换按钮,我找到了这个网站(https://proto.io/freebies/onoff/)您可以在其中创建自己的切换按钮。但是你收到的代码可以使用我不允许使用的类,所以我试图修改代码,使其只使用选择器,但它不起作用。也许有人可以在这里帮助我理解我的错误(除了复制代码片段而不是找出一些东西)。
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>
您不需要使用类,只要标签有一个与输入的id="..."
相同的for="..."
,并且标签正确地出现在输入标记之后即可。
标签元素上的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>