【问题标题】:Canvas in contenteditable elementcontenteditable 元素中的画布
【发布时间】:2022-11-17 20:04:51
【问题描述】:

.editor {
         width: 100%;
         min-height: 100%;
         height: 100%;
         background-color: black;
         color: #fff;
        }
 canvas {
            background-color: green;
        }
<div class="editor" contenteditable><canvas></canvas></div>

我怎样才能将画布添加到 contenteditable div

我有这个代码

<style>
.editor {
         width: 100%;
         min-height: 100%;
         height: 100%;
         background-color: black;
         color: #fff;
        }
 canvas {
            background-color: green;
        }
</style>


<div class="editor" contenteditable><canvas></canvas></div>

出于某种原因,我无法在 contenteditable div 中写入任何内容,甚至插入符号也不知何故消失了。我做错了什么?一个帮助将不胜感激。

【问题讨论】:

  • 我不确定是否理解。您的代码在 div 元素内正确地呈现了一个绿色画布,并且诸如 contenteditable 之类的 div 获得了输入焦点,并提供了在新文本内容之间移动画布并在其中键入文本的机会。你不能把焦点放在 div 上吗?一点也不?
  • 看起来像一个 Chrome 错误,在 Firefox 和 Safari 中工作正常。
  • 那将是crbug.com/242110

标签: javascript html css canvas contenteditable


【解决方案1】:

使用一点 Javascript,您可以通过添加空格然后强制将插入符号放置在内容的末尾来欺骗它

document.querySelector('.editor').onclick=e=>{
  if( e.target==e.currentTarget ){
    const setcaret=(n)=>{
      let oSel=window.getSelection();
          oSel.selectAllChildren( n );
          oSel.collapseToEnd();
    }
    
    e.target.innerHTML += '&nbsp;';
    setcaret( e.target );
  }
};
.editor {
  width: 100%;
  min-height: 100%;
  height: 100%;
  background-color: black;
  color: #fff;
  padding:1rem;
}

canvas {
  background-color: green;
  width:100px;height:100px;margin:1rem;
}
<div class="editor" contenteditable>
  <canvas></canvas>
</div>

【讨论】:

  • 之前需要同样的技巧来设置插入符号。
【解决方案2】:

.editor {
         width: 100%;
         min-height: 100%;
         height: 100%;
         background-color: black;
         color: #fff;
         position:relative;
        }
canvas {
            background-color: green;     color: #fff;
        }
<div class="editor" contenteditable>
  <canvas></canvas>
&nbsp;
<p>Hi</p>
</div>

contenteditable 说的是div的内容是可编辑的,而不是div本身,所以在div中使用一个p作为你的文本框或放置一个占位符,否则你将要编辑的内容是画布。正如其他答案指出的那样,这是一个 Chrome 错误,如果你想模拟其他浏览器的行为,你可以像这样在 div 中添加一个空格,否则 p 解决方案仍然有效。

【讨论】:

  • 这与仅仅使 div 内容可编辑没有什么不同。 OP 说他不能在里面输入文本,而实际上它的代码已经可以那样工作了。问题仍不清楚
  • 我在 Firefox 上对其进行了测试,它正在运行,但不适用于 chrome。
  • 好吧,我使用的是 chrome,这样就可以解释了,我的代码适用于所有浏览器
猜你喜欢
  • 1970-01-01
  • 2010-11-18
  • 2011-06-16
  • 2017-05-05
  • 1970-01-01
  • 2023-03-11
  • 2013-10-17
  • 2013-05-25
相关资源
最近更新 更多