全篇大概2000 字(含代码),建议阅读时间15分钟。
引言
当用户将鼠标悬停在超级英雄卡片上时,卡片中的模态框将从卡片底部滑动 出来,显示出关于该英雄的更多详细信息。
1. HTML 结构
首先,我们需要构建卡片的HTML结构。每张卡片都包含一个图片部分和一个模态框,模态框中包含该超级英雄的详细信息:
每张卡片通过
<div>
标签来包装,包含了卡片的图片以及一个<div class="modal">
模态框。模态框中的内容展示了该超级英雄的详细信息。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>超级英雄卡片</title>
<link href="https://fonts.googleapis.com/css2?family=Helvetica:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<!-- 蜘蛛侠卡片 -->
<div class="card">
<div class="card-image" id="spider-man">
<img src="spider-man.jpg" alt="Spider-Man">
<div class="modal">
<h2>蜘蛛侠</h2>
<p><strong>年份:</strong>2002</p>
<p><strong>评分:</strong>7.3</p>
<p><strong>介绍:</strong>彼得·帕克是一名普通的高中生,意外获得了超能力,成为了城市的保护者。</p>
<p><strong>演员:</strong>托比·马奎尔</p>
</div>
</div>
</div>
<!-- 其他卡片 -->
<!-- 可以添加更多超级英雄卡片,如钢铁侠和美国队长 -->
</div>
<script src="script.js"></script>
</body>
</html>
2. CSS 样式
在CSS中,我们定义了卡片的样式,包括卡片的大小、边框阴影、模态框的隐藏与显示等。模态框最开始是隐藏在卡片底部的,当用户将鼠标悬停在卡片上时,模态框会滑动出来。
卡片样式:使用
box-shadow
给卡片添加阴影效果,并且通过transform: scale(1.05)
在鼠标悬停时进行缩放,使卡片有更吸引人的交互效果。模态框样式:模态框初始状态下隐藏在卡片底部(通过
bottom: -100%
),当鼠标悬停时,通过transition
和bottom: 0
滑动显示。
body {
font-family: 'Helvetica', sans-serif;
background-color: #f5f5f7;
color: #333;
margin: 0;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 200px auto;
text-align: center;
}
.card {
position: relative;
display: inline-block;
width: 200px;
margin: 15px;
overflow: hidden;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
transition: transform 0.3s;
}
.card:hover {
cursor: pointer;
transform: scale(1.05);
}
.card-image img {
width: 100%;
height: 300px;
border-radius: 10px 10px 0 0;
}
.modal {
position: absolute;
bottom: -100%;
left: 0;
right: 0;
background-color: rgba(44, 62, 80, 0.8);
color: white;
padding: 15px;
border-radius: 0 0 10px 10px;
transition: bottom 0.3s;
}
.card:hover .modal {
bottom: 0;
}
.modal h2 {
margin: 0;
font-size: 1.5em;
color: #ecf0f1;
}
.modal p {
margin: 5px 0;
font-size: 0.9em;
}
3. JavaScript 动态效果
接下来我们使用JavaScript实现鼠标悬停时模态框的动态显示效果。通过mouseenter
和mouseleave
事件监听,我们可以控制模态框的显示和隐藏。
我们通过监听鼠标进入和离开的事件,控制模态框的
bottom
属性,来实现模态框的动态滑动效果。
document.querySelectorAll('.card').forEach(card => {
card.addEventListener('mouseenter', () => {
card.querySelector('.modal').style.bottom = '0';
});
card.addEventListener('mouseleave', () => {
card.querySelector('.modal').style.bottom = '-100%';
});
});
总结
通过这样的设计,用户可以在不离开页面的情况下查看每个超级英雄的详细信息,并享受到流畅的交互体验。