jQuery 单独设置每张幻灯片图片的停留时间 鼠标移动过去停止播放 鼠标移开后立即下一张 完整代码
时间: 2023-05-29 22:04:22 浏览: 133
以下是一个基于jQuery的幻灯片代码,可单独设置每张幻灯片图片的停留时间,并在鼠标移动到幻灯片上时停止播放,鼠标移开后立即播放下一张。
HTML代码:
```html
<div class="slideshow">
<img src="image1.jpg" data-time="5000">
<img src="image2.jpg" data-time="3000">
<img src="image3.jpg" data-time="7000">
</div>
```
CSS代码:
```css
.slideshow {
position: relative;
overflow: hidden;
width: 500px;
height: 300px;
}
.slideshow img {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 1s ease-in-out;
width: 100%;
height: 100%;
}
.slideshow img.active {
opacity: 1;
}
```
jQuery代码:
```javascript
$(document).ready(function() {
var slides = $(".slideshow img");
var currentSlide = 0;
// Set the first slide to active
slides.eq(currentSlide).addClass("active");
// Loop through each slide and set its display time
slides.each(function() {
var time = $(this).data("time");
$(this).data("timer", setTimeout(function() {
nextSlide();
}, time));
});
// Define a function to go to the next slide
function nextSlide() {
clearTimeout(slides.eq(currentSlide).data("timer"));
slides.eq(currentSlide).removeClass("active");
currentSlide = (currentSlide + 1) % slides.length;
slides.eq(currentSlide).addClass("active");
var time = slides.eq(currentSlide).data("time");
slides.eq(currentSlide).data("timer", setTimeout(function() {
nextSlide();
}, time));
}
// Define a function to stop the slideshow on mouseover
function stopSlideshow() {
clearTimeout(slides.eq(currentSlide).data("timer"));
}
// Define a function to resume the slideshow on mouseout
function resumeSlideshow() {
var time = slides.eq(currentSlide).data("time");
slides.eq(currentSlide).data("timer", setTimeout(function() {
nextSlide();
}, time));
}
// Bind the stop and resume functions to mouse events
$(".slideshow").on("mouseover", stopSlideshow);
$(".slideshow").on("mouseout", resumeSlideshow);
});
```
阅读全文