samlan
V2EX  ›  HTML

关于 iframe 操作的疑问

  •  
  •   samlan · Jul 21, 2016 · 4164 views
    This topic created in 3584 days ago, the information mentioned may be changed or developed.

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

    9 replies    2016-07-22 10:43:55 +08:00
    yunying
        1
    yunying  
       Jul 21, 2016
    请搜索 iframe 跨域通信相关的内容
    tmkook
        2
    tmkook  
    PRO
       Jul 21, 2016
    window.top.document.getElementsByTagName('iframe')[0].height = document.height
    cxe2v
        3
    cxe2v  
       Jul 21, 2016
    1 楼扯淡, 2 楼正解
    zonghua
        4
    zonghua  
       Jul 21, 2016
    iframe 默认四周有留空,可以设置边距为赋值,这样就能紧贴
    pubby
        5
    pubby  
       Jul 21, 2016
    @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  
    PRO
       Jul 21, 2016
    @pubby 跨域有很多解决办法
    1 、通过后端获取 test2 的内容给 test1 域下输出
    2 、 test2 下动态创建一个 test1 的 iframe ,再用 test1 的 iframe 设置父节点的高(同你的方法一样)
    3 、在 test1 下用 ajax 获取 test2 的内容(需设置允许跨域的头)
    YuJianrong
        7
    YuJianrong  
       Jul 21, 2016
    不考虑低版本浏览器兼容性的话可以试用 postMesage
    yunying
        8
    yunying  
       Jul 21, 2016
    @cxe2v 跨域还能按照 2 楼的方法直接操作父 iframe ?
    samlan
        9
    samlan  
    OP
       Jul 22, 2016
    @tmkook 比如引入页面中有不同选项点击后导致导入页面高度不断变化,这时需要后端的监听不断请求,增加服务器压力
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5536 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 362ms · UTC 08:35 · PVG 16:35 · LAX 01:35 · JFK 04:35
    ♥ Do have faith in what you're doing.