编写一段html代码实现创建5个图片和按钮 只展示一个图片,对应按钮颜色区分 点击按钮,对应图片展示,其他图片隐藏
时间: 2024-03-25 10:38:52 浏览: 46
以下是实现你所要求的html代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Show and Hide Images with Buttons</title>
<style>
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.image {
display: none;
}
.button {
margin: 10px;
padding: 5px 10px;
border: none;
border-radius: 5px;
color: #fff;
background-color: #333;
cursor: pointer;
}
.button:hover {
background-color: #555;
}
.active {
background-color: #f00;
}
</style>
</head>
<body>
<div class="container">
<img class="image active" src="image1.jpg" alt="Image 1">
<img class="image" src="image2.jpg" alt="Image 2">
<img class="image" src="image3.jpg" alt="Image 3">
<img class="image" src="image4.jpg" alt="Image 4">
<img class="image" src="image5.jpg" alt="Image 5">
</div>
<div class="container">
<button class="button active" onclick="showImage(1)">Image 1</button>
<button class="button" onclick="showImage(2)">Image 2</button>
<button class="button" onclick="showImage(3)">Image 3</button>
<button class="button" onclick="showImage(4)">Image 4</button>
<button class="button" onclick="showImage(5)">Image 5</button>
</div>
<script>
function showImage(n) {
let images = document.getElementsByClassName("image");
let buttons = document.getElementsByClassName("button");
// hide all images and remove active class from buttons
for (let i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
for (let i = 0; i < buttons.length; i++) {
buttons[i].classList.remove("active");
}
// show the selected image and add active class to the corresponding button
images[n-1].style.display = "block";
buttons[n-1].classList.add("active");
}
</script>
</body>
</html>
```
这段代码中,我们创建了一个包含5张图片和5个按钮的容器。默认情况下,只有第一张图片和第一个按钮是可见的,并且该按钮是选中状态。当用户点击其他按钮时,相应的图片将显示,其他图片将隐藏,并且相应的按钮将被选中。
阅读全文