前端经常看到图片滚动,理清楚原理就会很简单
滚动的原理: 所有的图片用li展示出来,ul设置固定宽度,超出的部分hidden,js使用定时器进行修改left,代码如下
<!doctype HTML>
<html>
<head>
<meta charset="UTF-8">
<title>exe1</title>
<link href="" rel="stylesheet" type="text/css"/>
<meta name="viewport" content="width=750">
<style>
* {
padding: 0;
margin: 0;
}
li {
list-style: none;
}
img {
border: 0;
}
.roll {
width: 698px;
height: 108px;
margin: 50px auto 0;
position: relative;
}
.btn_left {
display: block;
width: 68px;
height: 68px;
background: url(image/wufenggundong/btn.jpg) no-repeat -70px -69px;
position: absolute;
top: 20px;
left: 1px;
z-index: 1;
}
.btn_left:hover {
background: url(image/wufenggundong/btn.jpg) no-repeat -70px 0;
}
.btn_right {
display: block;
width: 68px;
height: 68px;
background: url(image/wufenggundong/btn.jpg) no-repeat 1px -69px;
position: absolute;
top: 20px;
right: 0;
z-index: 1;
}
.btn_right:hover {
background: url(image/wufenggundong/btn.jpg) no-repeat 1px 0;
}
.roll .wrap {
width: 546px;
height: 108px;
margin: 0 auto;
position: relative;
overflow: hidden;
}
.roll ul {
position: absolute;
top: 0;
left: 0;
}
.roll li {
float: left;
width: 182px;
height: 108px;
text-align: center;
}
.roll li a:hover {
position: relative;
top: 2px;
}
.control {
border-bottom: 1px solid #ccc;
background: #eee;
text-align: center;
padding: 20px 0;
display: none;
}
</style>
<script>
window.onload = function(){
var oDiv = document.getElementById("roll");
var oUl = oDiv.getElementsByTagName("ul")[0];
var aLi = oUl.getElementsByTagName("li");
var aA = oDiv.getElementsByTagName('a');
var aBtn = oDiv.getElementsByTagName("a");
//复制li的内容,避免在滚动的时候出现后端空白
var str=oUl.innerHTML+oUl.innerHTML;
oUl.innerHTML=str;
oUl.style.width = aLi[0].offsetWidth * aLi.length + "px";
var speed = -5;
timer = setInterval(move,30);
//负数,向左滚动
aBtn[0].onmousemove = function (){
speed = -5;
}
//正数,向右滚动
aBtn[1].onmousemove = function (){
speed = 5;
if(oUl.offsetLeft >=0){
oUl.style.left = "0px";
}
}
oUl.onmousemove = function (){
clearInterval(timer);
}
oUl.onmouseout = function (){
timer = setInterval(move,30);
}
function move(){
oUl.style.left = oUl.offsetLeft + speed + "px";
// ul向作滚动,所以是负数,即比较的时候用负数进行比较
//这里的比较是:在滚动到一半的时候其实就是重复的开始,将所有内容拉到最开始,避免出现空白
if(oUl.offsetLeft < -oUl.offsetWidth/2){
oUl.style.left = "0px";
}
//当left=0,右边会出现百边,将内容拉到自身宽度的一半
else if(oUl.offsetLeft >= 0){
oUl.style.left = "-"+ oUl.offsetWidth/2 + "px";
}
}
}
</script>
</head>
<body>
<div class="roll" id="roll">
<a href="javascript:void(0);" class="btn_left"></a>
<a href="javascript:void(0);" class="btn_right"></a>
<div class="wrap">
<ul>
<li><a ><img src="image/wufenggundong/1.jpg" /></a></li>
<li><a ><img src="image/wufenggundong/2.jpg" /></a></li>
<li><a ><img src="image/wufenggundong/3.jpg" /></a></li>
<li><a ><img src="image/wufenggundong/4.jpg" /></a></li>
</ul>
</div>
</div>
</body>
</html>
实现效果如下:
点击左右两边的按钮,可以实现左滚动有滚动,鼠标滑动到图片上可以实现暂停滚定,移除继续滚动