使用 jQuery 2.1+ 更改 css 会忽略转换属性

Changing css with jQuery 2.1+ ignores transition property

本文关键字:转换 属性 css jQuery 更改 使用      更新时间:2023-09-26

我正在从jQuery 2.0.3切换到2.1.0。

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

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

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

我想知道为什么对此有不同的处理方式,以及如何"打开"过渡效果。

在 jQuery 2.0.3 中,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.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 中,两者都可以正确制作动画

搜索四周后,我认为这可能与 v14164 发布期间对问题 #2.1.0 所做的更改有关。根据标题,"减少 init 或方法中的强制布局重排"。

我将 v2.0.3 源代码与 v2.1.0 源代码进行了比较,看起来围绕 .ready() 方法以及如何延迟事件进行了一些重构。更具体地说,我认为它可能与 v3407 中的 3408-2.1.0 行有关,其中最初调用了 .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>


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

$('.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>