CSS transition on an initially hidden elemement

前端 未结 6 502
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 13:22

I would like to make a css transition on an element which has display: none set. Consider the following code:


         


        
6条回答
  •  悲&欢浪女
    2020-12-19 13:55

    You should not necessarily relay on transitionend callbacks.
    To show with a transition on the opacity property (or others) an hidden element that initially has display:none, simply use inline style to set display:block then remove your CSS class .hidden to animate the element as you want:

    CSS:

    #foo {
        display: none;
        opacity: 1;
        /*optional, other ending properties...*/
        transition: opacity 1s;
    }
    .hidden {
        opacity: 0;
        /*optional, other starting properties...*/
    }
    

    HTML:

    
    

    finally, the javascript part to show the element with a transition:

    var elem = document.getElementById('foo');
    elem.style.display = 'block';
    elem.classList.remove('hidden');
    

提交回复
热议问题