Weird issues in setting style using JavaScript while using a DOCTYPE
I am trying to add a <div>
using JavaScript and then change its width/height/top/left attributes. But when I use the XHTML 1 Transitional doctype, it stops working.
This is how I am creating the <div>
:
var div=document.createElement("div");
document.body.appendChild(div);
div.innerHTML='<div id="myID" style="z-index:9998;border: 1px solid #000000;
border-radius:3px;position: absolute; display: block;top:-10000;left:-10000;
width:400; height:400;"></div>';
So initially myDiv
is not visible to user as its left and top are out of the screen
Then on some click action I am doing the following:
var myDiv=document.getElementById("myID");
myDiv.style.top=200;
myDiv.style.left=200;
This works fine if I do not put开发者_开发技巧 a doctype in the HTML. As soon as I put the doctype, it stops working.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
With the doctype, it stops accepting top/left/width/height values. But if I set the width/height/top/left values with units (i.e. px) then it works fine.
myDiv.style.top="200px";
myDiv.style.left="200px";
So, what is the impact of the doctype on the execution of JavaScript while modifying the style (or may be other things as well)?
Using raw numbers is technically invalid, even if the browser is letting you get away with it when you're not using a doctype (browsers do lots of funky things when you don't use a doctype).
The style properties really are like the CSS properties, strings with units on them. So "200px" is correct, 200 is incorrect. The properties (left
, for instance) can be lengths like "200px" or "10em", or percentages (or auto
or inherit
). (Those links are to the CSS 2.1 spec.)
You also need to include units in your string when creating the myID
div:
div.innerHTML = '<div id="myID" style="z-index:9998; ' +
'border: 1px solid #000000; ' +
'border-radius:3px;' +
'position: absolute;' +
'display: block;' +
'top:-10000px;' + // here
'left:-10000px;' + // here
'width:400px;' + // here
'height:400px;"' + // and here
'></div>';
Using the DOCTYPE
tells the browser that you are using a specific standard (in your case, XHTML 1.0) - the browser then uses an exact render mode (instead of the quirks mode that it would use without a DOCTYPE).
This means that it will interpret your code much more strictly - the sizes should always have a unit with them (200px, 1.2em etc...). Just a number is meaningless, so the browser will ignore these values when not in quirks mode.
精彩评论