我正在使用jQuery创建简单的幻灯片,并且它的工作正常我只想使用淡入淡出函数以及下面的代码。我使用了淡入淡出功能,但它正在工作,它不会在变化时淡化图像。
var mainImage = $('#mainImage');
var imageData = ['_images/gallery/beach_houses.jpg','_images/gallery/golden_gate.jpg','_images/gallery/red_rock_01.jpg'];
var imageIndex = 0;
function imageSlide(){
mainImage.fadeIn("slow",function(){
mainImage.attr("src",imageData[imageIndex]);
imageIndex++;
if(imageIndex >= imageData.length){
imageIndex = 0;
}
});
}
setInterval(imageSlide,1000);
答案 0 :(得分:1)
您已经使用过fadeIn
,但为了使图片淡出 ,必须隐藏它,最简单的方法就是将其淡出 out 第一。
使用fadeOut回调,你可以等待fadeOut完成,设置src然后fadeIn:
var mainImage = $('#mainImage');
var imageData = ['_images/gallery/beach_houses.jpg','_images/gallery/golden_gate.jpg','_images/gallery/red_rock_01.jpg'];
var imageIndex = 0;
function imageSlide() {
// fade out before changing src
mainImage.fadeOut("fast", function(){
mainImage.attr("src",imageData[imageIndex]);
imageIndex++;
if(imageIndex >= imageData.length){
imageIndex = 0;
}
// fade back in after changing src
mainImage.fadeIn("slow");
});
}
// Increase interval to provide enough time if needed
setInterval(imageSlide, 1000);
请注意"slow"
= 600毫秒,因此2x慢(淡出然后输入)将比你的setInterval 1000ms更长并且会产生一些疯狂的结果。
答案 1 :(得分:1)
看我的代码遵循3步,希望这可以帮到你!
mainImage
mainImage
注意:数组中最后一项的索引为imageData.length - 1
,此处将imageIndex
重置为零
var mainImage = $('#mainImage');
var imageData = ['http://www.vincenzo.net/isxkb/images/a/a9/Example.jpg','http://www.buzzlinestravel.co.uk/images/itinerary/1-1276781550ufzx.jpg','http://images.all-free-download.com/images/wallpapers_large/poppies_and_coreopsis_wallpaper_flowers_nature_wallpaper_1542.jpg'];
var imageIndex = 0;
function imageSlide(){
//1. you need hide before use fadeIn
mainImage.hide();
//2. you need find target source to show
mainImage.attr("src",imageData[imageIndex]);
imageIndex++;
if(imageIndex === imageData.length - 1){
imageIndex = 0;
}
//3. the last step, you got all data needed, you can fadeIn your image here
mainImage.fadeIn("slow");
}
setInterval(imageSlide,1000);
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.0.3.js"></script><!DOCTYPE html>
<html>
</head>
<body>
<img src="" alt="" id="mainImage">
</body>
</html>
答案 2 :(得分:0)
检查下面的代码。出于生产目的,你仍然需要“擦亮”它。祝你好运
var mainImage = $('#mainImage');
var imageData = ['https://www.maxcdn.com/blog/blog-assets/2016/01/firefox-subresource-integrity-error.png','https://www.typesettercms.com/data/_addondata/x_Addons/screenshots/5/245/thumbnail.png','https://cdn9.gaborszathmari.me/wp-content/uploads/2016/06/when-the-cdn-goes-bananas-cover.png'];
var imageIndex = 0;
function imageSlide(){
mainImage.attr("src",imageData[imageIndex]).fadeIn(1000,function(){
imageIndex++;
if(imageIndex >= imageData.length){
imageIndex = 0;
}
setTimeout(function(){
mainImage.fadeOut(1000,function(){
imageSlide();
});
},1000);
});
}
imageSlide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img style="display:none;" id="mainImage">