如何在HTML中指定在<iframe>中顯示的頁面HTML內容?


在本文中,我們需要在一個iframe中顯示頁面的HTML內容;瀏覽器視窗被分割成一個單獨的頁面。我們可以使用<iframe>標籤及其srcdoc屬性來實現此任務。

HTML <iframe> 標籤

HTML中的<iframe>標籤指定一個內聯框架。此內聯框架用於在當前HTML文件中嵌入另一個文件。此標籤受所有瀏覽器支援,例如Google Chrome、Microsoft Edge/Internet Explorer、Firefox、Safari和Opera等。

<iframe>標籤的“srcdoc”屬性用於指定要在<iframe>中顯示的頁面的HTML內容。此屬性將HTML程式碼作為值,並指定要在<iframe>中顯示的頁面的HTML內容。

示例1

在下面的示例中,我們使用了帶<iframe>標籤的"srcdoc"屬性來指定要在HTML的<iframe>中顯示的頁面(<h2>元素)的HTML內容。

<!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 Iframes的另一個示例,在這個示例中,我們在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"屬性來指定要在HTML的<iframe>中顯示的頁面(<div>元素)的HTML內容。

<!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>的樣式。

更新於:2024年7月5日

4K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告