如何在$(document).ready()中始终获得包含图像的DIV的高度(仅限Webkit中的问题)
我有这个片段来演示这个问题:
height query demo Demo of querying height
The source code of this document has a DIV prior to the H1. The DIV contains a subdiv which in turn contains an image.
Using jQuery's $(document).ready, the following processing takes place:
- DIV queried for its height
- DIV detached from the document
- height value written out here:
- DIV attached at end of document
$(document).ready(function() { var hyt = $('#opts').height(); var div_for_later = $('#opts').detach(); $('#hytmsg').text(''+hyt); $('body').append(div_for_later); });
将它加载到Opera或Gecko中,列表项3中的数字是合理的,如53.将它加载到Webkit浏览器(我的Windows机器上的Chrome 12,或基于旧版Webkit的Tear,在我的诺基亚N800上),以及数字是0。
如果细分的内容不是图像,或者图像是主div的直接子节点(即没有细分),则不会出现问题。 即使页面和图像都来自文件:URL(即,不依赖于网络延迟),它确实会发生。
我可以在页面加载时正确地获得高度值的简单更改,但保持DIV结构不变?
$(window).load()
而不是$(document).ready()
。
$(window).load(function() { var hyt = $('#opts').height(); var div_for_later = $('#opts').detach(); $('#hytmsg').text(''+hyt); $('body').append(div_for_later); });
因为$(document).ready()
仅检查已创建的所有DOM元素,而$(window).load()
实际上在所有页面内容都已加载时触发,包括图像。
准备好在加载图像之前特别触发,因此在脚本运行时不会加载它们。
您可以使用$(window).load(function () {
而不是ready。
通过style属性或CSS为img标记添加高度值。