简体   繁体   中英

how to animate movement of div when adjacent div is set to display:none

Please check out the code here: https://jsfiddle.net/pwasoutside/uaqbj30z/2/

You can see that posts appear on screen and then fade away after a few seconds. But, after a post is set to display:none, the post below immediately moves upward. I want this movement to be animated. How can I do this?

css:

.post {
    background-color: red;
    color: white;
    width: 300px;
    height: 50px;
    display: block;
    transition: transform 3s ease;
 }

.hidden {
    animation: fadeaway 2s;
}

@keyframes fadeaway {
    from {
        opacity: 1;
    }
  
    to {
        opacity: 0; 
    }
  }

js:

var posts = document.getElementById('posts');

var i = 0; 
var interval = setInterval(() => {
    if (i<5) {
        var post = document.getElementById('post' + i);
        post.classList.add('hidden');
        i++;
    } else {
        clearInterval(interval);
    }
}, 3000);

Please try this:

html, body {
    height: 100%;
    margin: 0px;
}
#posts {
    height: 100%;
}
.post {
    background-color: red;
    color: white;
    width: 100%;
    height: 100%;
    display: block;
    transition: transform 3s ease;
    margin: 0px;
}

p {
    margin: 0px;
}

.hidden {
    animation: fadeaway 2s;
}

@keyframes fadeaway {
    from {
        opacity: 1;
        height: 100%;
    }

    to {
        opacity: 0;
        height: 0px;
        margin: 0px;
    }
}
@keyframes fadeaway {
    0% {
        opacity: 1;
        height: 100%;
    }

    50% {
        opacity: 0;
    }

    100%{
        height: 0px;
        margin: 0px;
    }
}

as per Vahid's answer, the opacity and height animates simultaneously. Mine will first fade and then height changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM