更改下拉菜单的焦点和选择时的背景颜色

时间:2017-04-20 23:28:19

标签: html css

在我的表单中,我有多个字段,2个输入框和一个下拉列表。当我按Tab键时,我移动到下一个字段,直到我到达下拉列表。当我的标签索引到达下拉列表时,我希望它是黄色的,但是当我点击下拉列表时,它应该变成白色背景。我怎么能这样做?

select:focus{
  background-color: yellow;
  color: black;
}

select:hover{
  background-color: white;
}
<!DOCTYPE html>
<html>

<body>

First name: <input type="text" name="FirstName" value="Mickey"><br>
Last name: <input type="text" name="LastName" value="Mouse"><br>

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
  
</body>
</html>

enter image description here

1 个答案:

答案 0 :(得分:1)

你需要一些轻量级的JavaScript来解决这个问题,但这应该让你开始:

CSS

    .form-row {
      padding: 8px;
    }

    /* when the select is focused, change the bg color */
    select:focus {
      background: yellow
    }

演示标记:

    <div class="form-row">
      <label for="text">
        Write Something:
      </label>
      <input type="text" id="text">
    </div>

    <div class="form-row">
      <label for="select">
        Choose Something:
      </label>

      <select id="select">
        <option>
          opt 1
        </option>
        <option>
          opt 2
        </option>
        <option>
          opt 3
        </option>
      </select>
    </div>

的JavaScript

    <script>
      // since clicking a select also focuses it, we need to undo
      // the focus style. here i'm adding an inline style to do this
      // but you could add a class that overwrites the focus style instead
      document.getElementById('select').addEventListener('click', function () {
        this.style.background = '#fff'
      });

      // we want to be able to get the yellow focus again
      // if we leave the select box, but re-focus it again
      // so remove the inline style on blur
      document.getElementById('select').addEventListener('blur', function () {
        this.removeAttribute('style');
      });
    </script>