Why is last select option always shown, even when

2019-08-03 17:22发布

问题:

While answering another question I came across this weird bug. A quick search has not found an existing question, so here goes:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/93D3h/4/

<select>
    <option>Item1</option>
    <option>Item2</option>
    <option>Item3</option>
    <option class="hidden">Item4</option>
    <option class="hidden">Item5</option>
</select>

CSS:

.hidden {
    display: none;
}

Q: Why is Item5 always shown, even though it is styled as hidden? Item4 is not visible. Note: I am testing this in the latest version of Chrome.

Update:

Different people are getting different results on different browsers. The following (from answer below) works on Chrome but not on the latest IE (both Item4 and Item5 are shown):

.hidden {
    visibility: hidden;
}

Turns out this problem has been hit before (no surprise): How to hide a <option> in a <select> menu with CSS? but the surprising thing is that browsers do not support removing options with styling. Go figure!

回答1:

Styling OPTION elements using CSS is not a reliable solution because user agents implement this very differently and non-standard. I wouldn’t call this a bug, because there is no style attribute definition in the specs for the OPTION element: http://www.w3.org/TR/html401/interact/forms.html#h-17.6

You could use the disabled property instead:

<select>
    <option>Item1</option>
    <option>Item2</option>
    <option>Item3</option>
    <option disabled>Item4</option>
    <option disabled>Item5</option>
</select>

And/or use JavaScript to manipulate the DOM. A pretty good start would be to target the disabled elements for semantic fallback:

[].forEach.call(document.querySelectorAll('*[disabled]'), function(element) {
  element.parentNode.removeChild(element)
})

Demo: http://jsfiddle.net/93D3h/15/

Or use jQuery: $('[disabled]').remove()

Update: Based on the comments and the new requirements, I made a small toggle demo here using data attributes instead: http://jsfiddle.net/95Ed5/



回答2:

try this code

.hidden {
    visibility: hidden;
}

Designed to display or hide the element, including a frame around it and background. When you hide an element, although it is not displayed at a place that takes the element remains on him. If the intended output of different elements in the same place on the screen to bypass this feature should use absolute positioning, or use the property display.



回答3:

Your best shot (cross browser solution) would be to use jquery to store the hidden values. It can be done it regular javascript too.

var array = $(".hidden");
$(".hidden").remove();

And then when you need them you get them in array

Update

Here is the updated fiddle : http://jsfiddle.net/93D3h/16/
I added two buttons to show what you could do with the stored hidden values (add them back to the select, or remove them)