workaround for display block and css transitions not triggering

后端 未结 4 774
一个人的身影
一个人的身影 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 21:58

    Based on the code you present in your question I'm going on a completely different way here, and use animation instead, which will make the whole repaint issue go away

    Updated with a script the set the div to display: block

    var dom = {};
    dom.creative = document.getElementById('creative');
    dom.creative.style.display = 'none';
    
    var butt = document.getElementById('button');
    butt.addEventListener('click', function(e) {
      
      if (dom.creative.style.display == 'block') {
        dom.creative.style.display = 'none';    
      } else {
        dom.creative.style.display = 'block';
      }
    
    })
    #creative {
      display: none;
      opacity: 0;
      animation: opac 1s forwards;
      margin: 20px;
    }
    @keyframes opac {
      100% {
        opacity: 1;
      }
    }
    button {
      margin: 20px;
    }
    
    
    
    Sample text

    If display: none is not needed, one can use transition and simply toggle a class like this

    var dom = {};
    dom.creative = document.getElementById('creative');
    
    var butt = document.getElementById('button');
    butt.addEventListener('click', function(e) {
      
      dom.creative.classList.toggle('show');
    
    })
    #creative {
      opacity: 0;
      transition: opacity 1s;
      margin: 20px;
    }
    #creative.show {
      opacity: 1;
      transition: opacity 1s;
    }
    button {
      margin: 20px;
    }
    
    
    
    Sample text

    For transition, besides the offsetHeight and the setTimeout solution, there is a 3:rd, having the same visual effect as toggle display block/none, setting the height/width to 0.

    var dom = {};
    dom.creative = document.getElementById('creative');
    
    var butt = document.getElementById('button');
    butt.addEventListener('click', function(e) {
      
      dom.creative.classList.toggle('show');
    
    })
    #creative {
      width: 0;
      height: 0;
      opacity: 0;
      transition: opacity 1s, width 0s 1s;
      margin: 20px 0;
    }
    #creative.show {
      width: 100%;
      height: auto;
      opacity: 1;
      transition: opacity 1s, width 0s;
    }
    button {
      margin: 20px 0;
    }
    
    
    
    Sample text
    Other content

提交回复
热议问题