【问题标题】:Set focus to the middle of the Iframe in html5在 html5 中将焦点设置到 iframe 的中间
【发布时间】:2026-02-16 13:10:01
【问题描述】:

我在iframe 中显示一个外部网页,我想将焦点直接设置在网页的内容上,内容位于网页的中间。

我怎样才能做到这一点?

谢谢

【问题讨论】:

  • 你的意思是在 iframe 内设置焦点?
  • 是的..我想在 iframe 内设置焦点
  • 在这里查看:*.com/questions/369026/…

标签: html focus


【解决方案1】:

如果页面位于另一个域中,您将遇到 XSS(跨站点脚本)问题和浏览器为避免恶意操作而设置的障碍!

如果您自己提供页面,您可以这样做:

inner.html

<!doctype html>
<html>
<head><title>the iframe</title></head><body>
Hello World!<br/>
This is where we start to select something ..<br/>
.. right here: <input type="text" id="toBeSelected" size="12" value="this is to be selected" onfocus="this.select()"/><br/>
</body>
</html>

outer.html

<!doctype html>
<html>
<head><title>fun with IFRAME</title></head><body>
<ol type="i">
<li>wait for loading..</li>
<li>..<a href="#" id="andThen" style="display: none;" onclick="setFocus(); return false;">set focus</a></li>
<li>..see the effect.</li>
</ol>
<iframe id="theIFRAME" width="500" height="500" frameborder="1" data-src="inner.html" style="margin: 1em auto 0;">NO IFRAME support</iframe>
<script type="text/javascript"><!--

function setFocus(){
    var domIFRAME = document.getElementById('theIFRAME'), 
        docIFRAME = domIFRAME ? ( domIFRAME.contentDocument || domIFRAME.contentWindow.document ) : null;
    if( docIFRAME ) docIFRAME.getElementById('toBeSelected').focus(); else console.log("oups!");
}

function handleIframeContent(){
    console.log("okay, it has loaded.");
    document.getElementById('andThen').style.display = 'inline';
}

var domIFRAME = document.getElementById('theIFRAME');
domIFRAME.onload = handleIframeContent;
domIFRAME.src = domIFRAME.getAttribute('data-src');
// --></script>
</body>

当然,你可以在handleIframeContent()里面做.focus()位,这个demo只是想让你有时间去体会它实际上不是IFRAME里面页面的默认状态。

HTH

【讨论】: