HTML纯javaScript代码写图片轮播

时间:2023-03-09 09:21:59
HTML纯javaScript代码写图片轮播
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.imgbox {
width: 100%;
height: 400px;
position: relative;
top: 20px;
left: 15px;
} img {
opacity: 0;
position: absolute;
max-height: 400px;
max-width: 300px;
}
</style>
</head> <body>
<div class="imgbox" id="imgbox">
<img src="img/19.jpg" style="opacity: 1;" alt="" />
<img src="img/20.jpg" alt="" />
<img src="img/21.jpg" alt="" />
<img src="img/22.jpg" alt="" />
<img src="img/23.jpg" alt="" />
<img src="img/24.jpg" alt="" />
</div>
<input type="button" value="切换" onclick="change()" />
<script>
//全局地址
var index = 0; function change() {
//得到所 有图片长度
var imgs = document.getElementsByTagName("img").length;
var next = index + 1;
if (index == imgs - 2) {
//imgs-1为长度(从0开始);imgs-2为index(next+1)
next = 0;
}
//得到所有图片元素
var img = document.getElementById("imgbox").children;
img[index].style.opacity = 0;
img[next].style.opacity = 1;
index = next;
console.log(index);
}
window.setInterval("change()", 2000);
</script>
</body> </html>