我以前从未注意到这一点,但似乎在设置指向现有元素的哈希值时,不能在加载时将输入字段聚焦。
为什么会这样呢?
看看这个非常基本的例子:
<!doctype html>
<html>
<head>
<meta charset="utf8">
<title>Focus test</title>
</head>
<body>
<div id="bar">
<input name="foo">
</div>
<script>
console.log(document.activeElement);
document.getElementsByTagName('input')[0].focus();
console.log(document.activeElement);
</script>
</body>
</html>
如果您在Chrome中加载该页面,输入框将获得焦点。如果您将哈希设置为#bar并重新加载页面,则输入框不会获得焦点。如果您将哈希设置为#non-existing-element,则输入框再次获得焦点。
activeElement
会说无论是否设置了哈希,先是body
,然后是input
,这很奇怪。
setTimeout
之后设置focus
会有所帮助! - Rayondocument.activeElement
从来没有指向哈希中设置的元素。而且我也不知道设置哈希和聚焦元素是一样的。给input
一个id并将哈希指向它并不会使其获得焦点,所以我不明白它们怎么会是一回事。 - powerbuoysetTimeout
可以工作!:)非常感谢。请在答案中发布它,我会给你信用。 - powerbuoy