仅在完成加载后淡入图像
-
16-12-2019 - |
题
我的页面上有一些随机加载的图像,它们超过 100kbs,是否可以完全加载然后淡入而不是逐步加载?
我的JS看起来像这样......
(function($){
$.randomImage = {
defaults: {
//you can change these defaults to your own preferences.
path: '_images/', //change this to the path of your images
myImages: ['hero_eagle.jpg', 'hero_giraffe.jpg', 'hero_owl.jpg', 'hero_rabbit.jpg']
}
}
$.fn.extend({
randomImage:function(config) {
var config = $.extend({}, $.randomImage.defaults, config);
return this.each(function() {
var imageNames = config.myImages;
//get size of array, randomize a number from this
// use this number as the array index
var imageNamesSize = imageNames.length;
var lotteryNumber = Math.floor(Math.random()*imageNamesSize);
var winnerImage = imageNames[lotteryNumber];
var fullPath = config.path + winnerImage;
//put this image into DOM at class of randomImage
// alt tag will be image filename.
$(this).attr( { src: fullPath });
});
}
});
})(jQuery);
解决方案
应该可以,把图片设置成 display:none
在样式表中修改将 src 设置为以下的脚本部分:
$(this).attr( { src: fullPath }).load(function() {
$(this).fadeIn()
});
其他提示
从使用CSS隐藏的图像开始。然后使用:
$(document).ready(function() {
// Code goes here.
});
.
并在那里逐渐执行。
另一个如此讨论了使用jQuery的预加载图像:用jquery 预加载图像
引用顶部答案:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
. 如果您希望在衰落之前预先加载所有图像,并向用户显示加载消息,您可以使用这样的内容:
var gotime = imgArray.length;
$(".maxCount").text(gotime);
var imgCounter = 0;
$.each(imgArray, function(){
$(new Image()).load(function(){
imgCounter++;
$(".presentCount").text(imgCounter);
if (--gotime < 1) {
$("#content").fadeIn();
}
}).attr('src', this);
});
. 不隶属于 StackOverflow