为什么最后一个选择选项总是显示,即使在样式化 [英] Why is last select option always shown, even when styled out

查看:105
本文介绍了为什么最后一个选择选项总是显示,即使在样式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答另一个问题时,我遇到了这个奇怪的错误。快速搜索没有找到现有问题,所以这里:

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

<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;
}

问:为什么 Item5 始终显示,即使它的样式为隐藏? Item4 不可见。

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.

不同的人会有所不同结果在不同的浏览器。以下(来自下面的回答)适用于Chrome,但在最新的IE上不显示 (Item4和Item5都显示):

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;
}

原来这个问题已经被打了=http://stackoverflow.com/questions/9234830/how-to-hide-a-option-in-a-select-menu-with-css>如何隐藏< option>在< select>菜单与CSS?,但令人惊讶的是,浏览器支持删除选项与样式。 Go图!

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!

推荐答案

使用CSS的样式 OPTION 解决方案,因为用户代理实现这是非常不同和非标准。我不会调用这个bug,因为 OPTION 元素的规范中没有 style 属性定义: http://www.w3.org/TR/html401/interact /forms.html#h-17.6

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

您可以使用 disabled p>

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>

和/或使用JavaScript来操纵DOM。一个很好的开始是定位 disabled 元素用于语义回退:

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)
})

演示: http ://jsfiddle.net/93D3h/15/

或使用jQuery: $('[disabled]')。remove ()

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

更新:
根据评论和新要求,此处使用数据属性切换演示: http://jsfiddle.net/95Ed5/

这篇关于为什么最后一个选择选项总是显示,即使在样式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆