使用javascript來控制iframe,其實說白了,很簡單,用DOM,使用javascript的document.getElementById

在iframe中寫這樣的script: window.top.location=location
或者在主頁面中寫這樣的: location=document.getElementById("iframeid").src;
如果是在子頁面中寫,一定要注意不要在加載時自動改變window.top,不然會出現無限循環

也可以在設定iframe時,先不設定width及length,一樣使用DOM方式去設定

 

index.htm

<html>
<head><title>Index</title></head>
<frameset cols="80,*" frameborder="no" border="0" framespacing="0">
<frame src="frame1.htm" name="frame1" id="frame1" scrolling="auto" noresize="noresize">
<frame src="frame2.htm" name="frame2" id="frame2">
</frameset>
<noframes><body>您無法使用頁框架!</body></noframes>
</html>

很一般的 Frameset (頁框設定)

frame1.htm

<html><head><title>Frame1</title></head><body>
<label>

<input type="button" name="button1" value="iframe1" onClick="parent.frame2.my_iframe.location.href='iframe1.htm'">

<input type="button" name="button2" value="iframe2" onClick="parent.frame2.my_iframe.location.href='iframe2.htm'">

</label>
</body></html>

按鈕跳過三個頁框控制 iFrame,是 JavaScript 用法,target 的話只要 my_iframe 就可以了

frame2.htm

<html><head><title>Frame2</title></head><body>
<table border="1"><tr><td>
<iframe src="iframe1.htm" name="my_iframe" id="my_iframe" frameborder="0" marginwidth="0" marginheight="0"></iframe>
</td></tr></table>
</body></html>

Table 和 iFrame 標籤上都不要有尺寸設定

iframe1.htm

<html><head><title>iFrame1</title></head><body>
<script language="JavaScript">
<!--
parent.document.all.my_iframe.width=300;
parent.document.all.my_iframe.height=200;
// -->
</script>
iFrame1
</body></html>

以 JavaScript 控制 iFrame 尺寸

iframe2.htm

<html><head><title>iFrame2</title></head><body>
<script language="JavaScript">
<!--
parent.document.all.my_iframe.width=200;
parent.document.all.my_iframe.height=300;
// -->
</script>
iFrame2
</body></html>

 

只有 iFrame 尺寸和 iframe1.htm 不同

iFrame 好用的地方在於,裡面甚至可以放入一個網站,若應用得當,對網頁設計是很有幫助的喔!

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 totology 的頭像
    totology

    Mr. 8的單身日記

    totology 發表在 痞客邦 留言(0) 人氣()