1.设计思路:
- 通过鼠标点击获取星星出现的位置
- 创建星星这个对象
- 设置星星的属性
- 用匿名函数实现星星在几s后消失
- 设置星星的样式
- 给星星随机宽高使星星随机变化
代码展示:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <style type="text/css"> body{ position: relative; } img{ position: absolute; } </style> <body> <img src="./starsel.png" alt=""> <script type="text/javascript"> document.onclick=function(e){ console.log("点击了屏幕",e.clientX,e.clientY) let start = document.createElement("img"); start.setAttribute("src","./starsel.png"); let width = parseInt(Math.random()*30)+30 start.style.width = width+"px"; start.style.height = width+"px"; start.style.left =e.clientX-(width/2)+"px"; start.style.top =e.clientY-(width/2)+"px"; document.body.appendChild(start); setTimeout(function(){ start.remove() },2000) } </script> </body> </html>
2.运行结果