之前曾寫過一篇「[jQuery] ThickBox 跨越 iframe 顯示完整的黑底」,最近回去看了一下 thickbox 的網站,它也宣告停止繼續維護了。
它建議可改用的清單中,有個也滿好看的燈箱效果 ColorBox,最近有網友問到 ColorBox 可否也能做到跨越 iframe 顯示完整的黑底(overlay)呢?經實際測試是可以的,作法如下。
首先準備兩個檔案,index.html 首頁(嵌入 iframe)與 iframe 的內容 iframe.html 兩個檔案。
index.html 中,除引入所需的 jquery 與 colorbox 的 js, css 檔外,還要準備一個 iframe 內嵌框。
<link media="screen" rel="stylesheet" href="colorbox.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="../colorbox/jquery.colorbox.js"></script>
※路徑請依實際狀況變更。
iframe 內嵌框:
<iframe src="iframe.html" width="500" height="500"></iframe>
接著,來寫 iframe.html 的內容。
其同樣需引入所需的 js/css 檔,請參照上面囉。
再來寫一段請父視窗開啟連結(link)於 colorbox 的 JavaScript:
function OpenLink(link) {
parent.$.colorbox({ href: link, iframe: true, width: "50%", height: "50%" });
}
接著就可使用此方法開啟連結,本例為開啟 Google:
<a href='http://www.google.com' onclick="javascript:OpenLink('http://www.google.com'); return false;">Open from parent</a>
測試於 IE7/IE8/Firefox 皆正常。