vue3 直接用
<template>
<div class="plantingTrees">
<ul class="shop">
<li v-for="item in items">
<span>{{ item.text }}</span>
<span>{{ item.price }}</span>
<span><img :src="item.img" style="width: 50px; height: 50px" /></span>
<button @click="addCar($event, item.img)">添加</button>
</li>
</ul>
<div class="cart" ref="shopCar" id="son">
<div class="num">{{ count }}</div>
<img
src="https://img2.baidu.com/it/u=692835735,3511467736&fm=253&fmt=auto&app=138&f=JPEG?w=600&h=500"
/>
</div>
<!-- 小球图片 -->
</div>
</template>
<script setup>
import { ref, reactive } from "vue";
let shopCar = ref();
let showCart = ref(false);
let count = ref(0);
let items = ref([
{
text: "苹果",
price: 15,
img: "https://img2.baidu.com/it/u=3202947311,1179654885&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1677258000&t=c9cc2d40f9b9efeb866665d97f5cb951",
},
{
text: "香蕉",
price: 15,
img: "https://img1.baidu.com/it/u=407852637,3650486136&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1677258000&t=c6da04e21f034c6f5bcf26682821cd2a",
},
]);
const addCar = (event, items) => {
count.value++;
showCart.value = false;
let x = event.pageX - event.target.offsetWidth / 2;
let y = event.pageY - event.target.offsetWidth / 2;
createBall(x, y, items);
addAnimate();
};
/* 创建小球,添加动画 */
const createBall = (left, top, imgs) => {
let bar = document.createElement("img");
bar.style.position = "absolute";
bar.src = imgs;
bar.style.left = left + "px";
bar.style.top = top + "px";
bar.style.width = "50px";
bar.style.height = "50px";
bar.style.borderRadius = "50%";
// bar.style.backgroundColor = "#02b6fd";
bar.style.transition =
"left .6s ease-in-out, top .6s cubic-bezier(0.5, -0.5, 1, 1)";
document.body.appendChild(bar);
// 添加动画属性
setTimeout(() => {
let target = shopCar.value;
bar.style.left = target.offsetLeft + target.offsetWidth / 2 + "px";
bar.style.top = target.offsetTop + "px";
showCart.value = true;
console.log(bar.style.left, bar.style.top);
}, 0);
/**
* 动画结束后,删除自己
*/
bar.ontransitionend = function () {
this.remove();
showCart.value = false;
};
};
//购物车动画
const addAnimate = () => {
shopCar.value.animate(
[
{
transform: "scale(1.1)",
},
],
{
duration: 1000,
easing: "linear",
iterations: 1,
fill: "forwards",
delay: 0,
direction: "alternate",
}
);
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
index.scss >>>
.shop {
position: fixed;
top: 300px;
left: 500px;
}
.cart {
position: fixed;
bottom: 72px;
left: 32px;
}
.cart .num {
width: 30px;
height: 30px;
background-color: rgb(0, 160, 220);
color: rgb(255, 255, 255);
border-radius: 50%;
text-align: center;
line-height: 30px;
}
.cart > img {
width: 50px;
height: 50px;
}
.animationShake {
animation: bottomNav-shake 0.5s ease-in-out;
}
@keyframes bottomNav-shake {
0% {
transform: scale(1);
}
25% {
transform: scale(0.8);
}
50% {
transform: scale(1.1);
}
75% {
transform: scale(0.9);
}
to {
transform: scale(1);
}
}