2010-12-16 164 views
0

在我的网站上,我展示了很多箱子,多达60个。每个箱子都可以悬挂并具有自己的颜色。我认识到,用下面的JS:jQuery悬停问题

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

当一个盒子悬停它应该得到#68BFEF作为背景色,当鼠标离开箱子的颜色应该改变它的旧值。

这是我申请的CSS的方式:

<div id="primary"> 
    <div class="box" style="background:...."></div> 
    <div class="box" style="background:...."></div> 
    <div class="box" style="background:...."></div> 
    .... 
</div> 

我的问题是,悬停效果应该会更快,色彩应改变得更快。另一个问题是,并非所有的盒子都有旧的背景颜色。

任何想法?

回答

3

你需要拉你在数据离开悬停时存储的基本颜色,例如:

$(".box").each(function() { 
    $(this).data('baseColor',$(this).css('color')); 
    $(this).hover(function() { 
    $(this).animate({ backgroundColor: "#68BFEF" }, 500); 
    },function() { 
    $(this).animate({ backgroundColor: $(this).data('baseColor') }, 1000); 
    }); 
}); 

或者略偏优化的版本使用$.data()代替:

$(".box").each(function() { 
    $.data(this, 'baseColor', $(this).css('color')); 
    $(this).hover(function() { 
    $(this).stop().animate({ backgroundColor: "#68BFEF" }, 500); 
    },function() { 
    $(this).stop().animate({ backgroundColor: $.data(this, 'baseColor') }, 1000); 
    }); 
});