在博客文章列表或者作品集页面中,卡片是最常见的展示形式。但你有没有想过,仅仅是简单的悬停效果,就能让整个页面的质感提升好几个档次?
今天我们来实现三个高级卡片交互效果:3D 倾斜响应、磁性吸附和波纹扩散。不需要 JavaScript 框架,纯 CSS 就能完成!
效果演示区
效果一:3D 倾斜响应
3D 倾斜卡片
移动鼠标,感受卡片的3D倾斜效果。卡片会跟随光标方向产生透视变化。
CSS 3D Transform效果二:磁性吸附
效果三:波纹扩散
一、3D 倾斜响应
这个效果会让卡片跟随鼠标方向产生倾斜,像是一张纸放在桌面上转动。
核心原理
perspective- 创建 3D 透视效果transform: rotateX()/rotateY()- 根据鼠标位置旋转卡片transform-style: preserve-3d- 保持 3D 空间calc()- 动态计算旋转角度
关键代码
// 计算鼠标在卡片内的相对位置
const x = (e.clientX - rect.left) / rect.width;
const y = (e.clientY - rect.top) / rect.height;
// 中心点偏移 (-0.5 到 0.5)
const centerX = x - 0.5;
const centerY = y - 0.5;
// 计算旋转角度 (最大 ±15 度)
const rotateX = -centerY * 30;
const rotateY = centerX * 30;
// 应用变换
card.style.transform = `rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
原理图解
┌─────────────────────────────────────────┐
│ perspective: 1000px │
│ ┌─────────────────────────────────────┐ │
│ │ 鼠标位置 (x, y) │ │
│ │ ↓ │ │
│ │ centerX = x - 0.5 │ │
│ │ centerY = y - 0.5 │ │
│ │ ↓ │ │
│ │ rotateX = -centerY * 30deg │ │
│ │ rotateY = centerX * 30deg │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────┘
二、磁性吸附按钮
当鼠标靠近按钮时,按钮会"吸"向鼠标方向。
核心原理
- 计算鼠标与按钮中心的距离
- 根据距离计算位移向量
- 使用 CSS 变量动态设置
translate
// 计算鼠标到按钮中心的向量
const x = e.clientX - rect.left - rect.width / 2;
const y = e.clientY - rect.top - rect.height / 2;
// 距离越近,移动越多
const strength = Math.max(0, 1 - distance / maxDistance);
btn.style.setProperty('--x', `${moveX * strength}px`);
btn.style.setProperty('--y', `${moveY * strength}px`);
三、波纹扩散效果
点击按钮时,从点击位置扩散出一圈波纹。
实现步骤
- 获取点击位置
- 创建波纹元素
- 使用 CSS animation 执行扩散动画
.ripple {
position: absolute;
border-radius: 50%;
background: rgba(255, 255, 255, 0.4);
transform: scale(0);
animation: ripple-effect 0.6s linear;
}
@keyframes ripple-effect {
to {
transform: scale(4);
opacity: 0;
}
}
四、性能优化建议
| 优化点 | 说明 |
|---|---|
| 使用 transform 而非 left/top | transform 不会触发重排,只触发合成 |
| 使用 will-change | 对于复杂动画,提示浏览器优化 |
| 控制动画帧率 | 避免在动画中修改可能导致重排的属性 |
| 使用 CSS 变量 | 对于动态值,使用 CSS 变量性能更好 |
写在最后
这三个效果组合起来,就能创造出极具交互感的卡片体验。关键点在于:
- 3D 倾斜:让元素有了物理存在感
- 磁性吸附:创造了"响应"感
- 波纹反馈:给了用户操作确认
评语 (0)