gpt4 book ai didi

javascript - 下拉菜单为自定义文本添加颜色

转载 作者:行者123 更新时间:2023-12-03 02:36:47 27 4
gpt4 key购买 nike

我使用从数据库获取的下拉列表,并显示

2 号 - 缺货尺寸 4 - 库存尺码 5 - 缺货

如何通过js为缺货文本添加红色,为库存文本添加绿色?

我的下拉菜单:

<select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select">
<option><?php echo $this->__('Choose an Option...') ?></option>
</select>

最佳答案

你所要求的实际上是很难做到的。根据 HTML 规范, <option> 标签只能包含文本。这意味着您无法添加 <span>或者只定位“有货”/“缺货”文本的好东西。

话虽如此,您可以定位 <option> 的集合。元素本身,控制颜色的最简单方法是分配每个 <option>一个class同时通过 PHP 输出它们。然后您可以使用 .getElementsByClassName() 来定位它们,循环它们并通过 .style.color 设置文本颜色样式

var in_stock = document.getElementsByClassName('in_stock');
var out_of_stock = document.getElementsByClassName('out_of_stock');

for (var i = 0; i < in_stock.length; i++) {
in_stock[i].style.color = 'green';
}

for (var i = 0; i < out_of_stock.length; i++) {
out_of_stock[i].style.color = 'red';
}
<select>
<option class="in_stock">Size 2 - In Stock</option>
<option class="out_of_stock">Size 5 - Out Of Stock</option>
</select>

请注意,设置 <option> 的颜色元素不设置默认选择颜色。为此,您需要定位 <option>直接标记,可以使用 .getElementsByTagName() 来完成。您需要将其颜色设置为第一个 <option>默认情况下,以及选择更改时的选定选项:

var in_stock = document.getElementsByClassName('in_stock');
var out_of_stock = document.getElementsByClassName('out_of_stock');

for (var i = 0; i < in_stock.length; i++) {
in_stock[i].style.color = 'green';
}

for (var i = 0; i < out_of_stock.length; i++) {
out_of_stock[i].style.color = 'red';
}

/* Default <select> styling */
var the_select = document.getElementsByTagName('select')[0];
the_select.style.color = document.getElementsByTagName('option')[0].style.color;

/* Further <select> styling */
the_select.onchange = function() {
the_select.style.color = the_select.options[the_select.selectedIndex].style.color;
}
<select>
<option class="in_stock">Size 2 - In Stock</option>
<option class="out_of_stock">Size 5 - Out Of Stock</option>
</select>

希望这有帮助!

关于javascript - 下拉菜单为自定义文本添加颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48509673/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com