简体   繁体   中英

CSS Transitions: Trigger with JavaScript

I have previously asked a question about triggering a CSS transition with JavaScript & setTimeout ( JavaScript: Trigger CSS Transition with window.setTimeout ). This question is trying to get more information on that.

I have a function which changes the content and fades in a paragrapn p#test :

function test() {
    var done=false;
    var p=document.querySelector('p#test');
    window.setInterval(doit,4000);
    var data=0;

    function doit() {
        p.removeAttribute('on');    //  1
        p.offsetHeight;             //  2   force update
        p.innerHTML=data++;         //  3
        p.setAttribute('on',null);  //  4
    }
}

The CSS is:

p#test {
    opacity: 0;
}
p#test[on] {
    transition: opacity 1s;
    opacity: 1;
}

I note that the transition property must be set in the p#test[on] rule . If set for the p#test rule, it will not work.

I find that steps 2 & 3 above can be interchanged.

However, I cannot get it working at all if I try to set the properties in JavaScript alone:

function doit() {       //  DOES NOT WORK
    p.style.opacity=0;
    p.offsetHeight;
    p.innerHTML=data++;
    p.style.opacity=1;
}

So I conclude:

  • Changing an attribute (or class) in JavaScript will trigger a CSS transition
  • Changing a CSS property in JavaScript will not trigger a transition
  • The transition will only be triggered if the transition property in in the triggered rule.

Sorry about the long preamble. The question is:

Precisely what JavaScript will actually trigger a CSS transition? Is it only a change of class or attribute, or will anything else work?

I have added a Fiddle here: https://jsfiddle.net/comparity/a7qt297m/

Dumb question, but does the base element ( p#test ) also have the transition property on it? In your example code, the transition property is only there for the "on" state.

If that's not it, it could be because you're changing the opacity from 0 to 1 in immediate succession in the same function. See if a tiny setTimeout can make a difference for the opacity=1 line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM