我正在编写一些 Javascript 来调整大图像的大小以适应用户的浏览器窗口。(不幸的是,我不控制源图像的大小。)
所以像这样的东西会出现在 HTML 中:
<img id="photo"
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
有没有办法让我确定标签中的src
图像img
是否已下载?
我需要这个,因为如果$(document).ready()
在浏览器加载图像之前执行,我会遇到问题。 $("#photo").width()
并且$("#photo").height()
将返回占位符(alt文本)的大小。就我而言,这类似于 134 x 20。
现在我只是检查照片的高度是否小于 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));
}
});