سؤال

on my site I display a lot of boxes, up to 60. Each box can be hovered and has it's own color. I realize that with the following js:

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

When a box is hovered it should get #68BFEF as background-color, when the mouse leaves the box the color should change to it's old value.

This is the way I apply the css:

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

My problem is that the hover effect should be faster, the color should change faster. Another problem is that not all boxes get there old background color.

Any ideas?

هل كانت مفيدة؟

المحلول

You need to pull the base color you're storing in data when leaving the hover, for example:

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

Or, a bit more optimized version using $.data() instead:

$(".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);
  });
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top