【问题标题】:How do I access the iframe element from within that iframe?如何从该 iframe 中访问 iframe 元素?
【发布时间】:2017-02-02 21:52:31
【问题描述】:

我想使用 iframe 中存在的按钮关闭 iframe。

我有这两个文件,index.html 和 contents.html:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
  a {
    postion: relative;
    top: 100px;
    left: 100px;
  }
</style>
  </head>
  <body>
<iframe id="outerIframe" src="./contents.html" width="1000px" height="1000px"></iframe>
<div class="behind">
  <a href="http://www.google.com">Mark Behind</a>
</div>
</body>
</html>

contents.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>

<style media="screen">
  .big-box {
    height: 500px;
    width: 500px;
    background-color: #666;
  }
</style>
</head>


 <body>
<div class="big-box">
  <button class="closer" type="button" name="button">Click to close</button>
</div>


<script type="text/javascript">
  var button = document.querySelector('.closer');
  button.addEventListener('click', function() {
    document.getElementById('outerIframe').style.display = "none";
  });
</script>
</body>
</html>

当我单击该按钮时,我在控制台中收到一条错误消息,提示“无法读取 null 的属性 'style'。我知道这意味着我尝试获取 iframe 的尝试没有成功。我将如何获取 iframe 这个按钮驻留在其中以便我可以更改其样式?

【问题讨论】:

    标签: javascript html css iframe


    【解决方案1】:

    需要向上遍历到父窗口。 iframe 有自己的窗口

    试试

    button.addEventListener('click', function() {
        window.parent.document.getElementById('outerIframe').style.display = "none";
    });
    

    DEMO

    【讨论】:

    • 哦,好的,我明白了。一路出去,然后再回来。有道理。感谢您的帮助
    猜你喜欢
    • 2013-03-22
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多