实例:始终飞向鼠标的纸飞机
技术栈:HTML+CSS+JS
字体图标库:font-awesome
效果:
源码:
【html】【js】
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>始终飞向鼠标的纸飞机</title>
<!-- 引入字体图标 -->
<link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link rel="stylesheet" href="../css/80.css">
</head>
<body>
<div id="plane">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</div>
<script>
let plane=document.getElementById('plane');
let deg=0,ex=0,ey=0,vx=0,vy=0,count=0;
window.addEventListener('mousemove',(e)=>{
ex=e.pageX-plane.offsetLeft-plane.clientWidth/2;
ey=e.pageY-plane.offsetTop-plane.clientHeight/2;
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>
</body>
</html>
【css】
*{
/* 初始化 */
margin: 0;
padding: 0;
}
body{
/* 100%窗口高度 */
height: 100vh;
/* 渐变背景 */
background: linear-gradient(200deg,#005bea,#00c6fb);
}
#plane{
color: #fff;
font-size: 70px;
/* 绝对定位 */
position: absolute;
/* 弹性布局 水平+垂直居中 */
display: flex;
justify-content: center;
align-items: center;
}