div设置contentEditable="true"作为文本编辑器,定位光标解决办法

function set_focus(el) {
    el = el[0]; // jquery 对象转dom对象
    el.focus();
    if ($.browser.msie) {
        var rng;
        el.focus();
        rng = document.selection.createRange();
        rng.moveStart('character', -el.innerText.length);
        var text = rng.text;
        for (var i = 0; i < el.innerText.length; i++) {
            if (el.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) {
                result = i + 1;
            }
        }
    } else {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
}

function set_focus(el) {
    el = el[0]; // jquery 对象转dom对象
    el.focus();
    if ($.browser.msie) {
        var rng;
        el.focus();
        rng = document.selection.createRange();
        rng.moveStart('character', -el.innerText.length);
        var text = rng.text;
        for (var i = 0; i < el.innerText.length; i++) {
            if (el.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) {
                result = i + 1;
            }
        }
    } else {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
}

 

posted @ 2017-02-22 13:47  Lonely,lonelyBurning  阅读(3943)  评论(0编辑  收藏  举报