webkit css resize 不适用于儿童画布?

2022-01-17 00:00:00 webkit html css html5-canvas

假设下面的 html 和 css 代码片段:

Suppose the following html and css code snippet:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: 100%;
}

<div id="outer">
  <canvas id="inner"></canvas>
</div>

我希望 div 可以调整大小,而在 Firefox 中,确实如此.然而,在基于 webkit 的浏览器(例如 chrome 和 opera)中,情况并非如此.但是,如果我用 div 替换内部画布,它也可以在那里工作.所以我的问题是:为什么在这种情况下 canvas 元素会阻止外部 div 调整大小?我该如何解决这个问题?

I would expect the div to be resizeable, and in firefox, it is. However in webkit-based browsers such as chrome and opera, it isn't. If I replace the inner canvas with a div however, it works there too. So my question is: why does the canvas element in this case prevent the outer div from beeing resizeable? And how can I work around this?

推荐答案

似乎画布正在处理鼠标事件,阻止调整大小.如果您在画布上考虑 pointer-events:none 它将起作用:

it seems that the canvas is taking the mouse event preventing the resize. If you consider pointer-events:none on canvas it will work:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: 100%;
  pointer-events:none
}

<div id="outer">
  <canvas id="inner"></canvas>
</div>

为了更好地说明,稍微减小画布的大小以避免与调整大小的小部件重叠,它也会起作用:

To better illustrate, decrease the size of the canvas a little to avoid the overlap with the resize widget and it will also work:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: calc(100% - 10px);
  background:red;
}

<div id="outer">
  <canvas id="inner"></canvas>
</div>

你也可以玩z-index:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
  position:relative;
  z-index:0; /* mandatory to create a stacking context and keep the canvas inside */
}
#inner {
  width: 100%;
  height: 100%;
  position:relative;
  z-index:-1;
  background:red;
}

<div id="outer">
  <canvas id="inner"></canvas>
</div>

相关文章