javascript - div位置与DOCTYPE效果的关系

标签 javascript html canvas doctype

我有一个 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/

相关文章:

javascript - 使用 JQuery,如何使字段可编辑,但用户不能输入?

html - 解析超链接和描述的正则表达式

javascript - 如何使用 insertAdjacentHTML 方法在文章中显示 javascript 广告单元

javascript - onkeyup 和 onkeydown 没有捕捉到任何东西

html - 无法在 Firefox 中将 SVG 绘制到 HTMl5 Canvas (即使设置了高度和宽度)

javascript - 输入类型=范围。如何使 slider 值可以被 10 整除?

javascript - 将文件转换为数组然后输出对象值时遇到问题

javascript - 嵌入iframe-YouTube视频不循环播放

javascript - 仅水平滚动一个 div

delphi - 如何在 VCL 风格的页面控件上进行所有者绘制