Is it possible to animate Flexbox inserts & removes?

前端 未结 6 2123
时光取名叫无心
时光取名叫无心 2020-12-09 07:41

When I remove an item from a flexbox, the remaining items \"snap\" into their new positions immediately rather than animating.

Conceptually, since the items are chan

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 07:59

    I've done a codepen that animates the elements when you remove one, take a look: https://codepen.io/MauriciAbad/pen/eQoQbK

    It can be optimized, but works. ;D

    HTML

    ... more divs ...

    CSS

    .container{
        display: flex;
        flex-wrap: wrap;
    }
    .container > div{
        flex-grow: 1;
        transform-origin: left top;
    }
    

    JavaScript

    var cards = document.querySelectorAll('.container > div');
    cards.forEach((card) => {
        card.addEventListener('click', () => {removeCard(card);});
    });
    
    var cardsOldInfo = //example content
        {"cardId": {
            "x": 100,
            "y": 200,
            "width": 100
            }
        };
    var cardsNewInfo = cardsOldInfo;
    
    function removeCard(card){
        cardsOldInfo = getCardsInfo();
        card.parentNode.removeChild(card);
        cardsNewInfo = getCardsInfo();
        moveCards();
    }
    
    function getCardsInfo(){
        updateCards();
        let cardsInfo = {};
        cards.forEach((card) => {
            var rect = card.getBoundingClientRect();
            cardsInfo[card.id] = {
                "x": rect.left,
                "y": rect.top,
                "width": (rect.right - rect.left)
            };
        });
        return cardsInfo;
    }
    
    function moveCards(){
        updateCards();
        cards.forEach((card) => {
            card.animate([ 
                {
                    transform: `translate(${cardsOldInfo[card.id].x - cardsNewInfo[card.id].x}px, ${cardsOldInfo[card.id].y -cardsNewInfo[card.id].y}px) scaleX(${cardsOldInfo[card.id].width/cardsNewInfo[card.id].width})`
                }, 
                {
                    transform: 'none'
                }
            ], { 
                duration: 250,
                easing: 'ease-out'
            });
            });
    }
    
    function updateCards(){
      cards = document.querySelectorAll('.container > div');
    }
    

提交回复
热议问题