你可以用 JavaScript 和 CSS 做很多事情,但是这是一个非常解决的问题,有很多选项可以基本上显示幻灯片。所以最好看看其中之一。但无论如何,让我们试试吧!
HTML:
<div id="slideshow"></div>
CSS:
#slideshow {
border: 1px solid gray;
height: 330px;
width: 592px;
opacity: 0;
}
JavaScript:
$(document).ready(function() {
var timeToDisplay = 2000;
var opacityChangeDelay = 50;
var opacityChangeAmount = 0.05;
var slideshow = $('#slideshow');
var urls = [
'http://sipi.usc.edu/database/preview/aerials/2.1.07.png',
'http://sipi.usc.edu/database/preview/aerials/2.1.06.png',
'http://sipi.usc.edu/database/preview/aerials/2.1.12.png'
];
var index = 0;
var transition = function() {
var url = urls[index];
slideshow.css('background-image', 'url(' + url + ')');
index = index + 1;
if (index > urls.length - 1) {
index = 0;
}
};
var fadeIn = function(opacity) {
opacity = opacity + opacityChangeAmount;
slideshow.css('opacity', opacity);
if (opacity >= 1) {
slideshow.trigger('fadeIn-complete');
return;
}
setTimeout(function() {
fadeIn(opacity);
}, opacityChangeDelay);
};
var fadeOut = function(opacity) {
opacity = opacity - opacityChangeAmount;
slideshow.css('opacity', opacity);
if (opacity <= 0) {
slideshow.trigger('fadeOut-complete');
return;
}
setTimeout(function() {
fadeOut(opacity);
}, opacityChangeDelay);
};
slideshow.on('fadeOut-complete', function(event) {
transition();
fadeIn(0);
});
slideshow.on('display-complete', function(event) {
fadeOut(1);
});
slideshow.on('fadeIn-complete', function(event) {
setTimeout(function() {
slideshow.trigger('display-complete');
}, timeToDisplay);
});
transition();
fadeIn(0);
});
演示:jsfiddle
当然,jQuery 已经有了fadeIn
,fadeOut
所以我们可以使用它们来简化我们的代码:
$(document).ready(function() {
var timeToDisplay = 2000;
var slideshow = $('#slideshow');
var urls = [
'http://sipi.usc.edu/database/preview/aerials/2.1.07.png',
'http://sipi.usc.edu/database/preview/aerials/2.1.06.png',
'http://sipi.usc.edu/database/preview/aerials/2.1.12.png'
];
var index = 0;
var transition = function() {
var url = urls[index];
slideshow.css('background-image', 'url(' + url + ')');
index = index + 1;
if (index > urls.length - 1) {
index = 0;
}
};
var run = function() {
transition();
slideshow.fadeIn('slow', function() {
setTimeout(function() {
slideshow.fadeOut('slow', run);
}, timeToDisplay);
});
}
run();
});
演示:jsfiddle
我们也可以使用slideDown
and slideUp
: jsfiddle
那么为什么不直接使用它呢?好吧,您可以,但是我知道一个明显的缺陷:我们在确保浏览器已下载所有图像之前开始播放幻灯片。我们应该解决这个问题。毫无疑问,我们可能忽略了类似的问题,但您可以选择使用什么。