【问题标题】:jQuery animate: How do I prevent value from changing?jQuery animate:如何防止值发生变化?
【发布时间】:2011-12-12 07:04:47
【问题描述】:

我正在为一个名为 $('.plan') 的 div 设置动画。我想在一个变量中获取它的 originalWidth,并且在悬停动画之后不改变这个值所以我可以在动画完成后返回它。

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

});

我该怎么做?

嘿,它现在似乎可以工作了。怎么会?

【问题讨论】:

  • 怎么了?您在使用此代码时遇到什么错误/问题?
  • 尝试在 origWidth 变量前面添加一个“var”。根据您的代码,我不明白为什么它应该改变(即使有或没有我的后一个建议)。
  • @Romanulus 两个变量声明之间有一个逗号,所以origWidth 在技术上确实有一个var

标签: jquery jquery-animate dimensions


【解决方案1】:
$(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 变量,所以我假设这就是您的代码出错的地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2019-07-20
    • 1970-01-01
    相关资源
    最近更新 更多