如何拦截jQuery中的不透明度转换?

时间:2011-10-22 16:41:30

标签: jquery hover opacity fade intercept

我有以下悬停脚本,可用于我的导航链接图像:

$("nav a").hover(
    function() {
        $(".current", this).animate({
            opacity: 1
        }, {
            duration: 300,
            specialEasing: {
                opacity: 'linear',
            },
});
    }, function() {
        $(".current", this).animate({
            opacity: 0
        }, {
            duration: 2000,
            specialEasing: {
                opacity: 'linear',
            },

});
});

我想知道如果用户将光标移出悬停div然后在原始动画完成之前返回到动画中,则有一种拦截动画的方法。如果用户将光标移回div,我希望动画立即将.current div中图像的不透明度淡化为1。

我希望这很清楚,并且很乐意提供任何帮助。

谢谢,

尼克

2 个答案:

答案 0 :(得分:2)

您可以使用jQuery的stop()函数(info)来取消动画。将enter函数的第一行更改为:

    $(".current", this).stop().animate({

这会停止动画并立即将不透明度返回到1。

答案 1 :(得分:0)

我过去完成这样的事情的方法是在对象中存储对悬停元素的引用,并通过与悬停在其上的元素相关联的某种ID键入。

例如:

var hoveredElements = {previousId:null};
$("nav a").bind("mouseover mouseout",function(e) {
           if(e.type == "mouseover")
           {

              if(!hoveredElements.hasOwnProperty(this.id))
              {
                 hoveredElements[this.id] =  $(".current", this).animate({opacity:  1},300);
                 hoveredElements.previousId = this.id;
              }
              else if(hoveredElements.previousId == this.id)
              {
                if(hoveredElements.hasOwnProperty(this.id))
                {
                    hoveredElements[this.id].stop().css({opacity:1});
                } 
                else
                {
                  hoveredElements[this.id] = $(".current", this).css({opacity:1});
                }
              }
           }
           else
           {
             if(hoveredElements.hasOwnProperty(this.id))
             {
                 hoveredElements[this.id].animate({opacity:  0},2000,function(){
                    delete hoveredElements[this.id];
                 });
             }
           }
});

当然,ID不一定是HTML ID,只是一些唯一标识符(可能是元素本身)。

编辑:对不起,没有得到原来的问题!