javascript学习之带滚动条的图片
之前找了好久没有找到,就自已动手写了一个:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style type="text/css"> 7 *{margin:0; padding: 0;} 8 .div1{position: relative; height: 150px; width: 680px;border:1px solid black;margin:10px auto;overflow: hidden;} 9 .div1 ul {position: absolute;} 10 .div1 ul li{list-style: none;float: left;width: 150px; height: 112px;padding: 10px;} 11 .div1 ul li img{width: 150px; height: 112px;} 12 #scale{ height: 20px; background: #ccc; position: relative; top: 130px;} 13 #scale #tag{ width: 20px; height: 20px; background: red; position: absolute;} 14 </style> 15 <script type="text/javascript" src="move.js"></script> 16 <script type="text/javascript"> 17 window.onload = function(){ 18 var oDiv= document.getElementById("div1"); 19 var oDiv2= document.getElementById("scale"); 20 var oTag= document.getElementById("tag"); 21 var oUl = getByClass(oDiv,"ul1")[0]; 22 var oLi = oUl.getElementsByTagName('li'); 23 24 oUl.innerHTML += oUl.innerHTML;//复制一份Ul,和原来的叠加在一起 25 oUl.style.width = oLi.length * oLi[0].offsetWidth + "px";//设置Ul的宽度 26 oTag.onmousedown = function(ev){ 27 var oEvent = ev || event; 28 var disX = oEvent.clientX - oTag.offsetLeft; 29 document.onmousemove = function(ev){ 30 var oEvent = ev || event; 31 var l = oEvent.clientX - disX; 32 if(l < 0){ 33 l =0; 34 }else if(l > oDiv2.offsetWidth - oTag.offsetWidth){ 35 l = oDiv2.offsetWidth - oTag.offsetWidth; 36 } 37 oTag.style.left = l + "px"; 38 var scale = l/(oDiv2.offsetWidth - oTag.offsetWidth); 39 oUl.style.left = -(oUl.offsetWidth - oDiv.offsetWidth) * scale + 'px'; 40 } 41 document.onmouseup = function(){ 42 document.onmousemove = null; 43 document.onmouseup = null; 44 } 45 return false; 46 } 47 48 }; 49 function getByClass(obj,sClass){//用Class获取元素 50 var aEle = document.getElementsByTagName("*");//获取所有的元素 51 var i=0; 52 var aResult = []; 53 for(i=0;i<aEle.length;i++){ 54 if(sClass == aEle[i].className){//如果当前元素等于数组中的一个元素,那么取出来放在数组aResult中 55 aResult.push(aEle[i]); 56 } 57 } 58 return aResult; 59 } 60 </script> 61 </head> 62 <body> 63 <div class="div1" id="div1"> 64 <ul class="ul1"> 65 <li><img src="image/item1.jpg"></li> 66 <li><img src="image/item2.jpg"></li> 67 <li><img src="image/item3.jpg"></li> 68 <li><img src="image/item4.jpg"></li> 69 <li><img src="image/item5.jpg"></li> 70 <li><img src="image/item6.jpg"></li> 71 <li><img src="image/item7.jpg"></li> 72 </ul> 73 <div id="scale"> 74 <div id="tag"></div> 75 </div> 76 </div> 77 78 </body> 79 </html>