javascript前端方法向输入域中光标所在位置或无光标最后插入指定字符

工作中遇到的问题处理,特此记录下来,以备后用。废话不多说,方法如下:

/** 
*往输入域中插入字符串(光标所在位置) 
*@param $t document.getElementById('fieldId') 
*@param myValue 要插入的值 
**/
function addSplitToField($t,myValue){ 
    if (document.selection) { 
        $t.focus(); 
        sel = document.selection.createRange(); 
        sel.text = myValue; 
        $t.focus(); 
    }else if($t.selectionStart || $t.selectionStart == '0') { 
        var startPos = $t.selectionStart; 
        var endPos = $t.selectionEnd; 
        var scrollTop = $t.scrollTop; 
        $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length); 
        this.focus(); 
        $t.selectionStart = startPos + myValue.length; 
        $t.selectionEnd = startPos + myValue.length; 
        $t.scrollTop = scrollTop; 
    }else{ 
        $t.value += myValue; 
        $t.focus(); 
    } 
}


猜你喜欢

转载自blog.csdn.net/txp1993/article/details/79278715