Asp.net开发中在TextBox指定光标处插入字符串

  最近项目开发中涉及到一个公式编辑器功能,其中一个功能就是需要对Asp.net 中的TextBoxExtJs中的TextField 或者TextArea)进行光标处插入字符串的功能。开始发现很难处理,不像在桌面开发中很容易获取光标位置然后进行插入字符处理。查阅资料发现在web开发中也提供能相关处理的功能,现在分享给他家。

插入字符串函数
function InsertValue(str) {
    var tbFormula = document.getElementById("Formula");
    if (document.selection) {
        tbFormula.focus();
        document.execCommand("paste", 0, str)
    }
    else {
        var prefix,  suffix, start, len;
        len = str.length;
        start = tbFormula.selectionStart;
        prefix = tbFormula.value.substring(0, start);
        suffix = tbFormula.value.substring(tbFormula.selectionEnd);
        tbFormula.value = prefix + str + suffix;
        tbFormula.setSelectionRange(start + len, start + len);
    }
    tbFormula.focus();
}

 

原文地址:https://www.cnblogs.com/rpoplar/p/2644980.html