如何在悬停时更改选择选项的背景颜色

2022-01-19 00:00:00 frontend javascript html css

我想更改悬停时选择选项的背景颜色,我尝试了以下规则,但也没有用:

I want to change the background color of the select options on hover and i have tried the followed rules but it didn't worked either:

 select option {
    color: #fff;
  }
  select option:hover {
    color: #000;
    box-shadow: inset 20px 20px #fff;
  }

我必须应用哪些规则才能达到这种效果?JS 是否识别选项元素中的悬停?

What rules i have to apply to achieve that effect? Does JS recognize a hover in a option element?

推荐答案

你可以试试这样的:

#select {
  width: 100px;
}

select:hover {
  color: #444645;
  background: green;
  /* hover on select */
}

select:focus>option:checked {
  background: yellow;
  /* selected */
}

<select id="select">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

如果你需要选项列表的作弊码,那么你可以试试这个:

If you need a cheat code for the options list then you can try this:

#select {
  width: 100px;
}

select:hover {
  color: #444645;
  background: green;
  /* hover on select */
}

select option {
  color: #444645;
  background: red;
  /* hover on select */
}

option:hover {
  /*optional rendered */
  background-color: teal;
}

<select onfocus='this.size=9;' onblur='this.size=0;' onchange='this.size=1; this.blur();' id="select">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
  <option value="4">Four</option>
  <option value="5">Five</option>
  <option value="6">Six</option>
  <option value="7">Seven</option>
  <option value="8">Eight</option>
  <option value="9">Nine</option>
</select>

相关文章