用户输入时更新内容可编辑的文本

时间:2020-08-29 18:39:24

标签: javascript

如何在不镜像我的内容的情况下有效地更新我的contenteditable元素的内容?

期望的结果:<p>Hello</p>

当前结果:<p>olleH</p>

const editor = document.createElement("div");
document.body.appendChild(editor);
editor.addEventListener("keyup", handleChange, false);
editor.setAttribute("contenteditable", "true");
editor.setAttribute(
  "style",
  "background-color: lightgrey; height:50vh; width: 100vw"
);

function handleChange() {
  editor.innerHTML = `<p>${editor.textContent}</p>`
}

1 个答案:

答案 0 :(得分:0)

<p>${editor.innerHTML}</p>更改为<p>${editor.textContent}</p>

const editor = document.createElement("div");
document.body.appendChild(editor);
editor.addEventListener("keyup", handleChange, false);
editor.setAttribute("contenteditable", "true");
editor.setAttribute(
  "style",
  "background-color: lightgrey; height:50vh; width: 100vw"
);

function handleChange() {

  editor.innerHTML = `<p>${editor.textContent}</p>`
}

相关问题