我已经在一个表上实现了数据表,其中某些行应该具有与其他行不同的背景颜色,由 CSS类标识。
每当指针悬停在行上时,我想更改行的背景颜色。为此,我使用以下代码。
$(document).ready(function () {
oTable = $('#mytable').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"fnRowCallback": function () {
// Assigning colors to inactive rows
$('tr').each(function () {
if ($(this).hasClass('inactive')) {
$(this).css('background', '#fccfcf');
$(this).find('.sorting_1').each(function () {
$(this).css('background', '#fccfcf');
});
}
});
},
"aoColumns": /*3 column table*/
[{
"bSearchable": false,
"bSortable": false
},
null, null]
});
// Dynamically binding hover function to change color and pointer on mouse hover
oTable.$('tr').hover(function () {
previousBackground = $(this).css('background-color');
$(this).css('background-color', '#e2ebff');
$(this).find('.sorting_1').each(function () {
$(this).css('background', '#e2ebff');
});
$(this).css('cursor', 'pointer');
}, function () {
$(this).css('background-color', previousBackground);
$(this).find('.sorting_1').each(function () {
$(this).css('background', previousBackground);
});
});
});
首次加载时,表格会显示所需的结果。然而,当我对任何列进行排序时,一切都会崩溃。有些列正确显示背景颜色,有些列仅部分显示。如何在不让排序类影响背景颜色的情况下更改背景颜色?
答案 0 :(得分:1)
您的代码仅适用于样式。你应该使用CSS来做到这一点。
CSS中有一个特殊的:hover
选择器,允许您在鼠标指向元素时更改样式:
#myTable tbody tr.inactive,
#myTable tbody tr.inactive td.sorting_1 {
background-color: #fccfcf
}
#myTable tbody tr:hover,
#myTable tbody tr:hover td.sorting_1 {
background-color: #e2ebff;
cursor: pointer
}
放弃fnRowCallback
和.hover()
回调。