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!"); };
添加回答
舉報