js动态创建星空
又是个淅淅沥沥的雨天,不知道今晚能不能看见星星😟。趁着有空做了个星空(o゜▽゜)o☆
步骤
- 设置一个定时器
- 创建节点
- 设置图片的相关属性
- 将星星节点放入可视窗口内
- 插入节点
- 点击星星将其删除(另外加的事件)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body,html{
margin: 0;
padding: 0;
height: 100%;
background-color: black;
}
img{
position: absolute;
}
</style>
<body>
<script src="../js/public.js"></script>
<script>
setInterval(function(){
//创建节点
var img = document.createElement('img')
//设置图片的引用src
img.src = '../images/star.gif'
img.width = rand(5,20)
img.height = img.width
//把星星放在可视窗口内
//window.innerWidth,window.innerHeight可视窗口的宽高
img.style.left = rand(0,window.innerWidth-img.width)+'px'
img.style.top = rand(0,window.innerHeight-img.height)+'px'
//把节点插入
document.body.appendChild(img)
//把循环给每一个img标签添加点击事件
var imgs = document.querySelectorAll('img')
for(var i=0;i<imgs.length;i++){
imgs[i].onclick = function(){
this.remove()
}
}
},1000)
</script>
</body>
</html>
JS文件随机生成星星的位置
function rand(m,n){
var min = Math.min(m,n) //生成传进来最小的数字,并返回
var max = Math.max(m,n) //生成传进来最大的数字,并返回
min = Math.ceil(min) //向上取整,取小数部分清0,并向整数进1
max = Math.floor(max) //向下取整,小数部分舍弃
return min = Math.floor(Math.random()*(max-min+1))
}```
效果图:
星空是动态的噢~✨✨✨
下面是用到的星星图片,可自取噢🤗
以上就是我的星空啦~