图片轮播图

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="node_modules/jquery/dist/jquery.js"></script>
<title>切换图片</title>
<style>
* {
margin: 0;
padding: 0;
}

html {
background-color: #e7eee0;
}

#outer {
width: 500px;
height: 500px;
margin: 50px auto;
padding: 10px;
background-color: white;
box-shadow: 0 5px 5px 0 #dcdcdc;
text-align: center;
}

#outer img {
width: 100%;
height: 450px;
}
</style>
</head>
<body>
<div id="outer">
<p id="info"></p>
<img src="./img/01.webp" alt="图片">
<button id="last">上一张图片</button>
<button id="next">下一张图片</button>
</div>
</body>
</html>
<script>
// window.onload = function() {
$(function(){

// const last = document.getElementById("last");
// // $("#prev")
//
// const next = document.getElementById("next");

//切换图片就是更改img标签src的属性
//获取img图片标签
const img = document.getElementsByTagName("img")[0];


//创建一个数组来保存图片的路径
const imgArr = ["./img/01.webp", "./img/02.webp", "./img/03.webp", "./img/04.webp", "./img/05.webp"];

//创建一个变量来保存当前显示图片的索引
var index = 0;
// const info = document.getElementById("info");
//设置提示信息
info.innerHTML = "共" + imgArr.length + "张,当前第" + (index + 1) + "张";

//分别为两个按钮绑定单击响应函数
$("#last").click(function(){
// prev.onclick = function() {



index--;

if (index < 0) {
index = imgArr.length - 1;
}

img.src = imgArr[index];
//点击按钮更改信息
info.innerHTML = "共" + imgArr.length + "张,当前第" + (index + 1) + "张";

});
$("#next").click(function(){
// next.onclick = function() {

//切换到下一张index自加
index++;
if (index > imgArr.length - 1) {
index = 0;
}
img.src = imgArr[index];
//点击按钮更改信息
info.innerHTML = "共" + imgArr.length + "张,当前第" + (index + 1) + "张";

});

});
</script>
posted @ 2023-06-30 13:46  创克杨戒不掉  阅读(18)  评论(0)    收藏  举报