导读:今天开发的时候遇到个iframe自适应高度的问题,相信大家对这个不陌生,但是一般我们都是在同一个项目使用iframe嵌套页面,这个ifame高度自适应网上一搜一大把,今天要讲的如何在不同的网站下进行相互的调用跟在同一个网站下是一个效果:例如我在自己的项目里面Iframe 了第一博客的页面 http://www.diyibk.com/ 当第一博客的页面高度变化了怎么通知父页面呢? 这个时候在谷歌下肯定是拿不到 iframe里面的 docment元素的
解决方法:
新建index.html
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62 |
<!doctype html><html><head> <meta charset="utf-8"> <title>crossdomain | postMessage + window.name</title> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <style> body, button{ font-family: Verdana, Arial; color: #333; } h1{ text-align:center; font-size:24px; } .wrapper{ padding:10px; width:640px; } .wrapper, #child{ border:#A11111 2px solid; } #info{ color:#00F; height:30px; overflow-y:auto; } </style></head><body> <h1>CrossDomain using (postMessage + window.name)</h1> <div class=‘wrapper‘> <p>Host window, <strong>woiweb.net</strong></p> <input type="text" value="500px" id="val" /> <button id=‘trigger‘>Send Message</button> <p id=‘info‘></p> <iframe width=‘600‘ height=‘140‘ scrolling=‘auto‘ frameborder=‘0‘ </div> <script type=‘text/javascript‘ > var send = function() { var val = $E(‘val‘).value; val = val || ‘500px‘; var json = { ‘height‘ : val }; XD.sendMessage($E(‘child‘).contentWindow, json); }; var callback = function(data) { $E(‘info‘).innerHTML = jsonToStr(data); $E(‘child‘).style.height = data.height; }; XD.receiveMessage(callback); addEvent($E(‘trigger‘), ‘click‘, send); </script></body></html> |
在建一个iframe.html
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 |
<!doctype html><html><head> <meta charset="utf-8"> <title>crossdomain | postMessage + window.name</title> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <style> html{ font-family: Verdana, Arial; color: #333; background:#EEE; } #info{ color:#00F; height:30px; overflow-y:auto; } #box{ width:100px; height:100px; border:#A11111 2px solid; } </style></head><body> <p>Iframe window, <strong>crossdomain.sinaapp.com</strong></p> <input type="text" value="500px" id="val" /> <button id=‘trigger‘>Send Message</button> <p id=‘info‘></p> <script type=‘text/javascript‘ > var send = function() { var val = $E(‘val‘).value; val = val || ‘500px‘; var json = { ‘height‘ : val }; XD.sendMessage(parent, json); //区别在这里,第一个参数 }; var callback = function(data) { //演示改变 $E(‘info‘).innerHTML = jsonToStr(data); document.body.style.height = data.height; } XD.receiveMessage(callback); addEvent($E(‘trigger‘), ‘click‘, send); </script></body></html> |
兼容任何的浏览器。跨域调用JS不再是难题!