問題
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>