CSS:切换开关有问题。如何为整个 Toggle 呈现输入复选框的行为?
CSS: problem with Toggle Switch. How to render the behavior of an input checkbox for the whole Toggle?
我正在开发一个 Web 应用程序(使用 AngularJS),我需要创建一个 Toggle Switch。
网上的攻略好像不难,我照的是W3C的:https://www.w3schools.com/howto/howto_css_switch.asp
在本指南中,一切正常:我可以在“切换开关”区域中的任意位置单击,它会正常运行。
在它的后面,很明显,必须有一个checkbox
类型的输入。
不幸的是,这在我的应用程序中没有发生。这是我的代码(我使用 <div>
而不是 <label>
因为标签已经有合适的样式):
<style>
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
<div class="switch">
<input type="checkbox">
<span class="slider round"></span>
</div>
如您所见,这是完全相同的 W3C 代码(除了我没有模糊输入,否则我的情况不会发生任何事情!)。不幸的是发生了以下事情:
样式很完美,但只有单击左下角的小角(这将是 input checkbox
故意不被遮挡的地方!),行为才正确。如果我按照 W3C 的建议使复选框输入不可见,我将无法再单击那个角落并且什么也不会发生!
我不明白如何使 input checkbox
不可见但仍将其行为扩展到整个拨动开关!我哪里错了?
您需要使用 <label>
来代替
我正在开发一个 Web 应用程序(使用 AngularJS),我需要创建一个 Toggle Switch。 网上的攻略好像不难,我照的是W3C的:https://www.w3schools.com/howto/howto_css_switch.asp
在本指南中,一切正常:我可以在“切换开关”区域中的任意位置单击,它会正常运行。
在它的后面,很明显,必须有一个checkbox
类型的输入。
不幸的是,这在我的应用程序中没有发生。这是我的代码(我使用 <div>
而不是 <label>
因为标签已经有合适的样式):
<style>
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
<div class="switch">
<input type="checkbox">
<span class="slider round"></span>
</div>
如您所见,这是完全相同的 W3C 代码(除了我没有模糊输入,否则我的情况不会发生任何事情!)。不幸的是发生了以下事情:
样式很完美,但只有单击左下角的小角(这将是 input checkbox
故意不被遮挡的地方!),行为才正确。如果我按照 W3C 的建议使复选框输入不可见,我将无法再单击那个角落并且什么也不会发生!
我不明白如何使 input checkbox
不可见但仍将其行为扩展到整个拨动开关!我哪里错了?
您需要使用 <label>
来代替