双击喜欢
html部分
<h3>双击喜欢这个图 <i style="color: red;" class="iconfont icon-xin"></i></h3>
<small>你喜欢了 <span class="count">0</span> 次</small>
<div class="area">
<i style="color: red;" class="iconfont icon-xin heart"></i>
</div>
css部分
*{
margin: 0;
padding: 0;
}
body{
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 30px;
}
.area{
width: 200px;
height: 200px;
background: black;
box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.5);
position: relative;
}
.heart{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
font-size: 34px !important;
opacity: 0;
}
@keyframes active {
from{
opacity: 1;
}
to{
opacity: 0;
transform: scale(10);
}
}
.active{
animation: active .7s;
}
js部分
// 获取对象
const heart = document.querySelector(".heart");
const area = document.querySelector(".area");
const count = document.querySelector(".count");
// 单机次数
let num = 0;
let last_time = 0;
area.addEventListener("click", function (e) {
if (last_time == 0) {
last_time = new Date().getTime();
} else {
if (new Date().getTime() - last_time <= 800) {
show_heart(e)
last_time = 0;
} else {
last_time = new Date().getTime();
}
}
})
// 显示心
function show_heart(e) {
const off_x = e.offsetX;
const off_y = e.offsetY;
heart.style.left = off_x + "px";
heart.style.top = off_y + "px";
heart.classList.add("active");
num++;
count.innerHTML = num;
setTimeout(() => {
heart.classList.remove("active");
}, 700)
}
效果