原生js获取iframe中dom元素或父级元素
用原生js在父页面获取iframe子页面的元素,以及在子页面获取父页面元素,这是平时经常会用到的方法,这里写一个例子来总结下:
# 在父页面获取子页面节点
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>demo主页面</title>
<script type="text/javascript">
window.onload = function(){
var _iframe = document.getElementById('iframeId').contentWindow;
var _div =_iframe.document.getElementById('objId');
_div.style.backgroundColor = '#ccc';
}
</script>
</head>
<body>
<iframe src="demo-iframe.html" id="iframeId" height="150" width="150"></iframe>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 在子页面获取父页面节点
<!DOCTYPE>
<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='objId' style='width:100px;height:100px;background-color:red;'>子页面</div>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
上次更新: 2024/01/30, 00:35:17
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13