Get current CSS property value during a transition in JavaScript

前端 未结 2 1833
长情又很酷
长情又很酷 2020-12-29 09:14

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

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 09:43

    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;
    }

    getComputedStyle(box).backgroundColor:

    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.

    While the Mozilla docs seem to say that getComputedStyle would return either the start or the end value, they seem wrong, at least for WebKit. WebKit-based browsers' getComputedStyle implementation seems to return intermediate values.

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

提交回复
热议问题