javascript - jQuery 悬停问题

标签 javascript jquery jquery-hover

在我的网站上,我显示了很多框,最多 60 个。每个框都可以悬停并具有自己的颜色。我意识到使用以下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);
         });
    });

当一个框悬停时,它应该获得#68BFEF作为背景颜色,当鼠标离开该框时,颜色应该更改为其旧值。

这是我应用CSS的方式:

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

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

有什么想法吗?

最佳答案

您需要在离开悬停时拉出存储在数据中的基色,例如:

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

关于javascript - jQuery 悬停问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4459839/

相关文章:

javascript - 生成带有子数组的数组

javascript - 获取选择框的 html 并附加到另一个 div 中

jquery - 我的 JQuery CSS 菜单无法隐藏

javascript - 混合应用程序的应用内电子邮件功能

jquery - 如何在 jQuery 悬停菜单中保持子菜单打开?

javascript - 为数组中的所有对象添加属性

Javascript 静态方法与性能上的原型(prototype)/实例化方法

c# - 文本框中的扫描值(使用扫描仪)

jquery - 使用 jQuery 在悬停时更改当前图像

jquery - 悬停事件在追加()div内容后不起作用