Constant Speed and variable speed (buffer) movement in Javascript

Source: Internet
Author: User

Personal site

The movement of a div is actually a change in the distance between it and the browser border. If the change rate is certain, it isConstant SpeedIf the change rate is not certain, it is a variable speed movement. When the change rate is proportional to the distance from the browser's border, it can be said that DIV is doingBuffer Motion.
In fact, it is very simple to use a timer to change the border distance of the DIV aggregation browser at intervals.

For example, uniform motion:

Enter the Timer: (every 30 ms)
If (whether to reach the end point)
{Stop timer}
Else do {Change distance}

The method of changing the distance determines whether the constant speed or variable speed (buffer) motion.

For example:

Javascript Code
  1. VaRTimer =Null;
  2. FunctionStartmove ()
  3. {
  4. VaROdiv = Document. getelementbyid ('Div1');
  5. Clearinterval (timer );
  6. Timer = setinterval (Function(){
  7. VaRIspeed = 1;
  8. If(Odiv. offsetleft> = 300)
  9. {
  10. Clearinterval (timer );
  11. }
  12. Else
  13. {
  14. Odiv. style. Left = odiv. offsetleft + ispeed +'Px';
  15. }
  16. }, 30 );
  17. };

Buffer movement:

Java code
  1. VaR timer =Null;
  2. Function startmove ()
  3. {
  4. VaR itarget =300;
  5. VaR odiv = Document. getelementbyid ('Div1');
  6. Clearinterval (timer );
  7. Timer = setinterval (function (){
  8. VaR ispeed = (iTarget-oDiv.offsetLeft )/8;
  9. Ispeed = ispeed>0? Math. Ceil (ispeed): Math. Floor (ispeed );
  10. Ispeed = math. Ceil (ispeed );
  11. If(Odiv. offsetleft = itarget)
  12. {
  13. Clearinterval (timer );
  14. }
  15. Else
  16. {
  17. Odiv. style. Left = odiv. offsetleft + ispeed +'Px';
  18. }
  19. Document. Title = odiv. style. Left +''+ Ispeed;
  20. },30);
  21. };


In this way, a motion frame is ready! The principle is very simple, but it still needs to be improved. Come on!

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.