原生JavaScript实现图片切换效果
效果:
html布局``
<div class="slideshow">
<!-- 图片区域 -->
<div class="contentImg">
<input type="image" src="img/prev.png" class="prev">
<input type="image" src="img/next.png" class="next">
<span id="countBtn">
1/5
</span>
</div>
<!-- 按钮区域 -->
<div class="btns">
<input type="button" class="circulation" value="循环状态">
<input type="button" class="no_circulation" value="非循环状态">
</div>
</div>
css样式
body{
margin: 0;
padding: 0;
}
.slideshow{
height:445px;
width:650px;px
margin:150px auto 0; /*设置主盒子居中离上边距150px*/
}
.contentImg{
position: relative;
height:400px;
width: 650px;
background-image: url(../img/a1.jpg);
background-size: 100%; /*背景图片适应盒子大小*/
transition: 2s; /*过渡时间变为2s*/
}
.contentImg input{
height:60px;
width:60px;
top: 175px;
position: absolute;
outline: none; /*清除input框获取焦点的默认蓝色边框*/
}
.contentImg .prev{
left: 10px;
}
.contentImg .next{
right: 10px;
}
#countBtn{
display: block; /*转换为块元素*/
position:absolute;
height: 28px;
width:100px;
border-radius: 14px;
background-image:url(../img/backBotton.png);
background-repeat: no-repeat;
background-position-x: -5px; /*背景图片沿x轴偏移-5像素*/
bottom: 10px;
left: 50%;
margin-left:-50px;
text-align: center;
line-height: 28px;
font-size: 16px;
font-weight: 600;
color: white;
}
.btns{
width:100%;
text-align: center;
margin-top: 15px;
}
.btns input{
width: 190px;
height: 30px;
color: white;
font-size: 16px;
font-weight: 600;
cursor: pointer;
outline: none;
background: #2164f3;
border-radius: 10px;
border: none;
}
布局完成!此时效果图是这样的
对于css,html这里不做过多讨论,比较陌生的地方已经加上注释了
下面的功能我们用JavaScript来实现他
接下来就是最重要的JavaScript代码,以下用两种不同的写法来实现这个功能
第一种,比较普遍的demo写法
第一步.把元素获取到
var img = document.getElementsByClassName("contentImg")[0], //获取图片
prev = document.getElementsByClassName("prev")[0], // 获取上一张的按钮
next = document.getElementsByClassName("next")[0],//获取下一张的按钮
span = document.getElementById("countBtn"), // 获取当前图片计数
circulationNode = document.getElementsByClassName("circulation")[<