javascript学习之带滚动条的图片

时间:2022-02-08 19:56:57

之前找了好久没有找到,就自已动手写了一个:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{margin:0; padding: 0;}
.div1{position: relative; height: 150px; width: 680px;border:1px solid black;margin:10px auto;overflow: hidden;}
.div1 ul {position: absolute;}
.div1 ul li{list-style: none;float: left;width: 150px; height: 112px;padding: 10px;}
.div1 ul li img{width: 150px; height: 112px;}
#scale{ height: 20px; background: #ccc; position: relative; top: 130px;}
#scale #tag{ width: 20px; height: 20px; background: red; position: absolute;}
</style>
<script type="text/javascript" src="move.js"></script>
<script type="text/javascript">
window.onload = function(){
var oDiv= document.getElementById("div1");
var oDiv2= document.getElementById("scale");
var oTag= document.getElementById("tag");
var oUl = getByClass(oDiv,"ul1")[0];
var oLi = oUl.getElementsByTagName('li'); oUl.innerHTML += oUl.innerHTML;//复制一份Ul,和原来的叠加在一起
oUl.style.width = oLi.length * oLi[0].offsetWidth + "px";//设置Ul的宽度
oTag.onmousedown = function(ev){
var oEvent = ev || event;
var disX = oEvent.clientX - oTag.offsetLeft;
document.onmousemove = function(ev){
var oEvent = ev || event;
var l = oEvent.clientX - disX;
if(l < 0){
l =0;
}else if(l > oDiv2.offsetWidth - oTag.offsetWidth){
l = oDiv2.offsetWidth - oTag.offsetWidth;
}
oTag.style.left = l + "px";
var scale = l/(oDiv2.offsetWidth - oTag.offsetWidth);
oUl.style.left = -(oUl.offsetWidth - oDiv.offsetWidth) * scale + 'px';
}
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
}
return false;
} };
function getByClass(obj,sClass){//用Class获取元素
var aEle = document.getElementsByTagName("*");//获取所有的元素
var i=0;
var aResult = [];
for(i=0;i<aEle.length;i++){
if(sClass == aEle[i].className){//如果当前元素等于数组中的一个元素,那么取出来放在数组aResult中
aResult.push(aEle[i]);
}
}
return aResult;
}
</script>
</head>
<body>
<div class="div1" id="div1">
<ul class="ul1">
<li><img src="data:image/item1.jpg"></li>
<li><img src="data:image/item2.jpg"></li>
<li><img src="data:image/item3.jpg"></li>
<li><img src="data:image/item4.jpg"></li>
<li><img src="data:image/item5.jpg"></li>
<li><img src="data:image/item6.jpg"></li>
<li><img src="data:image/item7.jpg"></li>
</ul>
<div id="scale">
<div id="tag"></div>
</div>
</div> </body>
</html>

javascript学习之带滚动条的图片