关于 iframe 操作的疑问

2016-07-21 15:46:11 +08:00
 samlan

假如在 test.com/a.html 页面使用 iframe 引入的 test2.com/b.html 页面 如何实现 test2.com/b.html 中使用 js 动态控制 test.com/a.html 中 iframe 的高度?

3206 次点击
所在节点    HTML
9 条回复
yunying
2016-07-21 16:03:50 +08:00
请搜索 iframe 跨域通信相关的内容
tmkook
2016-07-21 16:09:59 +08:00
window.top.document.getElementsByTagName('iframe')[0].height = document.height
cxe2v
2016-07-21 16:21:37 +08:00
1 楼扯淡, 2 楼正解
zonghua
2016-07-21 16:26:02 +08:00
iframe 默认四周有留空,可以设置边距为赋值,这样就能紧贴
pubby
2016-07-21 16:44:01 +08:00
@tmkook 跨域了还能这样搞?

test2.com/b.html 中再嵌入一个隐藏 iframe2.src=test.com/x.html
b.html 中计算自己高度,动态改变 iframe2.src=test.com/x.html?myHeight=XXXX (也可以用 hash,比如 x.html#myHeight=XXXX )

x.html 中获取 myHeight 的改变 , window.parent.parent 就是 test.com/a.html 的 window 了,因为 x.html 和 a.html 同一个域,可以操作 dom 。
tmkook
2016-07-21 18:25:02 +08:00
@pubby 跨域有很多解决办法
1 、通过后端获取 test2 的内容给 test1 域下输出
2 、 test2 下动态创建一个 test1 的 iframe ,再用 test1 的 iframe 设置父节点的高(同你的方法一样)
3 、在 test1 下用 ajax 获取 test2 的内容(需设置允许跨域的头)
YuJianrong
2016-07-21 20:15:48 +08:00
不考虑低版本浏览器兼容性的话可以试用 postMesage
yunying
2016-07-21 22:35:42 +08:00
@cxe2v 跨域还能按照 2 楼的方法直接操作父 iframe ?
samlan
2016-07-22 10:43:55 +08:00
@tmkook 比如引入页面中有不同选项点击后导致导入页面高度不断变化,这时需要后端的监听不断请求,增加服务器压力

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/293963

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX