前端 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>
相关推荐
问心无愧05135 小时前
ctf show web入门160 161
前端·笔记
李小白665 小时前
第四天-WEB服务器基本原理,IIS服务
运维·服务器·前端
humcomm6 小时前
AI编程时代新前端职位
前端·ai编程
好家伙VCC6 小时前
Web Components主题热切换方案揭秘
java·前端
甲维斯6 小时前
Kimi版超级玛丽效果“惊人”,配额不足5厘米!
前端·人工智能
hboot6 小时前
AI工程师第一课 - Python
前端·后端·python
凉菜凉凉6 小时前
AI时代,被抛弃的前端
前端·ai
console.log('npc')7 小时前
AI前端工程与生成式UI学习路线
前端·人工智能·ui
梦曦i7 小时前
uni-router v1.1.1发布:守卫超时保护+路由监听
前端·uni-app
qq_2518364577 小时前
基于java Web网络订餐系统设计与实现 源码文档
java·开发语言·前端