Skip to content

[HTML] 頁面中使用 iframe 嵌入另一個 HTML 檔

在使用 HTML 撰寫網頁頁面時,如有需要在 HTML 當中嵌入另外一個 HTML 網頁,可以使用 “iframe” 標籤來完成此一功能。

iframe 有好處也有壞處,好處像是幾乎支援所有瀏覽器;壞處是會堵塞網頁載入、並且不利於 SEO …… 但本篇筆記暫時不論這些優缺點,只單純紀錄怎麼使用。


輸入網址

最簡單的使用方法便是輸入網址:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Main Page</title>
</head>
<body>
     <span>This is main page.</span>
     <iframe frameborder="0"
             noresize="noresize"
             style="position: absolute; background: transparent; width: 100%; height:100%;"
             src="https://clay-atlas.com"
             frameborder="0">
     </iframe>

</body>
</html>



Output:

我測試輸入的是我部落格的網址,可以看到,除了印出 “This is main page” 之外,我部落格的網站也被嵌入在頁面當中。


輸入自己的 HTML 檔案

輸入檔案也是相當常見的一種方法,比如說今天我們有這樣的兩個檔案:

我們要在 main.html 嵌入 iframe.html 的內容,那麼我們可以使用以下程式碼。

main.html:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Main Page</title>
</head>
<body>
     <span>This is main page.</span>
     <iframe frameborder="0"
             noresize="noresize"
             style="position: absolute; background: transparent; width: 100%; height:100%;"
             src="iframe.html"
             frameborder="0">
     </iframe>

</body>
</html>



iframe.html:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Main Page</title>
</head>
<body>
     <span>This is iframe page.</span>
</body>
</html>



然後我們 main.html 內 iframe 標籤中的 src 指向 iframe.html 這份檔案,我們輸出的結果便是:

iframe page 的內容被嵌入在 main page 當中。


直接輸入 HTML 程式碼

當然,我們也可以在 iframe 當中直接輸入 HTML 程式碼。只需要將 src 參數改為 srcdoc 即可。

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Main Page</title>
</head>
<body>
     <span>This is main page.</span>
             <iframe srcdoc="<div>hello</div>"</iframe>
</body>
</html>



Output:

當然這是一個比較粗糙的例子,實際上可以完成還滿漂亮的嵌入頁面的。


References

Tags:

Leave a Reply