使用js写一个表格,加边框
时间: 2024-09-12 18:11:52 浏览: 55
在JavaScript中创建一个带有边框的表格,你可以直接使用HTML来编写,因为大部分前端渲染都是基于DOM操作。下面是一个简单的例子:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
table {
border-collapse: collapse; /* 合并单元格边框 */
width: 100%; /* 表格宽度 */
border: 1px solid black; /* 设置边框,这里是黑色实线,宽度为1像素 */
}
th, td {
padding: 8px; /* 边距 */
text-align: left; /* 文本对齐方式 */
border: 1px solid black; /* 单元格边框 */
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>列1</th>
<th>列2</th>
<!-- 添加更多表头行 -->
</tr>
</thead>
<tbody>
<tr>
<td>行1,列1</td>
<td>行1,列2</td>
</tr>
<!-- 添加更多数据行 -->
</tbody>
</table>
</body>
</html>
```
这个例子中,`<table>`标签定义了一个表格,`<thead>`和`<tbody>`分别用于表头和主体内容。每个单元格使用`<th>`(表头单元格)和`<td>`(数据单元格)定义,并设置了统一的边框样式。
如果你想通过JavaScript动态生成这个表格,可以这样做:
```javascript
// 获取元素
const table = document.createElement('table');
const thead = document.createElement('thead');
const tbody = document.createElement('tbody');
// 创建表头行和单元格
const headerRow = document.createElement('tr');
headerRow.innerHTML = '<th>列1</th><th>列2</th>'; // 添加其他列
thead.appendChild(headerRow);
table.appendChild(thead);
// 创建数据行
const dataRow = document.createElement('tr');
dataRow.innerHTML = '<td>行1,列1</td><td>行1,列2</td>'; // 添加其他数据
tbody.appendChild(dataRow);
table.appendChild(tbody);
// 将表格添加到页面上
document.body.appendChild(table);
```
阅读全文
相关推荐
















