啥是轮播图
我们最常见到的轮播图是在类似京东淘宝这种购物网站上,一般在首页导航栏的下方,动态滚动的图片,自动切换给人一种高端大气上档次的效果感受。
效果实现方式
有两种方法,一种是图片从右至左,平移出现在显示窗口,一种是利用js进行定时器切换图片,我习惯用第二种方法。
布局
给一个div盒子用来做轮播图的播放窗口,下面两个按钮分别放在窗口的左右两侧,用于给用户自主翻页图片的功能效果的实现。
<div class="box">
<ul>
<li class="item active"><img src="img/1.jpg"></li>
<li class="item"><img src="img/2.jpg"></li>
<li class="item"><img src="img/3.jpg"></li>
<li class="item"><img src="img/4.jpg"></li>
<li class="item"><img src="img/5.jpg"/></li>
<li class="item"><img src="img/6.jpg"/></li>
<li class="item"><img src="img/7.jpg"/></li>
</ul>
<button type="button" class="btn" id="goPre"> < </button>
<button type="button" class="btn" id="goNext"> > </button>
</div>
下面再给出css样式,这个只要自己喜欢,好看就行了。里面还有一个小细节。
* {
margin: 0;
padding: 0;
list-style: none;
}
img {
width: 600px;
height: 450px;
}
.box {
position: relative;
width: 600px;
height: 450px;
margin: 100px auto 0 auto;
border: 1px solid black;
box-shadow: 0 0 10px black;
border-radius:5px ;
}
.item {
width: 600px;
height: 450px;
position: absolute;
opacity: 0;
transition: all 2s;
}
.btn {
width: 23px;
height: 44px;
position: absolute;
color: white;
border: none;
top: 213px;
z-index: 100;
background-color: rgba(0, 0, 0, .4);
cursor: pointer;
outline: none;
}
#goPre {
left: 0;
border-top-right-radius: 20px;
border-bottom-right-radius: 20px;
}
#goNext {
right: 0px;
border-top-left-radius: 20px;
border-bottom-left-radius: 20px;
}
.item.active {
z-index: 10;
opacity: 1;
}
在.item里有两行 {opacity: 0;;transition: all 2s;}
这是一个简单的切换效果。图片切换的时候有淡入的效果。就避免了切换图片的那种闪现生硬感觉。
下面上js代码
var box = document.getElementsByClassName("box")[0];//窗口
var items = document.getElementsByClassName("item");
var goPreBtn = document.getElementById("goPre");//左
var goNextBtn = document.getElementById("goNext");//右
var index = 0;
var clearActive = function(){
for(var i = 0;i < items.length;i++){
items[i].className = "item";
}
}
var goIndex = function(){
clearActive();
items[index].className = "item active";
}
var goNext = function(){
if(index < items.length - 1){
index ++;
}else{
index = 0;
}
goIndex();
}
var goPre = function(){
if(index == 0){
index = 6;
}else{
index --;
}
goIndex()
}
goNextBtn.addEventListener('click',function(){
goNext();
})
goPreBtn.addEventListener('click',function(){
goPre();
})
var lbshow = setInterval(goNext,2000);
box.onmouseover = function(){
clearInterval(lbshow)
}
box.onmouseout = function(){
lbshow = setInterval(goNext,2000)
}
goNext();是去下一张图片按钮的执行,goPre();是去上一张图片按钮的执行,利用定时器设置时间3秒执行一次goIndex,在执行clearActive里的for循环,给items[i]添加className为 "item"的属性名,写好的样式在css里,利用这种方法达到图片切换的效果。