在 Javascript 中,如果作为子窗口调用,则使用 focus() 设置 textarea 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19336794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Javascript setting a textarea with focus() does not work if called as a child window
提问by Ian Smith
I have a simple test page that sets the focus to a textarea on an oninit function. However the exact code fails to do this if the page is called as a child.
我有一个简单的测试页面,它将焦点设置为 oninit 函数上的 textarea。但是,如果页面被称为子页面,则确切的代码无法执行此操作。
Putting alert box proves that the oninit function is being called but fails to put the focus in the textbox. Pressing reload though does then focus correctly.
放置alert框证明oninit函数正在被调用,但是没有把焦点放在textbox上。虽然按下重新加载然后会正确聚焦。
So given that my code works perfectly when called on a main page, and also works in a child if reload is called, then why doesn't it work the first time?
因此,鉴于我的代码在主页面上调用时可以完美运行,并且如果调用 reload 也可以在子页面中运行,那么为什么它第一次不起作用呢?
<html>
<body onload="init()">
<script type="text/javascript">
function init()
{
document.getElementById("message").focus();
}
</script>
<textarea id="message" rows=10 cols=40></textarea>
</body>
</html>
Nothing clever here as you can, just only doesn't work if the page is loaded by window.open("test2.html");
这里没有什么聪明之处,只有当页面由 window.open("test2.html"); 加载时才不起作用。
回答by Hasib Hasan Arnab
which browser do you use? I check in firefox, chrome & IE. Your code runs perfect and focus on the textarea.
你使用哪个浏览器?我检查了 Firefox、Chrome 和 IE。您的代码运行完美并专注于 textarea。
I create two file test1.html and test2.html in a same directory. In test1.html i insert the the follwing code..
我在同一个目录中创建了两个文件 test1.html 和 test2.html。在 test1.html 我插入以下代码..
<html>
<body>
<script type="text/javascript">
function init()
{
window.open('test2.html');
}
</script>
<button onclick="init()">test</button>
</body>
</html>
And in test2.html..
而在 test2.html ..
<html>
<body onload="init()">
<script type="text/javascript">
function init()
{
document.getElementById("message").focus();
}
</script>
<textarea id="message" rows=10 cols=40></textarea>
</body>
</html>
Than, I run the test1.html and click the button and test2.html appears with focus on the textarea.
然后,我运行 test1.html 并单击按钮,test2.html 出现在 textarea 上。
回答by Ishan Liyanage
You can also use setTimeout irrespective of the event.
无论事件如何,您也可以使用 setTimeout。
setTimeout(function() {
document.getElementById("elementId").focus();
}, 0);