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

时间:2024-06-01 07:57:42

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

效果图:

代码实现:

<!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>