如何在 HTML 中指定要在 <iframe> 中显示的页面 HTML 内容?

htmlweb developmentfront end technology更新于 2024/6/24 5:32:17

在本文中,我们需要在 iframe 中显示页面的 HTML 内容;iframe 是一个被划分为单独页面的浏览器窗口。我们可以使用 <iframe> 标签及其 srcdoc 属性来实现此任务。

HTML <iframe> 标签

HTML 中的 <iframe> 标签指定一个内联框架。此内联框架用于在当前 HTML 文档中嵌入另一个文档。所有浏览器都支持此标签,例如 Google Chrome、Microsoft Edge/Internet Explorer、Firefox、Safari 和 Opera 等。

srcdoc <iframe> 标签的"srcdoc"属性用于指定要在 <iframe> 中显示的页面 HTML 内容。此属性将 HTML_code 作为值,并指定要在 <iframe> 中显示的页面 HTML 内容。

示例 1

在下面的示例中,我们使用了 <iframe> 标签的"srcdoc"属性来指定要在 HTML 格式的 <iframe> 中显示的页面 HTML 内容(<h2> 元素)。

<!DOCTYPE html> <html> <head> <title> How to specify the HTML content of the page to show in the "iframe" in HTML? </title> </head> <body> <h3>How to specify the HTML content of the page to show in the "iframe" in HTML?</h3> <p>We can do it by using <b>srcdoc</b> attribute of iframe in HTML.</p> <iframe srcdoc="<h2>You can find any tutorial on tutorialspoint</h2>"> <p>Browser does not support iframes.</p> </iframe> </body> </html>

正如我们在输出中看到的,文档中的 HTML 内容(<h2> 元素)显示在 <iframe> 中。

示例 2

以下是 HTML iframe 的另一个示例,在这个示例中,我们在 iframe 中创建了一个表格。

<!DOCTYPE html> <html> <head> <title> How to specify the HTML content of the page to show in the "iframe" in HTML? </title> </head> <body> <h3>How to specify the HTML content of the page to show in the "iframe" in HTML?</h3> <p>We can do it by using <b>srcdoc</b> attribute of iframe in HTML.</p> <iframe srcdoc="<table border = 3> <caption> Abbreviations </caption> <tr> <th> HTML </th> <th> CSS </th> </tr> <tr> <td> Hypertext markup language</td> <td> Cascading style sheet </td> </tr> </table>"> <p>Browser does not support iframes.</p> </iframe> </body> </html>

正如我们在输出中看到的,文档中的 HTML 内容(HTML 表格)显示在 <iframe> 中。

示例 3

默认情况下,所有浏览器都会将 <iframe> 显示为默认值。我们可以使用 CSS 更改 <iframe> 的样式。

在下面的示例中,

  • 我们通过使用 CSS 更改了 <iframe> 的宽度、高度和边框,从而更改了其样式。

  • 我们在 <iframe> 标签中使用了"srcdoc"属性,以指定页面(<div> 元素)的 HTML 内容显示在 HTML 格式的 <iframe> 中。

<!DOCTYPE html> <html> <head> <title> How to specify the HTML content of the page to show in the "iframe" in HTML? </title> </head> <body> <h3>How to specify the HTML content of the page to show in the "iframe" in HTML?</h3> <p>We can do it by using <b>srcdoc</b> attribute of iframe in HTML.</p> <iframe srcdoc="<div> Hello Disha</div>" width="50%" height="100" style="border:3px solid green;"> <p>Browser does not support iframes.</p> </iframe> </body> </html>

正如我们在输出中看到的,文档中的 HTML 内容(<div> 元素)显示在 <iframe> 中,并且我们还使用 CSS 更改了 <iframe> 的样式。


相关文章


有用资源