利用随机数和switch…case设计不定向位移。
基础动画:
<script type="text/javascript"> //创建一个简单函数,样式变化:垂直下移100px function movD(x) { x.style.transform="translateY(100px)" } //创建一个复合函数,直接调用上述简单函数 //样式变化:下移同时改变颜色 function comb(x) { x.style.backgroundColor="red"; movD(x) } </script> //在div上以onmouseover="comb(this)"直接调用复合函数 <div style="width: 100px; height: 68px; background-color: #49AFCD;" onmouseover="swt(this)" "></div>
随机方向实现方法:
随机数:
//利用Math.random()产生一个随机数,将其放大10倍用Math.floor()取整; //将获得的整数与4做取模,可随机获得0,1,2,3 rd = Math.random(); fl = Math.floor(rd * 10); md = fl%4;
switch…case:
利用0,1,2,3作为switch…case的4个条件分别执行不同的函数:
function swt(x) { rd = Math.random()*10; fl = Math.floor(rd); md = fl%4; switch (md) { case 1 : movR(x); break; case 2 : movL(x); break; case 3 : movU(x); break; case 0 : movD(x); break; } }
完整代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Untouchable</title> <style type="text/css"> div{position: absolute; top: 300px; left: 500px;} </style> </head> <body> <script type="text/javascript"> function movR(x) { x.style.transform="translateX(100px)" } function movL(x) { x.style.transform="translateX(-100px)" } function movU(x) { x.style.transform="translateY(-100px)" } function movD(x) { x.style.transform="translateY(100px)" } //--------------------------- function swt(x) { rd = Math.random()*10; fl = Math.floor(rd); md = fl%4; switch (md) { case 1 : movR(x); break; case 2 : movL(x); break; case 3 : movU(x); break; case 0 : movD(x); break; } } </script> <div style="width: 100px; height: 68px; background-color: #49AFCD;" onmouseover="swt(this)"> </div> <div style="width: 10px; height: 10px; background-color: #C43C35; text-align: center;"></div> </body> </html
END