【问题标题】:jQuery animate += and latest versionjQuery animate += 和最新版本
【发布时间】:2013-05-25 01:23:05
【问题描述】:

每次单击 div“蓝色”时,它都会移动 100 像素。它工作得很好,有一天我意识到它停止工作了。在尝试了很多事情之后,我发现问题出在最新版本的 jQuery 1.10 现在它只移动了 100px 一次。就像它忽略了 += 一样。我找不到它是否已被弃用?如果是这样,现在正确的做法是什么?

你可以看到它在这里工作:http://jsfiddle.net/RB4eJ/1/
(这在 jQuery 1.9.1 中有效。但它不在 1.10 中)

$(function(){
    $(".blue").click(function() {
        $(".blue").animate({left: "+=100"}, 500)    
    });
})

【问题讨论】:

标签: jquery jquery-animate


【解决方案1】:

如果这是一个错误,我希望他们修复它,因为它很有用。但是现在你可以这样做:

$(".blue").click(function() {
    var new_left = +$(this).css("left").replace("px", "") + 100;
    $(".blue").animate({left: new_left + "px"}, 500)    
});

或如@adeneo 建议的那样:

$(".blue").click(function() {
    $(this).animate({left: $(this).position().left+100}, 500);  
});

See working demo with jQuery 2.x

Performance test

【讨论】:

  • 或者只是$(this).animate({left: $(this).position().left+100}, 500)
  • @adeneo ty。这样更好
  • 改变了我的想法,offset() 可以在这个例子中使用,因为它是相对于文档的,但是 position() 真的应该被使用,因为它是相对于父级的,就像 CSS left 通常一样位置相对或绝对。
  • 这是一个不错的选择。我把它放在这里:jsfiddle.net/RB4eJ/3谢谢你们!
  • @vega 我认为现在最好的选择是使用 1.9 版本。但最好有这个解决方法,以防万一我们需要 2.0
【解决方案2】:

在使用 +=-= 时,它看起来像 animate 中的错误。该错误似乎在线

https://github.com/jquery/jquery/blob/master/src/effects.js#L48-L50

下面是代码参考,

// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
    //v--- bug
    start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :  
   +parts[ 2 ];

更改上述内容应该可以修复错误,

// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
    //v-- changed to tween.start
    tween.start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :  
   +parts[ 2 ];

用小提琴测试修复: http://jsfiddle.net/xEhuR/ [检查第 8878 行]

注意:好吧,上面的内容除了找出问题之外并没有多大作用。你应该坚持解决方法或等到 jQuery 修复。

发到票http://bugs.jquery.com/ticket/13939?comment:10#comment:10

【讨论】:

【解决方案3】:

这确实是 1.10.0 版本中的一个错误,并在 1.10.1 中修复

http://blog.jquery.com/2013/05/30/jquery-1-10-1-and-2-0-2-released/

http://bugs.jquery.com/ticket/13939

【讨论】:

  • 但我在这里尝试使用 2.0.1 版本,但它不起作用:jsfiddle.net/RB4eJ/4
  • 你用 1.10.1 试过了吗?
猜你喜欢
  • 1970-01-01
  • 2017-01-03
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
  • 2012-11-09
相关资源
最近更新 更多