当然,我可以为你提供一个简单的JavaScript实现图片切换的幻灯片效果的示例代码。这个示例将使用HTML来展示图片,CSS来设置基本的样式,以及JavaScript来控制图片的自动切换。
**HTML部分(index.html)**:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>幻灯片效果</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="slideshow-container">
<div class="mySlides fade">
<img src="img1.jpg" style="width:100%">
</div>
<div class="mySlides fade">
<img src="img2.jpg" style="width:100%">
</div>
<div class="mySlides fade">
<img src="img3.jpg" style="width:100%">
</div>
<!-- 可以在这里继续添加更多幻灯片 -->
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
<!-- 可以在这里继续添加更多圆点,与幻灯片数量匹配 -->
</div>
<script src="script.js"></script>
</body>
</html>
**CSS部分(styles.css)**:
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
.mySlides {
display: none;
}
.fade {
-animation-name: fade;
-animation-duration: 1.5s;
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
/* 前进和后退按钮 */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -22px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
/* 位置设置 */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* 圆点导航 */
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
/* 响应式设计 */
@media only screen and (max-width: 600px) {
.prev, .next,.text {font-size: 11px}
}
**JavaScript部分(script.js)**:
``
`javascript
let slideIndex = 1;
showSlides(slideIndex);
// 下一张幻灯片
function plusSlides(n) {
showSlides(slideIndex += n);
}
// 当前幻灯片
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
let i;
let slides = document.getElementsByClassName("mySlides");
let dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0;