admin管理员组文章数量:1304545
I'm trying to get div's width with javascript. Initially div's width is undefined, ie width depends on amount of text on it. Is it possible to get width of this kind of div? I'm trying to do it with following javascript code, but i'm getting width differerent from Chrome console when i'm inspecting div
var mydiv = document.getElementById("error_message");
var curr_width = mydiv.clientWidth;
alert(curr_width);
Thank you for your attention
I'm trying to get div's width with javascript. Initially div's width is undefined, ie width depends on amount of text on it. Is it possible to get width of this kind of div? I'm trying to do it with following javascript code, but i'm getting width differerent from Chrome console when i'm inspecting div
var mydiv = document.getElementById("error_message");
var curr_width = mydiv.clientWidth;
alert(curr_width);
Thank you for your attention
Share Improve this question asked Mar 9, 2011 at 17:29 andriyandriy 4,1649 gold badges50 silver badges72 bronze badges 5-
Initially an unstyled div will have a width equal to its container's width. That's due to the default
display:block
styling. – zzzzBov Commented Mar 9, 2011 at 17:31 - Can you add the HTML too ... im not sure your DIV will be the width of a the text within it ... its a BLOCK element – Manse Commented Mar 9, 2011 at 17:32
-
it's generated with
document.write("<div id=\"error_message\">Wrong username or password!</div>");
and css isdiv#error_message{ display:block; position: absolute; padding: 2px; top: 0px; border: 1px solid #FF0000; background: #FFCCFF; font-family: Arial; font-size: 13px; color: #FF0000; }
– andriy Commented Mar 9, 2011 at 17:34 - And what is the width thats being shown in the alert ? what did you expect is to be ? – Manse Commented Mar 9, 2011 at 17:49
- in alert it is 1008 and in console it is 183, so i'm expecting 183 – andriy Commented Mar 9, 2011 at 17:59
3 Answers
Reset to default 6use offsetWidth
clientWidth is calculated width, offsetWidth is the one in "Chrome inspect element" (i think)
also read the ments :P
While the OP doesn't specify one way or the other, if you happen to have jQuery available, you can always use this:
var curr_width = $('#error_message').width();
I managed to solve the problem! I was trying to create div directly in javascript, without defining div on html body. So inside of tag i've created
<div id="error_message" style="visibility:hidden;"></div>
and it's worked! Final javascript code is:
document.write("<div id=\"error_message\">Wrong username or password!</div>");
var mydiv = document.getElementById("error_message");
var curr_width = mydiv.offsetWidth;
alert(curr_width);
本文标签: htmlWrong div width when getting it with javascriptStack Overflow
版权声明:本文标题:html - Wrong div width when getting it with javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741788809a2397539.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论