js实现鼠标点击飘爱心效果

时间:2022-09-23 20:14:50

本文实例为大家分享了js实现鼠标点击飘爱心的具体代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html lang="en">
 
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>鼠标点击特效</title>
 <link rel="stylesheet" href="https://at.alicdn.com/t/font_1743249_grf4shm1g3t.css" >
 <style>
  html {
   cursor: pointer;
  }
 
  h3 {
   text-align: center;
   user-select: none;
  }
 
  .div-box {
   width: 30px;
   height: 30px;
   font-size: 30px;
   position: absolute;
  }
 </style>
</head>
 
<body>
 <h3>请点击屏幕查看效果</h3>
 <script>
  window.onclick = function (e) {
   //存储需要的颜色
   let arr = ["red", "yellow", "green", "pink", "blue", "purple", "orangered"];
   //随机产生一个颜色
   let heartNum = Math.floor(Math.random() * arr.length);
   let div = document.createElement("div");
   div.setAttribute("class", "iconfont iconzan div-box");
   div.style.color = arr[heartNum];
   document.body.appendChild(div);
   //获得鼠标的x,y轴的位置,并减去自身宽高的一半,使其能够在爱心的正中心
   let x = e.pageX - div.offsetWidth / 2;
   let y = e.pageY - div.offsetHeight / 2;
   div.style.left = x + "px";
   div.style.top = y + "px";
   //获得0-1的整数
   let num = Math.round(Math.random());
   let timer = setInterval(() => {
    y -= 10;
    if (num === 0) x -= 10;
    else x += 10;
    div.style.left = x + "px";
    div.style.top = y + "px";
    //如果超出屏幕范围,则删除此节点
    if (y < -100) {
     clearInterval(timer);
     div.remove();
    }
   }, 100);
  }
 </script>
</body>
 
</html>

效果图如下

js实现鼠标点击飘爱心效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/zhujun09/article/details/106902275