创建一个三行三列的表格(边框粗细为1px,表格内容随意填写),一个按钮,当点击按钮时表格的背景颜色变成绿色
时间: 2024-03-20 16:40:24 浏览: 49
好的,以下是HTML和CSS代码实现您的需求:
```html
<table id="myTable">
<tr>
<td>Apple</td>
<td>Banana</td>
<td>Orange</td>
</tr>
<tr>
<td>Carrot</td>
<td>Tomato</td>
<td>Cucumber</td>
</tr>
<tr>
<td>Chicken</td>
<td>Beef</td>
<td>Pork</td>
</tr>
</table>
<button onclick="changeColor()">Change color</button>
<style>
#myTable {
border-collapse: collapse;
border: 1px solid black;
}
#myTable td {
border: 1px solid black;
padding: 10px;
}
#myTable.green {
background-color: green;
}
</style>
<script>
function changeColor() {
var table = document.getElementById("myTable");
table.classList.toggle("green");
}
</script>
```
这段代码会创建一个三行三列的表格,并在下方放置一个按钮。当点击按钮时,表格的背景颜色会从默认的白色变成绿色。这是通过在CSS中定义一个名为“green”的类来实现的,然后通过JavaScript的classList属性将此类添加到或从整个表格中切换。请注意,我们还将表格的边框粗细设置为1px,并使用默认的黑色颜色。
阅读全文
相关推荐















