开发者

How to format contenteditable div as you type?

开发者 https://www.devze.com 2023-01-22 06:54 出处:网络
I\'m trying to write a function that allows a contenteditable div to do some auto formatting while the user is typing in the div. So far I only manage to make it work in IE. Anyone can help me?

I'm trying to write a function that allows a contenteditable div to do some auto formatting while the user is typing in the div. So far I only manage to make it work in IE. Anyone can help me?

function formatOnKeyUp(){
    if (window.getSelection) {
        // ???????
    } else if (document.s开发者_高级运维election) {
        cursorPos=document.selection.createRange().duplicate();
        clickx = cursorPos.getBoundingClientRect().left; 
        clicky = cursorPos.getBoundingClientRect().top;
    }

    text = document.getElementById('div1').innerHTML;
    text = text.replace(/this/gm, "<i>this</i>");
    // .... some other formating here...
    document.getElementById('div1').innerHTML = text;

    if (window.getSelection) {
        // ????????
    } else if (document.selection) {
        cursorPos = document.body.createTextRange();
        cursorPos.moveToPoint(clickx, clicky);
        cursorPos.select();
    }
}


You could use the selection save and restore module in my Rangy library, which uses invisible marker elements at the selection boundaries. I'd also suggest doing the replacement after a certain period of keboard inactivity rather than on every keyup event:

function formatText(el) {
    // Save the selection
    var savedSel = rangy.saveSelection();

    // Do your formatting here
    var text = el.innerHTML.replace(/this/gm, "<i>this</i>");
    el.innerHTML = text;

    // Restore the original selection 
    rangy.restoreSelection(savedSel);
}

var keyTimer = null, keyDelay = 500;

document.getElementById('div1').onkeyup = function() {
    if (keyTimer) {
        window.clearTimeout(keyTimer);
    }
    keyTimer = window.setTimeout(function() {
        keyTimer = null;
        formatText(document.getElementById('div1'));
    }, keyDelay);
};


The cursor position and text range stuff looks particular to Microsoft's JScript.

If you're replacing text as someone types, why do you need that code?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号