How to change the background color of a select option on hover

霸气de小男生 提交于 2021-01-29 13:36:26

问题


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;
  }

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


回答1:


you can try something like this:

#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>



回答2:


Use background or background-color to change the background color of an element. color is for text color, not background color.

div {
  background: #ffffff; /* equivalent to background-color */
}
div:hover {
  background: #000;
  color: #fff;
}
<div>Hover!</div>



回答3:


The element is notoriously difficult to style productively with CSS. You can affect certain aspects like any element. (Source: MDN). To produce a consistent appearance across all browsers, I suggest that you use libraries like Select2, which appends an additional div below the dropdown, essentially covering the original dropdown. This way, it allows a much more flexible styling since you're essentially styling the newly appended div.



来源:https://stackoverflow.com/questions/61232273/how-to-change-the-background-color-of-a-select-option-on-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!