时间:2022-04-23 08:45:36 | 栏目:JavaScript代码 | 点击:次
本文给大家分享一个用原生JS实现的复合运动,所谓复合运动就是在同一个进间段内不同的属性都会发生变化,效果如下:
实现代码如下,欢迎大家复制粘贴及吐槽。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>原生JS实现各种运动之复合运动</title> <style> #div1 { width: 100px; height: 100px; background: red; opacity: 0.3; } </style> <script> function getStyle(obj, attr) { if (obj.currentStyle) { return obj.currentStyle[attr]; } else { return getComputedStyle(obj, false)[attr]; } } function startMove(obj, json, fn) { clearInterval(obj.timer); obj.timer = setInterval(function () { //设定开关,防止某一个值达到后其它值停止变化 var bStop = true; for (var attr in json) { var iCur = 0; if (attr == 'opacity') { iCur = parseInt(parseFloat(getStyle(obj, attr)) * 100); } else { iCur = parseInt(getStyle(obj, attr)); }; var iSpeed = (json[attr] - iCur) / 8; iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); //如果某一个值还没有达到,bStop就为false if (iCur != json[attr]) { bStop = false; }; if (attr == 'opacity') { obj.style.filter = 'alpha(opacity:' + (iCur + iSpeed) + ')'; obj.style.opacity = (iCur + iSpeed) / 100; } else { obj.style[attr] = iCur + iSpeed + 'px'; } } //最后一轮循环时如果为true,才清除定时器 if (bStop) { clearInterval(obj.timer); if (fn) { fn(); } } }, 30) } </script> <script> window.onload = function () { var oBtn = document.getElementById('btn1'); var oDiv = document.getElementById('div1'); oBtn.onclick = function () { startMove(oDiv, { width: 400, height: 200, opacity: 100 }); }; }; </script> </head> <body style="background:#0F0;"> <input id="btn1" type="button" value="开始运动" /> <div id="div1"></div> </body> </html>