为什么插入符在 position:relative 的 contenteditable 中不可见?

Why is the caret invisible in a contenteditable with position:relative?

contenteditable 元素具有 position: relative 和背景颜色时,插入符号在放置在该元素中时是不可见的。这是一个例子:

.bug {
  position: relative;
  background-color: lightgrey;
}
<div contenteditable>
  This has caret
  <span class="bug">no caret here?!</span>
  this has caret
</div>

我的第一个想法是“这是一个浏览器错误”,但它在 Chrome 和 Firefox 上是完全相同的错误!

插入符号消失的原因是什么?有解决办法吗?

不知道问题的确切原因,但您可以通过多种方式解决它。

我之前的解释(可能有误):

This isn't a bug, you put the background color on a <span> tag (in position:relative) inside a contenteditable div element and so the span is on top of the contenteditable div.

我仍然认为与 z-index 有关,因为我们可以在 Chrome 焦点边框顶部的红色背景下方的图像上看到:

删除position:relative

删除 <span>position:relative 修复问题:

.no-bug {
  background-color: red;
}
<div contenteditable>
  This has caret
  <span class="no-bug">This has caret !</span>
  this has caret
</div>

z-index 添加到 <span> 元素

添加负数 z-index 也可以解决问题:

.no-bug {
  background-color: red;
  position: relative;
  z-index: -10;
}
<div contenteditable>
  This has caret
  <span class="no-bug">This has caret !</span>
  this has caret
</div>

display: inline-block 添加到 <span> 元素

添加 display: inline-block(或 display: block)解决问题:

.no-bug {
  background-color: red;
  position: relative;
  display: inline-block;
}
<div contenteditable>
  This has caret
  <span class="no-bug">This has caret !</span>
  this has caret
</div>

其他Whosebug相关问题

  • Edit cursor not displayed on Chrome in contenteditable
  • contenteditable cursor doesn't appear