【问题标题】:Why is the caret invisible in a contenteditable with position:relative?为什么插入符号在带有位置的内容可编辑中不可见:相对?
【发布时间】:2022-01-03 11:58:07
【问题描述】:

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 上的错误完全相同!

是什么导致插入符号消失?是否有解决方法?

【问题讨论】:

标签: html css contenteditable


【解决方案1】:

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

我之前的解释(可能是错的):

这不是错误,您将background color 放在&lt;span&gt; 标记上(在 position:relative) 在 contenteditable div 元素中等等 span 位于 contenteditable div 之上。

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

删除position:relative

删除&lt;span&gt; 中的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 添加到&lt;span&gt; 元素

添加否定的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 添加到&lt;span&gt; 元素

添加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>

其他 Stackoverflow 相关问题

【讨论】:

  • 但是span也有自己的.isContentEditable设置为true。插入符号位于该 span 元素内,您可以使用 Selection API 检查,它在逻辑上应该位于该元素的背景上。
  • @Kaiido 这是真的,我的回答不正确,我用解决问题的方法更新了我的回答,但不知道问题的根源是什么。
  • 感谢@BenSouchet - z-index: -1 为我解决了这个问题!由于a different browser bugdisplay: inline-block 不适合我。多么奇怪的问题!我想无论如何我都会将此报告为浏览器错误...
猜你喜欢
  • 2020-07-24
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
相关资源
最近更新 更多