开发者

onmouseout - revert back to css class color

This might be a really obvious question, I've just been stuck on it for a while and can't find anything on the web. Right now I have the following (extremely simple) html div:

<div class="unselected"
     onmouseover="this.style.backgroundColor='yellow'"
     onmouseout="this.style.backgroundCo开发者_JAVA技巧lor='??' >

In my webapp, I dynamically change the class of the div (between selected and unselected to change the background-color of the div). Is there a way to change the onmouseout backgroundColor to be the default background-color of the class (as defined in the stylesheet)?

In other words, I am looking for something like

onmouseout="this.style.backgroundColor=this.class.default-background-color

Is this possible? This seems almost necessary for every site (unless they want to change colors in two places instead of just the stylesheet), yet no guide online seems to address it.

Thanks a lot!


You should use an unobtrusive way, adding & removing a css class:

css:

.yellow {
    background-color: yellow !important;
}

$(function() {
    $('div.unselected').hover(function() {
        $(this).addClass('yellow');
    }, function() {
        $(this).removeClass('yellow');
    });
});


The nicest way to do this is with a class.

First, create a yellowBg class:

.yellowBg {
    background-color: #0ff;
}

Then use jQuery to apply it on mouseover and remove it on mouseout:

$(document).ready(function(){
    $('.unselected').mouseover(function(){
        $(this).addClass('yellowBg');
    }).mouseout(function(){
        $(this).removeClass('yellowBg');
    });
});


$('.unselected').hover(function(){ //mouseout
    // if not has data-origColor
    if(!$(this).data('origColor')) 
        $(this).data('origColor', this.style.backgroundColor);

    this.style.backgroundColor = 'yellow';
}, function(){ //mouseover
    this.style.backgroundColor = $(this).data('origColor'); //pull from data
});


Set a property to an empty string to revert back to the cascade from outside the style attribute.

<div class="unselected"
 onmouseover="this.style.backgroundColor='yellow'"
 onmouseout="this.style.backgroundColor='' >

(But, in general, try to keep the styling in stylesheet rather than style attributes and JS (use JS to set classes instead) and try to keep the JS in external files with event handlers being applied unobtrusively instead of using the intrinsic event attributes)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜