操作iframe

时间:2023-03-09 13:28:00
操作iframe

  iframe是在页面中嵌套的子页,当前页面(这里称为父页)和嵌套页面(这里称为子页)可以相互控制:
当父页控制子页用contentWindow,用法为 对象.contentWindow.document.XX  或用contentDocument.XX 来操作
子页控制父页用window.parent.document.XX   如果是多层嵌套想直接操纵祖先页面就用 window.top.document.XX  
  
<!DOCTYPE HTML>
<html>
<head>
<title>HTML5实现拖拽操作</title>
<meta charset="utf-8"/>
<style>
</style>
<script>
window.onload=function(){
var oinput=document.getElementById('input1');
var oif=document.getElementById('f1');
oinput.onclick=function(){
//alert(oif.contentWindow.document.getElementById('d1'));
//contentWindow全部浏览器都支持
//contentDocument 浏览器IE6,IE7不支持
oif.contentDocument.getElementById('d1').style.color='red';
//oif.contentWindow.document.getElementById('d1').style.color='red';
};
}
</script>
</head>
<body>
<input type='button' value='点我' id='input1'/>
<iframe src='iframe1.html' id='f1'> </iframe>
<div id='d1'>通过子更改我的背景色 </div>
</body>
</html>
   本实例牵扯到父页和多个子页,多重嵌套,要用到多个页面的多篇代码,原理很好理解,但要精确表达出却很困难,其核心知识就是开头介绍的几个方法。总之今天学的东西很多很杂,代码多次更改没有合理保存,以后不急不躁,一步一个脚印。

补充:禁止别人以iframe加载你的页面

if (window.location != window.parent.location) window.parent.location = window.location;