直接上代码,粘贴到IDE上自行运行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>小球游戏</title>
<style>
*{
margin: 0px;
padding: 0px;
}
#ball{
width: 100px;
height: 100px;
border-radius: 50%;
background-color: red;
position: absolute;
}
#board{
width: 300px;
height:50px;
background-color: chocolate;
position: absolute;
}
</style>
<script>
var directX= "right";
var directY = "bottom";
var speed = 2;//速度
window.onload = function (){
ball = document.getElementById("ball");
//获取浏览器的宽高(因为浏览器兼容的问题,不是所有浏览器都可以这样获取
width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
width = parseInt(width);
height = parseInt(height);
//获取下面的板子
board = document.getElementById("board");
board.style.left = "0px";
board.style.top = (height - 50) + "px";
inter = setInterval( function (){
moveBall();
},10);
document.onkeydown = function (event){
//获取键盘按下的是哪一个
var which = event.keyCode || event.which;
var left = parseInt(board.style.left);
if(which == 37){//向左
if(left - 10 >= 0)
board.style.left = (left-10) +"px";
}else if(which == 39){//向右
if(left + 10 + 300 <= width )
board.style.left = (left+10) +"px";
}
}
}
/**
* 移动球
*/
function moveBall (){
var left = ball.style.left;
left = left == "" ? 0 : parseInt(left);
var top = ball.style.top;
top = top == "" ? 0 : parseInt(top);
//水平移动
if(directX == "right"){
ball.style.left = (left + speed) + "px";
}else{
ball.style.left = (left - speed) + "px";
}
//垂直移动
if(directY == "bottom"){
ball.style.top = (top + speed) + "px";
}else{
ball.style.top = (top - speed) + "px";
}
//判断生死
//碰到边界的时候需要改变方向
if(left <= 0){
directX = "right";
}
if(left + speed + 100 >= width){
directX = "left";
}
if(top <= 0){
directY = "bottom";
}
if(top + speed + 100 >= height - 50){//碰到底边
var x = parseInt(board.style.left);
//小球必须在板子上
if(left + 50 >= x && left + 50 <= x + 300){
directY = "top";
} else if(top + speed + 100 >= height){
clearInterval(inter);
alert("游戏结束");
}
}
}
</script>
</head>
<body>
<div id="ball"></div>
<div id="board"></div>
</body>
</html>