先看效果图:
1.首先要解决如何让一个组件变成爱心的形状
用伪类实现,具体原理网上有
.heart {
position: fixed;
opacity: 1;
scale: 3;
width: 10px;
height: 10px;
background: red;
transform: rotate(45deg);
}
.heart:after,.heart:before {
content: "";
width: inherit;
height: inherit;
background: inherit;
border-radius: 50%;
position: absolute;
}
.heart:after{
top: -5px;
}
.heart:before {
left: -5px;
}
2.动画
首先做一个@keyframes使爱心从当前位置向上移动
@keyframes move {
100% {
transform: translateY(-20px) rotate(45deg);
opacity: 0;
}
}
rotate是保持爱心的形状,因为做出的形状其实是爱心顺时针旋转45度的图形
window.onclick = function() {
const heart = document.createElement("div")
document.body.appendChild(heart)
heart.classList.add("heart")
heart.style.left = event.clientX + "px"
heart.style.top = event.clientY + "px"
heart.style.animation = "move 1s normal forwards"
setTimeout(function () {
document.body.removeChild(heart)
},1000)
heart.style.backgroundColor = "rgb(" + (Math.random() * 255) + "," + (Math.random() * 255) + "," + (Math.random() * 255) + ")"
};
这段代码实现监听点击,并且在每次点击都创建一个爱心(div)在点击的位置,然后逐渐上浮消失,并且每次点击的颜色也是随机的。
为了防止占用内存(咱也不知道自动回收及不及时),在一秒后同步删除
2024.2.2改:原本是用document.addEventListener("mousedown",function() {...})但是这样如果页面上有其他需要监听点击的事件就失效了(各位可以试试)不知道为什么换成这样就好了,有懂得大佬指点一二