我正在尝试匹配同一父页下两个不同iframe中两个元素的位置和大小,但我不知道该怎么做。
使用以下代码,我设法将父页面中div(" div_parent_page' )的位置和大小与元素的位置相匹配( ' element_in_iframe-1" )在同一父网页下的iframe(' iframe-1' )内:
function myFunction() {
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
var positionInfo = ( document.getElementById('iframe-
1').contentWindow.document.getElementById('element_in_iframe-1')
).getBoundingClientRect();
var yheight = positionInfo.height;
var xwidth = positionInfo.width;
var x = getOffset( document.getElementById('iframe-
1').contentWindow.document.getElementById('element_in_iframe-1') ).left;
var y = getOffset( document.getElementById('iframe-
1').contentWindow.document.getElementById('element_in_iframe-1') ).top;
var d = document.getElementById('div_parent_page');
d.style.position = "absolute";
d.style.left = x+'px';
d.style.top = y+'px';
d.style.width = xwidth;
d.style.height = yheight; `
}
var timer = setInterval(myFunction, 1000);
现在,我在上面提到的div中添加了另一个iframe(' iframe-2' ),我的目标是匹配元素的位置和大小(' elementXXX' )div内的iframe-2,其位置和大小为 element_in_iframe-1 。我添加了以下代码:
var v = document.getElementById('iframe-
2').contentWindow.document.getElementsByClassName('elementXXX');
v.style.position = "absolute";
v.style.left = x+'px';
v.style.top = y+'px';
v.style.width = xwidth;
v.style.height = yheight;
}
显然,它没有用,但我不确定如何实现。希望你们能够启发我,因为我真的是一个编码的奶奶。感谢〜
答案 0 :(得分:0)
How can I get an object's absolute position on the page in Javascript?
https://jsfiddle.net/5aLp24dd/2/
var imframe1 = document.getElementById('iframe-1');
var innerDoc1 = imframe1.contentDocument ||
imframe1.contentWindow.document;
var x = innerDoc1.getElementById ( "carbonads" ).offsetLeft;
var y = innerDoc1.getElementById ( "carbonads" ).offsetTop;
alert('x offset: ' + x);
alert('y offset: ' + y);
var imframe2 = document.getElementById('iframe-2');
var innerDoc2 = imframe2.contentDocument ||
imframe2.contentWindow.document;
innerDoc2.getElementById ( "carbonads" ).style.position = "absolute";
innerDoc2.getElementById ( "carbonads" ).style.left = (x - 30) + 'px';
innerDoc2.getElementById ( "carbonads" ).style.top = (y - 30) + 'px';