有时我会遇到问题,试图获取有问题的 HTML 元素的大小。
我正在跟踪 JavaScript 代码,看到这个元素的宽度和高度返回为 0。
当我在浏览器的控制台中执行相同的代码时,会返回正确的大小。
演示此问题的示例代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title>Decorate image with button</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
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(" \
<table style='position: absolute;'> \
<tr style='background-color:transparent;'> \
<td style='width: 100%; background-color: transparent;'> \
<img src='http://30ttclan.extra.hu/e107_images/RTEmagicC_play_button.png.png' style='display: block; width: 25%; margin-left:auto; margin-right: auto;'></img> \
</td> \
</tr> \
</table>");
a.append(img);
// Make height of table equals to height of image
a.find("> table").width( w );
a.find("> table").height( h );
});
});
</script>
</head>
<body>
<a href="http://movies.apple.com/media/us/mac/ilife/iphoto/2010/features/apple-ilife-iphoto-features_whats_new-us-20100727_r848-9cie.mov">
<img src="http://kelsocartography.com/blog/wp-content/uploads/2009/01/iphoto09_map.png">
</a>
</body>
</html>
这段代码需要一个图像,包裹在锚点上并用“播放”按钮装饰它,它必须居中。
表格单元格用于居中。
在 Firefox 中它运行良好,但在 Safari 5 中则不行。
当我们跟踪代码时,“w”和“h”变量获取宽度和高度时,我们会看到它们的值为零。
当我们从浏览器的控制台说
$("a > img").width()
我们将获得正确尺寸的图像。
我想,我错过了一些东西......
我认为,我必须捕捉“渲染完成”之类的事件......但是,据我所知,它们并没有出现在 DOM 中。
我如何才能知道,当 HTML 元素被渲染并显示为 100% 确定时,我正在处理正确的尺寸?