项目需求,用户要能够输入和点击外面的公式去插入到textaera中,试了好几种方法,有的是在谷歌下好使,在ie下不好使,最后找到了下面这个方法,目前在ie8以上都可以生效。直接上代码
1 function insertAtCursor(myField, myValue) { 2 //IE support 3 if (document.selection) { 4 myField.focus(); 5 sel = document.selection.createRange(); 6 sel.text = myValue; 7 } 8 //MOZILLA and others 9 else if (myField.selectionStart || myField.selectionStart == ‘0‘) { 10 var startPos = myField.selectionStart; 11 var endPos = myField.selectionEnd; 12 myField.value = myField.value.substring(0, startPos) 13 + myValue 14 + myField.value.substring(endPos, myField.value.length); 15 myField.selectionStart = startPos + myValue.length; 16 myField.selectionEnd = startPos + myValue.length; 17 } else { 18 myField.value += myValue; 19 } 20 } 21
调用也相当的简单
insertAtCursor(‘DOM节点’,‘内容’);
原文地址:https://www.cnblogs.com/liys-kiki/p/11738393.html
时间: 2024-10-09 06:18:35