我使用这个javascript调整大小,最大为800px,页面上的大(5Mb)图像:
<script type="text/javascript">
$(document).ready(function () {
$('.detailImg').each(function () {
var maxWidth = 800; // Max width for the image
var maxHeight = 800; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if (width > maxWidth) {
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if (height > maxHeight) {
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
}
});
});
Run Code Online (Sandbox Code Playgroud)
加载页面时,图像不会调整大小.FireBug控制台上没有错误.如果我尝试使用F5刷新页面,图像会调整大小!如果我尝试Ctrl + F5,图像将以原始大小返回!
问题出在哪儿?为什么这个javascript只在页面刷新时才有效?
document.ready()运行时不会加载图像.document.ready()激活DOM的负载,但此时图像可能仍在加载 - 特别是如果它们是5MB!因此,在脚本运行时,图像高度和宽度不可用.我猜它正在研究,F5因为图像仍然被缓存,因此然后加载足够快,以便在脚本运行时知道它们的尺寸.Ctrl- F5清除图像缓存,之后,您回到开始的位置.
正如我在评论中指出的那样,使用load()图像事件可能有所帮助,但即便如此,有时它也不会被正确触发.例如,某些浏览器永远不会load()为已经在浏览器缓存中的图像触发事件(因为从技术上讲,它尚未加载...)
这样做有几种不同的解决方法 - 保罗爱尔兰的插件可能有用; 包括插件代码,然后使用类似的东西:
$('.detailImg',this).imagesLoaded(function() {
// Your existing function code
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您事先知道图像大小,只需在img元素中指定它,例如<img src="whatever" height="1200" width="1600" alt="whatever" />.这样jQuery就可以告诉图像是否加载的宽度和高度.