簡體   English   中英

使用 contenteditable=true 設置 div 的值

[英]Set value of div with contenteditable=true

給定一個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>

爪哇腳本:

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

如果您也想呈現 HTML 標簽,您需要一個清理回調來過濾標簽,例如SCRIPT標簽。

你可以改變div的innerHTML。 例如:

document.activeElement.innerHTML = "Changed text";

您還可以通過獲取相同的屬性來獲取 div 的當前內容,例如:

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

這個問題的 React參考版本答案:

// set the init value to it
const initText = "123\n123123\n123123123";
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讓初始的 cursor 也保持在垂直中心

.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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM