JavaScript实现动画的原理
JavaScript实现动画的本质: 采用修改元素的样式,使元素形态发生变化 从而实现相应的动画效果 JavaScript动画经常配合定时器使用,达到动画变更的效果
JavaScript动画和CSS动画的不同之处
JavaScript动画控制能力更强 可以在动画播放过程中对动画进行控制 如: 开始、暂停、回放、终止、取消等; JavaScript动画效果比CSS动画更丰富 如: 曲线运动,冲击闪烁,视差滚动等效果 只有JavaScript 动画才能完成; CSS动画存在兼容性问题 而JavaScript大多时候没有兼容性问题例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>linux28.com -JavaScript</title> <style> *{ margin: 0; padding: 0; } #box { width: 200px; height: 200px; margin-top: 10px; background: rgb(43, 221, 255); position: relative; left: -200px; top: 0; } #box span { width: 20px; background: rgb(255, 119, 157); position: absolute; left: 200px; top: 75px; color: #fff; text-align: center; cursor: pointer; padding: 5px 1px 5px 0; border-radius: 0 5px 5px 0; } #box span:hover { background: rgb(255, 84, 137); } </style> </head> <body> <div id="box"> <span id="share">分享</span> </div> <script> window.onload = function () { //动画 var div = document.getElementById("box"); var timer = null; div.onmouseover = function () { startMove(0); }; div.onmouseout = function () { startMove(-200); }; function startMove(targetPosition) { clearInterval(timer); var speed = 0; if (targetPosition < 0) { speed = -10; } else { speed = 10; } timer = setInterval(function () { if (div.offsetLeft == targetPosition) { clearInterval(timer); } else { div.style.left = div.offsetLeft + speed + 'px'; } }, 17); } }; </script> </body> </html>
例2:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>linux28.com -JavaScript</title> <style type="text/css"> * { margin: 0 auto; padding: 0; } ul { list-style: none; } #view { position: relative; width: 320px; height: 120px; border: 10px solid #bc8f8f; overflow: hidden; margin-top: 5px; } #img_list { position: absolute; width: 960px; } #img_list li { float: left; width: 320px; height: 120px; } </style> </head> <body> <div id="view"> <ul id="img_list"> <li style="background-color: #87ceeb;"></li> <li style="background-color: #ff69b4;"></li> <li style="background-color: #98fb98;"></li> </ul> </div> <script type="text/javascript"> var img_list = document.getElementById('img_list'); setInterval(function() { for (var i = 0; i <= 100; i++) { (function(pos) { setTimeout(function() { img_list.style.left = - (pos / 100) * 320 + 'px'; }, (pos + 1) * 10) })(i) } var current = img_list.children[0]; setTimeout(function() { img_list.appendChild(current); img_list.style.left = '0px'; }, 1100); }, 2000); </script> </body> </html>