使用jQuery交换字体和背景颜色

时间:2010-12-16 11:41:26

标签: javascript jquery jquery-selectors jquery-hover

我在页面上显示40多个框:

<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>

如您所见,我设置了背景颜色和文本颜色。在悬停时我想换掉颜色:

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

背景颜色的动画有效,但我无法更改a元素的字体颜色。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

正如@Brandon所提到的,你需要jQuery UI(或者某些东西;)来为非整数属性设置动画。

更大的问题是each回调中的上下文更改:在hover回调方法中,this的值并不总是您想要的。此外,创建新的jQuery对象(使用$(...))相对昂贵。尝试:

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);
    });
});

演示here

答案 1 :(得分:0)

jQuery不能自己动画颜色;你必须使用color plugin

至于交换周围的颜色,你必须有一个临时变量来临时存储其中一种颜色。一些伪代码就是这样:

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