当前位置:编程学习 > JS >>

iframe用法与自适应高度

irame用法与自适应高度


我们怎样来控制这个iframe,这里需要讲一下iframe对象。当我们给这个标记设置了id 属性后,就可通过文档
对象模型dom对iframe所含的html进行一系列控制。

  比如在example.htm里嵌入test.htm文件,并控制test.htm里一些标记对象:
  <iframe src="test.htm" id="test" width="250" height="200" scrolling="no" frameborder="0"></iframe>
test.htm文件代码为:
  <html>
   <body>
    <h1 id="myh1">hello,my boy</h1>
   </body>
  </html>
  如我们要改变id号为myh1的h1标记里的文字为hello,my dear,则可用:
  document.myh1.innertext="hello,my dear"(其中,document可省)
  在example.htm文件中,iframe标记对象所指的子窗体与一般的dhtml对象模型一致,对对象访问控制方式一样,就不再赘述。

  2、在子窗体中访问并控制父窗体中对象

  在子窗体中我们可以通过其parent即父(双亲)对象来访问父窗口中的对象。
  如example.htm:

  <html>
   <body onclick="alert(tt.myh1.innerhtml)">
    <iframe name="tt" src="frame1.htm" width="250" height="200" scrolling="no" frameborder="0"></iframe>
    <h1 id="myh2">hello,my wife</h1>
   </body>
  </html>


  如果要在frame1.htm中访问id号为myh2中的标题文字并将之改为"hello,my friend",我们就可以这样写:
  parent.myh2.innertext="hello,my friend"
  这里parent对象就代表当前窗体(example.htm所在窗体),要在子窗体中访问父窗体中的对象,无一例外都通过parent对象来进行

var adjustiframe = function (id) {
var iframe = document.getelementbyid(id)
var idoc = iframe.contentwindow && iframe.contentwindow.document || iframe.contentdocument;
var callback = function () {
var iheight = math.max(idoc.body.scrollheight, idoc.documentelement.scrollheight); //取得其高
iframe.style.height = iheight + "px"; }
if (iframe.attachevent) {
iframe.attachevent("onload", callback);
}
else
{
iframe.onload = callback
} }

代码二

<iframe id="frame_content" src="iframe_b.html" scrolling="no" frameborder="0"
 onload="this.height=100"></iframe>
<script type="text/网页特效">
function reinitiframe(){
var iframe = document.getelementbyid("frame_content");
try{
var bheight = iframe.contentwindow.document.body.scrollheight;
var dheight = iframe.contentwindow.document.documentelement.scrollheight;
var height = math.max(bheight, dheight);
iframe.height =  height;
}catch (ex){}
}
window.setinterval("reinitiframe()", 200);
</script>

补充:网页制作,js教程 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,