CSS—3D Hover Press Effect

觉得这样的效果确实挺不错的 很好玩 来看看怎么实现吧

主要用到的是CSS3D的知识 利用之前提过的perspective属性 和rotateX,Y,Z进行操作

CSS代码如下

body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background: #f5f5f5;
}

.container {
    perspective: 1000px;
    width: 300px;
    height: 300px;
}

.box {
    --rotateX: 0deg;
    --rotateY: 0deg;
    --pressDepth: 0px;
    width: 100%;
    height: 100%;
    background: #2196F3;
    border-radius: 12px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    transition: transform 0.15s ease-out;
    transform:
        perspective(1000px) rotateX(var(--rotateX)) rotateY(var(--rotateY)) translateZ(var(--pressDepth));
    transform-style: preserve-3d;
    cursor: pointer;
}

HTML和JS代码如下

<body>
    <div class="container">
        <div
            class="box"
            id="hover-box"
        ></div>
    </div>

    <script>
        const box = document.getElementById('hover-box');

        box.addEventListener('mousemove', (e) => {
            const rect = box.getBoundingClientRect();

            // 计算鼠标在盒子上的相对位置(-0.5 ~ 0.5)
            const x = (e.clientX - rect.left) / rect.width - 0.5;
            const y = (e.clientY - rect.top) / rect.height - 0.5;

            // 计算旋转角度(限制最大值)
            const maxRotate = 15; // 最大旋转角度
            const rotateX = -y * maxRotate; // 上下倾斜
            const rotateY = x * maxRotate;  // 左右倾斜

            // 计算按压深度(鼠标越靠近中心,凹陷越深)
            const pressDepth = -10 * (1 - Math.abs(x) * Math.abs(y));

            // 更新CSS变量
            box.style.setProperty('--rotateX', `${rotateX}deg`);
            box.style.setProperty('--rotateY', `${rotateY}deg`);
            box.style.setProperty('--pressDepth', `${pressDepth}px`);
        });

        // 鼠标离开时恢复原状
        box.addEventListener('mouseleave', () => {
            box.style.setProperty('--rotateX', '0deg');
            box.style.setProperty('--rotateY', '0deg');
            box.style.setProperty('--pressDepth', '0px');
        });
    </script>
</body>

和我们之前实现的鼠标移动边框变亮结合 就可以实现非常优雅的效果

灯火葳蕤 揉皱你眼眉
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇