以下是我将如何解决这个问题。我发现通读您的版本对于变量范围、传递参数和 jQuery 应用参数的特定组合有点令人困惑——这可能是您发现难以调试的原因。
- 如果您不需要,请避免使用闭包,它们可能很复杂,容易出错,如果您不小心,还会导致内存泄漏。
- 将 src 属性应用于图像时,我认为最好在这样做之前应用负载侦听器,但这可能只是虚构的,这只是我一直认为有意义的事情。
- 尽可能使用 jQuery 的强大功能,因为它让您的生活更轻松 :)
- 您不需要使用临时图像来避免 css 大小问题。
- IMG.complete 在图像缓存问题方面是您的朋友。
这使我想到以下内容:
var resizeImages = function( imgs, img_ratio ){
/// not sure what you're passing to this function but the following
/// should handle an array of images elms or a jQuery collection of images
var images = ( imgs instanceof jQuery ? imgs : $().pushStack(imgs) );
var resizeImage = function( img ){
var cn, st, ow;
/// make it so we can call this function in two ways
if ( !img ) { img = $(this); }
/// store items of the image
cn = img.attr('class');
st = img.attr('style');
/// remove those items so they don't get in the way of original width
img.attr('class','').attr('style','');
/// get the original width
ow = img.width();
/// place back the things we've removed - changes wont render visibly
/// till code execution finishes at the end of this function call.
img.attr('class',cn);
img.attr('style',st);
/// apply the resize
img.css('width', ow * img_ratio );
}
images.each(function(){
var img = $(this);
/// check if the image is already loaded, if so, resize directly
if ( img.get(0).complete ) {
resizeImage(img);
}
/// if the image isn't loaded yet, rely on an image load event
else {
img.load(resizeImage);
};
});
};
现在是不那么罗嗦的版本:)
var resizeImages = function( images, scale ){
var cn, st, ow, resizeImage = function( img ){
img = img || $(this);
cn = img.attr('class');
st = img.attr('style');
ow = img.attr('class','').attr('style','').width();
img.attr('class',cn).attr('style',st).css('width', ow * scale );
}
( images instanceof jQuery ? images : $().pushStack(images) )
.each(function(){
( this.complete ? resizeImage($(this)) : $(this).load(resizeImage) );
});
};
$(function(){
resizeImages( document.images, 0.5 );
});