iframe内外互调

日常工作中很少使用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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值