最近我遇到了一些我最终使用 CSS hack 的情况,以便用户能够将用于文本编辑的光标放置在 contenteditable div 中的先前位置。我的具体情况与以下情况接近:
div {
border: 1px solid blue;
padding: 5px;
margin: 10px;
}
p {
border: 1px solid green;
padding: 5px;
line-height: 4em;
min-height: 4em;
}
span {
visibility: hidden;
border: 1px solid red;
}
br:last-of-type {
display: none;
}
div.hack br:last-of-type {
display: inline-block;
height: 4em; // This seems to be necessary for the correct vertical alignment of the blinking input cursor
}
Using Google Chrome, Version 79.0.3945.130 (Official Build) (64-bit) Can't place the cursor here:
<div contenteditable="true">
<p>
<!-- This is an existing implementation. Hopefully someday I'll get to rewrite it. -->
<span> some hidden text for padding </span>
<!-- Can't put the cursor here for text input -->
<br />
</p>
</div>
But I can here:
<div class="hack" contenteditable="true">
<p>
<!-- This is an existing implementation. Hopefully someday I'll get to rewrite it. -->
<span> some hidden text for padding </span>
<!-- Can't put the cursor here for text input -->
<br />
</p>
</div>
我的猜测是问题在于段落中没有可选的内联元素,因此浏览器(我使用的是 Chrome)不允许用户将光标放在那里。在段落中的标签上设置显示样式可以<br/>
解决这个问题,但感觉很hacky。这个解决方案对我们的目的来说很好,但为了将来参考,我想知道是否有任何类型的规范来确定什么是 contenteditable div 中的有效文本输入位置。我做了一些谷歌搜索并没有找到太多,尽管我可能只是不知道这个问题的正确措辞。
旁注 - 文档的结构是一个现有的实现,我目前没有寻找替代方案。特别是,<br/>
标签是依赖项中的一个实现细节,并且基于他们的一些问答内容,这不太可能改变。
编辑:堆栈片段而不是 Codepen