在 <canvas> 上方显示一个 <div>

10

问题在Firefox和Chrome中都存在,我有一个带有纯色背景的canvas和一个带有纯色/图像背景的div。该div的margin覆盖在canvas上方,但是div不会显示在canvas上面。有趣的是,如果div中有文本,则文本将正确显示。这意味着这是两个浏览器中的浏览器错误。以下是一些代码,供那些想要尝试的人使用。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <style type="text/css">
        #d{background-color:#111;margin-top:-150px;z-index:999999;}
    </style>
    <script type="text/javascript">
        function load() {
            var c = document.getElementById("c").getContext("2d");
            c.fillStyle = "rgba(255, 200, 200, 1)";
            c.fillRect(0, 0, c.canvas.width, c.canvas.height);
        }
    </script>
</head>
<body onload="load()">
    <canvas id="c" width="500" height="300"></canvas>
    <div id="d" style="width:500px;height:300px"></div>
</body>
</html>

那么,有人有任何解决方法吗?或者我是错过了HTML5规范中说这是正确的东西吗?

顺便提一下,请不要问我为什么要使用边距而不是固定/绝对等替代方案。我需要边距。

5个回答

20

只有通过应用样式才能解决此问题:

#d {position:relative;}
或者
#d {position:absolute;}

3
请在回答之前仔细阅读问题。我说我不想要绝对或相对定位。 - Moncader
25
很不幸,因为绝对定位和相对定位是你唯一拥有的选项。 - Moses
2
你实际上不需要使用相对定位来定位元素,你只需要添加属性即可。只要你不添加 topright 等属性,你的 div 的位置就不会改变。 - webdesserts

2
最近我遇到了这个问题,与其改变布局方式,我选择从 div 切换到使用 span 并设置 display:inline-block
在 Firefox/Chrome/Safari 上运行良好。 尚未在 IE 上测试。

1
请使用以下代码,希望能对您有所帮助:

 <head>
     <style type="text/css">
          #c{background-color:#000;z-index:-1;position: fixed;}
          #d{background-color:#aa00aa;margin-top:-50px;z-index:0;}
     </style>
     <script type="text/javascript">
         function load() {
             var cntx = document.getElementById("c").getContext("2d");
             cntx.fillStyle = "rgba(255, 200, 200, 1)";
             cntx.canvas.top = "0";
             cntx.canvas.left = "0";
             cntx.fillRect(0, 0, cntx.canvas.width, cntx.canvas.height);

             var obj = document.getElementById("d");
             obj.style.position = "fixed";
             obj.style.top = 50;
             obj.style.left = 0;
         }
     </script>
 </head>
 <body onload="load()">
     <canvas id="c" width="500" height="300"></canvas>
     <div id="d" style="width:500px;height:300px"></div>
 </body>

0

在 #d 中添加 position:relative;(或 absolute)似乎在 Chrome 和 Firefox 中都可以使用。 如果你问我为什么,我也不知道原因。 对你有好处吗?


请在回答之前仔细阅读问题。我说过我不想要绝对或相对定位。 - Moncader

0

嗯,我已经阅读了你的问题,并且我明白你不想使用position……但是你必须使用position来让z-index起作用。在这种情况下,position:relative实际上什么也没做,除了满足你的要求。这里有一个解决方法,尽管它依赖于position:relative。 http://jsfiddle.net/jalbertbowdenii/Ar6Sh/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接