日期:2014-05-16 浏览次数:20371 次
//////// 文本框文字处理 //////// /* input 对象 if selectionStart=selectionEnd is point else 是string */ function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { //firefox input.focus(); input.setSelectionRange(selectionStart, selectionEnd); }else if (input.createTextRange) { //ie var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } } function setCaretToEnd (input) { setSelectionRange(input, input.value.length, input.value.length); } function setCaretToBegin (input) { setSelectionRange(input, 0, 0); } //自定义光标插入点位置 function setCaretToPos (input, pos) { setSelectionRange(input, pos, pos); } /*光标选中对象中的string input 对象 eg:"Visit W3School..."; string 是匹配字符串 eg: "w3school" */ function selectString (input, string) { //RegExp(string, "i") string 不区分大小写 var match = new RegExp(string, "i").exec(input.value);//input.value 是否匹配有string if (match) { setSelectionRange (input, match.index, match.index + match[0].length); } } //替换string function replaceSelection (input, replaceString) { if (input.setSelectionRange) { var selectionStart = input.selectionStart; var selectionEnd = input.selectionEnd; input.value = input.value.substring(0, selectionStart) + replaceString + input.value.substring(selectionEnd); if (selectionStart != selectionEnd) // has there been a selection setSelectionRange(input, selectionStart, selectionStart +replaceString.length); else // set caret setCaretToPos(input, selectionStart + replaceString.length); } else if (document.selection) { var range = document.selection.createRange(); if (range.parentElement() == input) { var isCollapsed = range.text == ''; range.text = replaceString; if (!isCollapsed) { // there has been a selection //it appears range.select() should select the newly //inserted text but that fails with IE range.moveStart('character', -replaceString.length); range.select(); } } } } /** * 文本框光标定位 **/ function setCaretPosition(elemId, caretPos) { var elem = document.getElementById(elemId); if(elem != null&&caretPos!=0) { if(elem.createTextRange) { var range = elem.createTextRange(); range.move('character', caretPos); range.select(); } else { if(elem.selectionStart) { elem.setSelectionRange(caretPos, caretPos); } elem.focus(); } elem.scrollTop = elem.scrollHeight; } }?