Javascript调整大图像大小仅适用于F5之后

Javascript resize big image only works after F5

本文关键字:适用于 F5 之后 调整 图像 Javascript      更新时间:2023-09-26

我使用这个javascript来调整页面上一个大(5Mb(图像的大小,最大为800px:

 <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
         }
     });
 });

加载页面时,不会调整图像大小。FireBug控制台上没有错误。如果我尝试用F5刷新页面,图像会被调整大小!如果我尝试Ctrl+F5,图像将返回原始大小!

问题出在哪里?为什么这个javascript只在刷新页面时有效?

document.ready()运行时不会加载图像。document.ready()在加载DOM时启动,但此时图像可能仍在加载中——尤其是当它们是5MB时!因此,图像的高度和宽度在脚本运行时不可用。我猜它在F5上工作,因为图像仍然是缓存的,所以加载速度足够快,以便在脚本运行时知道它们的尺寸Ctrl-F5清除图像缓存,所以在那之后,您又回到了开始的位置。

正如我在评论中所指出的,使用图像的load()事件可能会有所帮助,但即便如此,有时它也不会正确触发。例如,一些浏览器永远不会为已经在浏览器缓存中的图像触发load()事件(因为从技术上讲,它还没有加载…(

有几个不同的解决方法——Paul Irish的插件可能很有用;包括插件代码,然后使用类似的东西:

 $('.detailImg',this).imagesLoaded(function() {
   // Your existing function code
 });

或者,如果您事先知道图像大小,只需在img元素中指定即可,例如<img src="whatever" height="1200" width="1600" alt="whatever" />。通过这种方式,jQuery将能够判断图像是否已加载的宽度和高度。

将JS代码放在"body关闭标记"之前。

希望这能有所帮助。