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");
  }
}
相关推荐
zwjapple5 小时前
docker-compose一键部署全栈项目。springboot后端,react前端
前端·spring boot·docker
像风一样自由20207 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
aiprtem8 小时前
基于Flutter的web登录设计
前端·flutter
浪裡遊8 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
why技术8 小时前
Stack Overflow,轰然倒下!
前端·人工智能·后端
GISer_Jing8 小时前
0704-0706上海,又聚上了
前端·新浪微博
止观止8 小时前
深入探索 pnpm:高效磁盘利用与灵活的包管理解决方案
前端·pnpm·前端工程化·包管理器
whale fall8 小时前
npm install安装的node_modules是什么
前端·npm·node.js
烛阴8 小时前
简单入门Python装饰器
前端·python
袁煦丞9 小时前
数据库设计神器DrawDB:cpolar内网穿透实验室第595个成功挑战
前端·程序员·远程工作