[英]Read the width of a div with JavaScript
I'm trying to read the width of a div without jQuery. 我正在尝试在没有jQuery的情况下读取div的宽度。 The code I'm using is:
我使用的代码是:
JS: JS:
var windowwidth = parseInt(document.getElementById("window").style.width);
window.onload = function start() {
alert(windowwidth);
}
HTML: HTML:
<div id="window">
<p>Lorem ipsum dolor sit amet.</p>
</div>
CSS: CSS:
#window {
height: 250px;
margin: 0 auto;
width: 600px;
}
I don't understand why this isn't working, I've looked all over this site and google and can't figure out a solution. 我不明白为什么这行不通,我在整个网站和google上四处寻找,无法找到解决方案。 I don't want to use jQuery for this (it's a small custom HTML5 script so I don't need that huge library for one little thing) and even when I try the jQuery method, it still doesn't work.
我不想为此使用jQuery(这是一个小的自定义HTML5脚本,因此我不需要一件事就拥有那个巨大的库),即使当我尝试使用jQuery方法时,它仍然无法正常工作。
You're not guaranteed that document.getElementById()
will work (ie will return the required element) before the DOM is ready. 您不能保证在DOM准备就绪之前
document.getElementById()
将起作用(即返回所需的元素)。 So try: 因此,请尝试:
window.onload = function() { // removed the name to avoid some IE leaks
var windowwidth = parseInt(document.getElementById("window").style.width);
alert(windowwidth);
}
don't read the style property, read the actual width of the element: 不阅读style属性,而是阅读元素的实际宽度:
window.onload = function(){
alert(document.getElementById('window').offsetWidth);
}
offsetWidth
is what the browser says is the width, which can be different than what you're setting it to with CSS if, for example, the content stretches it wider. offsetWidth
是浏览器所说的宽度,例如,如果内容将其拉伸得更宽,则可能与您使用CSS设置的宽度不同。
如果您想了解jQuery的工作方式,请参见以下链接: https : //github.com/jquery/jquery/blob/master/src/dimensions.js
I would use jQuery to do such a thing. 我会用jQuery来做这样的事情。 You can find the exact thing you want right here: http://api.jquery.com/width/
您可以在此处找到所需的确切内容: http : //api.jquery.com/width/
You can get style.width only after the element is drawn. 仅在绘制元素后才能获得style.width。 Try to put your code to setTimeout().
尝试将您的代码放入setTimeout()。 Sometimes it helps me
有时候对我有帮助
window.onload = function(){
setTimeout(
function(){ alert(document.getElementById('window').style.width); },
200
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.