Вот javascript, который я написал, чтобы сделать именно это.
function ImageTile(parentdiv, imagediv) {
imagediv.style.position = 'absolute';
function load(image) {
//
// Reset to auto so that when the load happens it resizes to fit our image and that
// way we can tell what size our image is. If we don't do that then it uses the last used
// values to auto-size our image and we don't know what the actual size of the image is.
//
imagediv.style.height = "auto";
imagediv.style.width = "auto";
imagediv.style.top = 0;
imagediv.style.left = 0;
imagediv.src = image;
}
//bind load event (need to wait for it to finish loading the image)
imagediv.onload = function() {
var vpWidth = parentdiv.clientWidth;
var vpHeight = parentdiv.clientHeight;
var imgWidth = this.clientWidth;
var imgHeight = this.clientHeight;
if (imgHeight > imgWidth) {
this.style.height = vpHeight + 'px';
var width = ((imgWidth/imgHeight) * vpHeight);
this.style.width = width + 'px';
this.style.left = ((vpWidth - width)/2) + 'px';
} else {
this.style.width = vpWidth + 'px';
var height = ((imgHeight/imgWidth) * vpWidth);
this.style.height = height + 'px';
this.style.top = ((vpHeight - height)/2) + 'px';
}
};
return {
"load": load
};
}
И чтобы использовать его, просто сделайте что-то вроде этого:
var tile1 = ImageTile(document.documentElement, document.getElementById("tile1"));
tile1.load(url);
Я используюэто для слайд-шоу, в котором у меня есть две из этих «плиток», и я постепенно исчезаю, а другая - внутри. Загрузка выполняется на «плитке», которая не видна, чтобы избежать неприятного визуального эффекта сброса стиля назад.на «авто».