不同瀏覽器取得選取文字的 API 不同,需兼容 IE、標準瀏覽器。本文提供一個 getSelectedText() 函式,涵蓋三種情況。
function getSelectedText() {
var txt = "";
if (window.getSelection) { // 標準、Firefox、Chrome、Safari、IE9+
txt = window.getSelection();
} else if (document.getSelection) { // 部分舊版瀏覽器
txt = document.getSelection();
} else if (document.selection) { // IE 8 及以下
txt = document.selection.createRange().text;
}
return txt.toString(); // 確保回傳字串
}
window.getSelection() 回傳 Selection 物件,需 .toString() 取純文字。document.selection.createRange().text 直接回傳字串。window.getSelection().toString(),僅需支援 IE9+ 即可。