使用Vue实现点击页面触发特效

 效果描述 

在页面上的指定区域内进行点击,则会在页面上显示设置好的随机文本,此文本出现后会执行动画,动画效果为节点在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>

  • 19
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值