Get current CSS property value during a transition

2019-01-23 06:59发布

问题:

I would like to be able to read the value of a CSS property in the middle of a transition before it is fully executed. Is that possible? So if during a transition from 0% to 100%, I were to check halfway through, could I see it at 50%?

回答1:

Is it possible to get the current css property during a transition in JavaScript?

Yes

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);
div
{
    transition: height 10s;
    -moz-transition: height 10s;
    -webkit-transition: height 10s;
    width: 100px;
    height: 100px;
    background-color: #00F;
}

div:hover
{
    height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

So far I've only tested firefox & chrome, but it appears that you can get the current CSS height via JS.

I can't think of a reason why the browser wouldn't report the change in styles to the DOM during a CSS transition.



回答2:

Yes, it's possible. The corresponding property on the object returned by getComputedStyle will change gradually over the course of a transition, as shown in this demo:

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);
#box {
  width:50px;
  height:50px;
  transition: background-color 10s;
}
.pink {
  background: pink;
}
.blue {
  background: blue;
}
<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>

This behaviour is required by spec. https://www.w3.org/TR/css-transitions-1/#transitions- states:

The computed value of a property transitions over time from the old value to the new value. Therefore if a script queries the computed value of a property (or other data depending on it) as it is transitioning, it will see an intermediate value that represents the current animated value of the property.

(Hat tip to https://stackoverflow.com/users/27862/user123444555621 for their comment pointing out the relevant spec passage.)