Html 自动聚焦属性和历史导航问题

Html 自动聚焦属性和历史导航问题,html,usability,autofocus,Html,Usability,Autofocus,我有一个页面,其中一个搜索字段位于标题中。此输入使用autofocus属性自动将焦点置于字段中,以便用户可以立即开始搜索: <html> <head><title>autofocus issue</title></head> <body> <header> <form method="post"> <input name="search" autofo

我有一个页面,其中一个搜索字段位于标题中。此输入使用
autofocus
属性自动将焦点置于字段中,以便用户可以立即开始搜索:

<html>
  <head><title>autofocus issue</title></head>
  <body>
    <header>
      <form method="post">
        <input name="search" autofocus />
      </form>
    </header>
    <article>
      <p>Lots of contents here, so that the next link
         can only be reached by scrolling down ...</p>
      <a href="http://link.to/some/page">Go somewhere</a>
    </article>
  </body>
</html>

自动对焦问题
虽然这样做很好,但在历史上来回出现问题。如果用户向下滚动我的页面并单击链接,然后再次返回(使用浏览器历史记录),我的原始页面将滚动到搜索输入所在的顶部


这是一个可用性缺陷,因为回溯历史时滚动位置不应改变。如何避免这种情况?

如果用户通过“后退”按钮导航到您的页面,您需要使用JS检查HTML
autofocus
属性。然后,只有在它们没有的情况下,您才会调用
searchField.focus()

问题是,我看不到直接的解决办法。但是,只有在滚动0px时,才可以尝试调用
.focus()

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
if (scrollTop === 0) {
    searchField.focus();
}