简体   繁体   English

如何隐藏默认值 <select><option>点击下拉菜单时?

[英]How can I hide default <select> <option> when the drop-down is clicked?

I want to have a <select> element that's default chosen option is "____". 我想要一个<select>元素,默认选择的选项是“____”。 In other word's, blank. 换句话说,空白。

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 onFocus events to remove options, but that just unfocuses the element, and replaces the default option with another one. 我已经尝试使用onFocus事件来删除选项,但这只是取消了元素,并将默认选项替换为另一个。

You can leverage the hidden attribute in HTML. 您可以利用HTML中的hidden属性。 Try with this example 试试这个例子

<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 fiddle or the screenshots below. 检查这个小提琴或下面的截图。

Before clicking: 点击之前: 点击之前

After clicking: 点击后: 在此输入图像描述

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; 再次, display:none; does not work in all browsers on options ... 不适用于所有浏览器的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;
}

CSS is your friend, set display:none for 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;});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM