Temporary Onmouseover
Css "hover" selector applys a temporary style to an element, but it isn't definitive:
div:hover {
background-color: red;
}
I can do the sam开发者_运维技巧e thing with javascript but it is a bit complicate and impossible for several elements:
var elem = document.getElementsByTagName ("div")[0];
elem.onmouseover = function () {
this.style.backgroundColor = "red";
}
elem.onmouseout = function () {
this.style.backgroundColor = "transparent";
}
Is there a better way ? Something like this:
document.getElementsByTagName ("div")[0].ontemporarymouseover = function () { // LoL
this.style.backgroundColor = "red";
}
Thanks
No, there is no way to apply styles that go away by themselves.
Eventhough the CSS contains only one definition, it actually corresponds to the two state changes that triggers onmouseover
and onmouseout
. When the pointer enters the element, the :hover
pseudo class is added to it making the CSS rule apply. When the pointer leaves the element, the :hover
pseudo class is removed making the CSS rule no longer apply.
In JavaScript this behaviour can only be handled by listening to the mouseover
and mouseout
DOM events, as you did in your second example. However it is recommended to handle hovering styles with CSS, as in your first example.
// jQuery 'Temporary mouseevents'
$("element").bind
({
mouseover:
function ()
{
},
mouseout:
function ()
{
}
});
$("element").unbind('mouseover mouseout');
I hope this is a good approach for what you need.
I believe that if you use the jQuery JavaScript framework, you can do this:
$('div:first').hover(function(){
$(this).css('background-color','red');
},function(){
$(this).css('background-color','white');
});
精彩评论