前端 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>
相关推荐
换日线°2 分钟前
微信小程序三种裁剪动画有效果图
css·微信小程序
爱上python的猴子2 分钟前
chrome中的copy xpath 与copy full xpath的区别
前端·chrome
Lysun0011 小时前
dispaly: inline-flex 和 display: flex 的区别
前端·javascript·css
山禾女鬼0011 小时前
Vue 3 自定义指令
前端·javascript·vue.js
啊卡无敌1 小时前
Vue 3 reactive 和 ref 区别及 失去响应性问题
前端·javascript·vue.js
北桥苏1 小时前
Spine动画教程:皮肤制作
前端
涵信1 小时前
第九节:React HooksReact 18+新特性-React 19的use钩子如何简化异步操作?
前端·javascript·react.js
Aaaaaaaaaaayou1 小时前
浅玩一下 Mobile Use
前端·llm
这个昵称也不能用吗?1 小时前
react-native搭建开发环境过程记录
前端·react native·cocoapods
hy_花花1 小时前
Vue3.4之defineModel的用法
前端·vue.js