同域之下子iframe的DOM控制问题

原文链接: https://www.mk2048.com/blog/blog.php?id=h0222kabj1kj&title=%E5%90%8C%E5%9F%9F%E4%B9%8B%E4%B8%8B%E5%AD%90iframe%E7%9A%84DOM%E6%8E%A7%E5%88%B6%E9%97%AE%E9%A2%98

new_file.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-2.1.1.min.js"></script>
	</head>
	<style>
		iframe{
			border: 1px solid red;
		}
	</style>
	<body>
		<div id="father">父级的内容(点击导致子iframe的字体变蓝)</div>
		<iframe src="new_file2.html" id="myFrame" frameborder="0" width="200px" height="200px"></iframe>
		<div>点击iframe里面的标签触发父级的事件。</div>
		<div>点击父级的标签,触发iframe里的事件。</div>
		<script>
			$('#myFrame').on('load',function(event){
				$('#son',this.contentDocument).click(function(){
					alert('子级调父级');
					$('#father').css('color','red');
				})
			})
			$('#father').click(function(){
				alert('开始调子级');
				var son = document.getElementById('myFrame').contentWindow.document.getElementById('son');
				son.style.color='blue';
			})
		</script>
	</body>
</html>

new_file2.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div id="son">子iframe的内容(点击导致父级字体变红)</div>
	</body>
</html>

  说明:

1:为iframe中的某标签绑定事件,控制iframe之外的标签。

2:为父级body中的标签绑定事件,控制iframe之中的某标签。


更多专业前端知识,请上 【猿2048】www.mk2048.com

猜你喜欢

转载自blog.csdn.net/qq_29069777/article/details/102760041