工作中总能遇到 引用别人的页面,就会带来很多问题,比如iframe中的样式不满足我们的需求,这就需要修改iframe中的样式,
下面我们做一个修改 iframe 中样式的 Demo:
知识点:
let test =
document
.
getElementById
(
'
引用的iframeId
'
)
.
contentWindow
.
document
.
getElementById
(
'
修改样式的Id
'
)
;
test
.
style
.
width
=
"
200px
"
;
第1步:创建一个setIframeStyle文件夹
第2步:在setIframeStyle文件夹中创建1.html和2.html
2.1: 1.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" />
<script>
window.onload = function () {
var test =
document.getElementById('frame').contentWindow.document.getElementById('cc');
test.style.background = "#333";
}
</script>
</head>
<body>
<div>
这是 第一个 网页
</div>
<iframe src="2.html" frameborder="0" id="frame" width="100%" height="100%"></iframe>
</body>
</html>
2.2: 2.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="cc">
这是 2 网页
</div>
</body>
</html>
第3步: 运行 1.html 发现第2.html中id为cc的div背景变为灰色了,成功了!
but ....
不是所有的页面都是引用本地的,如果网络资源,比如百度呢?接下来说说引用网络资源
1.将1.html中 iframe 的 src 属性 修改为 www.baidu.com
<
iframe
src
=
"
https://www.baidu.com/
"
frameborder
=
"
0
"
id
=
"
frame
"
width
=
"
100%
"
height
=
"
100%
"
></
iframe
>
2.再运行 1.html 发现报错了
原因:跨页面操作涉及域的概念(origin),错误的意思是:未捕获的安全错误:阻止了一个域为null的frame页面访问另一个域为null的页面。代码运行时在本地直接用浏览器打开的,地址栏是file:///的页面,只需改为localhost访问就行 或者 自己下载个Xammp 搭建个服务器
下面 修改1.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" />
<script>
window.onload = function () {
var test =
document.getElementById('frame').contentWindow.document.getElementById('lg');
test.style.width = "200px";
}
</script>
</head>
<body>
<div>
这是 第一个 网页
</div>
<iframe src="https://www.baidu.com/" frameborder="0" id="frame" width="100%" height="100%"></iframe>
</body>
</html>
再次运行1.html 页面如下(百度的图标宽度发生了改变)