前端 CSS 经典:3D Hover Effect 效果

前言:有趣的 3D Hover Effect 效果,通过 js 监听鼠标移动,动态赋值 rotateX,rotateY 的旋转度来实现。

效果图:

代码实现:

html 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="initial-scale=1.0, user-scalable=no, width=device-width"
    />
    <title>document</title>
    <style>
      body {
        background: #000;
      }
      .card {
        margin: 200px auto;
        width: 400px;
        border-radius: 10px;
        transform: perspective(500px) rotateX(var(--rx, 0deg)) rotateY(var(--ry, 0deg));
        transition: 0.3s;
      }
      .card img {
        width: 100%;
        border-radius: inherit;
      }
      .card:hover {
        box-shadow: -3px -3px 10px #54a29e, 3px 3px 10px #a79d66;
      }
    </style>
  </head>
  <body>
    <div class="card">
      <img src="img.jpg" />
    </div>
    <script>
      const card = document.querySelector(".card");
      const yRange = [-10, 10];
      const xRange = [-10, 10];
      function getRotateDeg(range, value, length) {
        return (value / length) * (range[1] - range[0]) + range[0];
      }
      card.onmousemove = (e) => {
        const { offsetX, offsetY } = e;
        const { offsetWidth, offsetHeight } = card;
        const ry = -getRotateDeg(yRange, offsetX, offsetHeight);
        const rx = getRotateDeg(xRange, offsetY, offsetWidth);

        card.style.setProperty("--rx", `${rx}deg`);
        card.style.setProperty("--ry", `${ry}deg`);
        console.log(rx, ry);
      };
      card.onmouseleave = () => {
        card.style.setProperty("--rx", 0);
        card.style.setProperty("--ry", 0);
      };
    </script>
  </body>
</html>
相关推荐
你的人类朋友1 小时前
【Node】认识一下Node.js 中的 VM 模块
前端·后端·node.js
Cosolar1 小时前
FunASR 前端语音识别代码解析
前端·面试·github
@大迁世界4 小时前
Vue 设计模式 实战指南
前端·javascript·vue.js·设计模式·ecmascript
芭拉拉小魔仙4 小时前
Vue项目中如何实现表格选中数据的 Excel 导出
前端·vue.js·excel
jump_jump4 小时前
妙用 localeCompare 获取汉字拼音首字母
前端·javascript·浏览器
U.2 SSD4 小时前
Echarts单轴坐标系散点图
前端·javascript·echarts
德育处主任Pro5 小时前
前端玩转大模型,DeepSeek-R1 蒸馏 Llama 模型的 Bedrock 部署
前端·llama
Jedi Hongbin5 小时前
Three.js NodeMaterial 节点材质系统文档
前端·javascript·three.js·nodematerial
前端小马5 小时前
前后端Long类型ID精度丢失问题
java·前端·javascript·后端
用户1456775610375 小时前
干净的图片批量处理,处理速度飞快
前端