2010-12-16 144 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); 
    }); 
});