【发布时间】:2010-09-20 18:32:19
【问题描述】:
我正在编写一些 Javascript 来调整大图像的大小以适应用户的浏览器窗口。 (不幸的是,我不控制源图像的大小。)
所以 HTML 中会有这样的内容:
<img id="photo"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
我有没有办法确定img 标签中的src 图像是否已下载?
我需要这个,因为如果在浏览器加载图像之前执行$(document).ready(),我会遇到问题。 $("#photo").width() 和 $("#photo").height() 将返回占位符(替代文本)的大小。就我而言,这类似于 134 x 20。
现在我只是检查照片的高度是否小于 150,并假设如果是,它只是替代文本。但这是一个相当大的技巧,如果照片的高度小于 150 像素(在我的特定情况下不太可能),或者 alt 文本的高度超过 150 像素(可能发生在小的浏览器窗口上),它就会中断.
编辑:对于任何想查看代码的人:
$(function()
{
var REAL_WIDTH = $("#photo").width();
var REAL_HEIGHT = $("#photo").height();
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size()
{
if(REAL_HEIGHT < 150)
{
REAL_WIDTH = $("#photo").width();
REAL_HEIGHT = $("#photo").height();
if(REAL_HEIGHT < 150)
{
//image not loaded.. try again in a quarter-second
setTimeout(adjust_photo_size, 250);
return;
}
}
var new_width = . . . ;
var new_height = . . . ;
$("#photo").width(Math.round(new_width));
$("#photo").height(Math.round(new_height));
}
});
更新:感谢您的建议。如果我为$("#photo").load 事件设置回调,则存在不会触发事件的风险,因此我直接在图像标签上定义了 onLoad 事件。作为记录,这是我最终使用的代码:
<img id="photo"
onload="photoLoaded();"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
然后在Javascript中:
//This must be outside $() because it may get called first
var isPhotoLoaded = false;
function photoLoaded()
{
isPhotoLoaded = true;
}
$(function()
{
//Hides scrollbars, so we can resize properly. Set with JS instead of
// CSS so that page doesn't break with JS disabled.
$("body").css("overflow", "hidden");
var REAL_WIDTH = -1;
var REAL_HEIGHT = -1;
$(window).resize(adjust_photo_size);
adjust_photo_size();
function adjust_photo_size()
{
if(!isPhotoLoaded)
{
//image not loaded.. try again in a quarter-second
setTimeout(adjust_photo_size, 250);
return;
}
else if(REAL_WIDTH < 0)
{
//first time in this function since photo loaded
REAL_WIDTH = $("#photo").width();
REAL_HEIGHT = $("#photo").height();
}
var new_width = . . . ;
var new_height = . . . ;
$("#photo").width(Math.round(new_width));
$("#photo").height(Math.round(new_height));
}
});
【问题讨论】:
-
这太老了,您已经接受了答案,所以我将在这里发表评论。为什么不能使用 jQuery 插件“onImagesLoad”?而且,无论是否使用 jQuery,使用 Javascript 在图像样式中设置
max-width和max-height有什么问题?然后,您可以通过将最大宽度/高度设置为视口宽度/高度的大小来避免您需要编写的所有代码。 -
@jon.wd7:我不熟悉那个插件,它可能早在 08 年就没有了。至于最大宽度和最大高度,有两件事:1)IE 不支持它们(我不确定 IE 8); 2)如果视口改变大小(窗口大小调整等),那么我仍然需要javascript来改变最大宽度/最大高度(尽管如果我使用“100%”而不是像素测量,我可能不会)
-
根据 quirksmode.org 的说法,IE7 和 IE8 肯定支持它。所以我不确定你的问题。对于这样的小事,我个人不支持 IE6,所以他们看到的和没有启用 JS 的用户看到的一样。当然,您需要在调整大小时重置
max-width和max-height。但这是一项相当容易的任务,实际上是使用.resize()的单行代码。 -
complete 属性提供了了解图像是否已加载的必要方式。
-
@Adrien,Mozilla 现在 shows 已完成,所有主流浏览器都支持,除了 Andoid(未知)。
标签: javascript jquery image