JS Uniform motion Stop condition

Source: Internet
Author: User

Uniform motion, how to stop it when it arrives at the specified position?

Principle:

1, the difference between the object and the target distance is less than or equal to the speed, that is, stop

2, then move the object position equal to the target position

Example: Uniform motion Stop

HTML section

<input type= "button" value= "100 m" id= "btn1" onclick= "startmove (+);"/><input type= "button" value= "300 m" id= "Btn2" onclick= "Startmove", "/><div id=" Div1 "></div><div id=" Div2 "></div><div id= "Div3" ></div><style> #div1 {position:absolute; left:600px; width:100px; height:150px; background:red;} #div2 {position:absolute; left:300px; height:800px; width:1px; background:black;} #div3 {position:absolute; left:100px; height:800px; width:1px; background:black;} </style>

JS section:

<script>var timer = null;function Startmove (itarget) {var odiv = document.getElementById ("Div1"); var speed; Clearinterval (timer); timer = setinterval (function () {if (odiv.offsetleft<itarget) {speed = 7;} else {speed =-7;} if (Math.Abs (itarget-odiv.offsetleft) <= 7) {clearinterval (timer); oDiv.style.left = ITarget + "px";} else {Odiv.style . left = Odiv.offsetleft + speed + "px";}},30);} </script>

  

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.