如何使用 jQuery 将先前捕获的变量传递到背景属性中?我正在处理一个非常大的表格、很多单元格和大量数据。使用了多种颜色,应用于表格而不是单元格(有充分的理由)。
这是我的代码(高度压缩的 HTML)
<table>
<tr>
<td class="nonLevel"><ul class="list"><li>text to go here</li></ul></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></a></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></a></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></a></td>
<td class="block"><a href="#"><ul class="list"><li>text to go here</li></ul></a></td>
</tr>
</table>
$(".block").hover(function () {
var myColor = $(this).css("background-color");
$(this).css({'background-color' : 'yellow'});
}, function () {
var cssObj = {
'background-color' : myColor,
}
$(this).css(cssObj);
});
因此,我尝试在翻转时捕获原始颜色(当我将 myColor
变量传递到警报中时起作用),然后将颜色更改为黄色,然后在推出时切换回“我的颜色'。
我已经查看了 addClasss
和 removeClass
,但它们似乎并没有在如何设置方面进行削减。再次强调,背景颜色是在表格的 CSS 中设置的,而不是单元格的,这是无法更改的。
最佳答案
您还可以使用 jQuery 数据来存储原始颜色。然后在鼠标移开时获取它。
$(".block").each(function (index, elem) {
$(elem).data('orginalColor', $(elem).css("background-color"))
}).hover(function () {
$(this).css({'background-color' : 'yellow'});
}, function () {
$(this).css({'background-color' : $(this).data('orginalColor')});
});
您可以在此处阅读有关 jQuery 数据的信息:jQuery Data
此外,我建议改用委托(delegate)(jQuery 在某些情况下在内部为您使用它)。这只会为整个表绑定(bind)一个事件处理程序,而不是为每个“td”绑定(bind)一个事件处理程序
$('.block').each(function (index, elem) { //code });
$('table').delegate('td', 'mouseover', function() { //code });
$('table').delegate('td', 'mouseout', function() { //code });
..弗雷德里克
关于使用变量的 jQuery CSS 悬停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246598/