JS 实现"飞天神猪"


<script type="text/javascript">
var imgLeftInt;
var imgTopInt;
var imgWidth;
var imgHeight;
var winWidth;
var winHeight;
var speedX = randomSpeed();
var speedY = randomSpeed();
var dirX = 1;
var dirY = 1;

function pigMove()
{

imgLeftInt = parseInt(document.images["image"].style.left);
imgTopInt = parseInt(document.images["image"].style.top);
imgWidth =  parseInt(document.images["image"].width);
imgHeight = parseInt(document.images["image"].height);
winWidth = parseInt(ScreenCal().windWidth);
winHeight = parseInt(ScreenCal().windHeight);

if(dirX == 1)
goRight();
else   
goLeft();

if (dirY == 1)
goDown();
else
goUp();       

}

function goUp()
{
document.images["image"].style.top = (imgTopInt - speedY) + "px";
if (imgTopInt <= 0)
{
dirY = 1;
speedY = randomSpeed();
}

}

function goDown()
{
document.images["image"].style.top = (imgTopInt + speedY) + "px";
if (imgTopInt > (winHeight - imgHeight))
{
dirY = 0;
speedY = randomSpeed();
}
}
function goLeft()
{
document.images["image"].style.left = (imgLeftInt - speedX) + "px";
if (imgLeftInt <= 0 )
{
dirX = 1;
speedX = randomSpeed();
}
}
function goRight()
{
document.images["image"].style.left = (imgLeftInt + speedX) + "px";
if (imgLeftInt > (winWidth - imgWidth) )
{
dirX = 0;
speedX = randomSpeed();
}
}

function randomSpeed()
{
randomNum = Math.floor(Math.random()*5) + 3;
return randomNum;
}



function ScreenCal()
{
if (document.body.clientWidth)
{
this.windWidth = document.body.clientWidth;
this.windHeight = document.body.clientHeight;
}
else
{
this.windWidth = window.innerWidth;
this.windHeight = window.clientHeight;
}
return this;

}



</script>

<a href="javascript:var t=setInterval('pigMove()', 30)">Start pig</a>
<a href="javascript:clearInterval(t)">Stop</a>
<img id="image" src="pig.jpg" style="position:absolute; left:20px; top:50px;" />


Demo !!
http://www.lovetc.xinxiban.com/Demo/pig.html


posted @ 2010-01-22 18:26  Mangos  阅读(288)  评论(0编辑  收藏  举报