使用JavaScript和jQuery计算大小
有时我遇到问题,试图获得有问题的HTML元素的大小。
我正在跟踪JavaScript代码并看到,此元素的宽度和高度返回为0。
当我在浏览器控制台中执行相同的代码时,会返回正确的大小。
示例代码,演示此问题如下:
Decorate image with button jQuery(function($){ // Decorate image, wrapped to link to movie with "Play" button $("a > img").each(function(){ var img = $(this); var a = img.parent(); var w = img.width(); var h = img.height(); a.html(" \ \ \ \ \ \ \
"); a.append(img); // Make height of table equals to height of image a.find("> table").width( w ); a.find("> table").height( h ); }); });
此代码采用图像,包装为锚定并使用“播放”按钮对其进行装饰,该按钮必须位于其上方。
表格单元用于居中。
在Firefox中它运行良好,但在Safari 5中不行。
当我们跟踪代码时,“w”和“h”变量得到宽度和高度,我们将看到它们有零。
当我们从浏览器的控制台说
$("a > img").width()
我们将获得正确的图像尺寸。
我想,我错过了一些东西……
我想,我必须抓住“呈现完整”类似的事件……但是,据我所知,目前为止,他们并没有在DOM中呈现。
我如何才能知道,当HTML元素被渲染并显示为100%肯定时,我正在处理正确的大小?
问题已经解决了。
如上所述如何确保在JQuery插件中加载图像?
像Chrome这样的webkit浏览器通常会为图像返回0大小,因为它们是并行加载的。
我需要做的就是对图像使用“加载”事件。
$("a > img").load(function(){ var img = $(this); var a = img.parent(); var w = img.width(); var h = img.height(); a.html(" \ \ \ \ \ \ \
"); a.append(img); // Make height of table equals to height of image a.find("> table").width( w ); a.find("> table").height( h ); });
现在,我的尺码正确。