[英]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.