我有一个带有一些按钮的 IFrame。当按钮被点击时,父 DOM 被操作(它们都在同一个域中,所以不用担心同源策略)。
由于用户单击了按钮,焦点转到了 IFrame。但是,我想将焦点移回父文档(主要是由于 this FireFox problem )。
我该怎么做?
编辑:我创建了一个 js-fiddle这表明了问题。如果在父表单元素上调用 focus()
似乎可以工作,但它通常不起作用。正如您从 js-fiddle 中看到的那样,我的父文档中没有表单元素。
最佳答案
如果要从iframe内部将焦点设置回外窗,聚焦外窗本身不太可能给用户任何视觉反馈,所以最好在外页面中聚焦一个已知的表单元素.
您可以按如下方式执行此操作:
outer.html
<html>
<head>
<title>Outer</title>
</head>
<body>
<iframe id="iframe" src="inner.html">
</iframe>
</body>
</html>
inner.html
<html>
<head>
<title>Inner</title>
</head>
<body>
<form id="innerForm">
<input type="button" id="innerButton" value="Inner button" />
</form>
</body>
<script type="text/javascript">
// When we click the inner button...
document.getElementById('innerButton').addEventListener('click', function() {
/*
* Do whatever you need to do here
*/
// Focus the parent
parent.focus();
});
</script>
</html>
关于javascript - 如何将焦点移出 IFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10502099/