问题
I have a simple input like that
<input id="name-srch" type="text" data-type="string">
And my js (simplified)
$('#name-srch').autocomplete({
source: function (request, response) {
$.ajax({
url: ...,
data: ...,
success: function (data) {
// note that 'data' is the list of elements to display
response(data)
}
});
},
select: function (event, ui) {
// do some stuff
return false
},
focus: function (event, ui) {
console.log(ui.item.Name) // just to see if the focus event is triggered, and it is
return false
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.Name + "</a>")
.appendTo(ul);
};
JQuery Autocomplete fill the <ul>
with the <li>s
as it should and triggers a focus event on mouseover or down/up arrow key as it should.
The problem is that I want to apply a particular style to the focused item, so in my CSS I have something like that
.ui-state-focus {
background-color: red;
font-weight: bold;
}
There is my problem, the focused item never takes the ui-state-focus
class and therefore it never takes the defined style.
What am I doing wrong :( ?
EDIT : I already tried to add in my CSS something like
.ui-menu-item:hover {
background-color: red;
font-weight: bold;
}
Indeed it does the trick for the hover, but not for the focus via down/up arrow key. Moreover, I don't really like it, I would prefer to make it work the way it's meant to if I can...
回答1:
I managed to make it work.
For some reason JQuery Autocomplete doesn't apply the ui-state-focus
on the focused <li>
but does apply the ui-state-active
class on the <a>
inside the focused <li>
. Therefore I can apply the wanted style via
.ui-state-active {
background-color: red;
font-weight: bold;
}
I still have no idea why it applies a class only on the <a>
inside and not on the <li>
as describe on all the documentations but hey, it works...
回答2:
try this selector:
.ui-menu .ui-menu-item:hover, .ui-state-hover, .ui-widget-content .ui-state-hover, .ui-state-focus, .ui-widget-content .ui-state-focus {
background-color: red;
font-weight: bold;
}
There is a JSFIDDLE from another question that I've answered. Just check the last line in the CSS definition:
https://jsfiddle.net/g4bvs0we/5/
Update: I've updated the source code and jsfiddle link. I guess there were issue with CSS rule priority and putting more specific rule should help.
Can you please let me know if this works?
回答3:
Perhaps a different way to skin this is to add a class to the li in the javascript then add in something like this
.li-hover:hover {
background-color: red;
font-weight: bold;
}
Might do the trick, as a guess I think because you are setting a different render jquery autocomplete isn't doing the hover for you.
回答4:
I fixed this by using:
.ui-autocomplete {
.ui-state-focus {
border: 0px !important;
background: #yourcolour !important;
color: #yourcolour !important;
}
}
来源:https://stackoverflow.com/questions/39127815/jquery-autocomplete-cant-apply-style-on-the-focused-item