原生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")[
使用JavaScript实现图片轮播

这篇博客介绍了如何使用原生JavaScript实现图片切换效果,包括HTML布局、CSS样式和JavaScript代码实现。博主提供了两种不同的JavaScript写法,一种是常见的demo写法,另一种是使用构造函数。此外,还涉及到图片切换的循环与非循环状态,并给出了完整代码示例。
最低0.47元/天 解锁文章
1454





