abstrait:利用隨機數(shù)和switch…case設(shè)計不定向位移?;A(chǔ)動畫:<script type="text/javascript"> //創(chuàng)建一個簡單函數(shù),樣式變化:垂直下移100px function movD(x) { &n
利用隨機數(shù)和switch…case設(shè)計不定向位移。
基礎(chǔ)動畫:
<script type="text/javascript"> //創(chuàng)建一個簡單函數(shù),樣式變化:垂直下移100px function movD(x) { x.style.transform="translateY(100px)" } //創(chuàng)建一個復(fù)合函數(shù),直接調(diào)用上述簡單函數(shù) //樣式變化:下移同時改變顏色 function comb(x) { x.style.backgroundColor="red"; movD(x) } </script> //在div上以onmouseover="comb(this)"直接調(diào)用復(fù)合函數(shù) <div style="width: 100px; height: 68px; background-color: #49AFCD;" onmouseover="swt(this)" "></div>
隨機方向?qū)崿F(xiàn)方法:
隨機數(shù):
//利用Math.random()產(chǎn)生一個隨機數(shù),將其放大10倍用Math.floor()取整; //將獲得的整數(shù)與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個條件分別執(zhí)行不同的函數(shù):
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