我想同步多个iframes。也就是说,如果我在一个iframe中做了更改,那么结果应该显示在所有其他帧中。
背景:我想并行显示不同尺寸的显示器。
然而,我现在有一个循环调用。每个操作都会更改当前页面的URL。我想在另一个iframes中显示这个URL。
HTML代码
<div>
<h3>local display landscape</h3>
<iframe id="iframe_unit_landscape" name="iframe_unit_landscape" onload="loadIFrame(0)"
src="http://localhost:3000/mainmenu.html" height="240" width="320" class="iframe">
</iframe>
</div>
<div>
<h3>local display portrait</h3>
<iframe id="iframe_unit_portrait" name="iframe_unit_portrait" onload="loadIFrame(1)"
src="http://localhost:3000/mainmenu.html" height="320" width="240" class="iframe">
</iframe>
</div>
<div>
<h3>iPhone 8 landscape</h3>
<iframe id="iframe_iphone8_landscape" name="iframe_iphone8_landscape" onload="loadIFrame(2)"
src="http://localhost:3000/mainmenu.html" height="375" width="667" class="iframe">
</iframe>
</div>
<div>
<h3>iPhone 8 portrait</h3>
<iframe id="iframe_iphone8_portrait" name="iframe_iphone8_portrait" onload="loadIFrame(3)"
src="http://localhost:3000/mainmenu.html" height="667" width="375" class="iframe">
</iframe>
</div>JS代码
<script>
const iframes = ['iframe_unit_landscape', 'iframe_unit_portrait', 'iframe_iphone8_landscape', 'iframe_iphone8_portrait'];
function loadIFrame(id) {
let iframe = document.getElementById(iframes[id]);
for (var i = 0; i < iframes.length; i++) {
if (i !== iframe) {
var dest = document.getElementById(iframes[i]).src = src;
}
}
};
</script>发布于 2021-04-12 09:09:09
因此,我向所有的event listener添加了一个iframes,在加载时,iframes数组应该被过滤以删除没有相同src的帧,并设置src。
因此,每当过滤后的iframes加载并运行该函数时,如果没有相同的src阻止无限循环,就不会有其他iframe。
const iframes = ['iframe_unit_landscape', 'iframe_unit_portrait', 'iframe_iphone8_landscape', 'iframe_iphone8_portrait'].map(id => document.getElementById(id));
iframes.forEach(iframe => iframe.addEventListener('load', _ => iframes.filter(frame => frame.src != iframe.src).forEach(frame => frame.src = iframe.src)));<div>
<h3>local display landscape</h3>
<iframe id="iframe_unit_landscape" name="iframe_unit_landscape" src="http://localhost:3000/mainmenu.html" height="240" width="320" class="iframe"></iframe>
</div>
<div>
<h3>local display portrait</h3>
<iframe id="iframe_unit_portrait" name="iframe_unit_portrait" src="http://localhost:3000/mainmenu.html" height="320" width="240" class="iframe"></iframe>
</div>
<div>
<h3>iPhone 8 landscape</h3>
<iframe id="iframe_iphone8_landscape" name="iframe_iphone8_landscape" src="http://localhost:3000/mainmenu.html" height="375" width="667" class="iframe"></iframe>
</div>
<div>
<h3>iPhone 8 portrait</h3>
<iframe id="iframe_iphone8_portrait" name="iframe_iphone8_portrait" src="http://localhost:3000/mainmenu.html" height="667" width="375" class="iframe"></iframe>
</div>https://stackoverflow.com/questions/67055419
复制相似问题