Home > Web Front-end > JS Tutorial > js method to achieve buffering motion effect_javascript skills

js method to achieve buffering motion effect_javascript skills

WBOY
Release: 2016-05-16 16:04:55
Original
1046 people have browsed it

The example in this article describes the method of realizing buffering motion effect in js. Share it with everyone for your reference. The specific analysis is as follows:

This example can achieve the effect of starting very fast, then slowing down until it stops.

Key points:

var speed = (target-box.offsetLeft)/8;
Copy after login

The value of the target point minus the current position of the element is divided by 8. Because the value of offsetleft keeps getting bigger, the value of the speed keeps getting smaller

speed = speed>0?Math.ceil(speed):Math.floor(speed);
Copy after login

Forward speed is rounded up, and for reverse speed it is rounded down

Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="gb2312" />
<title>无标题文档</title>
<style>
<!--
body{margin:0; padding:0; font:12px/1.5 arial;}
#box{width:100px; height:100px; position:absolute;
background:#06c; left:0;}
-->
</style>
<script>
<!--
window.onload = function(){
 var box = document.getElementById("box");
 var btn = document.getElementById("btn");
 var timer=null;
 btn.onclick = function(){
  startrun(300);
 }
 function startrun(target){
  clearInterval(timer);
  timer = setInterval(function(){
  var speed = (target-box.offsetLeft)/8;
  speed = speed>0&#63;Math.ceil(speed):Math.floor(speed);
  if(box.offsetLeft == target){
   clearInterval(timer);
  }else{
   box.style.left = box.offsetLeft+speed+"px";
  }
  document.getElementById('abc').innerHTML+=box.offsetLeft+','+speed+'<br>';
  },30);
 }
}
//-->
</script>
</head>
<body>
<input id="btn" type="submit" value="向右运动">
<div id="box">
</div>
<br>
<textarea id="abc" cols="50" rows="10" 
style="margin-top:130px"></textarea>
</body>
</html>
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

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