A friend who is learning javascript can take it as a small exercise. Enhance your coding capability.
Reference code:
Copy codeThe Code is as follows:
<! 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">
<! -- JavaScript code can be placed in any position and executed sequentially among head labels. -->
<Script type = "text/javascript">
// Define global variables
// Ball Coordinate
BallX = 0;
BallY = 0;
// Move the ball in the direction of x and Y axes
DirectX = 1;
DirectY = 1;
// Move the ball
Function ballMove (){
// Move the ball
BallX + = 2 * directX;
BallY + = 2 * directY;
// Modify the top and width of the ball simultaneously
Div2.style. top = ballY + 'px ';
Div2.style. left = ballX + 'px ';
// Window. alert (div1.offsetWidth); // offsetwidth is used to obtain the width of an element in JS, which corresponds to offsetHeight.
// Determine turning
// LearInterval (I );
If (ballX + div2.offsetWidth> = div1.offsetWidth | ballX <= 0 ){
DirectX =-directX;
}
If (ballY + div2.offsetHeight> = div1.offsetHeight | ballY <= 0 ){
DirectY =-directY;
}
}
// Timer
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;"> </div>
</Div>
</Body>
</Html>
Figure: