简体   繁体   English

JavaScript focus()函数不会在页面加载时将textarea聚焦

[英]JavaScript focus() function doesn't focus textarea on page load

I have the following code. 我有以下代码。

<!DOCTYPE html>
<html>
<head>
<title>Focus issue</title>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
  var text = document.getElementById('text')
  window.onload = function() {
    text.focus()
  }
  window.onhashchange = function() {
    text.focus()
  }
}//]]>  
</script>
</head>
<body>
  <textarea id="text"></textarea>
  <p><a href="#focus">Click to focus</a></p>
</body>
</html>

Here is a JSFiddle demo of the above code: http://jsfiddle.net/DvU63/ 这是上面代码的JSFiddle演示: http//jsfiddle.net/DvU63/

Why doesn't the focus go on the textarea box when the page loads? 为什么页面加载时焦点不会转到textarea框? On clicking the link, the focus does go on the textarea box, but I also want the focus to go to the textarea box on page load. 在单击链接时,焦点确实在textarea框上,但我也希望焦点转到页面加载时的textarea框。 Why doesn't it happen? 为什么不发生?

Note: I am aware of the HTML5 autofocus attribute for textarea. 注意:我知道textarea的HTML5自动聚焦属性。 But this question is about why the above JavaScript code does not do what I intend to do. 但是这个问题是为什么上面的JavaScript代码没有做我想做的事情。

You're doing the .focus() statement from inside an onload handler that is itself defined inside an onload handler. 您正在onload处理程序内部执行.focus()语句,该处理程序本身在onload处理程序中定义。 This inner onload will not be called because by the time you define it the onload event will have occurred. 不会调用此内部onload因为在您定义它时会发生onload事件。 Try this: 试试这个:

window.onload=function(){
  var text = document.getElementById('text')
  text.focus()

  window.onhashchange = function() {
    text.focus()
  }
}

Your demo, updated: http://jsfiddle.net/DvU63/2/ 您的演示版已更新: http//jsfiddle.net/DvU63/2/

do this 做这个

<script type='text/javascript'> 
    window.onload=function(){
    var text = document.getElementById('text')

    text.focus();

    window.onhashchange = function() {
        text.focus();
    }
  }
</script>

fiddle 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM