最佳答案
我正在编写一些 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()
将返回占位符的大小(替换文本)。在我的例子中,它大概是134x20。
现在我只是检查照片的高度是否小于150,并假设如果是这样,它只是替换文本。但是,这是一个相当黑客,它会打破,如果一张照片不到150像素高(不太可能在我的特殊情况下) ,或如果替换文本超过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));
}
});