要在卡片之间添加向上或向下滑动的动画效果,可以使用CSS动画和JavaScript来实现。以下是一个简单的示例,展示了如何实现这种颤动效果。
@keyframes
规则定义动画序列,并使用animation
属性将其应用到元素上。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Card Shake Animation</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="card" id="card1">Card 1</div>
<div class="card" id="card2">Card 2</div>
<button onclick="shakeCard('card1')">Shake Card 1</button>
<button onclick="shakeCard('card2')">Shake Card 2</button>
<script src="script.js"></script>
</body>
</html>
.card {
width: 200px;
height: 200px;
background-color: #f0f0f0;
margin: 20px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
transition: transform 0.3s ease-in-out;
}
@keyframes shake-up {
0%, 100% { transform: translateY(0); }
25% { transform: translateY(-10px); }
75% { transform: translateY(10px); }
}
@keyframes shake-down {
0%, 100% { transform: translateY(0); }
25% { transform: translateY(10px); }
75% { transform: translateY(-10px); }
}
function shakeCard(cardId, direction = 'up') {
const card = document.getElementById(cardId);
let animationName;
if (direction === 'up') {
animationName = 'shake-up';
} else if (direction === 'down') {
animationName = 'shake-down';
}
card.style.animation = `${animationName} 0.5s`;
setTimeout(() => {
card.style.animation = '';
}, 500);
}
shake-up
和shake-down
,分别用于向上和向下滑动。shakeCard
函数接受卡片ID和方向参数,根据方向应用相应的动画,并在动画结束后清除动画效果。@keyframes
中的位移值或动画持续时间,以达到预期效果。通过这种方式,可以在卡片之间添加流畅且吸引人的滑动动画效果。
领取专属 10元无门槛券
手把手带您无忧上云