html代码:
这里仅供参考,实际图片地址请自行修改。
<div id="photo-list">
<ul id="scroll">
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=" src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
<li><a href=""><img src="" width="100px" height="100px" alt=""/></a></li>
</ul>
</div>
CSS代码:
* { padding:0; margin:0;}
body { text-align:center;}
#photo-list {
/* 3张图片的宽度(包含宽度、padding、border、图片间的留白)
计算:3*(100+2*2+1*2+9) - 9
之所以减去9是第三张图片的右边留白
*/
width:336px;
/* 图片的宽度(包含高度、padding、border)
计算:100+2*2+1*2
*/
height:106px;
margin:50px auto; overflow:hidden;
border:1px dashed #ccc;
}
#photo-list ul { list-style:none;}
#photo-list li { float:left; padding-right:9px;}
#photo-list img { border:1px solid #ddd; background:#fff; padding:2px;}
代码:
var id = function(el) {
return document.getElementById(el);
},
c = id('photo-list');
if(c) {
var ul = id('scroll'),
lis = ul.getElementsByTagName('li'),
itemCount = lis.length,
width = lis[0].offsetWidth, //获得每个img容器的宽度
marquee = function() {
c.scrollLeft += 2;
if(c.scrollLeft % width < = 1){ //当 c.scrollLeft 和 width 相等时,把第一个img追加到最后面
ul.appendChild(ul.getElementsByTagName('li')[0]);
c.scrollLeft = 0;
};
},
speed = 50; //数值越大越慢
ul.style.width = width*itemCount + 'px'; //加载完后设置容器长度
var timer = setInterval(marquee, speed);
c.onmouseover = function() {
clearInterval(timer);
};
c.onmouseout = function() {
timer = setInterval(marquee, speed);
};
};