我希望在用户完成选择时做一些事情——本质上,在每个 selectstart
之后的第一个 mouseup
事件上事件,我认为——在页面上。我想采用该选择并将其包装在要通过 CSS 设置样式的元素中。我假设 Selection API 为此提供了一个事件;然而,它似乎并没有。
我不只是简单地监听 mouseup
因为我特别希望它能与浏览器的查找功能产生的选择一起工作(“在此页面中查找...”;⌘+f).
let selContainer = document.createElement('span')
span.classList.add('user-selection')
const wrapSelection = () => {
window.getSelection().getRangeAt(0).surroundContent(selContainer)
}
/* ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ ┃
┃ The Selection API only ┃
┃ affords these events: ┃
┃ ┃
┃ - selectionchange ┃
┃ - selectstart ┏━━━━━┫
┃ ┃issue┃
┗━━━━━━━━━━━━━━━━━━━━┻━━━━━┛
*/document.addEventListener('selectfinish', wrapSelection)/*
┗━━━━┳━━━━━┛
┃
┃
no such
event */
最佳答案
One way that I've gotten it to work is to track the selectionchange
event and when the selection doesn't change for over 500ms, I consider that a select end.它并不完美,但它可以正常工作并正确触发任何类型的选择,无论是鼠标、键盘还是 CTRL+F。
let selectionDelay = null, selection = '';
document.addEventListener('selectionchange', () => {
const currentSelection = document.getSelection().toString();
if (currentSelection != selection) {
selection = currentSelection;
if (selectionDelay) {
window.clearTimeout(selectionDelay);
}
selectionDelay = window.setTimeout(() => {
wrapSelection();
selection = '';
selectionDelay = null;
}, 500);
}
});
关于javascript - Selection selectfinish/selectend 事件应该如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059855/