1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>HTML</title> 6 <style> 7 * { 8 padding: 0; 9 margin: 0; 10 } 11 #scrollWrapper { 12 width: 400px; 13 height: 100px; 14 background-color: #f00; 15 position: relative; 16 margin: 150px auto 40px; 17 background-color: #f00; 18 overflow: hidden; 19 } 20 ul { 21 width: 800px; 22 list-style: none; 23 position: absolute; 24 left: 0; 25 top: 0; 26 } 27 li { 28 float: left; 29 width: 100px; 30 height: 100px; 31 text-align: center; 32 line-height: 100px; 33 } 34 .li_1 { 35 background-color: #00f 36 } 37 .li_2 { 38 background-color: #0f0 39 } 40 .li_3 { 41 background-color: #666 42 } 43 .li_4 { 44 background-color: #aaa 45 } 46 #btnWrapper { 47 margin: 0 auto; 48 width: 150px; 49 } 50 .btn { 51 border: 1px solid #f00; 52 width: 60px; 53 float: left; 54 text-align: center; 55 } 56 #toRight { 57 float: right; 58 } 59 </style> 60 </head> 61 62 <body> 63 <div id="scrollWrapper"> 64 <ul> 65 <li class="li_1"> 66 1 67 </li> 68 <li class="li_2"> 69 2 70 </li> 71 <li class="li_3"> 72 3 73 </li> 74 <li class="li_4"> 75 4 76 </li> 77 </ul> 78 </div> 79 <div id="btnWrapper"> 80 <div id="toLeft" class="btn"> 81 向左 82 </div> 83 <div id="toRight" class="btn"> 84 向右 85 </div> 86 <div style="clear:both;"></div> 87 </div> 88 <script> 89 var oDiv = document.getElementById("scrollWrapper"); 90 var oUL = document.getElementsByTagName("ul")[0]; 91 var toRight = document.getElementById("toRight"); 92 var toLeft = document.getElementById("toLeft"); 93 var speed = 0; 94 var timer = null; 95 oUL.innerHTML += oUL.innerHTML; 96 /* 97 * 向右滚动 98 */ 99 function toRightScroll() { 100 speed = 2; 101 timer = setTimeout(function() { 102 if (oUL.offsetLeft > 0) { 103 //向右滚动left > 0时,置ul的left = -oUL.offsetWidth / 2 px 104 oUL.style.left = -oUL.offsetWidth / 2 + "px"; 105 } else { 106 oUL.style.left = oUL.offsetLeft + speed + "px"; 107 } 108 timer = setTimeout(arguments.callee, 30); 109 }, 30); 110 }; 111 toRight.onclick = toRightScroll; 112 /* 113 * 向左滚动 114 */ 115 function toLeftScroll() { 116 speed = -2; 117 setTimeout(function() { 118 if (oUL.offsetLeft < -oUL.offsetWidth / 2) { 119 //向左滚动到ul的一半时,置ul的left = 0px 120 oUL.style.left = 0; 121 } else { 122 oUL.style.left = oUL.offsetLeft + speed + "px"; 123 } 124 timer = setTimeout(arguments.callee, 30); 125 }, 30); 126 }; 127 toLeft.onclick = toLeftScroll; 128 oDiv.onmouseover = function(){ 129 clearTimeout(timer); 130 }; 131 </script> 132 </body> 133 </html>