<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.demo {
width: 50px;
height: 50px;
background: url(./img/snow.png) 0/cover;
position: absolute;
}
.demo1 {
width: 50px;
height: 50px;
border: chocolate 1px solid;
position: absolute;
}
</style>
</head>
<body>
<script>
//创建十个并排div,后期将雪花放在div中
for (let i = 0; i < 5; i++) {
let box = document.createElement('div')
document.body.appendChild(box)
box.classList.add('demo1')
box.style.left = 100 + 60 * i + 'px'
box.style.top = '100px'
}
//当鼠标移动时触发,出现div
window.onmousemove = function (e) {
let demo = document.createElement('div')
document.body.appendChild(demo)
demo.classList.add('demo')
let x = e.pageX
let y = e.pageY
demo.style.left = x + 'px'
demo.style.top = y + 'px'
//随机控制雪花飘的方向,左或者右
let direction = Math.round(Math.random())
let kuang = document.getElementsByClassName('demo1')
//随机得到十个div的下标,将雪花后期随机飘进这十个div中
let boxIndex = Math.floor(Math.random() * kuang.length)
console.log(kuang.length);
let time = setInterval(() => {
direction ? (x -= 10) : (x += 10)
y -= 10
demo.style.left = x + 'px'
demo.style.top = y + 'px'
//当雪花的top位置小于100时,飘进盒子中
if (y < 100) {
clearInterval(time)
demo.style.left = kuang[boxIndex].style.left
demo.style.top = kuang[boxIndex].style.top
}
}, 100)
}
</script>
</body>
</html>