当改变背景颜色的html选择,第一个选项改变它

When changing background-color of html select, first option changes with it

本文关键字:改变 第一个 选择 选项 html 背景 颜色      更新时间:2023-09-26

我试图创建一个HTML表单与几个选择元素,有颜色的选项供用户选择颜色。我能够创建一个概念验证文档,它成功地更改了选择的background-color属性,以匹配所选选项的background-color。然而,第一个选项(其值为"none",因此应该没有bg颜色)也会随着select元素而改变。我不知道如何解决这个问题,它有点烦人。

概念验证文档的源代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Drop Down List Test</title>
  <style>
    select
    {
      border: 2px solid black;
      width: 120px;
      height: 30px;
    }
    select option { height: 30px; }
    [value=none]  { background-color: transparent; }
    [value=red]   { background-color: red  ; }
    [value=green] { background-color: green; }
    [value=blue]  { background-color: blue ; }
  </style>
  <script>
    /*
    This function is called by the onChange event in the form element below
    The only input argument is a DOM reference to the form argument itself
    If the value of the form element is NOT "none",
        Then the background color will be whatever the user selected
    Else, the background color is set to transparent
    */
    function changeSelectBGColor(form_element)
    {
      if(form_element.value != "none")
           form_element.style.backgroundColor = form_element.value;
      else form_element.style.backgroundColor = "transparent";
    }
  </script>
</head>
<body>
  <form>
    <!--
    When the user selects a color value in this drop-down, 
      the background color changes to reflect the user's selection
    The onchange attribute calls the JS function defined above
    -->
    <select onchange="changeSelectBGColor(this)">
      <option value="none" ></option>
      <option value="red"  ></option>
      <option value="green"></option>
      <option value="blue" ></option>
    </select>
  </form>
</body>
</html>

请原谅我奇怪的OCD间隔约定。它使源代码更具可读性&

谁有什么想法,如何使这个工作?如果可能的话,我希望避免使用jQuery,以保持简单和轻量级,但我愿意接受使用jQuery的建议。

您需要设置元素的初始颜色。将元素设置为透明将从最近的背景色设置中提取,而不是从初始设置中提取。例如,设置初始的/"none" background-color元素来匹配文档的实际背景色。