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

时间:2020-10-19 09:25:15

标签: javascript webapi

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

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

ANSWER UPD:,您已经可以使用该库了,我已经发布了它,因为没有更合适的库了:https://github.com/xnimorz/selection-range-enhancer

2 个答案:

答案 0 :(得分:1)

使用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>

对于特定情况,例如span contenteditable,您可以制作一个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>

答案 1 :(得分:0)

如果我想以正确的方式表达自己的意愿,那么您想知道何时在页面上开始用户选择时,可以在selectstart上使用DOM。

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

更多信息MDN