2011-12-12 80 views
0

我正在为一个名为$('。plan')的div设置动画效果。我想抓住它的originalWidth在一个变量中,并且在悬停动画后没有这个值改变,所以我可以在动画完成后返回它。jQuery animate:我如何防止更改值?

$(document).ready(function() { 

    var $plan = $('.plan'), 
    origWidth = $plan.width(); 

    $plan.hover(function() { 
     $this = $(this); 
     $this.stop().animate({width: 200, backgroundColor:'#a4a4a4'}, 500)  
    }, function() { 
     $this.stop().animate({width: origWidth, backgroundColor:'#e2e2e2'}, 200) 
    }); 

}); 

我该怎么做?

嘿,好像它现在工作。怎么来的?

+0

出了什么问题?您使用此代码遇到什么错误/问题? – Vigrond

+0

尝试在该origWidth变量前加上一个'var'。根据你的代码,我不明白为什么它应该改变(即使有或没有我后面的建议)。 – Romanulus

+0

@Romanulus这两个变量声明之间有一个逗号,所以'origWidth'技术上确实有'var'。 – Jasper

回答

0
$(function() { 

    var $plan  = $('.plan'), 
     origWidth = $plan.width(); 

    $plan.hover(function() { 
     $(this).stop().animate({width: 200, backgroundColor:'#a4a4a4'}, 500)  
    }, function() { 
     $(this).stop().animate({width: origWidth, backgroundColor:'#e2e2e2'}, 200) 
    }); 

}); 

这里是一个演示:http://jsfiddle.net/Dc367/

这一切我真的改变是$this引用,你并不真的需要缓存的选择,如果你不打算使用它不止一次。而且你没有在第二个.hover()函数中声明$this变量,所以我认为这就是代码破坏的地方。