gpt4 book ai didi

html - 自动对焦属性和历史导航问题

转载 作者:行者123 更新时间:2023-11-28 01:02:13 25 4
gpt4 key购买 nike

我有一个页面,其中在页眉中放置了一个搜索字段。此输入使用 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 autofocus 属性,您需要使用 JS 检查。然后只有当他们不这样做时,您才会调用 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();
}

关于html - 自动对焦属性和历史导航问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41624909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com