[英]How to use javascript or jquery to get keyboard input when html drop down menu is show?
I want to get the input using javascript or jquery when user press the keyboard. 我想在用户按下键盘时使用javascript或jquery获取输入。 It is possible when the drop down menu is not show. 下拉菜单不显示时有可能。 When the drop down menu is show, onkeypress will not be fired. 显示下拉菜单时,不会触发onkeypress。
<html>
<body>
<select id="test" onkeypress="sayHello()">
<option value="1">1234</option>
<option value="5">5678</option>
</select>
</body>
<script>
function sayHello(){
alert("Hello");
}
</script>
</html>
I think this is not possible with the default select-dropdown, because the opened dropdown-menu is created on top of the browser window and not actually part of the document. 我认为默认选择下拉菜单是不可能的,因为打开的下拉菜单创建在浏览器窗口的顶部,而不是文档的一部分。
You could use/build some kind of replacement that renders a custom dropdown menu with html-elements inside the document and then capture all the events you want. 您可以使用/构建某种替换,以使用文档内部的html元素呈现自定义下拉菜单,然后捕获所需的所有事件。
For example take a look at Select2 . 例如看一下Select2 。 But there are also plenty other libraries. 但是,还有许多其他库。
Here is an example that uses select2 and only alerts if a keydown-event happens and the dropdown is open: 这是一个使用select2的示例,并且仅在发生keydown事件并且下拉列表处于打开状态时才发出警报:
$(document).ready(function() { $('#example').select2({ minimumResultsForSearch: 99 }); let isDropdownOpen = false; $('#example').on('select2:open', function(event) { isDropdownOpen = true; }); $('#example').on('select2:close', function(event) { isDropdownOpen = false; }); $(document).on('keydown', function(event) { if (isDropdownOpen) { event.preventDefault(); alert('Hello!'); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script> <select id="example" name="example"> <option value="1234">1234</option> <option value="5678">5678</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.