效果描述
在页面上的指定区域内进行点击,则会在页面上显示设置好的随机文本,此文本出现后会执行动画,动画效果为节点在1s之内向右上方移动并在移动的过程中完成180°翻转,最后消失。
效果展示
完整代码
<template>
<div ref="container" class="box" @click="handleRandom">
<span
:key="childKey"
ref="child"
:style="{ color: colorRandom(), left: childLeft, top: childTop }"
class="minbox"
>
{{ msg }}
</span>
</div>
</template>
<script setup>
import { ref } from "vue";
const container = ref(null);
const child = ref(null); // 鼠标点击后,在页面展示文本的节点
const childKey = ref(0); // 每次点击后,改变key以触发Vue重新渲染span
// 生成随机颜色
const colorRandom = () => {
let color;
do {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
color = `rgb(${r},${g},${b})`;
} while (color === "rgb(250,235,215)"); // 检查颜色是否是我们不想要的
return color;
};
const textArr = [
"( ^∀^)",
"富强",
"Σ(゚д゚;)",
"民主",
"(⊙o⊙)",
"文明",
"✈",
"和谐",
"☯",
"自由",
"☠",
"平等",
"〠",
"公正",
"❤",
"法治",
"爱国",
"★",
"敬业",
"诚信",
"友善",
];
// 生成随机数
const randomInd = () => {
return Math.floor(Math.random() * textArr.length);
};
const msg = ref(null); //在页面展示的文本
const childLeft = ref(0);
const childTop = ref(0);
// 鼠标点击事件
const handleRandom = (e) => {
childLeft.value = e.clientX + "px";
childTop.value = e.clientY + "px";
msg.value = textArr[randomInd()];
// 在每次点击后,改变key以触发Vue重新渲染span
childKey.value++;
};
</script>
<style lang="scss" scoped>
.box {
width: 500px;
height: 300px;
cursor: pointer;
background-color: rgb(250, 235, 215);
.minbox {
width: fit-content;
position: absolute;
animation: moveAndFadeout 1s ease-in-out forwards;
}
// 移动和、淡出以及翻转动画
@keyframes moveAndFadeout {
0% {
transform: translate(0, 0) scale(1) rotate(0deg);
opacit: 1;
}
100% {
transform: translate(20px, -80px) rotate(180deg) scale(2);
opacity: 0;
}
}
}
</style>