日期:2014-05-16  浏览次数:20389 次

不跨域的情况下父页面访问iframe内元素和js方法的完整步骤

1.首先两个页面在同一域下

?

例:A.HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>resize</title>
		<meta name="author" content="Administrator" />
		<!-- Date: 2013-08-30 -->
	</head>
	<body>
		<div>
       	<iframe name="test" src="B.HTML" id="test" frameborder="no" style="margin: 50px 80px 0 90px;width:90%;height: 500px;"></iframe>
       	</div>
	</body>
</html>

?B.HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>resize</title>
		<meta name="author" content="Administrator" />
		<!-- Date: 2013-08-30 -->
		<script>
			function resize() {
				var parentwh = parent.innerHeight;
				var parentww = parent.innerWidth;
				var parentscreenh = parent.screen.height;
				var parentscreenw = parent.screen.width;
				var gridDiv = document.getElementById("gridWropper");
				var got = gridDiv.offsetTop
				var winh = window.innerHeight;
				var winw = window.innerWidth
				var w = winh - got;

				var screenX = screenLeft;
				var screenY = screenTop

				var allFrames = parent.frames;
				var currentWin = null;
				for (var i = 0; i < allFrames.length; i++) {
					if (allFrames[i] == window) {
						currentWin = allFrames[i];
					}
				}
			}
		</script>
	</head>
	<body onresize="resize()">
		<div id="gridWropper" style="height:90%;width:100%;overflow:auto;border: 2px dashed black;word-break: break-all;"></div>
	</body>
</html>

?接下来如果要在A中访问B中的方法,首先得先判断B是否加载完成,加载完成后才能访问(这个太重要了)

?

?js

var iframe = document.getElementById("test");
            if (!/*@cc_on!@*/0) { //if not IE
                iframe.onload = function(){
                    alert("Local iframe is now loaded.chrome");
					alert(iframe.contentWindow.resize)
                };
            }
            else {
                iframe.onreadystatechange = function(){
                    if (iframe.readyState == "complete") {
                        alert("Local iframe is now loaded.ie");
                        //alert(iframe.document.getElementById("test"));
						alert(iframe.contentWindow.resize)
                    }
                };
            }

?