2 回答
TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用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,您可以制作一個(gè) 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貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
如果我以正確的方式取消描述,你想知道用戶何時(shí)開始在頁面上進(jìn)行選擇,你可以使用 DOM onselectstart。
document.onselectstart?=?function()?{
??console.log("Selection?started!");
};
添加回答
舉報(bào)
