华域联盟 JavaScript javascript实现左右缓动动画函数

javascript实现左右缓动动画函数

本文实例为大家分享了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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

本文由 华域联盟 原创撰写:华域联盟 » javascript实现左右缓动动画函数

转载请保留出处和原文链接:https://www.cnhackhy.com/143404.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们