处理选择标记之间的交集

asd*_*asd 9 javascript

我在UI上有一个标记按钮,单击该按钮,任何用户选择都标记为红色。没问题 我通过实现document.execCommand("insertHTML")

但是我还有一个附加要求,如果创建的新选择是旧选择标记的交集,则旧选择的红色标记应该消失。

举个例子:

在下图中:测试已标记。现在,如果我选择他是TES从一开始,点击标记,旧标志的这个测试应该离开,只有他是TES应标,因为有一个路口。

在此处输入图片说明

码:

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

button.addEventListener('click', ()=>{
	const s = window.getSelection();
  const selectionStr = s.toString();
  document.execCommand("insertHTML", false, `<span class="bg-red">${selectionStr}<span>`);
})
Run Code Online (Sandbox Code Playgroud)
.bg-red {  
background: red;
}
Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true">
 this is testing  this is testing  this is testing
</div>

<button id="button">mark</button>
Run Code Online (Sandbox Code Playgroud)

小智 4

您可以使用 找到所选文本的startContainer& ,并与 进行比较。如果它们不等于 ,则删除该类。endContainergetRangeAtcontentContainercontentContainerbg-red

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

button.addEventListener('click', ()=>{
  let contentContainer = document.getElementById("contentContainer");
  const selection = window.getSelection();
  if (selection.rangeCount > 0){
    let startContainer =  selection.getRangeAt(0).startContainer.parentNode;
    let endContainer =  selection.getRangeAt(0).endContainer.parentNode;
    if(startContainer != contentContainer)
      startContainer.classList.remove('bg-red')
    if(endContainer != contentContainer)
      endContainer.classList.remove('bg-red')
  }
  const selectionStr = selection.toString();
  document.execCommand("insertHTML", false, `<span class="bg-red">${selectionStr}<span>`); 
})
Run Code Online (Sandbox Code Playgroud)
.bg-red {  
  background: red;
}
Run Code Online (Sandbox Code Playgroud)
<div id="contentContainer" contenteditable="true">
 this is testing  this is testing  this is testing
</div>

<button id="button">mark</button>
Run Code Online (Sandbox Code Playgroud)