以下是一个简单的JavaScript图片切换代码示例,您可以将其保存为一个HTML文件并在浏览器中打开以查看效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片切换</title>
<style>
#img {
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<img id="img" src="image1.jpg" alt="图片">
<button onclick="prevImage()">上一张</button>
<button onclick="nextImage()">下一张</button>
<script>
const images = ["image1.jpg", "image2.jpg", "image3.jpg"];
let currentIndex = 0;
function prevImage() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
document.getElementById("img").src = images[currentIndex];
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
document.getElementById("img").src = images[currentIndex];
}
</script>
</body>
</html>希望这个示例和解释对您有所帮助!如有其他问题,请随时提问。
没有搜到相关的文章