2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iframe内のelementから親frameを含むpos座標を取得する方法

Last updated at Posted at 2017-03-01

問題

iframe内のelementを起点に、そのelementのブラウザ上の座標を取得したい

解決

parent.html
<!DOCTYPE html>
<html>
  <head>
    <title>parent html</title>
  </head>
  <body>
    <h1>parent html</h1>
    <div style="display:flex;">
      <iframe src="child.html" style="width:500px; height:200px; margin:auto;"></iframe>
    </div>
  </body>
</html>
child.html
<!DOCTYPE html>
<html>
  <head>
    <title>child html</title>
    <script type="text/javascript">
      function getPos() {
        const pos = { top: 0, left: 0 };

        const el = document.getElementById('targetElement');
        pos.top = el.getBoundingClientRect().top;
        pos.left = el.getBoundingClientRect().left;

        var doc = el.ownerDocument;
        var childWindow = doc.defaultView;

        while (window.top !== childWindow) {
          pos.top += childWindow.frameElement.getBoundingClientRect().top;
          pos.left += childWindow.frameElement.getBoundingClientRect().left;
          childWindow = childWindow.parent;
        }

        console.log(pos);
      };
    </script>
  </head>
  <body>
    <h1>child html</h1>
    <div id="targetElement" style="width:20%; height:20%; margin:auto; border:1px solid black;">target</div>
    <button onClick="getPos();">get pos</button>
  </body>
</html>
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?