workaround for display block and css transitions not triggering

后端 未结 4 745
一个人的身影
一个人的身影 2021-01-12 21:16

Sorry all for so many updates in this question and I\'m glad for everyone trying to help me. I think below there is a more clear way to understand this problem:

4条回答
  •  天涯浪人
    2021-01-12 22:01

    There are no transitions defined for absolute properties, like display. How do you interpolate between none and block? You can't. But you can create some post-functions that will run after the animation is done.

    Using setTimeout

    You can use setTimeout and execute some code after the animation is over:

    ANIMATION_TIME = 0.5 * 1000; // in ms
    
    function show(element) {
      // Display property must be set inmediatly; otherwise, the 'show' animation won't be visible until it ends.
      element.style.display = 'block';
      element.opacity = 1;
    }
    
    function hide(element) {
      element.opacity = 0;
    
      setTimeout(function() {
        element.style.display = 'none';
      }, ANIMATION_TIME);
    }
    
    // Call examples
    var dom = {};
    dom.creative = document.getElementById('creative');
    show(dom.creative);
    hide(dom.creative);
    

    Using animation events

    As @trustk has pointed out, you can also (and preferably) use DOM events:

    function show(element) {
      element.style.display = 'block';
      element.opacity = 1;
      element.removeEventListener("animationend", afterHide, false);
    }
    
    function afterHide(e) {
      // e.target -> element
      e.target.display = 'none';
    }
    
    function hide(element) {
      element.opacity = 0;
      element.addEventListener("animationend", afterHide, false);
    }
    

提交回复
热议问题