以下是一个使用 JavaScript 实现图片左右切换的简单示例代码:
<!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>
#imageContainer {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
}
#imageContainer img {
width: 100%;
height: auto;
position: absolute;
transition: all 0.5s;
}
</style>
</head>
<body>
<div id="imageContainer">
<img src="image1.jpg" alt="Image 1" id="currentImage">
</div>
<button onclick="prevImage()">上一张</button>
<button onclick="nextImage()">下一张</button>
<script>
const images = ["image1.jpg", "image2.jpg", "image3.jpg"];
let currentIndex = 0;
const currentImage = document.getElementById('currentImage');
function prevImage() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
currentImage.src = images[currentIndex];
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
currentImage.src = images[currentIndex];
}
</script>
</body>
</html>
基础概念:这段代码主要涉及 HTML 结构、CSS 样式和 JavaScript 逻辑。
优势:
类型:这是一个基于前端页面的交互功能。
应用场景:
可能遇到的问题及解决方法:
希望这个示例对你有帮助!
领取专属 10元无门槛券
手把手带您无忧上云