以下是一个使用JavaScript实现图片切换的简单示例代码:
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片切换</title>
<style>
#image {
width: 300px;
height: 200px;
}
</style>
</head>
<body>
<img id="image" src="image1.jpg" alt="图片">
<button onclick="prevImage()">上一张</button>
<button onclick="nextImage()">下一张</button>
<script src="script.js"></script>
</body>
</html>
JavaScript部分(script.js):
let images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
let currentIndex = 0;
function prevImage() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = images.length - 1;
}
document.getElementById('image').src = images[currentIndex];
}
function nextImage() {
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
document.getElementById('image').src = images[currentIndex];
}
基础概念:
<img>
元素的src
属性来实现图片切换。通过定义一个包含图片路径的数组images
,然后根据当前索引currentIndex
来确定显示哪张图片。优势:
应用场景:
如果遇到图片不切换的问题可能有以下原因:
images
数组中的图片路径是正确的,并且图片存在于指定的位置。<script>
标签在HTML元素之后加载(如上述示例),或者使用DOMContentLoaded
事件来确保DOM元素已经存在于页面中再进行操作。<img>
元素的id
与JavaScript中获取元素的id
一致。领取专属 10元无门槛券
手把手带您无忧上云