javascript 在焦点上打开 Select 元素的下拉菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7947936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open the dropdown of a Select element on focus
提问by user1021111
Possible Duplicate:
How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?
Is it possible to open the drop down list of a Select element when the Select element gets focus?
当 Select 元素获得焦点时,是否可以打开 Select 元素的下拉列表?
I know it automatically focuses when you click it ... but I want it to work when you tab it too.
我知道当你点击它时它会自动聚焦......但我希望它在你点击它时也能工作。
回答by Dany Khalife
Unfortunately the answer for your question is simply "No, its not possible with the current HTML and Javascript controls"
不幸的是,您的问题的答案只是“不,当前的 HTML 和 Javascript 控件无法实现”
However, if you use jQuery and this plugin (https://github.com/fnagel/jquery-ui/wiki/Selectmenu) for select menus i believe you could do :
但是,如果您使用 jQuery 和此插件 (https://github.com/fnagel/jquery-ui/wiki/Selectmenu) 来选择菜单,我相信您可以:
$("#idofSelect").selectmenu("open");
Also another alternative for your idea, but maybe not as fancy:
也是您想法的另一种选择,但可能没有那么花哨:
document.getElementById("idOfSelect").setAttribute("size", 5);
What this does is simply make it a multiline select, so in some way it displays the options... You could do this on focus, and then do another event on click where you reset its size to 1 and stop the event propagation (so that onfocus doesn't get called after..) but like i said, this is THAT professional, so either live with your select the way it is, or switch to jQuery select menus and have fun opening and closing them dynamically at your will :)
这只是简单地使它成为一个多行选择,所以它以某种方式显示选项......您可以在焦点上执行此操作,然后在单击时执行另一个事件,将其大小重置为 1 并停止事件传播(所以之后不会调用 onfocus ..) 但就像我说的那样,这太专业了,所以要么按照你的选择方式生活,要么切换到 jQuery 选择菜单,尽情享受随意打开和关闭它们的乐趣: )
回答by Crashdesk
As a starting point, if using JQuery you could use the trigger function eg If your select box has an id of "names" simply call $('#names').trigger('click');
作为起点,如果使用 JQuery,您可以使用触发器函数,例如,如果您的选择框的 id 为“名称”,只需调用 $('#names').trigger('click');