日常工作中很少使用iframe,突然间要使用还需要去查下使用方式,到处搜索,不如自己记录下,在segmentfault里查看还是比较方便的。。。。
效果
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="foo">
<ul>
<li><a id="bar" href="###">bar</a></li>
</ul>
</div>
<iframe id="demo" src="demo.html" width="200px" height="200px" frameborder="1"></iframe>
<script>
var word = 'hello';
function getWord() {
console.log(word+' world !');
}
// 调用子窗口中的元素、变量、方法
window.onload = function() { // 等iframe内容加载完成
var childWindow = document.getElementById('demo').contentWindow;
console.log(childWindow.age); // 24
childWindow.getAge(); // 24
childWindow.document.getElementById('main').style.cssText = 'font-size: 24px;color: #690;';
// jquery方式
$('#demo').contents().find('#main').css({'font-weight': 'bold', 'text-decoration': 'underline'});
}
</script>
</body>
</html>
demo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="main">123</div>
<script>
var age = 24;
function getAge() {
console.log(age);
}
// 调用父窗口中的元素、变量、方法
var parentWindow = window.parent;
parentWindow.document.getElementById('foo').style.cssText = 'border: 1px solid #f00'; // 设置样式
console.log(parentWindow.word); // hello
parentWindow.getWord(); // hello world !
// jquery方式 $(html,[ownerDocument])
$('#foo', parentWindow.document).find('li a').css('background-color', '#ccc');
</script>
</body>
</html>