简体   繁体   中英

how can I get the value of width with javascript

I put this on the head section

var d = parseInt(document.getElementById('test').style.width);
alert(d);

But the output is NaN .

how do you get the value?

UPDATED

Reading your question, it seems that you are executing the code in your head section before the DOM has loaded, try to put your script in the bottom of your page, just before </body> .


document.getElementById('test').clientWidth;
document.getElementById('test').offsetWidth;

UDPATED

I think the problem is that you've put the code in the <head> of your document, which means it's looking for the test element right away. Unfortunately, the test element hasn't been created yet, because your browser is still parsing the <head> .

So, make sure that code is placed after the test element, and use either .offsetWidth or .clientWidth , and it should work fine.

style.width will most probably only get the inline style, you have three options:

You can use .clientWidth , .offsetWidth or you can add a inline-style .

See my example : http://jsfiddle.net/WaSKP/2/

Just use,

window.onload=function(){
    alert(document.getElementById("test").clientWidth)
}

That should do the trick.

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