最近跟轮播图杠上了,以前也接触过这个轮播图的写法,但是一般都是用插件,久而久之就忘记了!昨晚有学习了一下自己写这个js,虽然是依靠零散的记忆写出来的,可能自己并未真正理解吧!!!以下是我写的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>小米官网轮播图仿照</title>
<style type="text/css">
.container{width: 1226px;height: 460px;margin:0 auto;position: relative;}
.container img{position: absolute;;top:0;left: 0;display:none;}
.left,.right{position: absolute;width: 30px;height: 60px;top:50%;margin-top:-30px;color:#fff; line-height: 60px;text-align: center; font-size: 30px;cursor:pointer;}
.left:hover,.right:hover{background-color: #777171;}
.left{left:0;}
.right{right: 0;}
.container ul{position: absolute;bottom:10px;right:10px;}
.container ul li{float: left;list-style: none;width: 10px;height:10px;background-color: #fff;border-radius: 100%;border:1px solid #fff;margin-right:10px; line-height: 10px;}
.container ul li.active{background-color: #776e6e;}
</style>
</head>
<body>
<div class="container">
<img src="images/lb/1.jpg" alt="">
<img src="images/lb/2.jpg" alt="">
<img src="images/lb/3.jpg" alt="">
<img src="images/lb/4.jpg" alt="">
<img src="images/lb/5.jpg" alt="">
<div class="left" id="left"><</div>
<div class="right" id="right">></div>
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script type="text/javascript">
var lis=document.getElementsByTagName('li');
var imgs=document.getElementsByTagName('img');
imgs[0].style.display='block';
len=lis.length;
var index=0;
for (var i =0; i<len; i++) {
lis[i].tt=i;
lis[i].οnclick=function(){
fadeOut(imgs[index],1);
index=this.tt;
changeImg(index);
fadeIn(imgs[index],1);
}
}
function getId(id){return document.getElementById(id);}
getId('right').οnclick=function(){
fadeOut(imgs[index],1);
index++;
if (index>len-1) {index=0;}
changeImg(index);
fadeIn(imgs[index],1);
}
getId('left').οnclick=function(){
fadeOut(imgs[index],1);
index--;
if (index<0) {index=0;alert('已经是第一张了!');}
changeImg(index);
fadeIn(imgs[index],1);
}
function changeImg(dd){
for(var j=0;j<len;j++){
lis[j].className='';
imgs[j].style.display='none';
}
lis[dd].className='active';
imgs[dd].style.display='block';
}
// 淡入淡出效果
function fadeIn(obj,speed){
obj.style.display='block';
// obj.style.opacity='0';
var opa=0;
var timer=null;
timer=setInterval(function(){
opa=opa+speed;
if (opa>100) {opa=100;clearInterval(timer);}
obj.style.opacity=opa/100;
},13);
}
function fadeOut(obj,speed){
// obj.style.display='none';
// obj.style.opacity='100';
var opa='100';
var timer=null;
timer=setInterval(function(){
opa=opa-speed;
if (opa<0) {opa=0;clearInterval(timer);}
obj.style.opacity=opa/100;
},13);
}
</script>
</body>
</html>
照几张图片,放上其实是看,是否能运行吧!来源:CSDN
作者:仰望星空的包子
链接:https://blog.csdn.net/sinat_21206105/article/details/53348568