Pergunta

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 but I can not change the font color of the a element. Any ideas?

Foi útil?

Solução

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.

Outras dicas

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;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top