1. 程式人生 > >點選滑鼠在textarea中游標當前位置插入指定字元

點選滑鼠在textarea中游標當前位置插入指定字元

 function insertText(obj,str) {
   //obj為textarea 元素,str為要插入字元
    if(Switch == 1){
    if (document.selection) {
        var sel = document.selection.createRange();
        sel.text = str;
        setcopy(0);
    } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
        var startPos = obj.selectionStart;
        var    endPos = obj.selectionEnd;
        var    cursorPos = startPos;
        var    tmpStr = obj.value;
        obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
        cursorPos += str.length;
        obj.selectionStart = obj.selectionEnd = cursorPos;
        setcopy(0);
    } else {
        obj.value += str;
        setcopy(0);
    }
    }
}