设置contenteditable=true的div值



给定一个带有contenteditable=true的div,如何向元素中添加文本?

<div aria-autocomplete="list" contenteditable="true" role="textbox" spellcheck="true">
</div>

我尝试过document.activeElement.value,但由于它是div,我无法设置值

关于innerHTML的其他答案,我担心如果innerHTML没有经过净化,攻击者可能会有机会运行不需要的恶意代码。

我宁愿选择textContent,因为OP想要添加文本。

HTML:

<div id="content" aria-autocomplete="list" contenteditable="true" role="textbox" spellcheck="true">
</div>

JAVASCRIPT:

document.getElementById('content').textContent = 'My text';

如果您也想呈现HTML标记,则需要一个净化回调来过滤标记,例如SCRIPT标记。

您只需更改div的innerHTML即可。例如:

document.activeElement.innerHTML = "Changed text";

您还可以通过获取相同的属性来获取div的当前内容,例如:

alert("User entered text: " + document.activeElement.innerHTML);

此问题的Reactref版本答案:

// set the init value to it
const initText = "123n123123n123123123";
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (ref && ref.current) {
ref.current.innerText = initText;
}
}, []);
const handleInput = (e: ChangeEvent<HTMLDivElement>) => {
console.log("input:", e.target.innerText);
};

注意,我们在这里使用的是innerText
对于innerHtmltextContent,它们不会使用下面的代码更改n的默认行

<div
ref={ref}
contentEditable={true}
onInput={handleInput}
style={{
height: 200,
width: 200,
border: "1px solid black",
display: "table-cell",
verticalAlign: "middle",
textAlign: "left",
padding: 8
}}
></div>

另外,我们可以使用CSS:empty让初始光标保持在垂直中心以及

.InputField {
height: 200px; // initial height, real size could auto increase
...
}
.InputField:empty {
line-height: 200px; // the same initial height's value as above
}

我发现设置内容的最佳方式是:

target.firstChild.data = "<some-new-value>";

其中firstChild是textNode。

相关内容

最新更新