【发布时间】: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 并且它为空时,插入符号的位置在左上角
我做了一些研究并找到了类似的答案:
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