我有一个 div 元素,基本上,我正在尝试将其移动到用户点击 canvas 元素的任何位置。
我有一个 div 的 CSS 样式,将位置设置为绝对位置,初始位置为(顶部,左侧)。
我有捕获用户点击事件的 javascript,并将 div 元素的左侧和顶部设置为点击的位置,并设置 div 的文本。
我的问题是,在我为 html 文件设置 DOCTYPE 之前,它工作正常。现在 div 保持在同一个位置,同时显示新文本,我假设位置问题与我使用 CSS 的方式有关。
设置 div 元素位置的正确方法是什么? html 或多或少是这样的:
<!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>
这是 javascript 的样子,它为我定位了 div:
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
在设置 DOCTYPE 之前,这在 Chrome、Firefox、Safari 移动版和 Opera 上运行良好。设置后,我可以在 IE9 中渲染到 Canvas ,但随后 div 在所有浏览器中的定位都停止工作 - 只是停留在初始位置。
最佳答案
我想出了我的问题。我用于设置新位置的 javascript 是这样的:
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)
在我使用 doctype 之前这工作正常,因为显然浏览器对我只提供一个数字没问题,但我不得不将代码更改为此,它工作:
var theDiv = getElementByID(...)
theDiv.style.left = selShp.pinx.toString() + 'px';
theDiv.style.top = selShp.piny.toString() + 'px';
我猜这是愚蠢的菜鸟错误。我对解决方案的理解是,标准 HTML 要求您将 left 和 top 设置为字符串,并指定单位。
关于javascript - div位置与DOCTYPE效果的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6712168/