今天给大家介绍一个网上会经常看到,也是比较使用的小特效轮播图的制作。
首先我们还是先要大概了解轮播图的基本思路;
①、布局:外层div:超出隐藏 ul :加长,往左运动 left,left=0, li左浮动
②、事件:鼠标经过 鼠标离开
③、左运动,-2px ,并且,超过一本,就拉回来。
右边运动:left>0 往左边拉回来一半
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {padding: 0;margin: 0;}
#box {width: 1000px;height: 180px;position: relative;margin: 100px auto;overflow: hidden;}
#imglist {position: absolute;top: 0;left: 0;}
img {width: 200px;height: 160px;float: left;}
#left {width: 50px;height: 35px;background: beige;color: #000;font-size: 16px;line-height: 35px;text-align: center;position: absolute;top: 10px;left: 25px;}
#right {width: 50px;height: 35px;background: beige;color: #000;font-size: 16px;line-height: 35px;text-align: center;position: absolute;top: 10px;left: 80px;}
</style>
<script type="text/javascript">
window.onload = function() {
var oBox = document.getElementById("box");
var oImg = document.getElementById("imglist");
var aImg = oImg.getElementsByTagName('img');
var oLeft = document.getElementById("left");
var oRigth = document.getElementById("right");
var speed = -2;
oImg.innerHTML = oImg.innerHTML + oImg.innerHTML;//复制两个盒子中的内容,内容加倍
oImg.style.width = aImg[0].offsetWidth * aImg.length + 'px';//oImg现在的宽度等于里面图片的宽度*图片的个数
function aa() {
if(oImg.offsetLeft < -oImg.offsetWidth / 2) {//往左边走
//判断如果oImg离左边的距离小于他本身宽度的一半,就要他离左边的的距离。一定记住往左边走这个数值就是越来越小就是负数。
oImg.style.left = '0';//
}
if(oImg.offsetLeft > 0) {//往右边走
//同理,往右走时越来越大。一开始就要把内容一般放在左侧
oImg.style.left = -oImg.offsetWidth / 2 + 'px';
}
oImg.style.left = oImg.offsetLeft + speed + 'px';
}
//给一个定时器
var timer = null;
clearInterval(timer);//运动之前先关闭定时器
timer = setInterval(aa, 30);
oBox.onmouseover = function() {//鼠标移入会关闭定时器
clearInterval(timer);
}
oBox.onmouseout = function() {//鼠标离开就开启定时器
timer = setInterval(aa, 30);
}
oLeft.onclick = function() {//点击左时,speed的值是-2也就是往左侧走
speed = -2;
}
oRigth.onclick = function() {//点击右键是speed的值是2,正数往又走。
speed = 2;
}
}
</script>
</head>
<body>
<div id="box">
<div id="imglist">
<img src="http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/08/00/ChMkJlexsMuIQie-AAg2b09O224AAUdPgM-mJwACDaH277.jpg">
<img src="http://pic1.win4000.com/wallpaper/0/57eb6be0cecfa.jpg">
<img src="http://pic2016.5442.com:82/2016/0830/6/11.jpg%21960.jpg">
<img src="http://desk.fd.zol-img.com.cn/t_s960x600c5/g5/M00/00/0A/ChMkJ1ecZb2IQdT8AATJRtrzV70AAT_1gNHoPkABMle872.jpg">
<img src="http://pic1.win4000.com/wallpaper/1/57ecc8dfb3ced.jpg">
</div>
</div>
<div id="left">左</div>
<div id="right">右</div>
</body>
</html>
具体的解析在代码中都有注释。