[英]Fix caret position on contenteditable div
我有一个带有contenteditable="true"
并resize: both
的 div resize: both
属性都通过 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
on :empty
选择器适用于水平居中,但对于垂直对齐问题仍然存在,修复line-height = initial height
on :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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.