Javascript 单击下拉菜单时如何隐藏默认的 <select> <option> ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27350843/
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
How can I hide default <select> <option> when the drop-down is clicked?
提问by Drazzah
I want to have a <select>element that's default chosen option is "____". In other word's, blank.
我想要一个<select>默认选择的元素是“____”。换句话说,空白。
When the drop-down is focused, I want the "____" option to not be in the options that can be selected. That way the user has to choose something other than "____" as their option.
当下拉集中时,我希望“____”选项不在可以选择的选项中。这样,用户必须选择“____”以外的其他选项作为他们的选项。
Does that make sense?
那有意义吗?
Illustrations
插图
Closed:
关闭:


Opened:
打开:


As you can see, the option "___" is not in the list when it is being selected. That is my desired end result.
如您所见,选项“___”在被选中时不在列表中。这就是我想要的最终结果。
I've tried using onFocusevents to remove options, but that just unfocuses the element, and replaces the default option with another one.
我曾尝试使用onFocus事件来删除选项,但这只会使元素失去焦点,并将默认选项替换为另一个选项。
采纳答案by rfornal
To hide the default option, allowing the others to show, there are a few ways to go.
要隐藏默认选项,允许其他选项显示,有几种方法。
Unfortunately, you can't hide option elements in all browsers.Again, display:none;does not work in all browsers on options...
不幸的是,您无法在所有浏览器中隐藏选项元素。同样,display:none;不适用于所有浏览器options...
In the past when I have needed to do this, I have set their disabled attribute, like so...
过去当我需要这样做时,我已经设置了他们的禁用属性,就像这样......
$('option').prop('disabled', true);
I've then used the hiding where it is supported in browsers using this piece of CSS...
然后,我使用这段 CSS 在浏览器支持的地方使用了隐藏...
select option[disabled] {
display: none;
}
回答by Nobita
You can leverage the hiddenattribute in HTML. Try with this example
您可以利用hiddenHTML 中的属性。试试这个例子
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check this fiddleor the screenshots below.
检查这个小提琴或下面的屏幕截图。
回答by Collector
CSSis your friend, set display:nonefor the option you want to hide.
CSS是您的朋友,设置display:none为您要隐藏的选项。
<select>
<option style="display:none" selected="selected" value=""> </option>
<option value="visi1">Visible1</option>
<option value="visi2">Visible2</option>
<option value="visi3">Visible3</option>
</select>
Here's an extra with jQuery that will ensure the first option of any select is invisible:
这里有一个额外的 jQuery 可以确保任何选择的第一个选项是不可见的:
$('select:first-child').css({display:none;});

