<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> *{ margin:0; padding:0; list-style: none; } div{ position: relative; width: 800px; height: 200px; border: 5px solid lightgreen; margin:10px auto; overflow: hidden; } div ul{ position: absolute; top:0; } div ul li{ width: 200px; height: 200px; float: left; } div ul li img{ width:100%; height: 100%; } </style> </head> <body> <div id="div1"> <ul class="run_ul"> <li class="run_li"> <img src=" " alt=""/> </li> <li class="run_li"> <img src=" " alt=""/> </li> <li class="run_li"> <img src=" " alt=""/> </li> <li class="run_li"> <img src=" " alt=""/> </li> </ul> </div> <script> /** * 跑马灯函数 * @param a ul 的class 必须写成字符串 -> 'txt' * @param b li 的class 必须写成字符串 -> 'txt' * @param t 时间 单位毫秒 速率 1/t(px/毫秒) 默认 10 最佳 * @param d direction 轮播方向 L -> left R -> right 必须写成字符串 -> 'txt' * 注意:css不要写ul的左或右绝对定位 */ var runBox = function(a,b,t,d) { var oUl = document.getElementsByClassName(a)[0]; var lis = oUl.getElementsByClassName(b); oUl.innerHTML += oUl.innerHTML; oUl.style.width = lis.length * lis[0].offsetWidth + 'px'; if(d === 'L'){ var l = null; var timer = function (){ l -= 1; if( l< -oUl.offsetWidth / 2){ l = 0; } oUl.style.left = l + 'px' }; } else { var r = null; var timer = function (){ r -= 1; if( r < -oUl.offsetWidth / 2){ r = 0; } oUl.style.right = r + 'px' }; } var play = setInterval(timer,t); oUl.onmouseover = function () { clearInterval(play) }; oUl.onmouseout = function () { play = setInterval( timer , t); } }
//调用 window.onload = function(){ runBox('run_ul','run_li',10,'R'); } </script> </body> </html>