js写了个鼠标进入卡片3D效果的demo

1、效果图

2、上代码 :)

js 复制代码
<template>
  <div class="w-150 h-180 p-12 perspective-1000px transform-style-preserve-3d transform-origin-0">
    <div id="demo" class="w-80 h-120 bg-rose-500 font-bold text-3xl text-center line-height-120 rounded-2xl cursor-grab pos-relative transform-style-preserve-3d shadow-black shadow-2xl">
      demo
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { ParallaxTiltEffect } from '@/utils/index.js'

onMounted(() => {
  const element = document.querySelector('#demo')
  new ParallaxTiltEffect(element)
})
</script>

<style lang="scss" scoped>
#demo{
  --X: 0;
  --Y: 0;
  transform: rotateX(var(--X)) rotateY(var(--Y));
  transition: all 0.5s ease;
}
</style>

封装了个class

js 复制代码
export class ParallaxTiltEffect{
  constructor(dom) {
    // 最大旋转角度
    this.maxRotateDeg = 20
    // 获取到元素
    this.element = dom
    // 获取宽高的一半
    this.halfW = this.element.clientWidth / 2
    this.halfH = this.element.clientHeight /2 
    this.init()
  }
  init(){
    // 绑定鼠标事件
    console.log('this', this);
    this.element.addEventListener("mouseenter", this.handleMouseEnter.bind(this))
    this.element.addEventListener("mousemove", this.handleMouseMove.bind(this))
    this.element.addEventListener("mouseleave", this.handleMouseLeave.bind(this))

  }
  computed(offsetX, offsetY){
    // 获取鼠标位置距离元素中心点的距离, 然后除以 this.halfW,得到百分比
    let dxPercent = (offsetX - this.halfW) / this.halfW
    let dyPercent = -(offsetY - this.halfH) / this.halfH
    console.log(dxPercent,dyPercent,'11')
    let rotateX = this.maxRotateDeg * dxPercent
    let rotateY = this.maxRotateDeg * dyPercent
    console.log(rotateX,rotateY,'22')
    this.setElementRotate(rotateY,rotateX)
  }
  handleMouseEnter(e){
    let {offsetX, offsetY} = e
    // requestAnimationFrame设置刷新帧率随浏览器画面刷新而刷新
    requestAnimationFrame(() => {
      return this.computed(offsetX, offsetY)
    })
  }
  handleMouseMove(e){
    let {offsetX, offsetY} = e
    requestAnimationFrame(() => {
      return this.computed(offsetX, offsetY)
    })
  }
  handleMouseLeave(e){
    setTimeout(() => {
      this.setElementRotate(0, 0)
    }, 200)
  }
  setElementRotate(rotateX, rotateY){
    // js设置css变量的方式
    this.element.style.setProperty('--X', rotateX + "deg");
    this.element.style.setProperty('--Y', rotateY + "deg");
  }
}
相关推荐
酒尘&2 小时前
JS数组不止Array!索引集合类全面解析
开发语言·前端·javascript·学习·js
学历真的很重要3 小时前
VsCode+Roo Code+Gemini 2.5 Pro+Gemini Balance AI辅助编程环境搭建(理论上通过多个Api Key负载均衡达到无限免费Gemini 2.5 Pro)
前端·人工智能·vscode·后端·语言模型·负载均衡·ai编程
用户47949283569154 小时前
"讲讲原型链" —— 面试官最爱问的 JavaScript 基础
前端·javascript·面试
用户47949283569154 小时前
2025 年 TC39 都在忙什么?Import Bytes、Iterator Chunking 来了
前端·javascript·面试
大怪v5 小时前
【Virtual World 04】我们的目标,无限宇宙!!
前端·javascript·代码规范
狂炫冰美式5 小时前
不谈技术,搞点文化 🧀 —— 从复活一句明代残诗破局产品迭代
前端·人工智能·后端
xw56 小时前
npm几个实用命令
前端·npm
!win !6 小时前
npm几个实用命令
前端·npm
代码狂想家6 小时前
使用openEuler从零构建用户管理系统Web应用平台
前端
dorisrv7 小时前
优雅的React表单状态管理
前端