同一页面iframe

时间:2017-09-06 16:43:31

标签: javascript html css

所以我被要求在html中创建一个并排的“frame”。当选择左侧iframe的内容时,它会在同一页面上填充其旁边的iframe中的链接。

附加背景:左侧是Tableau生成的菜单栏,右侧是附加的可视化。使用类似下面代码中的目标无效:

<div id="left">
<iframe src="http://www.weather.gov/" target="myDemoFrame"></iframe>
</div>

<div id="right">
<iframe name="myDemoFrame" src=""></iframe>
</div>

非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

假设您控制两个页面,您可以在iframes之间使用postMessage进行消息,左侧窗口消息传递父节点,父节点消息传递给右侧子节点,示例如下:

<强> outer.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .frame {
            width: 45vw;
            height:95vh;
        }
    </style>
</head>
<body>
<iframe src="left.html" class="frame" id="left"></iframe>
<iframe src="right.html" class="frame" id="right"></iframe>
</body>
<script>
    var l = document.getElementById("left");
    var r = document.getElementById("right");
    window.onmessage = function(e){
      if (l.contentWindow == e.source) {
        r.contentWindow.postMessage(e.data, '*')
      }
    };
</script>
</html>

<强> left.html

<!DOCTYPE html>
<html lang="en">
<body>
<button onclick="clickEvent()">SEND</button>
</body>
<script>
    function clickEvent() {
      window.top.postMessage({"payload": "Hello from the other side"}, '*')
    }
</script>
</html>

<强> right.html

<!DOCTYPE html>
<html lang="en">
<body>
</body>
<script>
  window.onmessage = function(e){
    if (e.source == window.top) {
      if (e.data["payload"]) {
        alert(e.data["payload"]);
      }
    }
  }
</script>
</html>

编辑 - 纯导航答案

<强> outer.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .frame {
            width: 45vw;
            height:95vh;
        }
    </style>
</head>
<body>
<iframe src="left.html" class="frame" id="left"></iframe>
<iframe class="frame" id="right"></iframe>
</body>
<script>
    var l = document.getElementById("left");
    var r = document.getElementById("right");
    window.onmessage = function(e){
      if (l.contentWindow == e.source && e.data["payload"]) {
        r.src = e.data["payload"]
      }
    };
</script>
</html>

<强> left.html

<!DOCTYPE html>
<html lang="en">
<body>
<button onclick="navigate('http://www.bing.com')">BING</button>
<button onclick="navigate('http://www.example.com')">EXAMPLE</button>
</body>
<script>
    function navigate(url) {
      window.top.postMessage({"payload": url}, '*')
    }
</script>
</html>