HTML DOM Caption 对象
htmlweb developmentfront end technology更新于 2025/9/23 2:52:17
HTML DOM Caption 对象与 HTML <caption> 元素关联。<caption> 元素用于设置表格的标题,并且应该是表格的第一个子元素。您可以使用 caption 对象访问 caption 元素。
属性
注意:HTML5 不支持以下属性。
以下是 HTML DOM Caption 对象的属性 −
| 属性 | 描述 |
|---|---|
| Align | 设置或返回标题对齐方式。 |
语法
以下是语法 −
创建标题对象 −
var x = document.createElement("CAPTION");
示例
让我们看一个 HTML DOM 标题对象的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px double black;
margin-top: 14px;
}
</style>
</head>
<body>
<p>Click the button below to create the caption for the table.</p>
<button onclick="createCaption()">CREATE</button>
<table id="SampleTable">
<tr>
<td colspan="2" rowpan="2">TABLE</td>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr>
</table>
<script>
function createCaption() {
var x = document.createElement("CAPTION");
var t = document.createTextNode("TABLE CAPTION");
x.appendChild(t);
var table = document.getElementById("SampleTable")
table.insertBefore(x, table.childNodes[0]);
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"创建"按钮 −

在上面的例子中 −
我们首先创建了一个"创建"按钮,点击 − 时会执行 createCaption() 方法。
<button onclick="createCaption()>CREATE</button>
createCaption() 方法使用文档对象的 createElement() 方法创建一个标题元素,并将其赋值给变量 x。然后,它创建了一个包含"TABLE CAPTION"文本的文本节点。然后我们将该文本节点附加到元素中。
最后,我们使用 id "SampleTable" 获取 <table> 元素,并使用 insertBefore() 方法将标题和文本节点一起插入到表格的第一个子元素中。<caption> 只能是表格的第一个子元素 −
function createCaption() {
var x = document.createElement("CAPTION");
var t = document.createTextNode("TABLE CAPTION");
x.appendChild(t);
var table = document.getElementById("SampleTable")
table.insertBefore(x, table.childNodes[0]);
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

