DIV CSS 佈局教程網

JavaScript 游標位置工具函式:選取、插入與定位的完整實作
編輯:關於JavaScript     

在 textarea 或 input 中處理游標位置,是 @提及功能、表情插入、程式碼編輯器等互動的地基。它需要同時應付兩套完全不同的 API:IE 的 document.selection 與標準的 setSelectionRange。本文把這些操作封裝成一個可串用的 selectRange 工具。

HTML 結構

 <p>文本框:</p> <textarea name="" id="textarea" cols="30" rows="10"> sASASADASDasfaDFDsfsDFAfdFADf </textarea> <button type="button" id="setSelectText">選中特定范圍的文本</button> <button type="button" id="insertAfterText">在光標後插入文本</button> <br> <hr> <br> <input type="number" name="" id="input"> <button type="button" id="setCurPosBtn">設置光標位置</button> <br> <hr> <br> <p id="selectText">我是一段可以選中的文字,請打開控制台查看。我是一段可以選中的文字,請打開控制台查看。我是一段可以選中的文字,請打開控制台查看。</p> 

工具函式實作

 /** * 光標位置組件 * ## selectRange對象的方法: * (1)selectRange.of(ele) [創建光標位置獲取的新對象] 參數: ele {{JavaScript DOM}} 光標所在的元素,原生JavaScript DOM * (2)selectRange.getCurPos() [獲取當前坐標位置] * (3)selectRange.setCurPos(pos) [設置當前光標位置] 參數: pos {{Int}} 當前光標位置 * (4)selectRange.getSelectText() [獲取選中文字] * (5)selectRange.setSelectText(startPos, endPos) [選中特定范圍的文本(只限於textarea和input)] * 參數: startPos {{Int}} 起始位置 endPos {{Int}} 終點位置 * (6)selectRange.insertAfterText(value) [在光標後插入文本] * 參數: value {{String}} 要插入的文本 * * * ## 使用實例: * selectRange.of(EleDom).getCurPos(); // 獲取當前坐標位置 * selectRange.of(EleDom).setCurPos(pos); // 設置當前光標位置為pos * selectRange.of(EleDom).getSelectText(); // 獲取選中文字 * selectRange.of(EleDom).setSelectText(startPos, endPos); // 選中startPos到endPos范圍的文本 * selectRange.of(EleDom).insertAfterText(value); // 在光標後插入值為value的文本 */ var selectRange = function(ele){ this.__element = ele; }; // 創建光標位置獲取的新對象 selectRange.of = function(ele){ if(ele) { return new selectRange(ele); } else { return {}; } }; selectRange.prototype = { constructor:selectRange, // 獲取當前坐標位置 getCurPos: function() { var _this = this, textDom = _this.__element; // 獲取光標位置 var cursorPos = 0; if (document.selection) { // IE Support textDom.focus(); var selectRange = document.selection.createRange(); selectRange.moveStart ('character', -textDom.value.length); cursorPos = selectRange.text.length; }else if (textDom.selectionStart || textDom.selectionStart == '0') { // Firefox support cursorPos = textDom.selectionStart; } return cursorPos; }, /** * 設置當前光標位置 * 參數: * pos [Int] 當前光標位置 */ setCurPos: function(pos) { var _this = this, textDom = _this.__element; if(textDom.setSelectionRange) { // IE Support textDom.focus(); textDom.setSelectionRange(pos, pos); }else if (textDom.createTextRange) { // Firefox support var range = textDom.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, // 獲取選中文字 getSelectText: function() { var _this = this, textDom = _this.__element, userSelection, text = ""; if (window.getSelection) { // Firefox support userSelection = window.getSelection(); } else if (document.selection) { // IE Support userSelection = document.selection.createRange(); } if (!(text = userSelection.text)) { text = userSelection; } return text; }, /** * 選中特定范圍的文本(只限於textarea和input) * 參數: * startPos [Int] 起始位置 * endPos [Int] 終點位置 */ setSelectText: function(startPos, endPos) { var _this = this, textDom = _this.__element, startPos = parseInt(startPos), endPos = parseInt(endPos), textLength = textDom.value.length; if(textLength){ if(!startPos){ startPos = 0; } if(!endPos){ endPos = textLength; } if(startPos > textLength){ startPos = textLength; } if(endPos > textLength){ endPos = textLength; } if(startPos < 0){ startPos = textLength + startPos; } if(endPos < 0){ endPos = textLength + endPos; } if(textDom.createTextRange){ // IE Support var range = textDom.createTextRange(); range.moveStart("character",-textLength); range.moveEnd("character",-textLength); range.moveStart("character", startPos); range.moveEnd("character",endPos); range.select(); }else{ // Firefox support textDom.setSelectionRange(startPos, endPos); textDom.focus(); } } }, /** * 在光標後插入文本 * 參數: * value [String] 要插入的文本 */ insertAfterText: function(value) { var _this = this, textDom = _this.__element, selectRange; if (document.selection) { // IE Support textDom.focus(); selectRange = document.selection.createRange(); selectRange.text = value; textDom.focus(); }else if (textDom.selectionStart || textDom.selectionStart == '0') { // Firefox support var startPos = textDom.selectionStart; var endPos = textDom.selectionEnd; var scrollTop = textDom.scrollTop; textDom.value = textDom.value.substring(0, startPos) + value + textDom.value.substring(endPos, textDom.value.length); textDom.focus(); textDom.selectionStart = startPos + value.length; textDom.selectionEnd = startPos + value.length; textDom.scrollTop = scrollTop; } else { textDom.value += value; textDom.focus(); } } }; // =============================================== // 實例代碼 var textareaDom = document.querySelector("#textarea"), setCurPosInput = document.querySelector("#input"), setCurPosBtn = document.querySelector("#setCurPosBtn"), selectText = document.querySelector("#selectText"), setSelectTextBtn = document.querySelector("#setSelectText"), insertAfterTextBtn = document.querySelector("#insertAfterText"); // 獲取當前光標位置 textareaDom.addEventListener("keydown", function() { console.log("getCurPos: " + selectRange.of(textareaDom).getCurPos()); }, false); // 設置當前光標位置 setCurPosBtn.addEventListener("click", function() { var curPos = parseInt(setCurPosInput.value); console.log("curPos: " + curPos); selectRange.of(textareaDom).setCurPos(curPos); }, false); // 獲取選中文字 selectText.addEventListener("mouseup", function() { console.log("selectText: " + selectRange.of(this).getSelectText()); }); // 選中特定范圍的文本 setSelectTextBtn.addEventListener("click", function() { selectRange.of(textareaDom).setSelectText(0, 21); }, false); // 在光標後插入文本 insertAfterTextBtn.addEventListener("click", function() { var insertText = "===hello world, I'm insert content.==="; selectRange.of(textareaDom).insertAfterText(insertText); }, false); 

設計重點

用 of() 當靜態工廠。這個工具沒有直接 new,而是透過 selectRange.of(ele) 取得實例。傳入無效參數時回傳空物件,呼叫方不會拿到 undefined 而崩潰,形成一層防護。

標準 API 是主角。現代瀏覽器走的是 selectionStart/selectionEnd 讀取、setSelectionRange(start, end) 設定。注意 getCurPos 中 textDom.selectionStart == '0' 那個額外判斷——這是因為游標在位置 0 時 selectionStart 為 0,在 JS 中 falsy,單獨寫 if (textDom.selectionStart) 會誤判成不支援。這是極易忽略的細節。

insertAfterText 保留了 scrollTop。插入文字後再設定 scrollTop,可避免長文字方塊的捲動位置被重置而突然跳到頂端,是使用者體驗上的重要細節。同時它也把游標移到插入內容之後,讓使用者能連續輸入。

setSelectText 做了完整的邊界檢查。起始與終點都會被夾在 0 到文字長度之間,負值則改為從尾端往回計算。這種防禦性寫法能避免傳入不合理數值時引發錯誤。

可以簡化的部分

今天你不需要再寫 IE 分支。所有現代瀏覽器都支援 selectionStart、setSelectionRange、window.getSelection,把 document.selection 相關程式碼全部移除後,這個工具的體積能砍掉將近一半,可讀性也大幅提升。

另一個值得注意的地方是 getSelectText:它主要針對「頁面上任意選取的文字」,用 textarea 時其實直接讀 value.substring(selectionStart, selectionEnd) 更準確,因為 textarea 內部的選取不會反映在 window.getSelection() 上。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved