HTML DOM Figcaption 对象

htmlweb developmentfront end technology更新于 2024/5/29 8:12:17

HTML DOM Figcaption 对象用于表示 HTML5 <figcaption> 元素。您可以分别使用 createElement() 和 getElementById() 方法创建或访问 figcaption 元素。

语法

以下是语法 −

创建 Figcaption 对象 −

var p = document.createElement("FIGCAPTION");

示例

让我们来看一个 Figcaption 对象的示例 −

<!DOCTYPE html>
<html>
<head>
<script>
   function createCaption() {
      var caption = document.createElement("FIGCAPTION");
      var txt = document.createTextNode("Learn Java Servlets");
      caption.appendChild(txt);
      var f=document.getElementById("Figure1");
      f.appendChild(caption);
   }
</script>
</head>
<body>
<h2>Caption</h2>
<p>Create a caption for the below image by clicking the below button</p>
<button onclick="createCaption()">CREATE</button>
<figure id="Figure1">
<img src="https://www.cainiaomax.com/servlets/images/servlets-mini-logo.jpg"
alt="Servlets" width="250" height="200">
</figure>
</body>
</html>

输出

这将产生以下输出 −

点击"创建"按钮 −

在上面的例子中 −

我们首先创建了一个 id 为"Figure1"的 figure 元素,它内部包含一个 img 元素 −

<figure id="Figure1">
<img src="EiffelTower.jpg" alt="Eiffel Tower" width="250" height="200">
</figure>

然后我们创建一个按钮 CREATE(),当用户点击该按钮时,它将执行 createCaption() 方法 −

<button onclick="createCaption()">CREATE</button>

createCaption() 方法使用 document 对象的 createElement() 方法创建一个 figcaption 元素。使用 document body 的 createTextNode() 方法创建一个文本节点,并将其附加到 figcaption 元素。然后我们使用 getElementById() 方法获取 figure 元素,并使用 appendChild() 方法将 figcaption 和文本节点作为子元素附加 −

function createCaption() {
   var caption = document.createElement("FIGCAPTION");
   var txt = document.createTextNode("Eiffel Tower in Paris,France");
   caption.appendChild(txt);
   var f=document.getElementById("Figure1");
   f.appendChild(caption);
}

相关文章


有用资源