textarea控件表情按光标插入
1 var start = 0; 2 var end = 0; 3 //表情定位光标1 4 function MoveCursortoPos(id, pos) {//定位光标到某个位置 5 var obj = document.getElementById(id); 6 pos = pos ? pos : obj.value.length; 7 if (obj.createTextRange) {//IE浏览器 8 var range = obj.createTextRange(); 9 range.moveStart("character", pos); 10 range.collapse(true); 11 range.select(); 12 } else {//非IE浏览器 13 obj.setSelectionRange(obj.value.length, pos); 14 } 15 obj.focus(); 16 } 17 //添加表情 18 function add(title) { 19 var facetitle = "[" + title + "]"; 20 var textBox = document.getElementById("layim_write"); 21 var pre = textBox.value.substr(0, start); 22 var post = textBox.value.substr(end); 23 textBox.value = pre + facetitle + post; 24 MoveCursortoPos("layim_write", start + facetitle.length); 25 // $("#layim_write").blur(); 26 $(".layim_facelist").hide(); 27 } 28 //表情定位光标2 29 function savePos(textBox) { 30 //如果是Firefox(1.5)的话,方法很简单 31 if (typeof (textBox.selectionStart) == "number") { 32 start = textBox.selectionStart; 33 end = textBox.selectionEnd; 34 } 35 //下面是IE(6.0)的方法,麻烦得很,还要计算上'\n' 36 else if (document.selection) { 37 var range = document.selection.createRange(); 38 if (range.parentElement().id == textBox.id) { 39 // create a selection of the whole textarea 40 var range_all = document.body.createTextRange(); 41 range_all.moveToElementText(textBox); 42 //两个range,一个是已经选择的text(range),一个是整个textarea(range_all) 43 //range_all.compareEndPoints()比较两个端点,如果range_all比range更往左(further to the left),则 //返回小于0的值,则range_all往右移一点,直到两个range的start相同。 44 // calculate selection start point by moving beginning of range_all to beginning of range 45 for (start = 0; range_all.compareEndPoints("StartToStart", range) < 0; start++) 46 range_all.moveStart('character', 1); 47 // get number of line breaks from textarea start to selection start and add them to start 48 // 计算一下\n 49 for (var i = 0; i <= start; i++) { 50 if (textBox.value.charAt(i) == '\n') 51 start++; 52 } 53 // create a selection of the whole textarea 54 var range_all = document.body.createTextRange(); 55 range_all.moveToElementText(textBox); 56 // calculate selection end point by moving beginning of range_all to end of range 57 for (end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end++) 58 range_all.moveStart('character', 1); 59 // get number of line breaks from textarea start to selection end and add them to end 60 for (var i = 0; i <= end; i++) { 61 if (textBox.value.charAt(i) == '\n') 62 end++; 63 } 64 } 65 } 66 //document.getElementById("start").value = start; 67 //document.getElementById("end").value = end; 68 }
<textarea class="layim_write" id="layim_write" onKeydown="savePos(this)" onKeyup="savePos(this)" onmousedown="savePos(this)" onmouseup="savePos(this)" onfocus="savePos(this)" ></textarea>