前端 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>
相关推荐
呵呵哒( ̄▽ ̄)"9 分钟前
React - 编写选择礼物组件
前端·javascript·react.js
Coding的叶子13 分钟前
React Flow 简介:构建交互式流程图的最佳工具
前端·react.js·流程图·fgai·react agent
像素工坊可视化3 小时前
WebGL 开发的前沿探索:开启 3D 网页的新时代
3d·webgl
apcipot_rain5 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
ShallowLin5 小时前
vue3学习——组合式 API:生命周期钩子
前端·javascript·vue.js
Nejosi_念旧6 小时前
Vue API 、element-plus自动导入插件
前端·javascript·vue.js
互联网搬砖老肖6 小时前
Web 架构之攻击应急方案
前端·架构
pixle06 小时前
Vue3 Echarts 3D饼图(3D环形图)实现讲解附带源码
前端·3d·echarts
麻芝汤圆7 小时前
MapReduce 入门实战:WordCount 程序
大数据·前端·javascript·ajax·spark·mapreduce
juruiyuan1118 小时前
FFmpeg3.4 libavcodec协议框架增加新的decode协议
前端