html +css+js 自己封装的轮播图
css 代码部分
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box {
margin: 100px auto;
padding: 7px;
border: 1px solid #CCC;
width: 500px;
}
.box ul {
list-style: none;
width: 3000px;
position: absolute;
}
.box ul li {
float: left;
}
.box .screen {
width: 500px;
height: 200px;
overflow: hidden;
border: 1px solid #ccc;
position: relative;
}
.box ol {
list-style: none;
position: absolute;
top:158px;
right: 10px;
}
.box ol li {
float: left;
width: 30px;
background-color: rgba(255,100,0,.7);
margin-right: 5px;
font-size: 18px;
line-height: 30px;
text-align: center;
border-radius: 20px;
cursor: pointer;
color: #fff;
}
.box ol li.current {
background-color: rgba(255,100,0,1);
}
</style>
HTML代码部分
<body> <div class="box" id="box"> <div class="screen" id="screen"> <ul> <li class="current"> <img src="images/1.jpg" alt=""></li> <li> <img src="images/2.jpg" alt=""></li> <li> <img src="images/3.jpg" alt=""></li> <li> <img src="images/4.jpg" alt=""></li> <li> <img src="images/5.jpg" alt=""></li> </ul> </div> </div> </body>
js代码部分
<script type="text/javascript">
function $(id) {return document.getElementById(id);}
var ul = $("screen").children[0];
var ul_li = ul.children;
//拼接OL開始
var ol = document.createElement("ol");
$("screen").appendChild(ol);
for (var i = 0,len=ul_li.length; i < len; i++) {
var li = document.createElement("li");
li.innerHTML = i+1;
ol.appendChild(li);
};
//拼接OL結束
//鼠標滑過下標滾動圖片開始
var ol_li = $("screen").children[1].children;
for (var i = 0,len = ol_li.length; i < len; i++) {
ol_li[i].index=i;
ol_li[i].onmouseover = function (){
animate(ul,-500*(this.index));
for (var j = 0; j < ol_li.length; j++) {
ol_li[j].className="";
};
ol_li[this.index].className = "current";
current = this.index;
}
};
//鼠標滑過下標滾動圖片結束
//3秒自動滾動圖片開始
var current = 0;
var timers = setInterval(autoplay, 1000);
function autoplay (){
current++;
if (current > ul_li.length -1) {
ul.style.left = 0;
current = 0;
}
for (var j = 0; j < ol_li.length; j++) {
ol_li[j].className="";
};
ol_li[current].className = "current";
animate(ul,-500*current)
}
//3秒自動滾動圖片結束
$("box").onmouseover = function(){
clearInterval(timers);
}
$("box").onmouseout = function(){
timers = setInterval(autoplay, 1000)
}
//動畫函數
function animate(obj ,target){
clearInterval(obj.timers);
var speed = obj.offsetLeft < target ? 50 : -50;
obj.timers = setInterval(function(){
obj.style.left = obj.offsetLeft + speed +"px";
if ( Math.abs(target - obj.offsetLeft) <=50 ) {
clearInterval(obj.timers);
obj.style.left = target+"px";
};
},30)
}
</script>
该轮播图不需引用其他js框架 纯原生js
实现功能 鼠标放到轮播图上 停止轮播 移除继续轮播
鼠标放到右下角图标上自动滚动到对应的图片上
该轮播图自己配置ol-li (右下角图标) 不需要自己在html中书写
浙公网安备 33010602011771号