在Web开发中,常常会遇到需要使用开关按钮切换的场景。这时,我们可以使用CSS来实现这个功能。以下是两个基本的开关按钮切换的代码示例:.switch { : relative; display: in...
在Web开发中,常常会遇到需要使用开关按钮切换的场景。这时,我们可以使用CSS来实现这个功能。以下是两个基本的开关按钮切换的代码示例:
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
transform: translateX(26px);
} 以上代码实现了一个基本的开关按钮切换功能。在HTML中,我们需要使用input标签,在CSS中使用伪类选择器:checked和:before来控制样式变化。
.switch {
position: relative;
display: inline-block;
width: 70px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
border-radius: 34px;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
border-radius: 50%;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(35px);
-ms-transform: translateX(35px);
transform: translateX(35px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
} 以上代码实现了另一个基本的开关按钮切换功能。我们可以看到,在这个示例中,使用了-webkit-transition和-ms-transition来控制样式变化的过程。此外,还可以使用.round类来控制开关按钮的形状。