在 div 中使用箭头键
我有两个div。其中一个包含输入字段,另一个包含建议列表。我希望用户能够使用箭头键进入第二个 div,并滚动浏览建议列表。它看起来是这样的:
<div id="first"><input type="text" /></div>
<div id="second">
<ul>
<li>suggestion</li>
<li>suggestion2</li>
<li>suggestion3</li>
</ul>
</div>
我实际上在 Stack 上找到了一些东西: Fiddle
但我做不到之所以有效,是因为它使用类名,而我使用的是 ID。 如果有人能为我重写这个,以便我可以附加 ID,我将非常感激。
I have two divs. One of them contains an input field the other a list of suggestions. What I would like is the ability for the user to come down in the second div with the use of the arrow key an also scroll through the list of suggestions. This is how it looks:
<div id="first"><input type="text" /></div>
<div id="second">
<ul>
<li>suggestion</li>
<li>suggestion2</li>
<li>suggestion3</li>
</ul>
</div>
I actualy found something here at Stack: Fiddle
But I can't make it work because it uses class names and I'm using ID's instead.
I would very much appreciate if someone would rewrite this for me so I can append ID's.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个非常简单的改变,让小提琴按照你想要的方式工作:
jsfiddle
类名是仅在那里突出显示所选项目。小提琴使用 id 来引用输入和项目包装器。它与您的代码实际上没有太大不同。现在您可以看到它与您的代码一起工作,您应该能够进行您认为合适的其他更改。希望有帮助。
编辑:糟糕。看来我忘记更新小提琴了。这已得到修复。
It was a pretty simple change to get that fiddle to work how you wanted it:
jsfiddle
The class names were only there to highlight the selected item. The fiddle uses id's to reference the input and items wrapper. It wasn't much different than your code really. Now that you can see it working with your code you should be able to make and additional changes you see fit. Hope it helps.
EDIT: Woops. Looks like I forgot to update the fiddle. This has been fixed.
使用像这样的 onKeyDown 事件
那么您的输入 HTML 将如下所示:
请注意,我的示例没有使用通常不必要的 jQuery 库。
在实际事件中,您将更改列表项的样式并保存用户选择的用于自动完成的值,您现在应该能够自己弄清楚。
Use the onKeyDown event like
Then your input HTML would look like:
Note that my example does not make use of the often unnecessary jQuery library.
In the actual events you would then change the style of the list items and save which value was selected by the user for autocompletion, which you should be able to figure out for yourself now.