样式不能在数据列表选项上工作



我试图改变悬停选项的背景颜色,但我无法在datalist中做到这一点。有什么办法可以做到这一点吗?我尝试通过给内联css,外部css,事件(onmouseover,onmouseenter,onmouseleave)

/*  React Js Code */
<input  type="text" list="browsers" />
<datalist id="browsers">
/* iterating values from array and showing in option */
<option style={{backgroundColor:'red'}} onMouseOver={e=>e.target.style.color = 'green'}  onMouseEnter={(e)=>e.target.style.background = 'red'} 
onMouseLeave={(e)=>e.target.style.background = 'black'} >{d}</option>
</datalist>

你可以使用CSS自定义数据列表,但你必须禁用/忽略OOB数据列表功能,并使用JavaScript重写该功能,结果如下:

input.onfocus = function() {
browsers.style.display = 'block';
input.style.borderRadius = "5px 5px 0 0";
};
for (let option of browsers.options) {
option.onclick = function() {
input.value = option.value;
browsers.style.display = 'none';
input.style.borderRadius = "5px";
}
};
input.oninput = function() {
currentFocus = -1;
var text = input.value.toUpperCase();
for (let option of browsers.options) {
if (option.value.toUpperCase().indexOf(text) > -1) {
option.style.display = "block";
} else {
option.style.display = "none";
}
};
}
var currentFocus = -1;
input.onkeydown = function(e) {
if (e.keyCode == 40) {
currentFocus++
addActive(browsers.options);
} else if (e.keyCode == 38) {
currentFocus--
addActive(browsers.options);
} else if (e.keyCode == 13) {
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (browsers.options) browsers.options[currentFocus].click();
}
}
}
function addActive(x) {
if (!x) return false;
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
x[currentFocus].classList.add("active");
}
function removeActive(x) {
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("active");
}
}
input {
font-size: 18px;
padding: 5px;
height: 35px;
width: 350px;
border: 1px solid #000;
outline: none;
border-radius: 5px;
color: #000;
/*   border-bottom: none; */
}
datalist {
position: absolute;
background-color: white;
border: 1px solid #000;
border-radius: 0 0 5px 5px;
border-top: none;
width: 350px;
padding: 5px;
}
option {
background-color: white;
padding: 4px;
color: #000;
margin-bottom: 1px;
font-size: 18px;
cursor: pointer;
background: #eeeeee
}
option:hover,
.active {
background-color: red;
}
<input autocomplete="off" role="combobox" list="" id="input" name="browsers">
<!-- Its important that you keep list attribute empty to hide the default dropdown icon and the browser's default datalist -->
<datalist id="browsers" role="listbox">
<option value="Chrome">Chrome</option>
<option value="Safari">Safari</option>
<option value="Microsoft Edge">Microsoft Edge</option>
</datalist>

从开发

为什么不直接给它添加一个类,并使用css:hover方法,如:

<option className="my-option" />

然后在CSS中只是

.my-option:hover{
background-color:'red';
}

相关内容

  • 没有找到相关文章

最新更新