<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>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>运行结果如下:
图1:JavaScript 动画效果
提示:如今,大多数显示器的刷新率为 60HZ,为了实现更加平滑的动画效果,使用定时器的最佳循环间隔约为 17ms。
下面再通过一个示例来演示如何创建 JavaScript 动画,示例代码如下:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>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>运行结果如下:
图2:JavaScript动画效果
本文链接:http://task.lmcjl.com/news/17880.html