javascript 在 <option> 标签内添加 span 并设置样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25199135/
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
Add span inside <option> tag and style it
提问by Filip Bartuzi
I would like to add span before text inside <option>
tag and style it (it should represent color in select menu). However it does't seem to work...
我想在<option>
标签内的文本之前添加跨度并为其设置样式(它应该代表选择菜单中的颜色)。然而它似乎不起作用......
How to make this piece of code working?
如何使这段代码工作?
JsFiddle: http://jsfiddle.net/bartuz/08e0L9j2/2/
JsFiddle:http: //jsfiddle.net/bartuz/08e0L9j2/2/
It seems example above does work in Firefox only... what about other browsers?
上面的例子似乎只在 Firefox 中工作......其他浏览器呢?
采纳答案by Alastair Campbell
This will depend on your web browser. In the latest version of Firefox, it works fine. However, it doesn't work in the latest version of Internet Explorer.
这将取决于您的网络浏览器。在最新版本的 Firefox 中,它运行良好。但是,它在最新版本的 Internet Explorer 中不起作用。
Your question is a bit loaded - and I suspect that's why it got downvoted - you are asking why it's not working, rather than how to get it to work.
你的问题有点重——我怀疑这就是它被否决的原因——你问的是为什么它不起作用,而不是如何让它起作用。
It's not working because it's not really a supported feature of selectboxes (yet!)
它不起作用,因为它不是选择框真正支持的功能(还!)
I'd suggest you look into using JavaScript to achieve the same result (and specifically, the jQuery UI selectmenu) which should support this type of 'advanced' select box.
我建议您考虑使用 JavaScript 来实现相同的结果(特别是jQuery UI selectmenu),它应该支持这种类型的“高级”选择框。
回答by Red
You shouldn't rely on the fact that your hack works on Firefox, does not mean it should on Chrome too.
你不应该依赖你的 hack 在 Firefox 上工作的事实,并不意味着它也应该在 Chrome 上工作。
Anyway, styling selects was always frustrating and there's no easy way to customize native select elements.
无论如何,样式选择总是令人沮丧,并且没有简单的方法来自定义本机选择元素。
If you're looking for a way to style the native select elements, maybe this will help:
https://catalin.red/making-html-dropdowns-not-suck/
如果您正在寻找一种方式来设置本机选择元素的样式,也许这会有所帮助:https:
//catalin.red/making-html-dropdowns-not-suck/
回答by Zee
An option element isn't allowed to have child elements. I've extended your same answer, but instead applied the background color to the option element as demonstrated in this jsfiddle link: https://jsfiddle.net/go4zee/6L0jjjoa/
选项元素不允许有子元素。我已经扩展了您的相同答案,而是将背景颜色应用于选项元素,如此 jsfiddle 链接所示:https://jsfiddle.net/go4zee/6L0jjjoa/
$('#tag_item_color option').each(function () {
var color = $(this).text();
console.log(color);
$(this).closest("option").css({"background-color":color});
})