【问题标题】:Issue with autofocus attribute and history navigation自动对焦属性和历史导航问题
【发布时间】:2017-05-28 06:04:04
【问题描述】:

我有一个页面,其中在标题中放置了一个搜索字段。此输入使用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>

虽然这可以正常工作,但在历史中来回时会出现问题。如果用户向下滚动我的页面并单击链接然后再次返回(使用浏览器历史记录),我的原始页面将滚动到搜索输入所在的顶部。

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

【问题讨论】:

    标签: html usability autofocus


    【解决方案1】:

    如果用户通过后退按钮导航到您的页面,您需要检查 JS,而不是使用 HTML autofocus 属性。那么只有他们没有,你才会打电话给searchField.focus()

    问题是,我看不到detect if the user clicked the “back” button 的直接方法。但是,您可以尝试 getting the scroll position,并仅在滚动 0px 时调用 .focus()

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

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 2020-03-22
      • 2015-03-06
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多