[英]Is there a way to subscribe to changes in window.getSelection?
我们可以通过window.getSelection()
获得选择范围。 我想知道是否有办法订阅window.getSelection
更改。
我想到的唯一方法是使用超时(这显然是不好的)或订阅每个用户的键\\鼠标按下事件并手动跟踪更改。
ANSWER UPD:你可以使用这个库,我已经发布了它,因为没有更合适的: 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>
对于诸如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>
如果我以正确的方式不建议您想知道用户何时开始在页面上进行选择,您可以使用 DOM onselectstart。
document.onselectstart = function() {
console.log("Selection started!");
};
更多信息MDN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.