我有一个带有
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 并且它是空的时,插入符号位置位于左上角
我做了一些研究并找到了如下答案:
在 contenteditable 中与 Flexbox 居中时的插入符位置
将占位符插入符号置于 contentEditable 元素的中心
text-align:center
上的 :empty
选择器适用于水平居中,
但对于垂直对齐问题仍然存在,在 line-height = initial height
选择器上使用 :empty
进行修复在我的情况下不起作用,因为这个 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;
}
}
};
使用 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>
</div>