jQuery 为什么jQuery为div的高度返回null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3680811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does jQuery return null for the height of the div?
提问by matt
$(document).ready(function(){
function getDocumentHeight()
{
// What's the page height?
var height = $('#mainbody').height();
alert(height);
...
getDocumentHeight(); }
jQuery keeps alerting null
for the height of my #mainbody
div. I don't get why, it should at least be 500px
or so.
jQuery 不断提醒null
我#mainbody
div的高度。我不明白为什么,至少应该是500px
这样。
采纳答案by Steven
If the content is being loaded dynmically, the elements may not have a height yet. Try moving this code to the bottom of the page, directly above and see if that resolves.
如果内容是动态加载的,元素可能还没有高度。尝试将此代码移动到页面底部,正上方,看看是否能解决。
UPDATE: Try placing your code in
更新:尝试将您的代码放入
$(window).load(function() {
var height = $('#mainbody').height();
alert(height);
});
outside of your
在你之外
$(document).ready();
回答by Rick
If you are using a template for your markup for example with angular or ember use the script tag and call the script from the template.
如果您使用模板作为标记,例如带有 angular 或 ember,请使用脚本标签并从模板调用脚本。
<script type="text/javascript" src="/js/script.js"></script>
回答by hey
With 100ms delay works well for me. Without delay not working.
100 毫秒的延迟对我来说效果很好。毫不拖延地不工作。
setTimeout(function(){
var imgWidth = $('#id').width();
var imgHeight = $('#id').height();
console.log(imgWidth);
console.log(imgHeight);
}, 100);