我目前正在为我的应用程序构建一个搜索栏。我一直在到处阅读关于聚焦输入字段的文档,我发现HTML有一个内置的功能“自动聚焦”,但我还没有能够找到一个解决方案,如何聚焦在输入字段上,例如我点击网页上的空白区域。
<input type="text" class="form-control srch-bar" id="myInput" onkeyup="myFunction()" title="Type in a name" autofocus>
我目前正在为我的应用程序构建一个搜索栏。我一直在到处阅读关于聚焦输入字段的文档,我发现HTML有一个内置的功能“自动聚焦”,但我还没有能够找到一个解决方案,如何聚焦在输入字段上,例如我点击网页上的空白区域。
<input type="text" class="form-control srch-bar" id="myInput" onkeyup="myFunction()" title="Type in a name" autofocus>
2条答案
按热度按时间pcww981p1#
我假设你的搜索栏应该永久拥有焦点。即使用户点击了外面,焦点也不应该被移除。这基本上是一个非常糟糕的用户体验和糟糕的设计理念。尽管如此,我还是会给你展示一个可能的解决方案。
您已经找到了必需的属性
autofocus
。这将使您的输入字段在页面加载后自动获得焦点。现在您必须防止焦点被移除。您可以使用onblur
事件来实现这一点。onblur事件在元素失去焦点时发生。当触发此事件时,您只需再次将焦点设置在输入字段上。同样,我强烈建议不要使用这个实现,即使你认为它是你问题的解决方案,也会有更有用的方法。
wvmv3b1j2#
我希望这能有所帮助,我不会给予太多的解释,因为它是非常简单的。(代码中的注解)
我在这里乞讨,在javascript上,我不知道这是否是更好的方法。