开发者

Change and keep background color on click

I am having the following structure on a website I am building:

<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>
        &l开发者_如何转开发t;td class="header link"><a href="w" >W</td>

</tr>

All cells have the same background color initially.

What I would like to accomplish is the following:

When any of the links is clicked, the background color of the cell containing the link changes to new color and stays changed, until another link is selected.

When the other link is selected, the color of the firstly selected link changes back to the original color, while the cell of the newly selected link changes to new color.

Currently what I have in place is working hover function:

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

How do I accomplish the above?


Try this:

$(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"));
                });
        });
});

Working example: http://jsfiddle.net/Hbgz3/2/


You could use the .click event in a similar way you used the .hover function:

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


Use the click handler instead of hover()

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


Try adding the color to the link using a data-value.

data-value="#ffcc00"

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜