【问题标题】:Fix caret position on contenteditable div修复 contenteditable div 上的插入符号位置
【发布时间】:2021-08-28 10:24:25
【问题描述】:

我有一个带有contenteditable="true"resize: both 属性的div,它通过flexbox 使文本居中

.edit-area {      
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: rgba(206, 206, 206, 0.5);
      border: 0.1rem solid gray;
      resize: both;
      overflow: hidden;
}

问题在于,当您聚焦 div 并且它为空时,插入符号的位置在左上角

只有当您键入 1 个字符时,插入符号才会跳到中心

我做了一些研究并找到了类似的答案:
Caret position when centering with flexbox in contenteditable
Centering the placeholder caret in contentEditable element

text-align:center on :empty 选择器用于水平居中, 但是对于垂直对齐问题仍然存在,在我的情况下使用:empty 选择器上的line-height = initial height 修复将不起作用,因为可以调整此div 的大小,是否有任何方法可以通过onFocus 事件或其他一些方式以编程方式在中心设置插入符号CSS 技巧?

在@Spectric 回答的帮助下,我最终得到了解决方案:

const FILLCHARACTER = String.fromCharCode(8203);

node
  .on("input", textInputHandler)
  .on("keydown", textKeyDownHandler);

  const textInputHandler = () => {
    const nodeDOM = d3.select(textNode.current).node();
    if (nodeDOM.innerText.toString().length == 0) {
      nodeDOM.innerHTML = FILLCHARACTER;
    }
  };

  const textKeyDownHandler = (event) => {
    if (event.key == "Backspace") {
      const selectionText = window.getSelection().toString();
      const selectionLength = selectionText.length;
      const currentTextLength = textValue.current.length;
      if (
        selectionLength === currentTextLength ||
        (selectionLength === 1 &&
          (/\u200B/g.test(selectionText) ||
            selectionText.indexOf(FILLCHARACTER) !== -1))
      ) {
        d3.select(textNode.current).node().innerHTML = FILLCHARACTER;
      }
    }
  };

【问题讨论】:

  • 试试这个。 .edit-area{ 位置:固定;证明内容:中心;对齐项目:居中;背景色:rgba(206, 206, 206, 0.5);边框:0.1rem 纯灰色;调整大小:两者;溢出:隐藏; }
  • 如果你有多个容器,如果你有一个父容器和一个直接子元素,我建议使用 flex
  • @WeyersdeLange 我正在使用 flex,因为我需要在 contenteditable div 上居中文本,如果有任何其他方法可以做到这一点,我想尝试一下,让我知道如何,也没有得到位置背后的想法:固定(顺便说一句没用)。

标签: javascript html css d3.js dom-events


【解决方案1】:

使用 JavaScript,您可以在检测到 contenteditable 为空时插入空格 (' ')。这会将插入符号的位置推到中心。

document.querySelector('.edit-area').addEventListener("input", function() {
  if (this.innerText.toString().length == 0) {
    this.innerHTML= ' ';
  }
})
.edit-area {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(206, 206, 206, 0.5);
  border: 0.1rem solid gray;
  resize: both;
  overflow: hidden;
}
<div class="edit-area" contenteditable>
&nbsp;
</div>

【讨论】:

  • 这是一种方法,但我建议还添加一个 keydown 处理程序并检查退格使用情况并使用 ​ 而不是空格字符
猜你喜欢
  • 2011-06-02
  • 1970-01-01
  • 2012-05-11
  • 2014-07-29
  • 2023-03-29
  • 2013-01-11
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
相关资源
最近更新 更多