前端代码 控制开关的颜色
时间: 2024-01-23 12:45:04 浏览: 24
以下是一种控制开关颜色的前端代码示例:
HTML:
```html
<div class="toggle-switch">
<input type="checkbox" class="toggle-switch-checkbox" id="toggle-switch" name="toggle-switch">
<label class="toggle-switch-label" for="toggle-switch">
<span class="toggle-switch-inner"></span>
<span class="toggle-switch-switch"></span>
</label>
</div>
```
CSS:
```css
/* 控制开关样式 */
.toggle-switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.toggle-switch-checkbox {
display: none;
}
.toggle-switch-label {
display: block;
overflow: hidden;
cursor: pointer;
border-radius: 34px;
margin: 0;
}
.toggle-switch-inner {
display: block;
width: 200%;
margin-left: -100%;
transition: margin 0.3s ease-in-out, background-color 0.3s ease-in-out;
}
.toggle-switch-inner::before,
.toggle-switch-inner::after {
display: block;
float: left;
width: 50%;
height: 34px;
padding: 0;
line-height: 34px;
font-size: 14px;
color: white;
font-weight: bold;
box-sizing: border-box;
}
.toggle-switch-inner::before {
content: "ON";
padding-left: 10px;
background-color: #28a745;
}
.toggle-switch-inner::after {
content: "OFF";
padding-right: 10px;
background-color: #dc3545;
}
.toggle-switch-switch {
display: block;
width: 18px;
height: 18px;
margin: 8px;
background-color: white;
position: absolute;
top: 0;
bottom: 0;
right: 36px;
border-radius: 50%;
transition: all 0.3s ease-in-out;
}
/* 控制开关颜色 */
.toggle-switch-checkbox:checked + .toggle-switch-label .toggle-switch-inner {
margin-left: 0;
}
.toggle-switch-checkbox:checked + .toggle-switch-label .toggle-switch-switch {
right: 0px;
}
.toggle-switch-checkbox:checked + .toggle-switch-label .toggle-switch-inner::before {
background-color: #dc3545;
}
.toggle-switch-checkbox:checked + .toggle-switch-label .toggle-switch-inner::after {
background-color: #28a745;
}
```
JavaScript:
```javascript
// 无需 JavaScript
```
这段代码中,我们使用了 HTML 和 CSS 来创建一个控制开关,并使用 JavaScript 来控制开关的状态。在 CSS 中,我们使用了伪元素和过渡效果来创建了一个平滑的开关。同时,我们使用了:checked 伪类来控制开关颜色。当开关被选中时,我们可以使用:checked 伪类和相应的 CSS 属性来改变开关的颜色。