点击后更改并保持背景颜色

时间:2011-06-29 14:48:15

标签: jquery colors background

我正在建立的网站上有以下结构:

<tr>

        <td class="header link"><a href="x" >X</a></td>
        <td class="header link"><a href="y" >Y</a></td>
        <td class="header link"><a href="z" >Z</a></td>
        <td class="header link"><a href="w" >W</td>

</tr>

所有细胞最初都具有相同的背景颜色。

我想要完成的是:

单击任何链接时,包含链接的单元格的背景颜色将更改为新颜色并保持更改,直到选择了另一个链接。

当选择其他链接时,首先选择的链接的颜色会变回原始颜色,而新选择的链接的单元格会更改为新颜色。

目前我所拥有的是工作悬停功能:

$(document).ready(function()
 {    $(function(){ $('.header').hover(function() {$(this).css('background-color', '#EBA521');},         
 function() { $(this).css('background-color', '#6F0000'); });  
 });
 }); 

我如何完成上述工作?

4 个答案:

答案 0 :(得分:1)

试试这个:

$(document).ready(function() {
        $('.header.link a').click(function() {
                $('.header.link a').css('background-color', '#6F0000');
                $(this).css('background-color', '#EBA521');
                $(this).data("bgColor", "#EBA521")
                return false;
        });
});

$(document).ready(function() {
        $(function() {
                $('.header.link a').hover(function() {
                        $(this).data("bgColor", $(this).css('background-color'));
                        $(this).css('background-color', '#EBA521');
                }, function() {
                        $(this).css('background-color', $(this).data("bgColor"));
                });
        });
});

工作示例:http://jsfiddle.net/Hbgz3/2/

答案 1 :(得分:0)

使用点击处理程序代替hover()

$(function() {
    $("a").click( function() {
        $(".header.link").css('background-color', '#6F0000');
        $(this).parent().css('background-color', '#EBA521');
    });
});

答案 2 :(得分:0)

您可以使用与.hover函数类似的方式使用.click事件:

$('.header').click(function(){
  //change color of this
  //change color of all other .header elements to default color
});

答案 3 :(得分:0)

尝试使用数据值将颜色添加到链接。

data-value="#ffcc00"

$('.header a').click(function() {
    $('.header').css('background-color','#ffffff');
    $(this).parent().css('background-color',$(this).attr('data-value'));
});