vue3(setup) 实现小球动画 保姆级教程

创建JS文件

let createBall = (left, top, box) => {

  //获取的是div外层需要div包裹

  const ball = document.createElement("div");

  ball.style.position = "absolute";

  ball.style.left = left - 2 + "px";

  ball.style.top = top - 5 + "px";

  ball.style.width = "20px";

  ball.style.height = "20px";

  ball.style.borderRadius = "20%";

  ball.style.backgroundColor = "red";

  ball.style.transition = "left .6s linear, top .6s cubic-bezier(0.5,-0.5,1,1)";

  document.body.appendChild(ball);

  //使用 requestAnimationFrame() 方法,这样可以避免一些性能问题

  requestAnimationFrame(() => {

    //获取 box 元素的左边距和顶部距离

    ball.style.left =

      box.getBoundingClientRect().left + box.offsetWidth / 2 + "px";

    ball.style.top = box.getBoundingClientRect().top + "px";

  });

    //移除过渡动画

  ball.ontransitionend = function () {

    ball.remove();

  };

};

//方法

const Add = (e, Box) => {

  // e:传递的ev  Box:加入的购物车 ref

  const { clientX, clientY } = e;

  createBall(clientX, clientY, Box);

};

export default Add;

vue3代码

<script setup>

import { ref } from "vue";

//引入JS文件

import Add from "./Add";

const car = ref();

//点击按钮事件

const onClick = (ev) => {

  mai(ev);

};

const mai = (ev) => {

  const { clientX, clientY } = ev;

  console.log(

    car.value.offsetWidth,

    "ev",

    ev.clientX,

    "x轴",

    clientX,

    "y轴",

    clientY

  );

  console.log(car.value.getBoundingClientRect().left + "px");

  Add(ev, car.value);

};

</script>

<template>

  <div>

    <div class="balls">

      <!-- 点击事件发送小球 -->

      <button @click="onClick($event)">点击</button>

    </div>

    <div ref="car" class="carts">

      <h1>我的车</h1>

    </div>

  </div>

</template>

CSS代码

.balls {

  position: relative;

  top: 70px;

}

.carts {

  position: relative;

  top: 550px;

  left: 250px;

  width: 100px;

  background-color: green;

  border-radius: 50%;

  z-index: 999;

}

 

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值