I am essentially highlighting each li
when clicked, and want to "un-highlight" the clicked li
when clicking elsewhere or tabbing out (by effecting the background-color
property).
This behavior would essentially be emulating <select>
in its' highlighting behavior... I'm not using select
though, because I want to nest HTML inside the listed items -- you can't do this with <option>
.
I'm attempting to use onblur
, which is not working...
#list {
list-style-type: none;
}
...here is the CSS:
function getEventTarget(e) {
e = e || window.event;
return e.target || e.srcElement;
}
function highlightSelection(selection) {
alert("It worked!");
$(selection).css("background-color","#FFFF00");
}
// this function is not being triggered:
function removeHighlight(selection) {
$(selection).css("background-color","none");
}
var ul = document.getElementById("list");
ul.onclick = function(event) {
var target = getEventTarget(event);
highlightSelection(target);
};
// this event is not working:
ul.onblur = function(event) {
var target = getEventTarget(event);
removeHighlight(target);
};
...and here is the jQuery/javascript:
function getEventTarget(e) { e = e || window.event; return e.target || e.srcElement; } function highlightSelection(selection) { alert("It worked!"); $(selection).css("background-color","#FFFF00"); } // this function is not being triggered: function removeHighlight(selection) { $(selection).css("background-color","none"); } var ul = document.getElementById("list"); ul.onclick = function(event) { var target = getEventTarget(event); highlightSelection(target); }; // this event is not working: ul.onblur = function(event) { var target = getEventTarget(event); removeHighlight(target); };
Since you're already using JQuery...
<ul id = "list">
<li tabindex="1">asdf</li>
<li tabindex="2">qwerty</li>
<ul>
var ul = $("#list");
ul.on('click focus','li',function(){
$(this)
.css("background-color","#FFFF00")
.siblings().css('background','');
}).on('blur','li',function(){
$(this).css('background','');
});
I wasn't sure of what effect you wanted when you tab away from a list item... It seems you would just want to leave it highlighted. You can add focus-ability to your list items by giving them a tabindex
attribute.
The li
s don't blur because they don't focus. Try with mouseout
or mouseleave
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.