上次幫一個粉絲寫了這個純HTML加CSS實現3D立體動態相冊,女朋友看到了,說我就沒有給她寫過這些小玩意,哄她開心。
蛤,聽了這話我就很難過。我對她說,等着,馬上爲你量身定做一個去,你愛玩遊戲,整好今天週末給你做個小小的遊戲,讓你耍一耍~哈哈哈哈,我太機智了。
效果如下:
css部分代碼:
<style>
#main{
width: 600px;
height:300px;
background: gray;
margin-left: 300px;
position: absolute;
}
#ball {
width: 20px;
height: 20px;
background-color: yellow;
border-radius: 50%;
position: relative;
}
#board{
width: 80px;
height: 10px;
background: red;
position: absolute;
bottom: 0;
left: 450px;
}
</style>
html部分代碼:
<div id="main">
<div id="ball" style="left:0;top:0;"> </div>
<div id="board"></div>
</div>
js部分代碼:
<script>
var main = document.getElementById('main');
var ball = document.getElementById('ball');
var board = document.getElementById('board');
//設置小球運動速度
ball.speedX = 3;
ball.speedY = 4;
//控制小球運動軌跡
ball.run = function(){
//parseInt:將字符串轉換爲整數
var left = parseInt(this.style.left) + this.speedX;
var top = parseInt(this.style.top) + this.speedY;
this.style.left = left + 'px';
this.style.top = top + 'px';
this.check( left,top);
}
//檢測碰撞實踐
ball.check = function(left,top){
if(left <= 0 || left >= 580){
this.turnX();
}
//球撞到上邊轉向
if(top <= 0){
this.turnY();
}
//小球碰到下邊時,未用擋板則輸
if(top >= 282){
clearInterval(); //非setInterval
alert("您輸了!點擊確定再來一局!");
this.init();
}
//碰撞擋板後Y轉向
var board_left = parseInt(board.style.left); //擋板的左邊距
var board_top = parseInt(board.style.top); //擋板的上邊距
if(left >= board_left && left <= board_left+80 && top+20 >=board_top){
this.turnY();
}
}
//控制小球轉向
ball.turnX = function(){
this.speedX = -this.speedX;
}
ball.turnY= function(){
this.speedY= -this.speedY;
}
//設置小球移動時間間隔爲20ms
var clock = setInterval(function(){
ball.run();
},20)
//移動擋板
main.onmousemove=function(e){
//如果進入非main區,則直接返回,無變化。用於防止鼠標進入紅色擋板內發生相對於擋板的移動。
if(e.target!== main){ //嚴格不等於
return;
}
//假設位置是長方形擋板的底邊中點。
board.style.left=e.offsetX-25+'px'; //數字與px(像素)之間不可有空格。
board.style.top=e.offsetY-9+'px';
}
ball.init = function(){
ball.style.left = 0;
ball.style.top = 0;
}
</script>
畢竟是閒着沒事給女朋友寫的小玩意,功能單一,隨便消遣消遣時間罷了,路過的大佬不求點贊,只求莫噴。哈哈哈…