HTML DOM Column 对象
htmlweb developmentfront end technology更新于 2024/6/1 22:04:17
HTML DOM Column 对象与 HTML <col> 元素关联。Column 对象用于获取或设置 <col> 元素的属性。<col> 标签仅在 <table> 中使用。元素。
属性
以下是列对象 − 的属性
| 属性 | 描述 |
|---|---|
| Span | 设置或返回列的 span 属性值。 |
语法
以下是语法 −
创建列对象 −
var a = document.createElement("COL");
示例
让我们看一个列对象的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid blue;
}
#Col1{
background-color:pink;
}
</style>
</head>
<body>
<h3>COL OBJECT</h3>
<table>
<colgroup>
<col id="Col1" span="2">
<col style="background-color:lightgreen">
</colgroup>
<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 get span of the "COL1" col element</p>
<button onclick="colObj()">COLUMN</button>
<p id="Sample"></p>
<script>
function colObj() {
var x = document.getElementById("Col1").span;
document.getElementById("Sample").innerHTML = "The Col1 element has span= "+x;
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击 COLUMN 按钮 −

在上面的例子中,我们创建了一个包含 2 行 3 列的表格。表格整体应用了样式。表格内部有两个 <col> 元素,其中一个跨度等于 2,另一个应用了内联样式。由于第一个 <col> 跨度等于 2,因此其样式将应用于恰好两列,而第二个 <col> 将其样式应用于其余列 −
table, th, td {
border: 1px solid blue;
}
#Col1{
background-color:pink;
}
<table>
<colgroup>
<col id="Col1" span="2">
<col style="background-color:lightgreen">
</colgroup>
<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>
然后,我们创建了一个按钮 COLUMN,当用户点击 − 时,它将执行 colObj() 方法。
<button onclick="colObj()">COLUMN</button>
colObj() 方法使用 document 对象上的 getElementById() 方法获取第一个 <col> 元素。然后,它获取 <col> 元素的 span 属性值并将其赋值给变量 x。存储在变量 x 中的 span 属性值随后会使用段落的 innerHTML 属性显示在 id 为 "Sample" 的段落中 −
function colObj() {
var x = document.getElementById("Col1").span;
document.getElementById("Sample").innerHTML = "The Col1 element has span= "+x;
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

