首页 > 解决方案 > 如何根据用户选择的 HTML 选项更改选择的背景颜色?

问题描述

当用户选择红色选项然后选择全红色的背景时,我想更改选择的背景颜色。当用户选择粉红色时,选择背景颜色为粉红色。尝试解决这个问题大约 3 个小时。

我已经尝试了 addEventListener,也在选择中进行了 onchange,但没有工作。

const select = document.querySelector('#select');

select.addEventListener('change', (event) => {
  console.log(event.target.value)

  if (event.target.value = 'red') {
    select.style.background = 'red';
  }
  else if (event.target.value = 'pink') {
    select.style.background = 'pink'
  }
  else {
    select.style.background = 'yellow'
  }
});
<select id="select">
  <option value="red">red</option>
  <option value="pink">pink</option>
  <option value="yellow">yellow</option>
</select>

在控制台中,我可以看到 event.target.value = red、pink、yellow。选择的颜色只改变一次红色,如果你选择另一个选项 - 什么也不会发生。编辑器或控制台中没有错误。希望有人可以帮助我,非常感谢。

标签: javascripthtmlselect

解决方案


document.querySelector是一种方法,因此您应该将其作为函数调用:

document.querySelector('#select')

此外,您可以直接将选择值写入背景颜色,这样您就不需要 if/else 条件:

select.style.background = event.target.value

最终版本可能如下所示:

const select = document.querySelector('#select');

select.addEventListener('change', (event) => {
 select.style.background = event.target.value
});
<select id="select"> 
  <option value="red">red</option>
  <option value="pink">pink</option>
  <option value="yellow">yellow</option>
</select>


推荐阅读