css transition doesn't work if element start hidden

后端 未结 5 2055
感情败类
感情败类 2020-11-29 12:47

I have 2 divs, one of them is hidden via display:none;. Both have the same css transition on the property right.

If I change t

5条回答
  •  没有蜡笔的小新
    2020-11-29 13:18

    jQuery show() without a parameter basically does this

    $('.b').css('display', 'block');
    

    So what you are doing is this

    $('button').on('click',function(){
      $('.b').css('display', 'block');
      $('.b').css('right','80%');
      $('.a').css('right','80%');
    })
    

    which is basically the same as

    $('button').on('click',function(){
      $('.b').css({
        'display': 'block',
        'right': '80%'
      });
      $('.a').css('right','80%');
    })
    

    But you can't transition anything, if the display is changed at the same time.

    Adding a duration value to the show() call, does something more complex than just changing the display. It will add the element to an animation queue like this

    $('.b').css({
      'display': 'block', 
      'overflow': 'hidden',
      'height': '0',
      'width': '0',
      'margin': '0',
      'width': '0',
      'opacity': '0'
    });
    $('.b').animate({
      height: '50px',
      padding: '0px',
      margin: '0px', 
      width: '50px', 
      opacity: '1'
    }, 0)
    

    So what you need to do is putting the duration value of 0 (zero) into the show() call as a parameter

    $('button').on('click',function(){
      $('.b').show(0);
      $('.b').css('right','80%');
      $('.a').css('right','80%');
    })
    body {
      width:800px;
      height:800px;
    }
    
    div {
      width:50px;
      height:50px;
      background-color:#333;
      position:absolute;
      display:none;
      right:5%;
      top:0;
      transition:right .5s .1s cubic-bezier(0.645, 0.045, 0.355, 1);
      color: white;
    }
    
    .a {
      display:block;
      top:60px;
    }
    
    
    A
    B

提交回复
热议问题