2015-05-01 41 views
0

大家好,請有人幫忙。我在div中有一個基本的HTML代碼表,我想在鼠標移過行時更改background colour。我已經用我附上的代碼正常工作。但是,如果div中的內容是動態的,並且在頁面運行後發生更改/加載,我無法更改background colourjquery對動態div進行更改

$(document).ready(function() { 
    $("tr").mouseover(function() { 
     $(this).css({ 
      "background-color": "red" 
     }); 
    }) 
}); 
+1

你爲什麼不使用CSS? – MrUpsidown

回答

0

最好的方法是使用CSS。

<style type="text/css"> 
tr:hover 
{ 
    background-color:red; 
} 
</style> 

如果你想使過渡更平滑,可以用:

$(document).ready(function() { 
    $("tr").on("hover", function() { 
     $(this).css({ "background-color","red"}); 
    }) 
}); 

這必將幫助,如果您有:

tr {  
    -webkit-transition: background-color .1s ease-in-out; 
    -moz-transition: background-color .1s ease-in-out; 
    -o-transition: background-color .1s ease-in-out; 
    -ms-transition: background-color .1s ease-in-out; 
    transition: background-color .1s ease-in-out; 
} 
+0

只是添加到這個答案,如果你已經在被徘徊的行中的單元格上有特定的背景顏色,那麼這個答案將不會覆蓋該顏色。如果你想,你可以這樣做:'tr:hover td {background-color:red; }' – wf4

+0

我不這麼認爲。我做了很多次。它取代了當前的顏色。 – ShahiM

+0

在這裏你可以看到@ShahiM - 表1是你的解決方案,表2是我的。 http://jsfiddle.net/17d592bd/ – wf4

-1

可以按如下方式編寫相同使用正確選擇器。

<style type="text/css"> 
selector:hover 
{ 
    background-color:red; 
} 
</style> 
-1

使用CSS:

<style type="text/css"> 
#divId tr:hover 
{ 
    background-color:red; 
} 
</style> 

使用jQuery:

$(document).ready(function() { 
    $("tr").mouseover(function() { 
     $(this).attr("style","background-color:red"); 
    }) 
}); 
-1

最好的辦法是使用CSS

<style type="text/css"> 
tr:hover 
{ 
    background-color:red; 
} 
</style> 
您也可以如下做到這一點

如果您確實想使用jQuery,請在創建並追加行後添加該屬性。

$(document).ready(function() { 
    var table = $("#table"); //select the table.let its id 'table' 
    var tr = $("<tr>"); // creating row 
    $(table).append(tr); // appending 
    $(tr).mouseover(function() { // applying style 
     $(this).css({ 
      "background-color": "red" 
     }); 
    }) 
});