2 回答
TA贡献1860条经验 获得超8个赞
使用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>
TA贡献1786条经验 获得超11个赞
如果我以正确的方式取消描述,你想知道用户何时开始在页面上进行选择,你可以使用 DOM onselectstart。
document.onselectstart = function() { console.log("Selection started!"); };
添加回答
举报