[英]How to change background color only of selected option with javascript?
當用戶選擇某個選項時,我正在嘗試更改背景顏色。 我是用 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;
}
}
但它會更改所有選項的背景顏色。
我還在互聯網上看到了如何更改所選選項的顏色,但它不會更改顯示的選項,就像這里(第一響應) - 選擇時更改選項的顏色 - JavaScript
我想為顯示的選項着色,當用戶單擊此選擇以查看其他選項時,我希望它們根本不着色。 有任何想法嗎?
您必須訪問所選選項並更改背景
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>
像這樣嘗試。
我為option
背景添加了一個 css。 在 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>
嘗試這個
$('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.