Home > Web Front-end > JS Tutorial > body text

How to use JS to implement buffering motion

php中世界最好的语言
Release: 2018-06-01 14:19:58
Original
1146 people have browsed it

This time I will show you how to use JS to implement buffering movement, and what are the precautions for using JS to implement buffering movement. The following is a practical case, let's take a look.

Buffering requires numerical rounding, rounding up:

Math.ceil() Rounding downMath.floor()

The effect of slowly slowing down the moving speed, moving speed = (end position - current position) / a number

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS缓冲运动</title>
<style>
#p{
  width:150px;
  height:150px;
  background:#0C6;
  position:absolute;
  left:0;
  top:50px;
}
#p2{
  background:#000;
  height:600px;
  position:absolute;
  left:500px;
  width:2px;
}
</style>
</head>
<script>
var speed;
var time;
window.onload = function(){
  var btn = document.getElementById('btn');
  btn.onclick = function(){
    speed = 0;
    move(500);
  };
  btn2.onclick = function(){
    speed = 0;
    move(0);
  };
};
function move(e){
  var p = document.getElementById('p');
  clearInterval(time);
  time = setInterval(function(){
    //改变位置,如果向左则e==500, 向上取整, 否则向右,向下取整,速度=(终点位置 - 当前位置)/一个数
    e==500 ? speed = Math.ceil((e-(p.offsetLeft))/30):speed = Math.floor((e-(p.offsetLeft))/30)
    if (e <= p.style.left){//达到,关闭定时器
      clearInterval(time);
    }
    else
    {
      p.style.left = p.offsetLeft+speed+&#39;px&#39;;
    }
  },30);
};
</script>
<body>
<input type="button" value="向右运动" id="btn" />
<input type="button" value="向左运动" id="btn2" />
<p id = "p">
</p>
<p id = "p2">
</p>
</body>
</html>
Copy after login
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other php Chinese websites related articles!

Recommended reading:

How to use Vux in a Vue project

Opening and closing the menu without JS

The above is the detailed content of How to use JS to implement buffering motion. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template