Chrome 中可编辑容器内不可编辑元素的奇怪行为

问题描述 投票:0回答:1
javascript html css contenteditable
1个回答
0
投票

监听文本区域的按键事件。如果按下退格键(或删除),则获取所有标签并暂时删除 user-select: none。然后添加一个 setTimeout(func, 0) 来恢复最后一个标签删除后的 user-select: none

const input = document.getElementById("snafu");
const button = document.getElementById("button");

const onClick = () => {
  const tag = document.createElement("span");
  tag.setAttribute("contenteditable", false);
  tag.classList.add("xml-tag");
  tag.innerHTML = "t";
  input.append(tag);
};

button.addEventListener("click", onClick);

// +++++ ADD THIS +++++
input.addEventListener("keydown", (event) => {
  // if backspace or delete pressed
  if (event.keyCode === 8 || event.keyCode === 46) {

    // make tags selectable, so they can be removed
    const tags = input.querySelectorAll(".xml-tag");
    tags.forEach(tag => tag.style["user-select"] = "auto");

    // make tags not selectable after deletion
    setTimeout(function() {
      tags.forEach(tag => tag.style["user-select"] = "none");
    }, 0);
  }
});
body {
  font-family: sans-serif;
}

.input {
  color: green;
  box-shadow: 2px 2px 10px mediumaquamarine;
  padding: 8px;
  border-radius: 8px;
  margin-bottom: 24px;
}

.xml-tag {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 16px;
  height: 16px;
  margin-inline: 2px;
  user-select: none;
  border-radius: 50%;
  background: lime;
  font-size: 10px;
  white-space: pre;
}

.button {
  background: transparent;
  box-shadow: 3px 3px 5px limegreen;
  border: none;
  border-radius: 8px;
  padding: 8px;
}

.button:hover {
  transform: scale(1.1);
  cursor: pointer;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div id="app">
      <div spellcheck="false" contenteditable="true" class="input" id="snafu">
        <span
          >Add at least 2 non-editable tags by clicking the button below. Then
          put the cursor at the end of line and press 'Backspace'</span
        >
      </div>

      <button id="button" class="button">Add me a tag, daddy!</button>
    </div>
  </body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.