|
热门文章 |
|
|
|
相关文章 |
|
没有相关文章 |
|
|
JavaScript实现碰壁反弹效果 |
来源:源码爱好者 更新时间:2011/1/1 11:11:00 阅读次数: 我要投稿 |
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>碰壁反弹</title> <style> #text {width:500px;height:300px;border:10px red solid;margin:0 auto;position:relative;} #div1 {width:50px;height:50px;border:5px yellow solid;position:absolute;} </style> </head> <body> <div id="text"> <div id="div1"></div> </div> <input type="button" value="开始"/> <input type="button" value="变大"/> <input type="button" value="变小"/> <input type="button" value="停止"/> </body> <script type="text/javascript"> var text = document.getElementById("text"); var div1 = document.getElementById("div1"); var a = div1.offsetTop; var b = div1.offsetLeft; var id = true; var id2 = true; var ss=null; var qw = 50; var ge = true; var gg = true; function pbft(){ var width = text.clientWidth; var height = text.clientHeight; var width2 = div1.offsetWidth; var height2 = div1.offsetHeight; var width3 = width - width2; var height3 = height - height2; if(id){ if(b<width3){ b++; this.div1.style.left = b + "px"; }else{ id = false; } }else{ if(b>0){ b--; this.div1.style.left = b + "px"; }else{ id=true; } } if(id2){ if(a<height3){ a++; this.div1.style.top = a + "px"; }else{ id2 = false; } }else{ if(a>0){ a--; this.div1.style.top = a + "px"; }else{ id2=true; } } } function dian(){ var da = document.getElementsByTagName("input")[1]; var xiao = document.getElementsByTagName("input")[2]; var stop = document.getElementsByTagName("input")[3]; var kais = document.getElementsByTagName("input")[0]; ade(da,'click',function(){bd()}); ade(xiao,'click',function(){bx()}); ade(stop,'click',function(){tz()}); ade(kais,'click',function(){ks()}); } function ade(a,b,c){ if (a.addEventListener) { a.addEventListener(b,c,false) }else{ a["on"+b] = c ; } } function ks(){ if (ss) { clearInterval(ss); } ss = setInterval(pbft,10); } function bd(){ if (qw<=200) { qw++; this.div1.style.width = qw + "px"; this.div1.style.height = qw + "px"; clearTimeout(ge); gg = setTimeout(bd,20) } } function bx(){ if (qw>50) { qw--; this.div1.style.width = qw + "px"; this.div1.style.height = qw + "px"; clearTimeout(gg); ge = setTimeout(bx,20) } } function tz(){ clearInterval(ss); clearTimeout(gg); clearTimeout(ge); } dian(); </script> </html> |
特效说明: |
JavaScript碰壁反弹效果代码,碰壁物体可设置大小,设置完成,点击“开始”可看到运动效果,当物体的四边或论是哪个边碰到外框时,都会自动反弹,类似的效果被广泛应用于游戏开发中。 |
|
上一篇文章: JavaScript 过河游戏下一篇文章: JavaScript编写的打砖块网页游戏 |
|
|