日期:2014-05-16 浏览次数:20379 次
var focus_tag = { first:function(area){ area.focus(); if (area == null) { area = event.srcElement; } if(document.selection){ var rtextRange = area.createTextRange(); rtextRange.moveStart('character', area.value.length); rtextRange.collapse(true); rtextRange.select(); } },getCursorPosition:function(textarea) { var rangeData = {text: "", start: 0, end: 0 }; textarea.focus(); if (textarea.setSelectionRange) { // W3C rangeData.start= textarea.selectionStart; rangeData.end = textarea.selectionEnd; rangeData.text = (rangeData.start != rangeData.end) ? textarea.value.substring(rangeData.start, rangeData.end): ""; } else if (document.selection) { // IE var i, oS = document.selection.createRange(), oR = document.body.createTextRange(); oR.moveToElementText(textarea); rangeData.text = oS.text; rangeData.bookmark = oS.getBookmark(); for (i = 0; oR.compareEndPoints('StartToStart', oS) < 0 && oS.moveStart("character", -1) !== 0; i ++) { if (textarea.value.charAt(i) == '\n') { i ++; } } rangeData.start = i; rangeData.end = rangeData.text.length + rangeData.start; } return rangeData; }, setCursorPosition:function(textarea, rangeData) { if(!rangeData) { alert("You must get cursor position first."); } if (textarea.setSelectionRange ) { // W3C textarea.focus(); textarea.setSelectionRange(rangeData.start, rangeData.end); } else if (textarea.createTextRange) { // IE var oR = textarea.createTextRange(); if(textarea.value.length === rangeData.start) { oR.collapse(false); oR.select(); } else { oR.moveToBookmark(rangeData.bookmark); oR.select(); } } },add:function (textarea, rangeData,text) { var oValue, nValue, oR, sR, nStart, nEnd, st; this.setCursorPosition(textarea, rangeData); if (textarea.setSelectionRange) { // W3C oValue = textarea.value; nValue = oValue.substring(0, rangeData.start) + text + oValue.substring(rangeData.end); nStart = nEnd = rangeData.start + text.length; st = textarea.scrollTop; textarea.value = nValue; if(textarea.scrollTop != st) { textarea.scrollTop = st; } textarea.setSelectionRange(nStart, nEnd); } else if (textarea.createTextRange) { // IE sR = document.selection.createRange(); sR.text = text; sR.setEndPoint('StartToEnd', sR); sR.select(); } } }?