V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Dive into HTML5
http://diveintohtml5.org/
samlan
V2EX  ›  HTML

关于 iframe 操作的疑问

  •  
  •   samlan · 2016-07-21 15:46:11 +08:00 · 3171 次点击
    这是一个创建于 2807 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    9 条回复    2016-07-22 10:43:55 +08:00
    yunying
        1
    yunying  
       2016-07-21 16:03:50 +08:00
    请搜索 iframe 跨域通信相关的内容
    tmkook
        2
    tmkook  
       2016-07-21 16:09:59 +08:00
    window.top.document.getElementsByTagName('iframe')[0].height = document.height
    cxe2v
        3
    cxe2v  
       2016-07-21 16:21:37 +08:00
    1 楼扯淡, 2 楼正解
    zonghua
        4
    zonghua  
       2016-07-21 16:26:02 +08:00
    iframe 默认四周有留空,可以设置边距为赋值,这样就能紧贴
    pubby
        5
    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
        6
    tmkook  
       2016-07-21 18:25:02 +08:00
    @pubby 跨域有很多解决办法
    1 、通过后端获取 test2 的内容给 test1 域下输出
    2 、 test2 下动态创建一个 test1 的 iframe ,再用 test1 的 iframe 设置父节点的高(同你的方法一样)
    3 、在 test1 下用 ajax 获取 test2 的内容(需设置允许跨域的头)
    YuJianrong
        7
    YuJianrong  
       2016-07-21 20:15:48 +08:00
    不考虑低版本浏览器兼容性的话可以试用 postMesage
    yunying
        8
    yunying  
       2016-07-21 22:35:42 +08:00
    @cxe2v 跨域还能按照 2 楼的方法直接操作父 iframe ?
    samlan
        9
    samlan  
    OP
       2016-07-22 10:43:55 +08:00
    @tmkook 比如引入页面中有不同选项点击后导致导入页面高度不断变化,这时需要后端的监听不断请求,增加服务器压力
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1231 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:23 · PVG 07:23 · LAX 16:23 · JFK 19:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.