CSS transitions do not work when assigned trough JavaScript

前端 未结 3 1523
攒了一身酷
攒了一身酷 2020-11-28 08:51

I\'m having some major headache trying to apply CSS3 transitions to a slideshow trough JavaScript.

Basically the JavaScript gets all of the slides in the slideshow a

3条回答
  •  野性不改
    2020-11-28 09:09

    To make transition work, three things have to happen.

    1. the element has to have the property explicitly defined, in this case: opacity: 0;
    2. the element must have the transition defined: transition: opacity 2s;
    3. the new property must be set: opacity: 1

    If you are assigning 1 and 2 dynamically, like you are in your example, there needs to be a delay before 3 so the browser can process the request. The reason it works when you are debugging it is that you are creating this delay by stepping through it, giving the browser time to process. Give a delay to assigning .target-fadein:

    window.setTimeout(function() {
      slides[targetIndex].className += " target-fadein";
    }, 100); 
    

    Or put .target-fadein-begin into your HTML directly so it's parsed on load and will be ready for the transition.

    Adding transition to an element is not what triggers the animation, changing the property does.

    // Works
    document.getElementById('fade1').className += ' fade-in'
    
    // Doesn't work
    document.getElementById('fade2').className = 'fadeable'
    document.getElementById('fade2').className += ' fade-in'
    
    // Works
    document.getElementById('fade3').className = 'fadeable'
    
    window.setTimeout(function() {
      document.getElementById('fade3').className += ' fade-in'
    }, 50)
    .fadeable {
      opacity: 0;
    }
    
    .fade-in {
      opacity: 1;
      transition: opacity 2s;
    }
    fade 1 - works
    fade 2 - doesn't work
    fade 3 - works

提交回复
热议问题