js实现脉冲动画效果:
鼠标点击时,添加动画类,进而实现动画效果,鼠标离开时,移除动画类,回归静态图效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>点击实现脉冲动画效果</title>
<style>
/* 容器定位和尺寸设置 */
.pulse-container {
position: relative;
top: 50px;
left: 50px;
width: 50px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
border: 2px solid transparent; /* 透明色 */
}
.pulse-center {
width: 50px;
height: 50px;
background-color: rgb(137, 207, 240); /* 背景色 */
border-radius: 50%; /* 使其成为圆形 */
}
/* 创建两个用于脉冲动画的伪元素 */
.pulse-container::before,
.pulse-container::after {
content: '';
position: absolute;
width: 100%;
height: 100%;
border-radius: 50%;
border: 2px solid rgb(137, 207, 240);
opacity: 0.5;
}
/* 激活状态下的动画效果 */
.pulse-container.active::before,
.pulse-container.active::after {
animation: pulse 2s linear infinite; /* 2秒循环动画 */
}
/* 第二个伪元素延迟1秒,创造交错效果 */
.pulse-container.active::after {
animation-delay: 1s;
}
/* 定义脉冲动画关键帧 */
@keyframes pulse {
0% {
transform: scale(1); /* 开始时缩小到0.5倍 */
opacity: 1;
}
100% {
transform: scale(2); /* 结束时放大到1.5倍 */
opacity: 0; /* 完全透明 */
}
}
</style>
</head>
<body>
<div class="pulse-container">
<div class="pulse-center"></div>
</div>
</body>
<script>
const pulseContainer = document.querySelector('.pulse-container');
// 鼠标按下时添加动画
pulseContainer.addEventListener('mousedown', () => {
pulseContainer.classList.add('active');
});
// 鼠标松开时移除动画
pulseContainer.addEventListener('mouseup', () => {
pulseContainer.classList.remove('active');
});
</script>
</html>
实现效果:
(左侧为静态图,右侧为脉冲动态效果图)