I am trying to insert a div dynamically with it's width equal to the page width using the window.innerWidth property.
It doesn't seem to work and the width is set to '0' automatically.
Thanks in advance.
HTML
<body onload="lb()"></body>
JS
function lb()
{
var h=window.innerHeight
||document.body.clientHeight
||document.documentElement.clientHeight;
var w=window.innerWidth
||document.body.clientWidth
||document.documentElement.clientWidth;
alert("Width: "+w+"\n"+"Height: "+h);
var x=document.createElement("div");
x.id="heder";
x.style.width=w;
x.style.height='150px';
x.style.backgroundColor='#000000';
x.style.position='absolute';
x.style.margin='0px';
x.style.padding='0px';
document.body.appendChild(x);
}
Example fiddle : http://jsfiddle.net/xyyUy/1
You fogot to add " px " with width value
should be
x.style.width=w+"px";
instead of
x.style.width=w;
As @Suman Bogati said you need to add the 'px'. Also your Fiddle was throwing an error executing the lb() function. I tweaked it in this fiddle to work. I just did a simple call to
lb();
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.