Javascript模拟加速运动与减速运动代码分享

加速运动,即一个物体运动时速度越来越快;减速运动,即一个物体运动时速度越来越慢。现在用Javascript来模拟这两个效果,原理就是用setInterval或setTimeout动态改变一个元素与另外一个元素的距离,如xxx.style.left或xxx.style.marginLeft,然后每次运动后都使速度增加,这样加速运动的效果就出现了,减速运动是同样的道理。

  下面是两个示例:

  加速运动

  复制代码 代码如下:

  <!DOCTYPE html>

  <html>

  <head>

  <meta charset="utf-8">

  <title>Javascript加速运动</title>

  <style type="text/css">

  * {margin: 0; padding: 0;}

  .div1 {width: 100px; height: 100px; background: #f60 url(qiuweiguan.gif) no-repeat center center;}

  </style>

  <script type="text/javascript">

  var $$ = function (id) {

  return document.getElementById(id);

  }

  window.onload = function () {

  var oBtn = $$("btn1");

  var oDiv = $$("div1");

  var timer = null;

  var speed = 0;

  oBtn.onclick = function () {

  clearInterval(timer);

  timer = setInterval(function () {

  speed ++;

  oDiv.style.marginLeft = oDiv.offsetLeft + speed + "px";

  }, 30);

  }

  }

  </script>

  </head>

  <body id = "body">

  <button id="btn1" class="btn1">GO</button>

  <div id="div1" class="div1"></div>

  </body>

  </html>

  注:本示例中,点击GO后,div块会一直向右做加速运动

  减速运动

  复制代码 代码如下:

  <!DOCTYPE html>

  <html>

  <head>

  <meta charset="utf-8">

  <title>Javascript减速运动</title>

  <style type="text/css">

  * {margin: 0; padding: 0;}

  .div1 {width: 100px; height: 100px; background: #f60 url(qiuweiguan.gif) no-repeat center center;}

  </style>

  <script type="text/javascript">

  var $$ = function (id) {

  return document.getElementById(id);

  }

  window.onload = function () {

  var oBtn = $$("btn1");

  var oDiv = $$("div1");

  var timer = null;

  var speed = 30;

  oBtn.onclick = function () {

  clearInterval(timer);

  timer = setInterval(function () {

  speed — ;

  oDiv.style.marginLeft = oDiv.offsetLeft + speed + "px";

  }, 30);

  }

  }

  </script>

  </head>

  <body id = "body">

  <button id="btn1" class="btn1">GO</button>

  <div id="div1" class="div1"></div>

  </body>

  </html>

  注:本示例中,点击GO后,div块会一直向右做减速运动,直到速度减为零后,速度变为负值,再向左做加速运动
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值