您的位置:首页 > Web前端 > JavaScript

js操作iframe总结

2014-09-22 14:36 375 查看

一 在父页面操作子页面

IE下操作IFrame内容的代码:

document.frames["MyIFrame"].document.getElementById("s").style.color="blue";


但是这在Firefox下无效。
所以,想到在Firefox下用FireBug来调试。经过调试发现在Firefox下可用以下代码来实现:

document.getElementById("MyIFrame").contentDocument.getElementById("s").style.color="blue";


详细代码如下:
TestIFrame.htm:

<html>
<head>
<script type="text/javascript">
function f(){
var doc;

if (document.all){//IE
doc = document.frames["MyIFrame"].document;
}else{//Firefox
doc = document.getElementById("MyIFrame").contentDocument;
}

doc.getElementById("s").style.color="blue";
}
</script>
</head>
<body onload="f()">

<iframe id = "MyIFrame" name = "MyIFrame" src = "MyIFrame.htm" width = "100" height="100"></iframe>

</body>
</html>


其实可以用一种通用方法:

<html>
<head>
<script type="text/javascript">
function f(){
//var doc = window.frames["MyIFrame"].document;  2中都可以
var doc = document.getElementById("MyIFrame").contentDocument;
doc.getElementById("s").style.color="blue";
}
</script>
</head>
<body onload="f()">

<iframe id = "MyIFrame" name = "MyIFrame" src = "MyIFrame.html" width = "100" height="100"></iframe>

</body>
</html>


二 在子页面中操作父页面

父页面操作子页面

<html>
<head>
</head>
<body>

<h2 id="s">55555555555555555555555555</h2>
<script>
       //window.parent是获得父窗口的window对象
window.parent.document.getElementById("txt").innerHTML="你猜怎么样";

</script>
</body>
</html>


三 在父页面调用子页面的函数

<html>
<head>

</head>
<body>
<iframe id = "MyIFrame" name = "MyIFrame" src = "MyIFrame.html" width = "100" height="100"></iframe>
<script type="text/javascript">
window.onload=function(){
//window.frames["MyIFrame"].window.test();
document.getElementById("MyIFrame").contentWindow.test();
}
</script>
</body>
</html>


四 在子页面调用父页面的函数

<html>
<head>
</head>
<body>
<h2 id="s">55555555555555555555555555</h2>
<script type="text/javascript">
window.onload=function(){
window.parent.test();
}
</script>
</body>
</html>


总结:iframe中的src是不能跨域的,如果跨域则无法进行操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: