首页 > 解决方案 > 如何为具有不同位置的元素设置动画以向同一个位置/元素移动?

问题描述

我正在为 CV 创建一个鞋店网站。我在主页上呈现了多个项目,可以选择添加到购物车。当用户单击添加到购物车时,我想为元素的图片设置动画以进入标题中的购物车。我可以使用元素的相对位置开始动画,但我不知道如何让具有不同相对位置的元素最终到达同一个地方?现在我可以让他们上去然后离开,但我希望他们准确地到 CART 上。(例如,就像在 Humble bundle 页面中一样)。我看到人们通过使用 jquery 的动画来提供解决方案,但我的应用程序是基于反应的,所以我尽可能避免使用 jquery。

@keyframes item-to-card-animation{
0%{ 
    position: relative;
    opacity:100%;
    top:0px;
    left:0px;
    transform: scale(1);
}

99%{
top:-1000px;
left:100px;
transform: scale(0.2);
z-index:100;
}
100%{
    opacity:0%;
}

}

标签: javascriptcsscss-animations

解决方案


好的,所以如果有人偶然发现这一点。我在 javascript 中克隆了一个元素,然后从 javascript 中放置内联位置(因为您可以从那里访问它),然后使用绝对定位对其进行动画处理。

    const bodyRect = document.body.getBoundingClientRect();
    const elemRect = document.getElementById(this.state.itemToCart._id).getBoundingClientRect();
    const top = elemRect.top - bodyRect.top;
    const left = elemRect.left - bodyRect.left;
    let cloneItem =  document.getElementById(this.state.itemToCart._id).cloneNode(true);
    cloneItem.style.position = "absolute";
    cloneItem.style.top = top + "px";
    cloneItem.style.left = left + "px";
    cloneItem.classList.add('item-to-card-animation');
    document.querySelector('#root').appendChild(cloneItem);
    setTimeout(() => {
     cloneItem.remove();
    },1000)

@keyframes item-to-card-animation{
0%{ 
    opacity:100%;
    transform: scale(1);
}

99%{
   top:-150px;
   left:1150px;
   transform: scale(0.2);
   z-index:100;
}
100%{
   opacity:0%;
}

}


推荐阅读