有没有办法订阅 window.getSelection 中的更改?

Is there a way to subscribe to changes in window.getSelection?

我们可以通过window.getSelection()得到一个选择范围。 我想知道是否有办法订阅 window.getSelection 更改。

我想到的唯一方法是使用超时(这显然很糟糕)或订阅每个用户的键\鼠标按下事件并手动跟踪更改。

回答更新:你可以使用这个库,我已经发布了它,因为没有更合适的库了:https://github.com/xnimorz/selection-range-enhancer

使用 onselect 事件。

function logSelection(event) {
  const log = document.getElementById('log');
  const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd);
  log.textContent = `You selected: ${selection}`;
}

const textarea = document.querySelector('textarea');
textarea.onselect = logSelection;
<textarea>Try selecting some text in this element.</textarea>
<p id="log"></p>

针对spancontenteditable等特定情况,可以做一个polyfill:

function logSelection() {
  const log = document.getElementById('log');
  const selection = window.getSelection();
  log.textContent = `You selected: ${selection}`;
}

const span = document.querySelector('span');

var down = false;
span.onmousedown = () => { down = true };
span.onmouseup = () => { down = false };
span.onmousemove = () => {
  if (down == true) {
    logSelection();
  }
};
<span contenteditable="true">Try selecting some text in this element.</span>
<p id="log"></p>

如果我以正确的方式取消描述,你想知道用户何时在页面上开始选择,你可以使用 DOM onselectstart。

document.onselectstart = function() {
  console.log("Selection started!");
}; 

更多信息MDN