jQuery 轮播图 每张图设置不同停留时间 完整代码
时间: 2023-05-30 21:01:55 浏览: 118
<!DOCTYPE html>
<html>
<head>
<title>jQuery 轮播图</title>
<meta charset="utf-8">
<style type="text/css">
#slider {
width: 600px;
height: 350px;
margin: 0 auto;
overflow: hidden;
position: relative;
}
#slider img {
width: 600px;
height: 350px;
position: absolute;
top: 0;
left: 0;
display: none;
}
#slider img:first-child {
display: block;
}
#slider .slider-control {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 1;
width: 100%;
}
#slider .slider-control button {
display: inline-block;
background-color: #333;
color: #fff;
border: none;
padding: 10px 20px;
margin: 0 10px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.5s ease;
}
#slider .slider-control button:hover {
background-color: #555;
}
</style>
</head>
<body>
<div id="slider">
<img src="https://via.placeholder.com/600x350/ff0000/ffffff?text=Image%201" alt="Image 1" data-delay="5000">
<img src="https://via.placeholder.com/600x350/00ff00/ffffff?text=Image%202" alt="Image 2" data-delay="10000">
<img src="https://via.placeholder.com/600x350/0000ff/ffffff?text=Image%203" alt="Image 3" data-delay="3000">
<div class="slider-control">
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var sliderInterval;
var currentSlide = 0;
var sliderDelay = 5000;
var sliderImages = $('#slider img');
var sliderCount = sliderImages.length;
// Set the delay for each slide
sliderImages.each(function() {
var delay = $(this).data('delay');
if (delay) {
$(this).data('delay', delay);
} else {
$(this).data('delay', sliderDelay);
}
});
// Start the slider
startSlider();
// Previous slide button click event
$('#prev').click(function() {
stopSlider();
prevSlide();
startSlider();
});
// Next slide button click event
$('#next').click(function() {
stopSlider();
nextSlide();
startSlider();
});
// Function to start the slider
function startSlider() {
sliderInterval = setInterval(function() {
nextSlide();
}, sliderDelay);
}
// Function to stop the slider
function stopSlider() {
clearInterval(sliderInterval);
}
// Function to go to the previous slide
function prevSlide() {
currentSlide--;
if (currentSlide < 0) {
currentSlide = sliderCount - 1;
}
showSlide();
}
// Function to go to the next slide
function nextSlide() {
currentSlide++;
if (currentSlide >= sliderCount) {
currentSlide = 0;
}
showSlide();
}
// Function to show the current slide
function showSlide() {
sliderImages.stop().fadeOut();
sliderImages.eq(currentSlide).stop().fadeIn(sliderImages.eq(currentSlide).data('delay'));
}
});
</script>
</body>
</html>
阅读全文