最近在浏览网页的时候发现一个3D悬停效果,现在分享给大家。在下面文章中,我们将使用HTML、CSS的Transform属性和一点Javascript 创建这种 3D悬停效果。
效果演示
HTML结构
首先,HTML是最基础的,我们得先有元素作为内容的主要容器,任何类型的 HTML 都可以使用。
新建一个article元素,article里面有一个div包含h2标题、一些段落文本和一个button.
<article class="card">
<div class="content">
<h2>qinyi素材网</h2>
<p>免费分享jQuery插件、HTML模板、CSS样式的插件库。</p>
<button type="button"><a href="https://www.qinyi.info/">进入</a></button>
</div>
</article>
CSS代码
最重要的部分开始了,定义一些样式。
* {
box-sizing: border-box;
}
body {
font-family: Arial, Helvetica, sans-serif;
}
p {
margin-top: 0;
font-size: 20px;
}
a {
text-decoration: none;
}
h2 {
font-size: 42px;
margin-bottom: 15px;
}
button {
background: #e85757;
border: none;
border-radius: 30px;
cursor: pointer;
display: block;
font-size: 18px;
font-weight: 700;
padding: 16px;
width: 120px;
color: #fff;
}
button a{
color: white;
}
.card {
background: url(/images/pattern-bg.png) no-repeat;
background-size: cover;
max-width: 500px;
margin: auto;
height: auto;
padding: 40px;
position: relative;
color: #fff;
transition: transform 0.1s ease;
transform-style: preserve-3d;
will-change: transform;
}
.card::before {
content: "";
background: rgba(0, 0, 0, 0.4);
position: absolute;
height: 100%;
width: 100%;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
/* Slight parallax effect on hover */
.card:hover .content {
transform: translateZ(12px);
}
.content {
position: relative;
z-index: 1;
transition: transform 0.3s ease;
}
/* Demo only */
.container {
margin-top: 100px;
}
JavaScript代码
const card = document.querySelector(".card");
const motionMatchMedia = window.matchMedia("(prefers-reduced-motion)");
const THRESHOLD = 15;
function handleHover(e) {
const { clientX, clientY, currentTarget } = e;
const { clientWidth, clientHeight, offsetLeft, offsetTop } = currentTarget;
const horizontal = (clientX - offsetLeft) / clientWidth;
const vertical = (clientY - offsetTop) / clientHeight;
const rotateX = (THRESHOLD / 2 - horizontal * THRESHOLD).toFixed(2);
const rotateY = (vertical * THRESHOLD - THRESHOLD / 2).toFixed(2);
card.style.transform = `perspective(${clientWidth}px) rotateX(${rotateY}deg) rotateY(${rotateX}deg) scale3d(1, 1, 1)`;
}
function resetStyles(e) {
card.style.transform = `perspective(${e.currentTarget.clientWidth}px) rotateX(0deg) rotateY(0deg)`;
}
if (!motionMatchMedia.matches) {
card.addEventListener("mousemove", handleHover);
card.addEventListener("mouseleave", resetStyles);
}