獲取textarea文本框所選字符光標位置索引,以及選中的文本值;textarea高度自適應,隨著內容增加高度增加;獲取輸入框中的光標位置
阿新 • • 發佈:2019-05-05
creat substring ons osi 內容 poi name range init
獲取textarea文本框所選字符光標位置索引,以及選中的文本值
$.fn.selection = function () { var s, e, range, stored_range; if (this[0].selectionStart == undefined) { var selection = document.selection; if (this[0].tagName.toLowerCase() != "textarea") {var val = this.val(); range = selection.createRange().duplicate(); range.moveEnd("character", val.length); s = (range.text == "" ? val.length : val.lastIndexOf(range.text)); range = selection.createRange().duplicate(); range.moveStart("character", -val.length); e = range.text.length; } else { range = selection.createRange(), stored_range = range.duplicate(); stored_range.moveToElementText(this[0]); stored_range.setEndPoint(‘EndToEnd‘, range); s = stored_range.text.length - range.text.length; e = s + range.text.length; } } else { s = this[0].selectionStart, e = this[0].selectionEnd; } var te = this[0].value.substring(s, e); return {start: s, end: e, text: te}; };
textarea高度自適應,隨著內容增加高度增加
$.fn.autoHeight = function(){ return this.each(function(){ var $this = jQuery(this); if( !$this.attr(‘_initAdjustHeight‘) ){ $this.attr(‘_initAdjustHeight‘, $this.outerHeight()); } _adjustH(this).on(‘input‘, function(){ _adjustH(this); }); }); /** * 重置高度 * @param {Object} elem */ function _adjustH(elem){ var $obj = jQuery(elem); return $obj.css({height: $obj.attr(‘_initAdjustHeight‘), ‘overflow-y‘: ‘hidden‘}) .height( elem.scrollHeight ); } };
獲取輸入框中的光標位置
$.fn.getCursorPosition = function () { var el = $(this).get(0); var pos = 0; if (‘selectionStart‘ in el) { pos = el.selectionStart; } else if (‘selection‘ in document) { el.focus(); var Sel = document.selection.createRange(); var SelLength = document.selection.createRange().text.length; Sel.moveStart(‘character‘, -el.value.length); pos = Sel.text.length - SelLength; } return pos; };
獲取textarea文本框所選字符光標位置索引,以及選中的文本值;textarea高度自適應,隨著內容增加高度增加;獲取輸入框中的光標位置