文本框里现在有一些字,现在打算点其中间利用JS加一个字符在网上看到有一种解决方案是利用选中的方式模拟,用selection.createRange();方式
但是这样方式 实际上只用IE是可以的 IE貌似把点击看成选中了一小点
但是谷歌,火狐等浏览器是不兼容的谁有完成 点击后 插入字符的兼容JS代码

解决方案 »

  1.   


    <script>
        function AddText(txt) {
        obj = document.getElementById('message');
        selection = document.selection;
        checkFocus();
        if(typeof(obj.selectionStart)!='undefined') {
        //document.getElementById('logs').innerHTML+=obj.selectionStart+' '+obj.selectionEnd;
        obj.value = obj.value.substr(0, obj.selectionStart) + txt + obj.value.substr(obj.selectionEnd);
        } else if(selection && selection.createRange) {
        var sel = selection.createRange();
        sel.text = txt;
        sel.moveStart('character', -txt.length);
        } else {
        obj.value += txt;
        }
        }
         
        function checkFocus() {
        obj.focus();
        }
    </script>
    <textarea id="message" name="message" onClick="AddText('test')">12345</textarea>IE,FF下都测试了。