在JavaScript过渡期间获取当前CSS属性值

Tim*_*imE 12 javascript css transition css3

我希望能够在完全执行之前在转换过程中读取CSS属性的值.那可能吗?因此,如果在从0%到100%的过渡期间,我要检查一半,我能看到50%吗?

zzz*_*Bov 13

在JavaScript过渡期间是否可以获取当前的css属性?

var timer;

function test(e) {
    var $this;
    $this = $(this);
    timer = setInterval(function () {
        console.log($this.height());
    }, 500);
}
function untest(e) {
    clearInterval(timer);
}

$('div').mouseenter(test).mouseleave(untest);
Run Code Online (Sandbox Code Playgroud)
div
{
    transition: height 10s;
    -moz-transition: height 10s;
    -webkit-transition: height 10s;
    width: 100px;
    height: 100px;
    background-color: #00F;
}

div:hover
{
    height: 300px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我只测试了firefox和chrome,但看起来你可以通过JS获得当前的CSS高度.

我无法想到浏览器在CSS转换期间不会向DOM报告样式更改的原因.

  • 它也是[规范的一部分](http://www.w3.org/TR/css3-transitions/#transitions-):"如果脚本在转换时查询属性的计算样式,它将看到中间值,表示属性的当前动画值." (4认同)
  • 我想指出的是,这个已经很好的例子可以通过使用 offsetHeight 变得免费。 (2认同)

Mar*_*ery 8

是的,这是可能的。返回的对象上的相应属性getComputedStyle将在转换过程中逐渐改变,如本演示所示:

const box = document.getElementById('box'),
      turnBlueButton = document.getElementById('turnblue'),
      turnPinkButton = document.getElementById('turnpink'),
      computedStyleValueSpan = document.getElementById('computedstylevalue');
      
turnBlueButton.onclick = () => {
  box.classList.add('blue');
  box.classList.remove('pink');
}
turnPinkButton.onclick = () => {
  box.classList.add('pink');
  box.classList.remove('blue');
}

const computedStyleObj = getComputedStyle(box);

setInterval(() => {
  computedStyleValueSpan.textContent = computedStyleObj.backgroundColor;
}, 50);
Run Code Online (Sandbox Code Playgroud)
#box {
  width:50px;
  height:50px;
  transition: background-color 10s;
}
.pink {
  background: pink;
}
.blue {
  background: blue;
}
Run Code Online (Sandbox Code Playgroud)
<div id="box" class="pink"></div>

<p>
  <code>getComputedStyle(box).backgroundColor:</code>
  <code><span id="computedstylevalue"></span></code>
</p>

<button id="turnblue">Turn blue</button>
<button id="turnpink">Turn pink</button>
Run Code Online (Sandbox Code Playgroud)

此行为是规范所要求的。https://www.w3.org/TR/css-transitions-1/#transitions-指出:

属性的计算值随着时间的推移从旧值转变为新值因此,如果脚本在转换时查询属性的计算值(或依赖于该属性的其他数据),它将看到一个表示属性当前动画值的中间值。

虽然 Mozilla 文档似乎说getComputedStyle会返回开始值或结束值,但它们似乎是错误的,至少对于 WebKit 来说是这样。基于 WebKit 的浏览器的getComputedStyle实现似乎返回中间值。

(向/sf/users/1950371/致敬,感谢他们的评论指出了相关的规范段落。)