开发者

Swap font and background color using jQuery

I display 40+ boxes on a page:

<div id="primary">
    <div class="box" style="background:....">
        <a href="" style="color:....">box1</a>
    </div>
    <div class="box" style="background:....">
        <a href="" style="color:....">box2</a>
    </div>
    ....
</div>

As you can see I set background-color and text-color. On hover I want to swap the colors:

      $(".box").each( function () {
          $(this).data('baseColor',$(this).css('background-color'));
          $(this).find('a').data('fontColor',$(this).css('color'));
          $(this).hover(function() {
            $(this).animate({ backgroundColor:
                       $(this).data('fontColor') }, 500);
          },function() {
            $(this).animate({ backgroundColor: 
                       $(this).data('baseColor') }, 1000);
          });
        });

The animation of the background-color works开发者_如何学Go but I can not change the font color of the a element. Any ideas?


As @Brandon mentioned, you need jQuery UI (or something ;) to animate non-integer properties.

The bigger issue is the change of context in your each callback: inside the hover callback methods, the value of this won't always be what you want. Also, creating new jQuery objects (with $(...)) is relatively expensive. Try:

var cssBox = {
    backgroundColor: $('.box').css('background-color'),
    color: $('.box').css('color')
};

var cssLink = {
    backgroundColor: $('.box > a').css('background-color'),
    color: $('.box > a').css('color')
};

$(".box").each(function() {
    var $this = $(this),
        $this_a = $this.children('a');

    $this.data('baseColor', $this.css('background-color'));
    $this.data('fontColor', $this_a.css('color'));
    $this.hover(function() {
        $this.animate(cssLink, 500);
        $this_a.animate(cssBox, 500);
    }, function() {
        $this.animate(cssBox, 1000);
        $this_a.animate(cssLink, 1000);
    });
});

Demo here.


jQuery can't animate colors on it's own; you'll have to use the color plugin.

As for swapping the colors around, you'll have to have an interim variable to temporarily store one of the colors. Some pseudocode would be this:

var bgCol = $(this).backgroundColor()
$(this).backgroundColor = $(this).textColor();
$(this).textColor = bgCol;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜