<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>OOP无缝滚动</title> <style type="text/css"> body { margin: 0; padding: 0; } div.container { position: relative; width: 815px; height: 160px; margin: 20px auto; border: 20px solid springgreen; overflow: hidden; } ul { position: absolute; margin: 0; padding: 0; } li { width: 200px; height: 160px; display: inline-block; list-style: none; } </style> <script type="text/javascript"> function GuoMove(oDiv){ var oUl = oDiv.getElementsByTagName("ul")[0]; oUl.innerHTML = oUl.innerHTML + oUl.innerHTML; var aLi = oDiv.getElementsByTagName("li"); oUl.style.width = aLi[0].offsetWidth * aLi.length + "px"; this.oTimer = setInterval(function(){ if(oUl.offsetLeft < -oUl.offsetWidth/2) oUl.style.left = oUl.offsetLeft + oUl.offsetWidth/2 + "px"; else oUl.style.left = oUl.offsetLeft - 2 + "px"; },30); var _this = this; oDiv.onmouseover = function(){ //注意变量的作用域,什么时候这些变量能在函数内部直接用,什么时候这些变量需要作为参数传递给函数后才能在函数内部使用,区分原型方法。 //clearInterval(_this.oTimer); _this.fnOver(); }; oDiv.onmouseout = function(){ _this.fnOut(oUl); }; } GuoMove.prototype.fnOver = function(){ clearInterval(this.oTimer); }; GuoMove.prototype.fnOut = function(oUl){ this.oTimer = setInterval(function(){ if(oUl.offsetLeft < -oUl.offsetWidth/2) oUl.style.left = oUl.offsetLeft + oUl.offsetWidth/2 + "px"; else oUl.style.left = oUl.offsetLeft - 2 + "px"; },30); }; window.onload = function(){ var oDiv = document.getElementsByClassName("container")[0]; var oGuoMove = new GuoMove(oDiv); }; </script> </head> <body> <div class="container"> <ul> <li style="background-color: red"></li> <li style="background-color: yellow"></li> <li style="background-color: blue"></li> <li style="background-color: grey"></li> </ul> </div> </body> </html>