2012-06-15 17 views
2

我希望能夠懸停在一行上並突出顯示所有內容,但由於某些單元格具有不同的背景,因此我遇到了下面的代碼問題。tr onmouse events

<tr style="" onmouseover="this.style.background='Red';" onmouseout="this.style.background='#595959'" > 

這是好的所有細胞都具有相同的背景,但如果我點擊單元格它強調它和onmouseout="this.style.background='#595959'"總是復位。

我如何更改爲類似:

onmouseout="this.style.background='currentCellBGColor" 
+0

我會認爲它只是添加和刪除類而不是存儲和檢索特定樣式會更容易。 – j08691

回答

3

它可以用純CSS的解決方案來實現。沒有所需的JavaScript

純CSS的解決方案,在IE8 +工作的其他所有現代瀏覽器

tr:hover td { background-color:yellow } 
td.selected { background-color: green; } 
tr:hover td.selected { background-color: lime; } 

Fiddle

如果需要IE7,你需要onmosueover添加一個類的錶行,並刪除這個課程上課。

tr:hover td, tr.hover td { background-color:yellow } 
td.selected { background-color: green; } 
tr:hover td.selected, tr.hover td.selected { background-color: lime; } 
+0

不像預期的那樣工作,因爲當我將鼠標移過一個以及如何爲整行onlick設置TR bgcolor時,所有行都被高亮顯示爲黃色? –

+0

我想這是行不通的,因爲表與另一個表的td嵌套 –

+0

否如果您將CSS規則鎖定爲僅指定要突出顯示的一個表,則它將起作用。使規則更具體。對於onclick添加在行上設置類的JavaScript。 – epascarello

2

即使我同意更好地使用CSS懸停,我喜歡回答這個問題,如何用javascript做到這一點。

你可以將它保存在一個屬性,並用它來恢復它爲:

<script> 
function setBackground(me, color) 
{ 
    me.setAttribute("data-oldback", me.style.background);  
    me.style.background=color; 
} 

function restoreBackground(me) 
{ 
    me.style.background = me.getAttribute("data-oldback"); 
}  
</script> 

<tr onmouseover="setBackground(this, 'Red');" 
    onmouseout="restoreBackground(this);" 
    style="background:blue;" > 

和測試:http://jsfiddle.net/AdDgS/3/http://jsfiddle.net/AdDgS/4/