问题描述
所以我有一个图像文件夹,看起来像这样 - img
- 001
--- banner_620x350.jpg
--- banner_300x130.jpg
--- banner_180x60.jpg
- 002
--- banner_300x130.jpg
- - banner_180x60.jpg
- 003
--- banner_180x60.jpg
我目前加载图像的方式如下所示:
< img src =img / 003 / banner_620x350.jpgalt = 001onError =this.onerror = null; this.src ='img / 003 / banner_180x60.jpg'; />
因为我们总是有180x60的图片,但我们并不总是有600x350或300x130
我想要做的是这个
如果600x350存在使用它
else如果300x130存在使用它
else使用180x60
PS:我可以'检查服务器端。
创建一个函数,检查图像是否可以加载,如果不能,到下一个等等,如果它们都失败了,它仍然会返回数组中的最后一个:
函数checkSource(src ){
var def = $ .Deferred(),
res = ['620x350','180x60','180x60'];
(函数s(i){
$('< img />',{src:(src +'_'+ res [i] +'.jpg') })。on({
load:function(){
def.resolve(this.src);
},
error:function(){
if (i!= res.length-1){
s(++ i);
} else {
def.resolve(this.src);
}
}
});
}(0));
return def.promise();
};
您可以这样称呼:
<$ p $($'code $> $'code> checkSource('banner')。done(function(file){
$('img#banner')。prop('src',file);
} );
它将源设置为可以加载的图像,按照 res
数组,即按此顺序:
banner_620x350.jpg
banner_300x130.jpg
banner_180x60.jpg
So I have a folder of images that look like this
- img
-- 001
--- banner_620x350.jpg
--- banner_300x130.jpg
--- banner_180x60.jpg
-- 002
--- banner_300x130.jpg
--- banner_180x60.jpg
-- 003
--- banner_180x60.jpg
My current way to load an image looks like this
<img src="img/003/banner_620x350.jpg" alt="001" onError="this.onerror=null;this.src='img/003/banner_180x60.jpg';" />
because we well always have a 180x60 image but we not always have a 600x350 or 300x130
What I would like to do is this
if 600x350 exists uses it
else if does 300x130 exists use it
else use 180x60
PS: I can't check server side.
Create a function that checks if the image can be loaded, if it can't, move on to the next etc. and if all of them fails, it still returns the last one in the array :
function checkSource(src) {
var def = $.Deferred(),
res = ['620x350', '180x60', '180x60'];
(function s(i) {
$('<img />', {src : (src + '_' + res[i] + '.jpg')}).on({
load: function() {
def.resolve(this.src);
},
error: function() {
if (i != res.length-1) {
s(++i);
}else{
def.resolve(this.src);
}
}
});
}(0));
return def.promise();
};
You can call it like :
checkSource('banner').done(function(file) {
$('img#banner').prop('src', file);
});
and it sets the source to whatever image could be loaded, in the order of the res
array, i.e. in this order :
banner_620x350.jpg
banner_300x130.jpg
banner_180x60.jpg
这篇关于如果较高的一次可用,则加载较低质量的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!