动画封装

it2024-04-21  15

1 <body> 2 <button id="btn">开始动画</button> 3 <div id="box"></div> 4 <script> 5 window.addEventListener('load', function (ev) { 6 linearAnimation('btn', 'box', 50, 800); 7 }); 8 9 function linearAnimation(btnId, boxId, step, target) { 10 // 1. 获取需要的标签 11 var btn = document.getElementById(btnId); 12 var box = document.getElementById(boxId); 13 14 var intervalID = null, begin = 0; 15 16 // 2. 事件触发 17 btn.addEventListener('click', function (ev1) { 18 // 2.1 清除定时器 19 clearInterval(intervalID); 20 21 // 2.2 设置定时器 22 intervalID = setInterval(function () { 23 // 改变起始值 24 begin += step; 25 26 // 判断 27 if(begin >= target){ 28 begin = target; 29 // 清除定时器 30 clearInterval(intervalID); 31 } 32 console.log(begin); 33 34 // 动起来 35 box.style.marginLeft = begin + 'px'; 36 }, 10); 37 }); 38 } 39 </script>

 

转载于:https://www.cnblogs.com/zhangzhengyang/p/11198068.html

最新回复(0)