| 瀏覽器 | 獲取選區對象 | 獲取文本 |
|---|---|---|
| IE ≤ 10 | document.selection.createRange() | range.text |
| IE 11 | window.getSelection() | selection.toString() |
| 現代瀏覽器 | window.getSelection() | selection.toString() |
function getSelectedText() {
var text = '';
if (window.getSelection) { // IE11+, 現代瀏覽器
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != 'Control') { // IE ≤ 10
text = document.selection.createRange().text;
}
return text;
}
// 測試
document.addEventListener('mouseup', function() {
console.log('選中文本:', getSelectedText());
});
function getInputSelectedText(inputEl) {
// 標準 API(IE9+ 含 IE11)
if (typeof inputEl.selectionStart === 'number') {
return inputEl.value.substring(inputEl.selectionStart, inputEl.selectionEnd);
}
// IE ≤ 8 降級
if (document.selection) {
inputEl.focus();
var range = document.selection.createRange();
return range.text;
}
return '';
}
document.selection,全面對齊標準 window.getSelection()。<input>/<textarea> 內部選區,**優先用元素自身的 selectionStart/End**,最穩健、跨瀏覽器一致。window.getSelection()。IE11 處理選中文本請用標準 window.getSelection().toString() 或輸入框 selectionStart/End,棄用舊 document.selection API。一套代碼兼容所有現代瀏覽器含 IE11。