不确定我是否可以充分解释这一点,但在这里。我正在一个地方悬停并显示带有框架/背景和标题的图片。除了我第一次盘旋之外,这一切都真的很棒......
我正在尝试使用以下代码检索图像的宽度:
/* Retrieve the width of the image */
var trashImg = new Image(); // declare an image object
trashImg.src = this.href; // instanciate it to the current image
IMG_WIDTH = trashImg.width; // get the width of the image
问题是,我第一次悬停时,它正确检索“trashImg.src”,但“trashImg.width”返回0(零)。我第二次悬停时,“trashImg.width”返回正确的大小。我在“jQuery(document).ready(function($){...”函数中有这个代码,所以大概是在这时加载了图像。
我一直盯着这段代码几个小时,无法弄清楚原因。有人有什么想法吗?感谢。
答案 0 :(得分:1)
您不会等到图像实际加载完毕。
您应该将width
支票包装到图片的load
事件处理程序中:
trashImg.onload = function() { IMG_WIDTH = trashImg.width; }
trashImg.src = this.href; // Remember to do this AFTER defining the load handler
(有可能在加载函数中将图像称为this
而不是trashImg
,但我现在不确定它是否会按预期完全正常工作)< / em>的
请注意,您不知道何时会触发load
事件,因此您需要将依赖于IMG_WIDTH
的所有代码放入该函数中(或从那里调用它)。
虽然这通常会起作用,但图像上的加载事件有一些已知的不可靠性,这是很好的了解。来自jQuery manual:
与图像一起使用时加载事件的注意事项
开发人员尝试使用.load()快捷方式解决的常见挑战是在图像(或图像集合)完全加载时执行函数。应该注意有几个已知的警告。这些是:
- 它不能始终如一地工作,也不能可靠地跨浏览器
- 如果图像src设置为与之前相同的src,则无法在WebKit中正确触发
- 它没有正确地冒泡DOM树
- 可以停止触发已存在于浏览器缓存中的图像
答案 1 :(得分:0)
document.ready并不意味着已经加载了所有图像,只是加载了“基本结构”(因此您知道可以找到所有ID等)。您可以查看load()函数:http://api.jquery.com/load-event/来正确执行此操作
答案 2 :(得分:0)
由于我编写代码的方式,我能够完成这项工作的唯一方法是预加载图像。
$('div.imgTooltip').children().each(function(){
/* Preload the images */
var trashImg = new Image(); // declare an image object
trashImg.src = this.href; // instantiate it to the current image
$('.profile').append(trashImg); // insert preloaded image into the DOM tree
});
现在到了这段代码
/* Retrieve the width of the image */
var trashImg = new Image(); // declare an image object
trashImg.src = this.href; // instanciate it to the current image
IMG_WIDTH = trashImg.width; // get the width of the image
执行,图像已经加载。我不知道这是否真的是最好的方法,但它似乎有效(至少在我的广泛测试中都是如此)。