用js實現小球的自由行動程式碼

來源:互聯網
上載者:User

正在學習javascript 的朋友可以把它當作小練習動手做一做。加強自己的動手編碼能力。

參考代碼:
複製代碼 代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>ggggg</title>
<link rel="stylesheet" type="text/css" href="">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!--js代碼可以放置在任意位置,按照先後順序依次執行 一般放在head標籤之間-->
<script type="text/javascript">

    //定義全域變數
    //小球座標
    ballX=0;
    ballY=0;
    //小球在x,y軸移動的方向
    directX=1;
    directY=1;
    //小球移動
    function ballMove(){
        //小球移動
        ballX+=2*directX;
        ballY+=2*directY;
        //同時修改小球的top 和width
        div2.style.top=ballY+'px';
        div2.style.left=ballX+'px';
        //window.alert(div1.offsetWidth);//offsetwidth在JS中是擷取元素的寬,對應的還有offsetHeight
        //判斷轉向
        //learInterval(i);
        if(ballX+div2.offsetWidth>=div1.offsetWidth ||ballX<=0){
            directX=-directX;
        }
        if(ballY+div2.offsetHeight>=div1.offsetHeight || ballY<=0){
            directY=-directY;
        }
    }
    //定時器
    var i=setInterval("ballMove()",10);
</script>
</head>
<body>
    <div id="div1" style="width:400px;height:300px;border:1px solid silver;POSITION: absolute; TOP: 100px">
        <div id="div2" style="position:absolute;left:0px;top:0px;"><img src="ball.png"></div>
    </div>
</body>
</html>

圖:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.