有时我会遇到问题,尝试获取相关 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>
此代码采用一个图像,将其包裹为 anchor ,并使用“播放”按钮对其进行装饰,该按钮必须位于其上方。
表格单元格用于居中。
在 Firefox 中它运行良好,但在 Safari 5 中则不然。
当我们跟踪代码时,“w”和“h”变量获取宽度和高度,我们会看到它们有零。
当我们说从浏览器控制台
$("a > img").width()
我们将获得正确的图像尺寸。
我想,我错过了一些东西......
我想,我必须捕捉“渲染完成”之类的事件......但是,据我所知,它们没有在 DOM 中呈现。
当 HTML 元素被渲染并显示为 100% 确定时,我如何才能知道我正在处理正确的尺寸?
最佳答案
问题已解决。
正如问题中提到的How to ensure images are loaded inside a JQuery plugin?
webkit browsers like Chrome often return 0 size for images because they're loaded in parallel.
我需要做的就是使用图像的“load”事件。
$("a > img").load(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 );
});
现在,我得到了正确的尺寸。
关于javascript - 使用 JavaScript 和 jQuery 计算尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3994321/