我将打开一个包含 iframe 的对话框,然后在打开对话框后将焦点设置在 iframe 内。
目前,我尝试在加载内容时将焦点放在 iframe 上:
<iframe src="../credits.html" onload="this.contentWindow.focus()"></iframe>
它适用于除 Firefox 之外的所有浏览器,我不明白为什么。
有人能告诉我为什么吗?谢谢
我将打开一个包含 iframe 的对话框,然后在打开对话框后将焦点设置在 iframe 内。
目前,我尝试在加载内容时将焦点放在 iframe 上:
<iframe src="../credits.html" onload="this.contentWindow.focus()"></iframe>
它适用于除 Firefox 之外的所有浏览器,我不明白为什么。
有人能告诉我为什么吗?谢谢
Firefox 似乎没有 contentWindow 属性,你应该使用 contentDocument
更新:
经过一番小小的辩论,我想出了一个更好的解决方案:
<html>
<head>
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(function() {
$("#xframe").bind("load", function(){
$(this).contents().find("#xa").focus();
});
});
</script>
</head>
<body>
<iframe id="xframe" src="./y.html"></iframe>
</body>
</html>
在这个例子中,我假设 y.html 中有一个输入字段,它有一个“xa”id。它适用于 Chrome 和 Firefox。
旧答案
更好的是,您应该使用 jquery,例如:
<html>
<head>
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#xframe").focus();
});
</script>
</head>
<body>
<iframe id="xframe" src="./y.html"></iframe>
</body>
</html>
当然你可以做一些额外的检查来看看 iframe 是否准备好了。
更多信息可以在这里找到http://www.w3schools.com/jsref/prop_frame_contentwindow.asp
尝试使用 jquery 执行此操作
// focus an input in iframe
$('#xframe').contents().find('input').get(0).focus()
// or simply iframe window
var iframe= $('#xframe')[0];
var iframewindow= iframe.contentWindow? iframe.contentWindow : iframe.contentDocument.defaultView;
iframewindow.focus()