jquery动画产生奇怪的结果

时间:2010-12-10 15:39:26

标签: javascript jquery

我有一些图标,当我将鼠标悬停在它们上方时会触发一个动画,其中包含动画不同图像左侧和顶部位置的动画。然后当我鼠标移出图标时,图像返回到原始状态。麻烦的是,如果我疯狂地将光标快速移动到所有图标上,动画图像的左侧和顶部位置不会按预期返回其初始状态。

这是代码 - 任何想法如何我可以整理它并防止这个和任何进一步的问题?

$("div").hover( function() {

        $(this).find("span").slideDown(100);
        $(this).css("background-color","#89A7BA");
        var currentlyHovered = $(this).find("img").attr("id").replace("-icon", "");
        $("img#" + currentlyHovered + "-spot").animate({
            width: "17px",
            height: "17px",
            left: parseInt($("img#" + currentlyHovered + "-spot").css("left")) - 5,
            top: parseInt($("img#" + currentlyHovered + "-spot").css("top")) - 5
        }, 100);


    }, function() {

        $(this).find("span").slideUp(100);
        $(this).css("background-color","#000");
        $("img#" + currentlyHovered + "-spot").animate({
            width: "7px",
            height: "7px",
            left: parseInt($("img#" + currentlyHovered + "-spot").css("left")) + 5,
            top: parseInt($("img#" + currentlyHovered + "-spot").css("top")) + 5
        }, 100);
        currentlyHovered = "";

    });

对于任何有兴趣的人,这是完整的解决方案。

$.fn.hoverAnimation = function () {
        return this.each(function () {
            var currentlyHovered = $(this).find("img").attr("id").replace("-icon", "");
            var originalLeft = parseInt($("img#" + currentlyHovered + "-spot").css("left"));
            var originalTop  = parseInt($("img#" + currentlyHovered + "-spot").css("top"));
            return $(this).hover(function () {
                $(this).find("span").slideDown(100);
                $(this).css("background-color","#89A7BA");
                $("img#" + currentlyHovered + "-spot").animate({
                    width: "17px",
                    height: "17px",
                    left: originalLeft - 5,
                    top: originalTop - 5
                }, 100);
            },function () {
                $(this).find("span").slideUp(100);
                $(this).css("background-color","#000");
                $("img#" + currentlyHovered + "-spot").animate({
                    width: "7px",
                    height: "7px",
                    left: originalLeft,
                    top: originalTop
                }, 100);
            });
        });
    }

    $("div").hoverAnimation();

1 个答案:

答案 0 :(得分:1)

我认为它没有回到它的原始位置的原因是原始位置被视为动画中期。我建议为你做一个简单的插件:

$.fn.hoverAnimation = function () {
  return this.each(function () {
    var originalLeft = parseInt($("img#" + $(this).find(img).attr(id) + "-spot").css("left"));
    var originalTop  = parseInt($("img#" + $(this).find(img).attr(id) + "-spot").css("top"));
    return $(this).hover(function () {
      ...
    },function () {
      ...
    });
  }
};

$('div').hoverAnimation();