将 css 更改为 jQuery 2.1+ 会忽略转换 属性

Changing css with jQuery 2.1+ ignores transition property

我正在从 jQuery 2.0.3 切换到 2.1.0。

我注意到在 v2.1.0 中直接设置 css 属性时 css transition 属性 被忽略

$('#someElement').css('width','100px');

v2.0.3 中,我的元素将保持它的 css 过渡,而我在 v2.1.0 中失去了它.

我想知道为什么要区别对待,以及如何 'turn on' 过渡效果。

随着jQuery 2.0.3,csstransition属性生效

$(function() {
  $('.myClass').css('width', '100px');
});
.myClass {
  height: 50px;
  width: 300px;
  background-color: red;
  transition: width 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="myClass"></div>

在 jQuery 2.1.0 中,css transition 属性 被忽略

$(function() {
  $('.myClass').css('width', '100px');
});
.myClass {
  height: 50px;
  width: 300px;
  background-color: red;
  transition: width 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="myClass"></div>

编辑:

我在 Chrome 版本 47.0.2526.106 m

中看到了这种奇怪的行为

在 Firefox 42.0 中,两者都可以正确设置动画

经过四处搜索,我认为这可能与针对问题#14164 during the v2.1.0 release. As per the title, "Reduce forced layout reflows in init or methods"所做的更改有关。

我比较了 v2.0.3 source code with the v2.1.0 source code,看起来围绕 .ready() 方法和事件如何延迟进行了一些重构。更具体地说,我认为它可能与 v2.1.0 中的第 3407-3408 行有关,其中 .ready() 方法最初被调用(这在 v2.0.3 中不存在):

// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();

至于解决方法,这种转换行为似乎在浏览器之间不一致。要解决 Chrome 中的问题,您可以推迟代码的执行并强制重绘。

setTimeout(function () {
  $('.myClass').css('width', '100px');
}, 0);
.myClass {
  height: 50px;
  width: 300px;
  background-color: red;
  transition: width 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="myClass"></div>


或者,您也可以通过将脚本移动到页面底部,在 元素之后加载 jQuery 。仍然令人困惑的是,为什么这在 Chrome 中有所不同,但在 Firefox 中却无关紧要;它必须与事件后 DOM 是 drawn/painted 的方式有关。

$('.myClass').css('width', '100px');
.myClass {
  height: 50px;
  width: 300px;
  background-color: red;
  transition: width 3s;
}
<div class="myClass"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

它似乎也可以使用 animate() 而不是 css()

$('.myClass').animate({'width': '100px'});
.myClass {
  height: 50px;
  width: 300px;
  background-color: red;
  transition: width 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="myClass"></div>