SoFunction
Updated on 2025-02-28

Use js to implement free movement code for small balls


<!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 code can be placed in any position and executed in sequence in sequence. It is usually placed between the head tags-->
<script type="text/javascript">

//Define global variables
//Ball coordinates
    ballX=0;
    ballY=0;
//The direction of the ball moving in the x and y axis
    directX=1;
    directY=1;
//The ball moves
    function ballMove(){
//The ball moves
        ballX+=2*directX;
        ballY+=2*directY;
//Change the top and width of the ball at the same time
        =ballY+'px';
        =ballX+'px';
//();//offsetwidth is used to obtain the width of the element in JS, and the corresponding offsetHeight is also used.
//Judge the direction
        //learInterval(i);
        if(ballX+>= ||ballX<=0){
            directX=-directX;
        }
        if(ballY+>= || ballY<=0){
            directY=-directY;
        }
    }
//Timer
    var i=setInterval("ballMove()",10);
</script>
</head>
<body>
    <div style="width:400px;height:300px;border:1px solid silver;POSITION: absolute; TOP: 100px">
        <div style="position:absolute;left:0px;top:0px;"><img src=""></div>
    </div>
</body>
</html>