我正在尝试在主页上做一个简单的旋转图像。在引擎盖下,我正在读取一个目录,然后将图像的URL填充到一个数组中。我想做的是交叉淡化图像。如果只是显示下一个问题,那很容易,但是因为我需要交叉淡入淡出,所以有点困难。我想我想要做的是通过在animate()
标记的opacity
值上调用<img>
并在交换css background-image
属性之间进行淡出。封闭<div>
。但结果并不那么好。
我已经使用工具进行更多功能齐全的幻灯片演示,但是我不想要添加插件的开销,如果我可以避免它,并且简单的交叉渐变似乎应该更容易。
这是我的JavaScript(我使用的是jQuery 1.3.2):
var slideshow_images = ["http:\/\/example.com\/wordpress\/wp-content\/themes\/testtheme\/sidebar-home-bg\/bg1.jpg","http:\/\/example.com\/wordpress\/wp-content\/themes\/testtheme\/sidebar-home-bg\/bg2.jpg","http:\/\/example.com\/wordpress\/wp-content\/themes\/testtheme\/sidebar-home-bg\/bg3.jpg"];
var slideshow_index = 0;
var delay = 4000;
var swapSlides = function() {
var slideshow_count = slideshow_images.length;
// initialize the background to be the current image
$('#home-slideshow').css({
'background-image': 'url(' + slideshow_images[slideshow_index] + ')',
'background-repeat:': 'no-repeat',
'width': 200,
'overflow': 'hidden'
});
slideshow_index = ((slideshow_index + 1) == slideshow_count) ? 0 : slideshow_index + 1;
// fade out the img
$('#home-slideshow img').animate({opacity: 0}, delay);
// now, the background is visible
// next change the url on the img
$('#home-slideshow img').attr('src', slideshow_images[slideshow_index]);
// and fade it up
$('#home-slideshow img').animate({opacity: 1.0}, delay);
// do it again
setTimeout('swapSlides()', 4000);
}
jQuery(document).ready(function(){
if (swapSlides) {
swapSlides();
}
});
这是我正在使用的标记:
<div id="home-slideshow"><img src="http://example.com/wordpress/wp-content/themes/testtheme/sidebar-home-bg/bg1.jpg" alt="" /></div>
答案 0 :(得分:2)
您应该注意的第一件事就是导致代码出现问题:animate方法不同步!所以当你这样做时:
$('#home-slideshow img').animate({opacity: 0}, delay);
// now, the background is visible
// next change the url on the img
$('#home-slideshow img').attr('src', slideshow_images[slideshow_index]);
您开始制作动画,但该方法会立即返回。您可以将动画想象为后台线程,尽管JavaScript中没有线程,所有内容都是使用settimeout调用实现的。
因此,在您的代码中,当您更改src属性时,图像可能仍然可见99%。然后你开始将它设置为100%不透明度,但此时它仍然是98%,并且两个“线程”将尝试同时使其显示/消失!
所以在你的代码中需要设置超时以正确的顺序执行任务(总是在中间留下几毫秒的余量),或者,当你有许多连续的函数调用时,更安全但可能更少的可读性,使用回调动画方法的功能。例如:
$('#home-slideshow img').animate({opacity: 0}, delay, function(){
// now, the background is visible
// next change the url on the img
$('#home-slideshow img').attr('src', slideshow_images[slideshow_index]);
// and fade it up
$('#home-slideshow img').animate({opacity: 1.0}, delay, function(){
// do it again
setTimeout('swapSlides()', 4000);
});
});
最后,你正在做的是淡出+淡入。如果你想要一个真正的交叉淡入淡出,你需要在某个时刻同时拥有2个元素:
答案 1 :(得分:2)
试试这个:
jQuery
的几行$(function(){
$('#home-slideshow img:gt(0)').hide();
setInterval(function(){
$('#home-slideshow :first-child').fadeOut()
.next('img').fadeIn()
.end().appendTo('#home-slideshow');},
3000);
});
2行 CSS
#home-slideshow { position:relative; height:332px; width:500px; }
#home-slideshow img { position:absolute; left:0; top:0; }
HTML
<div id="home-slideshow">
<img src="image.jpg" alt=""/>
<img src="image.jpg" alt=""/>
<img src="image.jpg" alt=""/>
...
...
</div>