- 相關(guān)推薦
javascript實(shí)現(xiàn)小球的自由移動(dòng)代碼
用javascript實(shí)現(xiàn)小球的自由移動(dòng)是不是很神奇啊?下面小編交給大家實(shí)現(xiàn)的方法,歡迎閱讀以下代碼,更多詳情請(qǐng)關(guān)注應(yīng)屆畢業(yè)生考試網(wǎng)。
代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>javascript實(shí)現(xiàn)小球的自由移動(dòng)-www.javaweb.cc</title>
<link rel="stylesheet" type="text/css" href="">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript">
//定義全局變量
//小球坐標(biāo)
ballX=0;
ballY=0;
//小球在x,y軸移動(dòng)的方向
directX=1;
directY=1;
//小球移動(dòng)
function ballMove(){
//小球移動(dòng)
ballX+=2*directX;
ballY+=2*directY;
//同時(shí)修改小球的top 和width
p2.style.top=ballY+'px';
p2.style.left=ballX+'px';
//window.alert(p1.offsetWidth);
//offsetwidth在JS中是獲取元素的寬,對(duì)應(yīng)的還有offsetHeight
//判斷轉(zhuǎn)向
//learInterval(i);
if(ballX+p2.offsetWidth>=p1.offsetWidth || ballX<=0){
directX=-directX;
}
if(ballY+p2.offsetHeight>=p1.offsetHeight || ballY<=0){
directY=-directY;
}
}
//定時(shí)器
var i=setInterval("ballMove()",10);
</script>
</head>
<body>
<p id="p1" style="width:400px;height:300px;border:1px solid silver;POSITION: absolute; TOP: 100px">
<p id="p2" style="position:absolute;left:0px;top:0px;">
<img src="ball.png">
</p>
</p>
</body>
</html>
【javascript實(shí)現(xiàn)小球的自由移動(dòng)代碼】相關(guān)文章:
JavaScript簡(jiǎn)單實(shí)現(xiàn)放大鏡效果代碼09-24
Javascript實(shí)現(xiàn)全選并賦值給文本框代碼實(shí)例08-24
php動(dòng)態(tài)生成JavaScript代碼10-03
JavaScript重置表單的實(shí)現(xiàn)09-23
PHP滾動(dòng)日志的代碼實(shí)現(xiàn)11-15
Java 隊(duì)列實(shí)現(xiàn)原理及簡(jiǎn)單實(shí)現(xiàn)代碼09-13
php實(shí)現(xiàn)無限級(jí)分類實(shí)現(xiàn)代碼07-03