[英]How to change background color only of selected option with javascript?
I'm trying to change background color when user selects some option.当用户选择某个选项时,我正在尝试更改背景颜色。 I did it with onchange function that simply contains:
我是用 onchange 函数完成的,它只包含:
function colorSameValues(select, color){
for (var i=0; i<selects.length; i++){
if (selects[i].value ==='') selects[i].style.backgroundColor='';
if (selects[i].value === select.value) selects[i].style.backgroundColor=color;
}
}
but it changes background color of all options.但它会更改所有选项的背景颜色。
I also saw on the internet how to change color of selected option, but it doesn't change option that is displayed, like here (first response) - Change the color of an option when selected - JavaScript我还在互联网上看到了如何更改所选选项的颜色,但它不会更改显示的选项,就像这里(第一响应) - 选择时更改选项的颜色 - JavaScript
I would like to color displayed option, and when user clicks on this select to see other options I would like them not to be colored at all.我想为显示的选项着色,当用户单击此选择以查看其他选项时,我希望它们根本不着色。 Any ideas?
有任何想法吗?
You have to access the selected option and change the background您必须访问所选选项并更改背景
function a(e) { e.options[e.selectedIndex].style.backgroundColor=e.options[e.selectedIndex].textContent; console.log(e.options[e.selectedIndex].textContent) }
<select onchange="a(this)"> <option>Red</option> <option>Blue</option> <option>Green</option> </select>
Try like this.像这样尝试。
I added a css for option
background.我为
option
背景添加了一个 css。 and in JS, I set the background for select box.在 JS 中,我设置了选择框的背景。
function changeColor(colorParam) { let color = colorParam.value.toLowerCase(); var optionElement = document.getElementById('rgb'); optionElement.style.background = color; };
option{ background:#fff; }
<select onchange="changeColor(this);" class="color" id="rgb"> <option id="red" value="Red">Red</option> <option id="green" value="Green">Green</option> <option id="blue" value="Blue">Blue</option> <option id="white" value="White">White</option> <option id="pink" value="Pink">Pink</option> </select>
Try this尝试这个
$('button#first').on('click', function() {
$('#mySelect option').attr('selected', false); // clears all
var options = [];
for (var i=0; i < $('#mySelect optgroup[label="first"] option').length; i++){
options.push($('#mySelect optgroup[label="first"] option')[i].value);
};
$('#mySelect').val(options);
$("#mySelect").trigger("chosen:updated"); // updates chosen
return false; // returns false not to post the surrounding form
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.