jquery - 使用 jQuery 定位 Canvas

标签 jquery css html dom canvas

我正在使用 HTML5 canvas 创建一个绘图应用程序,但在定位方面遇到了问题。

我有一个动态放置 Canvas 的 div。 div 有一个顶部 div 和一个底部 div,我想将 Canvas 放在中间。现在 Canvas 与顶部 div 重叠,因此我想将其向下移动。我试过为 Canvas 设计样式(position:absolute,顶部:40)但没有任何反应。我怎样才能做到这一点?

$('<canvas/>', {
  'id': 'paint',
}).appendTo('#box');

var theCanvas = document.getElementById('paint');
theCanvas.width  = 420;
theCanvas.height = 300;

div 看起来像这样:

-----------------
     top div       
-----------------


    canvas


-----------------
    bottom div
-----------------

div 的样式:

#box {
  position: absolute;
  left:50px;
  top: 60px;  
  margin-left: auto;
  margin-right: auto;
}

.topDiv {
  position: absolute;
  top: 0;
  height: 60px;
  overflow: hidden;
}

.bottomDiv {
  position: absolute;
  bottom: 0px;
}

顶部的 div 和底部的 div 在 #box 内。

最佳答案

我已经对您要完成的确切目标做出了一些假设。根据我认为你想做的事情,我假设有一个包含两个 div 的框和一个 Canvas (并且可能在屏幕上的任何地方),我将 html 模拟为:

<div id="box">
    <div class="topDiv">
        this is the top div
    </div>
    <div class="bottomDiv">
        this is the bottom div
    </div>
</div>

而且,我建议更改您的 javascript,以便在 bottomDiv 之前插入 Canvas 。

$('<canvas/>', {
    'id': 'paint',
}).insertBefore('#box .bottomDiv');

并更改 bottomDiv 和 topDiv 上的类样式,使它们处于 position: relative。这应该完成你正在寻找的东西。基本上 #box 控制组的位置,顶部和底部 div 在该组控件中保持固定。

这是一个带有一些边框颜色的 jsFiddle,用于显示框的位置:http://jsfiddle.net/fordlover49/HKtn5/

关于jquery - 使用 jQuery 定位 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8594020/

相关文章:

javascript - 如何找出一个 HTML 元素是否在另一个 HTML 元素后面?

jquery - 如何使用 Bootstrap 修复标题中的图像大小

javascript - 数据表中的列排序问题

css - Grails 过滤器禁用样式/CSS

html - 尝试创建一个跨浏览器兼容的 HTML 手册

php - Laravel Chained Select 无法加载资源 : the server responded with a status of 500

css - 更改输入类型 ='submit' 字体系列

javascript - 更改单选按钮上的产品图像

html - 为什么这些 Youtube 元素(建议列表项)具有相同的 ID

html - 图像显示方向错误