仅针对特定元素的JavaScript selectionchange事件

Git*_*bia 6 javascript jquery

我想selectionchange在特定div元素上实现JavaScrit 事件,因此,如果用户从DOM中选择文本,我想显示一个荧光笔框。我已经通过onmouseup事件实现了此功能。但是我一直坚持尝试为移动设备实现这一点。

对于移动浏览器,我将document.selectionchange事件绑定在DOM上,但是我希望这仅适用于具有content-editable类的特定元素。因此,仅当用户在页面上具有content-editable类的容器中选择文本时,荧光笔才会显示。

document.addEventListener("selectionchange", function(evt) { 
  // Now this functionality only apply for content-editable class div.
});
Run Code Online (Sandbox Code Playgroud)

如何实现此功能?也许可以使用递归函数来实现,以找到所选文本parentElement的类,anchorNode例如:

var selection = ctrl.window.getSelection();
Run Code Online (Sandbox Code Playgroud)

做这个的最好方式是什么?

Ali*_*Oli 7

相反,监听selectstart目标元素的事件。仅当触发此事件时才获得选择。

const targetDiv = document.getElementById("interestingDiv");
function logSelection() {  
  console.log(document.getSelection().toString());
}
targetDiv.addEventListener("selectstart", () => {
  console.log("Selection started in targetDiv");
  document.addEventListener("selectionchange", logSelection);
});
Run Code Online (Sandbox Code Playgroud)

selectstart一旦做出新的选择,该事件就会触发,因此您将需要某种方法来在选择完成后获取该选择。我们可以收听selectionchange,并通过某种方式在选择后停止收听。一种选择是停止监听mouseleave

targetDiv.addEventListener("mouseleave", () => {
 document.removeEventListener("selectionchange", logSelection);
})
Run Code Online (Sandbox Code Playgroud)