javascript - 设置哈希后无法聚焦输入

标签 javascript html forms focus

我以前从未注意到这一点,但如果设置了指向现有元素的散列,则似乎不可能将输入字段集中在加载上。

这是为什么?

看看这个非常基本的例子:

<!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,无论是否设置了哈希值或不够奇怪。

最佳答案

考虑此用例有 4 个场景:

  1. Page is loaded/refreshed when there is no hash in the URL

在本例中,Element.focus()工作正常。

  1. Hash in the URL is appended but page is not reloaded/refreshed

在本例中, HashChangeEvent 可用于设置focus超过元素。

  1. Page is loaded/refreshed when there is hash in the URL

在本例中,Element.focus() 如果callback中调用则工作正常的setTimeout 。甚至是setTimeout(callback,0)会起作用的!

  1. Page is loaded/refreshed when there is hash in the URL but target does not exist in the Page

在本例中,Element.focus()工作正常

最终想法:

拥有focus 任何场景中的任何元素,使用setTimeoutwindow.onload回调 delay 0

window.onload = function () {
  setTimeout(function () {
    document.getElementsByTagName('input')[0].focus();
    console.log(document.activeElement);
  }, 0);
};

关于javascript - 设置哈希后无法聚焦输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37566555/

相关文章:

javascript - 如何使用 array.map 函数不返回任何内容(空数组)

javascript - 三元运算符第二部分不渲染 React JS

html - 与 chrome 或 mozilla 相比,Internet Explorer 11 或 IE 8 显示不同的网页布局

php - 使用 PHP 针对 MYSQL 数据库验证表单字段

php - 如果我使用 header() 函数,登录索引表单无法与 login.php 一起使用

javascript - 如何在外部文件中创建选择菜单并将其嵌入到 html 中以显示菜单

css - 如何在父 div 中居中数据?

jquery - Bootstrap Carousel - 图片数量

php - WooCommerce 以编程方式创建的产品忽略价格排序过滤器

javascript - JS : Bookmarklet - Create a bookmarklet that fires a local js file to fill up fields in a form of the current page