实现轮播图
思路:
通过js来控制轮播的图片的样式,可以控制display:none or block 可以控制opacity:‘0’ or ‘1’ 也可以通过z-index来控制图片的摆放顺序。
Html代码:
这里的图片一般是通过绝对定位放在一个div盒子里面,图片堆叠在一起。
[if !supportLists]1. [endif]首先固定外层框的宽度与长度width与height并且设置相对定位
<div id="main" style="width: height: 740px;position: relative;">
<div class="scollimg" style=" height: 740px;position: relative;overflow: hidden;">
<img src="images/1.jpg" alt="">
<img src="images/2.jpg" alt="">
<img src="images/3.jpg" alt="">
</div>
</div>
[if !supportLists]2. [endif]将图片显示在一个框中,不让图片排列出来(设置图片:display:absolute)
<img src="images/1.jpg" alt="" style="position: absolute;top: 0;left: 0;">
<img src="images/2.jpg" alt="" style="position: absolute;top: 0;left: 0;">
<img src="images/3.jpg" alt="" style="position: absolute;top: 0;left: 0;">
[if !supportLists]3. [endif]设置左右移动的按钮
<div class="btn" style="width: 100%; height: 220px;position: absolute;top:300px;">
<div id="btnleft" style="position: absolute;left: 0;top: 0"><img src="images/up.svg" style="width: 100px"></div>
<div id="btnright" style="position: absolute;right: 0;top: 0"><img src="images/next.svg" style="width: 100px"></div>
</div>
[if !supportLists]4. [endif]设置下面显示的点(显示)
<div class="item" style="position: absolute;bottom: 30px;left: 48%;width: 200px;height: 16px;">
<span style="width: 16px;height: 16px;background: #ccc;display: inline-block;border-radius: 50%;"></span>
<span style="width: 16px;height: 16px;background: #ccc;display: inline-block;border-radius: 50%;"></span>
<span style="width: 16px;height: 16px;background: #ccc;display: inline-block;border-radius: 50%;"></span>
</div>
[if !supportLists]5. [endif]页面设置完了之后,需要设置行为(js)
var imgs=document.getElementsByClassName("carousel_img");
var spans=document.getElementsByClassName("carousel_span");
function InitMove(index){
for(var i=0;i<imgs.length;i++){
imgs[i].style.opacity='0';
spans[i].style.background='#ccc';
}
imgs[index].style.opacity='1';
spans[index].style.background='red';
}
主要功能是将index的东西,将其设置透明度为1,下面的span背景设置成red
//第一次初始化,将第一个图片显示出来
InitMove(0);
//设置当图片到最后一张的时候,自动返回到第一个,否则++将count传递过去
var count=1;
function fMove(){
if(count==imgs.length){
count=0;
}
InitMove(count);
count++;
}
//设置自动轮播定时器;
var scollMove=setInterval(fMove,2500);
//点击下一张和上一张的事件
var btnleft=document.getElementById('btnleft');
var btnright=document.getElementById('btnright');
btnleft.onclick=function(){
clearInterval(scollMove);
if(count==0){
count=imgs.length;
}
count--;
InitMove(count);
scollMove=setInterval(fMove,2500);
};
btnright.onclick=function(){
clearInterval(scollMove);
fMove();
scollMove=setInterval(fMove,2500);
};
//鼠标浮动在上方的时候,停止定时器,当鼠标移出来时,重新开始定时器
var scollimg = document.getElementById("scollimg");
scollimg.onmouseover=function(){
console.log('hover');
clearInterval(scollMove);
};
scollimg.onmouseout=function(){
console.log('hoverout');
scollMove=setInterval(fMove,2500);
};
网友评论