JavaScript元素动画效果
分类:实例代码
分享一段代码实例,它实现了js以动画方式操作dom元素,实现改变元素属性的功能。
代码实例如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <style type="text/css"> * { margin: 0; padding: 0; } #box { position: absolute; width: 200px; height: 200px; background: red; } </style> <script type="text/javascript"> window.onload = function() { var btn = document.getElementById("btn"); var box = document.getElementById("box"); function getStyle(obj, style) { if (window.getComputedStyle) { return window.getComputedStyle(obj, null)[style]; } else { return obj.currentStyle[style]; } } function animationRetard(obj, json, fn) { clearInterval(obj.anime); obj.anime = setInterval(function() { var flag = true; for (var key in json) { var now = parseInt(getStyle(obj, key)); var step = json[key] > now ? Math.ceil((json[key] - now) / 10) : Math.floor((json[key] - now) / 10); now += step; if (Math.abs(json[key] - now) > Math.abs(step)) { obj.style[key] = now + "px"; flag = false; } else { obj.style[key] = json[key] + "px"; } } if (flag) { clearInterval(obj.anime); if (fn) { fn(); } } }, 20); } btn.onclick = function() { animationRetard(box, { "width": 600, "height": 400, "top": 100, "left": 100 }, function() { animationRetard(box, { "width": 300, "height": 200, "top": 50, "left": 50 }, function() { animationRetard(box, { "width": 600, "height": 500, "top": 400, "left": 1000 }) }) }) } } </script> </head> <body> <input id="btn" type="button" value="改变"/> <div id="box"></div> </body> </html>
JavaScript元素动画效果,这样的场景在实际项目中还是用的比较多的,关于JavaScript元素动画效果就介绍到这了。
JavaScript元素动画效果属于前端实例代码,有关更多实例代码大家可以查看。