开发者

Relation between div position and DOCTYPE's effects

I have a div element that I'm trying, basically, to move wherever the user clicks on a canvas element.

I have a CSS style for the div setting the position to absolute, with an initial position (top,left).

I have javascript that captures the user's click event, and sets the div element's left and top to the location of the click, and set the text of the div.

My problem is that this worked fine before I set a DOCTYPE on the html file. Now the div stays in the same place, while displaying the new text, and I'm assuming the position issue is something to do with how I'm using CSS.

What's the right 开发者_Go百科way to set the position of a div element? The html goes more or less like this:

<!DOCTYPE HTML>
<html>
<head>
   <style type="text/css">
    #myDiv{
     position:absolute;
     top:100px;
     left:835px;
   }
   </style>
</head>
<body><canvas id='canv'></canvas>
<div id='myDiv'>-</div>
</body>
</html>

Here's what the javascript looks like, which locates the div for me:

var theDiv = document.getElementById('myDiv');
theDiv.style.left = selShp.pinx; // selShp.pinx is the position of a shape object I've created, which is how I position the shape on the canvas
theDiv.style.top = selShp.piny; // piny is just the y position

Before setting a DOCTYPE, this worked beautifully on Chrome, Firefox, Safari mobile, and Opera. With it set, I can render to the canvas in IE9, but then the positioning of the div in all the browser stops working - just stays in the initial position.


I figured out my problem. My javascript for setting the new position went like this:

var theDiv = getElementByID(...)
theDiv.style.left = selShp.pinx; // selShp is the selected shape object, and pinx is x location (numeric) on canvas
theDiv.style.top = selShp.piny; // piny is y location on canvas (numeric)

This worked fine before I was using the doctype, because apparently the browser was fine with me just giving a number, but I had to change the code to this, and it works:

var theDiv = getElementByID(...)
theDiv.style.left = selShp.pinx.toString() + 'px'; 
theDiv.style.top = selShp.piny.toString() + 'px';

Stupid, rookie mistake, I guess. My understanding of the solution is, standard HTML requires you to set the left and top as strings, with units specified.


The real problem begins with not using a doctype. A doctype is required of all modern web pages to keep the browser out of 'quirks mode'. In that case, the box model is different than it should be using current web standards. You should read about quirks on Wikipedia or Google for it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜