2010-12-23 47 views
0

這可能是一個非常明顯的問題,我剛剛停留了一段時間,無法在網上找到任何東西。現在,我有以下(非常簡單)HTML DIV:onmouseout - 恢復爲css class color

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

在我的webapp,我動態改變類的div(選中和未選中改變div的背景色之間)。有沒有辦法將onmouseout backgroundColor更改爲類的默認背景顏色(如樣式表中定義的那樣)?

換句話說,我在尋找類似

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

這可能嗎?這似乎幾乎每個網站都必須(除非他們想改變兩個地方的顏色,而不是隻是樣式表),但沒有任何在線指南似乎解決它。

非常感謝!

回答

5

您應該使用一個不顯眼的方式,加入&刪除CSS類:

CSS:

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

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

做,這是一類的最好方式。

首先,創建一個yellowBg類:

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

然後使用jQuery它適用於鼠標懸停,將其取下鼠標移開時:

$(document).ready(function(){ 
    $('.unselected').mouseover(function(){ 
     $(this).addClass('yellowBg'); 
    }).mouseout(function(){ 
     $(this).removeClass('yellowBg'); 
    }); 
}); 
1
$('.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 
}); 
0

設置屬性,以一個空字符串從style屬性外部還原到級聯。

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

(不過,在一般情況下,儘量保持造型的樣式而不是樣式屬性和JS(使用JS設置類代替),並儘量保持JS與事件處理外部文件正在悄悄地應用,而不是使用固有事件屬性)