怎么在html表格中动态生成开关滑动按钮
时间: 2024-04-29 22:02:34 浏览: 11
要在HTML表格中动态生成开关滑动按钮,可以使用HTML的`<input>`元素和CSS样式来实现。
首先,在表格中的单元格中添加一个`<input>`元素,将其类型设置为“checkbox”:
```html
<td><input type="checkbox"></td>
```
接下来,为这个`<input>`元素添加一个`id`属性,这样就可以在CSS样式中使用它来定义按钮的样式:
```html
<td><input type="checkbox" id="toggle"></td>
```
接下来,在CSS样式中定义`<input>`元素的样式。这里我们使用`::before`和`::after`伪元素来创建开关滑动按钮的外观:
```css
input[type=checkbox] {
display: none;
}
input[type=checkbox] + label {
display: inline-block;
cursor: pointer;
position: relative;
padding-left: 40px;
margin-right: 15px;
font-size: 16px;
line-height: 20px;
}
input[type=checkbox] + label::before,
input[type=checkbox] + label::after {
content: '';
display: inline-block;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
input[type=checkbox] + label::before {
width: 30px;
height: 14px;
background-color: #ddd;
border-radius: 14px;
margin-right: 10px;
}
input[type=checkbox] + label::after {
width: 20px;
height: 20px;
background-color: #fff;
border-radius: 50%;
left: 0;
transition: all 0.3s;
}
input[type=checkbox]:checked + label::before {
background-color: #6fcf97;
}
input[type=checkbox]:checked + label::after {
left: 16px;
}
```
最后,将`<label>`元素与`<input>`元素相关联,这样就可以通过单击标签来切换按钮的状态:
```html
<td>
<input type="checkbox" id="toggle">
<label for="toggle">开关</label>
</td>
```
以上就是在HTML表格中动态生成开关滑动按钮的方法。