使用 window.getSelection() 方法獲取鼠標划取部分的起始位置和結束位置
返回一個 Selection
對象,表示用戶選擇的文本范圍或光標的當前位置。
const selection = window.getSelection() ;
selection
是一個Selection
對象。 如果想要將selection
轉換為字符串,可通過連接一個空字符串("")或使用String.toString()
方法。function foo() { let selObj = window.getSelection(); console.log(selObj); let selRange = selObj.getRangeAt(0); // 其他代碼 }
在 JavaScript中,當一個對象被傳遞給期望字符串作為參數的函數中時(如
window.alert
或document.write
),對象的toString()
方法會被調用,然后將返回值傳給該函數。- 參考:https://www.cnblogs.com/strangerqt/p/3745426.html
//Firefox, Safari, Opera下,可以用window.getSelection(), 參考MDC
//IE下,可以用document.selection.createRange().text, 參考MSDN放在一起:
//注意:當選中的是input[type=text]里面的值時getSelection在Firefox和Opera下無法獲取到選取值
//,在Safari下沒問題。function getSelectionText() {
if(window.getSelection) {
return window.getSelection().toString();
} else if(document.selection && document.selection.createRange) {
return document.selection.createRange().text;
}
return '';
} -
function test(){ var txt = window.getSelection?window.getSelection():document.selection.createRange().text; alert(txt) } document.onmouseup = test
移除選中內容: html: <div>你不能選中我,不信你試試</div> js2: function test(){ window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); } document.onmouseup = test