写了一个简单:移动鼠标就会移动的小球。
主要是高中同桌经常说:敌不动我动。就是球球挺晃眼的。
这是基本的布局。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>movingBall</title>
<style>
</style>
</head>
<body>
<div id="ball">
<span id="startbn">开始</span>
</div>
</body>
</html>
这是基本的样式:
#ball {
width: 50px;
height: 50px;
position: absolute;
background: yellow;
border-radius: 50%;
left:50%;
top:50%;
text-align: center;
line-height:50px;
}
#ball span{
display:inline-block;
width:30px;
height:30px;
font-size:10px;
background:lightblue;
border-radius:50%;
line-height:30px;
}
基本的脚本:
<script>
var ball = document.getElementById("ball");
var start=document.getElementById("startbn");
function randomN(min, max) {
return Math.floor(Math.random() * (max - min) + min)
};
function getInnerWidth() {
return window.innerWidth;
};
function getInnerHeight(){
return window.innerHeight;
}
function getCursor(){
document.onmousemove = function (e) {
if(e){
move();
}
};
}
function move(){
ball.style.left=randomN(0,getInnerWidth())+"px";
ball.style.top=randomN(0,getInnerHeight()/2)+"px";
}
start.onclick=function(){
move();
getCursor();
}
</script>
最终效果如下图: