js设置光标插入文字和HTML

在一个textarea的某个光标位置插入文字或者在某个编辑器中插入图片html内容,我最近经常和这些打交道,但总是一团模糊,今天整理一下关于如何插入文字,设置光标,移动光标等操作。

应用场景:新浪微博(网站留言本)中输入框某个位置插入表情、话题或者@ 某个人涉及到插入文本,重新设置光标位置。

代码一:在textarea某个位置插入文本

function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
    	console.log('ie');
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    //MOZILLA and others
    else if (myField.selectionStart || myField.selectionStart == '0') {
    	console.log('modern');
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
            + myValue
            + myField.value.substring(endPos, myField.value.length);
        myField.selectionStart = startPos + myValue.length;
        myField.selectionEnd = startPos + myValue.length;
    } else {
        myField.value += myValue;
    }
}

演示 来源

代码二:设置光标位置

function setSelectionRange(input, selectionStart, selectionEnd) {
  //IE9 and non-IE
  if (input.setSelectionRange) {
  // console.log('IE9 and non-IE');
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);

  //IE < 9
  } else if (input.createTextRange) {
  // console.log('IE < 9');
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos(input, pos) {
  setSelectionRange(input, pos, pos);
}

演示 来源

jQuery版本

$.fn.selectRange = function (start, end) {
    if (typeof end === 'undefined') {
        end = start;
    }
    return this.each(function () {
        if ('selectionStart' in this) {
            this.selectionStart = start;
            this.selectionEnd = end;
        } else if (this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};
//使用
$('#hw').selectRange(8);

演示 来源

代码三:获取光标位置

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0; rng.compareEndPoints("EndToStart", rng) > 0; rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len }; rng.compareEndPoints("EndToStart", rng) > 0; rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

演示 来源

代码四:在可编辑div或者iframe处插入HTML

function pasteHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // only relatively recently standardized and is not supported in
            // some browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}

演示 来源

今天先写这些,后面再详细说说这些兼容性问题。

原文链接:js设置光标插入文字和HTML 版权所有,转载时请注明出处,违者必究。
注明出处格式:前端开发博客 (http://caibaojian.com/js-insertcur.html)

发表评论

请登录后发表评论: