想針對使用者選取的文字做點什麼——加粗、引用、查詢——第一步就是把它讀出來。這件事在不同瀏覽器上要走不同分支,是個典型的相容性問題。
<script type="text/javascript">
function getFieldSelection(select_field) {
var word = '';
if (document.selection) {
// 舊 IE 分支:透過 document.selection 取得 Range
var sel = document.selection.createRange();
if (sel.text.length > 0) {
word = sel.text;
}
}
else if (select_field.selectionStart || select_field.selectionStart == '0') {
// 標準分支:用 selectionStart / selectionEnd
var startP = select_field.selectionStart;
var endP = select_field.selectionEnd;
if (startP != endP) {
word = select_field.value.substring(startP, endP);
}
}
return word;
}
</script>
<textarea id="a" rows="3" cols="20">選擇我,然後點擊下面的按鈕</textarea><br />
<button onclick="alert(getFieldSelection(document.getElementById('a')))">
button_click
</button>
標準做法利用 input/textarea 元素自帶的 selectionStart 與 selectionEnd,兩者分別是選取區間的起點與終點索引,用 substring 切出來即可。注意那個看似奇怪的條件 selectionStart == '0':這是為了處理「起點正好是 0」的情況——在部分舊瀏覽器中 0 是 falsy,直接寫 if (obj.selectionStart) 會誤判為「沒有選取」。
舊 IE 做法則是用 document.selection.createRange() 取得文字範圍物件,再讀它的 text。
原範例特別提醒了一點,值得細說:在 IE 中,當你點擊的不是 button 而是其他元素(例如 span、div)時,整個頁面的選取狀態會被改變。也就是說,使用者先在 textarea 選好文字,接著點一個 span,等 click 事件跑起來時,document.selection 已經不是原本那段文字了,取到的結果是空的。
在 Firefox、Opera 中沒有這個問題,因為它們的 selection 是綁在元素上的。所以範例刻意用 <button> 觸發——button 不會破壞選取狀態。實務上的解法有兩個:
// 解法一:在 mousedown(早於 click 且 selection 還在)時先存起來
el.addEventListener('mousedown', function () {
window.__savedSelection = getFieldSelection(textarea);
});
// 解法二(現代瀏覽器):用 mousedown 的 preventDefault 阻止焦點跳走
el.addEventListener('mousedown', function (e) {
e.preventDefault(); // 焦點留在 textarea,選取不消失
});
今天不必再寫 document.selection 分支了,IE11 以後的環境都支援標準 API:
function getSelection(el) {
var start = el.selectionStart;
var end = el.selectionEnd;
return (start !== end) ? el.value.slice(start, end) : '';
}
若需要取得「頁面上任意位置」被選取的文字(不限於輸入框),用:
var text = window.getSelection().toString();
最後提醒:讀取使用者選取內容屬於對隱私敏感的行為,不該在未告知的情況下將其送出到伺服器。若功能確有必要,請在介面上明確說明用途。