为什么jQuery为div的高度返回null?
$(document).ready(function(){ function getDocumentHeight() { // What's the page height? var height = $('#mainbody').height(); alert(height); ... getDocumentHeight(); }
jQuery一直警告我的#mainbody
div的高度为null
。 我不明白为什么,至少应该是500px
左右。
如果以动态方式加载内容,则元素可能还没有高度。 尝试将此代码移动到页面底部,直接在上方,看看是否解析。
更新:尝试将代码放入
$(window).load(function() { var height = $('#mainbody').height(); alert(height); });
在你的外面
$(document).ready();
如果您使用标记的模板(例如使用angular或ember),请使用脚本标记并从模板中调用脚本。
延迟100ms对我来说效果很好。 毫不拖延地不工作。
setTimeout(function(){ var imgWidth = $('#id').width(); var imgHeight = $('#id').height(); console.log(imgWidth); console.log(imgHeight); }, 100);