简体   繁体   中英

Wrong div width when getting it with javascript

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

use offsetWidth

clientWidth is calculated width, offsetWidth is the one in "Chrome inspect element" (i think)

also read the comments :P

虽然OP没有指定一种方式,但如果您碰巧有jQuery可用,您可以随时使用:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM