javascript - 如何为具有不同位置的元素设置动画以向同一个位置/元素移动?
问题描述
我正在为 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%;
}
}
解决方案
好的,所以如果有人偶然发现这一点。我在 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%;
}
}
推荐阅读
- r - 正则表达式查找带有可选“final”点的字符串(仅此而已)
- foreach - 从另一个数组原型 forEach 中移除事件监听器
- flutter - 在动画期间重建称为更改选项卡
- javascript - 将对象属性更改/映射为枚举值
- linux - 原生 Linux 和 macOS 应用程序的 Shell 脚本?
- powershell - 如何将特定文件制作为零字节文件
- css - 特定于设备的@media 查询似乎不起作用
- c - 为 Visual Studio 安装 vcpkg 时出现问题
- python - 如何从人类日期获得一致的日期时间对象?
- python - 我的 django 网站在崩溃后停止工作,错误毫无意义