在写一个小型的编辑器时,有很多的鼠标点击事件,用于设定markdown语法。那么如何获取光标的所在位置,并插入一串字符,且将光标定位到特定位置?
接下来就是在网上查看的方法以及如何实现该功能的代码:
talk is cheap,show me the code

showdownContainer.prototype.insertStrAtCursor = function(textareaObj,insertString){//IE support
    if (document.selection) {
        textareaObj.focus();
        var sel = document.selection.createRange();
        sel.text = myValue;
        sel.select();
    }
    //MOZILLA/NETSCAPE support
    else if (textareaObj.selectionStart || textareaObj.selectionStart == '0') {
        var startPos = textareaObj.selectionStart;
        var endPos = textareaObj.selectionEnd;
        // save scrollTop before insert
        var restoreTop = textareaObj.scrollTop;
        textareaObj.value = textareaObj.value.substring(0, startPos) + insertString + textareaObj.value.substring(endPos, textareaObj.value.length);
        if (restoreTop > 0) {
            // restore previous scrollTop
            textareaObj.scrollTop = restoreTop;
        }
        textareaObj.focus();
        textareaObj.selectionStart = startPos + insertString.length;
        textareaObj.selectionEnd = startPos + insertString.length;
    } else {
        textareaObj.value += insertString;
        textareaObj.focus();
    }
};
/**
 * 设置光标位置
 * @param textareaObj  文本域元素对象
 * @param insertString  待插入的字符串
 * @param posLen 定位光标在插入字符串的第几个字符处
 */
showdownContainer.prototype.setCursorPosition = function(textareaObj,insertString,posLen){
    var cursorPosition = 0;
    if(textareaObj.selectionStart){
        cursorPosition = textareaObj.selectionStart;
    }
    this.insertStrAtCursor(textareaObj,insertString);
    textareaObj.focus();
    textareaObj.setSelectionRange(textareaObj.value.length,cursorPosition + posLen);
};
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐