当前位置:主页 > 查看内容

javascript实现左右缓动动画函数

发布时间:2021-07-14 00:00| 位朋友查看

简介:本文实例为大家分享了js实现左右缓动动画函数的封装代码,供大家参考,具体内容如下 !DOCTYPE htmlhtml head meta charset="utf-8" link rel="stylesheet" href="bootstrap-4.4.1.css" style .box{ width: 100px; height: 100px; background-color: chartreu……

本文实例为大家分享了js实现左右缓动动画函数的封装代码,供大家参考,具体内容如下

<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8">
 <link rel="stylesheet" href="bootstrap-4.4.1.css" >
 <style>
 
 .box{
 width: 100px;
 height: 100px;
 background-color: chartreuse;
 position:absolute;
 }
 </style>
 </head>
 <body>

 <button class="btn1">移动400px</button>
 <button class="btn2">移动800px</button>
 <div class="box"></div>

 <script>

 let btn1 = document.querySelector('.btn1');
 let btn2 = document.querySelector('.btn2');
 let box = document.querySelector('.box');

 btn1.onclick = function(){
 animate(box,400);
 }

 btn2.onclick = function(){
 animate(box,800);
 }

 // 缓动动画
 function animate(element,target){
 // 清除定时器
 clearInterval(element.timeId);

 element.timeId = setInterval(function(){
  // 获取元素当前的位置
  let current = element.offsetLeft;
  // 当current越大,step越小,先快后慢
  let step = (target - current) / 10;
  // 当step大于0时,step向上取整,否则,step向下取整
  step = step > 0 ? Math.ceil(step) : Math.floor(step);
  current += step;
  element.style.left = current + 'px';
  // 不用担心到达不了目标位置,因为step最小达到1
  if(current == target){
  clearInterval(element.timeId);
  }
  console.log("目标位置:" + target + "当前位置:" + current + "每次移动的步数:" + step);
 },20);
 }

 </script>
 
 </body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持站长技术。


原文链接:https://m.jb51.net/article/200605.htm
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:在Vue中使用mockjs代码实例 下一篇:没有了

推荐图文


随机推荐