始终飞向鼠标的纸飞机
实现思路:
鼠标移动事件( onmousemove )是鼠标在页面上进行移动时触发事件处理程序,可以在该事件中用document对象实时读取鼠标在页面中的位置;
纸飞机当前的坐标,是距离最近的距具有参照物元素距离减内容区域的二分之一;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 100vh;
background: linear-gradient(2000deg, #005bea, #00c6fb);
}
#plane {
color: #fff;
font-size: 70px;
position: absolute;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div id="plane">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</div>
</body>
</html>
<script>
let plane = document.getElementById('plane')
let deg = 0,
ex = 0,
ey = 0,
vx = 0,
vy = 0,
count = 0
// addEventListener(事件监听方法),该方法将时间处理程序附加到指定元素
window.addEventListener("mousemove", (e) => {
// 属性名 飞机的x坐标 距离最近的具有参照物的元素左边的距离 内容区域的宽/2
ex = e.x - plane.offsetLeft - plane.clientWidth / 2
// 属性名 飞机的y坐标 距离最近的具有参照物的元素上边的距离 内容区域的高/2
ey = e.y - plane.offsetTop - plane.clientHeight / 2
// Math.atan()是用于返回一个数
deg = 360 * Math.atan(ey / ex) / (2 * Math.PI) + 45
if (ex < 0) {
deg += 180
}
count = 0
})
function draw() {
plane.style.transform = 'rotate(' + deg + 'deg)'
if (count < 100) {
vx += ex / 100
vy += ey / 100
}
plane.style.left = vx + 'px'
plane.style.top = vy + 'px'
count++
}
setInterval(draw, 1)
</script>

浙公网安备 33010602011771号