HTML DOM ColumnGroup 对象
htmlweb developmentfront end technology更新于 2024/6/1 21:00:17
HTML DOM ColumnGroup 对象与 HTML <colgroup> 元素关联。<colgroup> 元素用于将 CSS 样式应用于特定数量的列或所有列。这使我们能够更好地控制表格中存在的列。
属性
以下是 ColumnGroup 属性 −
| 属性 | 描述 |
|---|---|
| span | 设置或返回列组 span 属性的值 |
语法
以下是语法 −
创建 ColumnGroup 对象 −
var x = document.createElement("COLGROUP");
示例
让我们看一个 ColumnGroup 对象的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
#DIV1{
background-color:pink;
}
</style>
</head>
<body>
<table id="TABLE1">
<tr>
<th>FRUIT</th>
<th>COLOR</th>
<th>Price</th>
</tr>
<tr>
<td>MANGO</td>
<td>YELLOW</td>
<td>100RS</td>
</tr>
<tr>
<td>GUAVA</td>
<td>GREEN</td>
<td>50RS</td>
</tr>
</table>
<p>Click the below button to create a colgroup element with span = 2.</p>
<button onclick="colFun()">COLGROUP</button>
<script>
function colFun() {
var x = document.createElement("COLGROUP");
x.setAttribute("id","DIV1");
x.setAttribute("span","2");
document.getElementById("TABLE1").appendChild(x);
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击 COLGROUP 时 −

在上面的例子中 −
我们首先创建了一个三行三列的表格,id 为"TABLE 1"。我们还对表格及其子元素应用了一些样式 −
table, th, td {
border: 1px solid black;
}
<table id="TABLE1">
<tr>
<th>>FRUIT</th>
<th>COLOR</th>
<th>Price</th>
</tr>
<tr>
<td>MANGO</td>
<td>YELLOW</td>
<td>100RS</td>
</tr>
<tr>
<td>GUAVA</td>
<td>GREEN</td>
<td>50RS</td>
</tr>
</table>
然后,我们创建了一个按钮 COLGROUP,当用户点击时,它将执行 colFun() 函数 −
<button onclick="colFun()">COLGROUP</button>
colFun() 方法创建一个 <colgroup> 元素并将其赋值给变量 x。使用 setAttribute() 方法,我们为新创建的 <colgroup> 元素分配一个 id,并将 span 设置为 2。然后,我们使用 <table> 元素上的 appendChild() 方法,将 <colgroup> 元素作为表的第一个子元素附加到该元素上 −
function colFun() {
var x = document.createElement("COLGROUP");
x.setAttribute("id","DIV1");
x.setAttribute("span","2");
document.getElementById("TABLE1").appendChild(x);
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

