一,首先在页面中操作被嵌入进来iframe中的内容。
方法一:
<script>
window.onload=function(){
var oInput=document.getElementById('btn1');
var oIframe=document.getElementById('iframe1');
oInput.onclick=function(){
oIframe.contentWindow.document.getElementById('div1').style.color='red';
}
};
</script>
<body>
<input type='button' value='点击' id='btn1'>
<iframe src='被嵌入页面的地址' id='iframe1'></iframe>
</body>
以上方法在ie6以上版本都合适,谷歌浏览器必须在服务器上管用。火狐浏览器适合。
方法二:
<script>
window.onload=function(){
var oInput=document.getElementById('btn1');
var oIframe=document.getElementById('iframe1');
oInput.onclick=function(){
oIframe.contentDocument.getElementById('div1').style.color='red';
这个方法在ie6,7下是不支持的,别的都可以
}
};
</script>
<body>
<input type='button' value='点击' id='btn1'>
<iframe src='被嵌入页面的地址' id='iframe1'></iframe>
</body>
二,在iframe中怎么操作他的父亲页面中的东西呢
<script>
window.onload=function(){
var oInput=document.getElementById('btn1');
oInput.onclick=function(){
window.parent.document.getElementById('div1').style.color='red';
这个方法是操作父亲页面中的内容
window.top.document.getElementById('div1').style.color='red';
操作最顶层父亲页面中的内容
}
};
</script>
<body>
<input type='button' value='点击' id='btn1'>
</body>
三,iframe加载完会有一些事件
<script>
window.onload=function(){
var oIframe=document.createElement('iframe');
oIframe.src='iframe1.html';
document.body.appendChlid(oIframe);
oIframe.onload=function(){
alert(112)
}; 上面这种方法在ie下不管用。ie下iframe的onload事件必须用绑定的形式,如下所示
oIframe.attachEvent('onload',function(){
alert(1111)
})
}
};
</script>
<body>
</body>
例子:
1.防止被钓鱼网站嵌套
<body>
<iframe src='www.baidu.com'></iframe>
</body>
如果百度不想自己被被人iframe的话就写下面几段代码
<script>
window.onload=function(){
if(window!=window.top){
window.top.location.href=window.location.href;
};
};
</script>
2,动态获取iframe的高度
<script>
window.onload=function(){
var oInput1=document.getElementById('btn1');
var oInput2=document.getElementById('btn2');
var oIframe=document.getElementById('iframe1');
function changeHeight(){
oIframe.height=oIframe.contentWindow.document.body.offsetHight;
};
changeHeight();
oInput1.onclick=function(){
oIframe.src='被嵌入进来的页面';
changeHeight();
};
oInput2.onclick=function(){
oIframe.src='被嵌入进来的改变高度的页面';
changeHeight();
};
如果单纯这么写的话,发现并没有改过来,所以我们要加一个定时器,让他有一个反应过程;
};
</script>
<script>
window.onload=function(){
var oInput1=document.getElementById('btn1');
var oInput2=document.getElementById('btn2');
var oIframe=document.getElementById('iframe1');
function changeHeight(){
setTimeout(function(){
oIframe.height=oIframe.contentWindow.document.body.offsetHight;
},100)
};
changeHeight();
oInput1.onclick=function(){
oIframe.src='被嵌入进来的页面';
changeHeight();
};
oInput2.onclick=function(){
oIframe.src='被嵌入进来的改变高度的页面';
changeHeight();
};
};
</script>
<body>
<input type='button' value='切换一' id='btn1'>
<input type='button' value='切换二' id='btn2'>
<iframe src='被嵌入页面的地址' id='iframe1'></iframe>
</body>