欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

JS div匀速移动动画与变速移动动画代码实例

时间:2021-05-29 07:42:44|栏目:JavaScript代码|点击:

1.匀速移动代码

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>title</title>
 <style>
  * {
   margin: 0;
   padding: 0;
  }
 
  div {
   margin-top: 20px;
   width: 200px;
   height: 100px;
   background-color: green;
   position: absolute;
   left: 0;
   top: 0;
  }
 </style>
</head>
<body>
<input type="button" value="移动到400px" id="btn1"/>
<input type="button" value="移动到800px" id="btn2"/>
<div id="dv">
 <script src="common.js"></script>
 <script>
  //点击按钮移动div
 
  my$("btn1").onclick = function () {
   animate(my$("dv"), 400);
  };
  my$("btn2").onclick = function () {
   animate(my$("dv"), 800);
  };
 
  //匀速动画
  function animate(element, target) {
   //清理定时器
   clearInterval(element.timeId);
   element.timeId = setInterval(function () {
    //获取元素的当前位置
    var current = element.offsetLeft;
    //移动的步数
    var step = 10;
    step = target > current ? step : -step;
    current += step;
    if (Math.abs(current - target) > Math.abs(step)) {
     element.style.left = current + "px";
    } else {
     clearInterval(element.timeId);
     element.style.left = target + "px";
    }
   }, 20);
  }
 </script>
</div>
</body>
</html>

2.变速移动代码

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>title</title>
 <style>
  * {
   margin: 0;
   padding: 0;
  }
 
  div {
   margin-top: 20px;
   width: 200px;
   height: 100px;
   background-color: green;
   position: absolute;
   left: 0;
   top: 0;
  }
 </style>
</head>
<body>
<input type="button" value="移动到400px" id="btn1"/>
<input type="button" value="移动到800px" id="btn2"/>
<div id="dv">
 <script src="common.js"></script>
 <script>
  //点击按钮移动div
 
  my$("btn1").onclick = function () {
   animate(my$("dv"), 400);
  };
  my$("btn2").onclick = function () {
   animate(my$("dv"), 800);
  };
 
  //变速动画
  function animate(element, target) {
   //清理定时器
   clearInterval(element.timeId);
   element.timeId = setInterval(function () {
    //获取元素的当前位置
    var current = element.offsetLeft;
    //移动的步数
    var step = (target-current)/10;
    step = step>0?Math.ceil(step):Math.floor(step);
    current += step;
    element.style.left = current + "px";
    if(current==target) {
     //清理定时器
     clearInterval(element.timeId);
    }
    
   }, 20);
  }
 </script>
</div>
</body>
</html>

common.js

/**
 * 获取指定标签对象
 * @param id 标签的id属性值
 * @returns {Element}根据id属性值返回指定标签对象
 */
function my$(id) {
  return document.getElementById(id);
}

上一篇:用JS判断IE版本的代码 超管用!

栏    目:JavaScript代码

下一篇:React学习之JSX与react事件实例分析

本文标题:JS div匀速移动动画与变速移动动画代码实例

本文地址:http://www.codeinn.net/misctech/130856.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有