Use js to implement free-moving code for small balls

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.