我想更改这个jQuery背景图像脚本,以便图像淡入淡出或淡出淡出或滑入或滑出。
现在新图像只是弹出不好看的东西。 也无法弄清楚如何使图像随机加载。
(function ($) {
var count = 0;
var milliseconds = 4000;
var transitionTime = 1500;
var selector = "#target";
setInterval(function () {
var images = ["images/pic1.png", "images/pic2.jpg"];
var tempImage = new Image();
tempImage.src = images[count];
$(tempImage).on("load", function () {
$(selector).css("opacity", "0")
.animate({ opacity: 1 }, { duration: transitionTime });
$(selector).css("background-image", "url(" + tempImage.src + ")");
});
if (count < images.length - 1) {
count++;
}
else {
count = 0;
}
}, milliseconds);
})(jQuery);
答案 0 :(得分:0)
如果我理解正确你的意思是你希望一个图像在淡入淡出时淡出?它确实看起来更顺畅。
这是一个简单的解决方案。请注意,您的图像必须绝对放在彼此之上。
您可以使用动画完成回调使其更加简洁。如果你使用了css过渡和toggleClass,你可能会把它挤成几行。
$(document).ready( function() {
var milliseconds = 4000;
var transitionTime = 1500;
var $showing, $target1, $hidden, $target2;
$showing = $target1 = $("#selector1");
$hidden = $target2 = $("#selector2");
var images = ["images/pic1.png", "images/pic2.png"];
// You could also use this instead of incrementing count.
// Just remember not to show the same image twice in a row
var count = Math.floor( Math.random() * images.length );
var showImage = function(index, duration) {
var tempImage = new Image();
tempImage.src = images[count];
$(tempImage).on("load", function () {
$hidden.css("opacity", "0")
.animate({ opacity: 1 }, { duration: duration })
.css("background-image", "url(" + tempImage.src + ")");
$showing.animate({ opacity: 0 }, { duration: duration });
var $temp = $showing;
$showing = $hidden;
$hidden = $temp;
});
};
// show the first image immediately
showImage(count, 0);
setInterval(function () {
showImage(count, transitionTime);
if (count < images.length - 1) {
count++;
}
else {
count = 0;
}
}, milliseconds);
});