有时我会遇到问题,试图获取有问题的HTML元素的大小。使用JavaScript和jQuery进行尺寸计算
我跟踪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%确定,我正在处理正确的大小?
看起来像图像在请求尺寸时完全加载。因此,您将使用一种机制来确保在查询维度之前加载所有图像。看看:http://stackoverflow.com/questions/1285375/how-to-ensure-images-are-loaded-inside-a-jquery-plugin – 2010-10-22 06:13:09
令人惊叹!有用 !非常感谢,Suresh库马尔! :) – AntonAL 2010-10-22 06:19:12