本文提供了一段纯JavaScript实现的图片轮播代码,无需依赖任何第三方库。代码包含HTML结构、CSS样式以及核心的JS逻辑,支持自动播放、上一张/下一张按钮切换功能。适合前端初学者参考学习,可直接复制使用或根据需求修改参数。
纯JavaScript图片轮播实现
下面直接展示使用纯JavaScript编写图片轮播功能的完整代码。该实现逻辑清晰,便于理解和二次开发,具体代码内容如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js图片轮播切换</title>
<style type="text/css">
.imgCon{width: 400px;height: 400px;border: 2px solid #DCDCDC;margin: 100px auto;position: relative;}
.imgCon span{display: block;position: absolute;left: 0px;width: 100%;height: 30px;background: #808080;text-align: center;font-size: 18px;line-height: 30px;}
.numStyle{top: 0px;}
.textStyle{bottom: 0px;}
.imgCon strong{font-size: 30px;color: #000000;position: absolute;top: 50%;display: block;background: gray;cursor: pointer;}
.imgCon .prev{left: 10px;}
.imgCon .next{left: 370px;}
img{width:400px;height: 400px;}
</style>
</head>
<body>
<div class="imgCon">
<span id="numCon" class="numStyle">加载中...</span>
<span id="textCon" class="textStyle">加载中...</span>
<strong id="prev" class="prev"><</strong>
<strong id="next" class="next">></strong>
<img src="" id="imgChange"/>
</div>
<script type="text/javascript">
var numCon = document.getElementById('numCon');
var textCon = document.getElementById('textCon');
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var imgChange = document.getElementById('imgChange');
var imgArr = ['img/ad1.jpg','img/ad2.jpg','img/ad3.jpg','img/ad4.jpg'];
var imgText = ['第一张','第二张','第三张','第四张'];
var num = 0;
//数字 图片变化函数
function imgTab(){
numCon.innerHTML = num+1 + '/' + imgArr.length; //数字变化
textCon.innerHTML = imgText[num]; //底部文字内容变化
imgChange.src = imgArr[num]; //图片变化
}
imgTab();
//下一张 按钮
next.onclick = function(){
num++;
if(num == imgArr.length){
num = 0;
}
imgTab();
}
//上一张 按钮
prev.onclick = function(){
num--;
if(num == -1){
num = imgArr.length-1;
}
imgTab();
}
</script>
</body>
</html>
以上即为纯JavaScript手写图片轮播的完整实现方案,希望能为各位开发者提供实用的参考。如果在阅读或应用过程中遇到任何问题,欢迎随时留言交流,小编会尽快给予回复。同时也非常感谢大家对本网站的支持与关注!