1. 程式人生 > >iframe父元素獲取子頁面的元素

iframe父元素獲取子頁面的元素

父頁面
<iframe src="iframe.html" id="iframeId" height="150" width="150"></iframe>
子頁面

<div id="div">
    iframe頁面
</div>


window.onload = function(){
    var _iframe = document.getElementById('iframeId').contentWindow;
    var _div =_iframe.document.getElementById('div');

    _div.style.backgroundColor = 'red';
    _div.onclick=function(){
        alert(1)
    }
}

子頁面控制父頁面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>子頁面demo13-iframe.html</title>
    <script type="text/javascript">
        window.onload = function(){
            var _iframe = window.parent;
            var _div =_iframe.document.getElementById('parDiv');
            _div.style.color = 'red';
        }
    </script>
</head>

<body>
<div id='div' style='width:100px;height:100px;background-color:red;'>子頁面</div>
</body>
</html>