在JavaScript中为表格添加样式表,通常有以下几种方式:
style
属性设置样式。<head>
部分使用<style>
标签定义样式。.css
文件中,并通过<link>
标签引入到HTML文档中。<table id="myTable" style="border-collapse: collapse; width: 100%;">
<tr>
<th style="border: 1px solid black; padding: 8px;">Header 1</th>
<th style="border: 1px solid black; padding: 8px;">Header 2</th>
</tr>
<tr>
<td style="border: 1px solid black; padding: 8px;">Row 1, Cell 1</td>
<td style="border: 1px solid black; padding: 8px;">Row 1, Cell 2</td>
</tr>
</table>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#myTable {
border-collapse: collapse;
width: 100%;
}
#myTable th, #myTable td {
border: 1px solid black;
padding: 8px;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
</table>
</body>
</html>
styles.css
#myTable {
border-collapse: collapse;
width: 100%;
}
#myTable th, #myTable td {
border: 1px solid black;
padding: 8px;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<table id="myTable">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
</table>
</body>
</html>
!important
关键字(不推荐,除非必要)。@media (max-width: 600px) {
#myTable th, #myTable td {
padding: 4px;
}
}
通过以上方法,你可以灵活地为JavaScript中的表格添加样式表,并根据需要进行调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云