Domanda

Hey all you awesome smart people,

I need some help with user input. I am creating a basic word processor, and I need to make a certain selected area bold. The user will highlight the area with the mouse and press the button. The computer will then replace their highlighted text with <b>+originaltext+</b>, supposedly making it bold. Problem is, the computer is turning those open and closed carrots into &lt; and therefore preventing it from doing its job.

How can I force the computer to hand it over as real bold tags?

Here is what I am doing basically:

function replaceSelectedText() {
var sel, range, txtstuff;
if (window.getSelection) {
    txtstuff = '<b>'+window.getSelection()+'</b>'
    sel = window.getSelection();
    alert(txtstuff, sel);
    if (sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();
        range.insertNode(document.createTextNode(txtstuff));
    }
} else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    range.text = txtstuff;
}
}

Thanks for any help in advance!

UPDATE: This is in an editable div.

È stato utile?

Soluzione

Working code:

function replaceSelectedText() {
    var sel, range, txtstuff;
    if (window.getSelection) {
        txtstuff = '<b>'+window.getSelection()+'</b>'
        sel = window.getSelection();
        alert(txtstuff, sel);
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            var b = document.createElement('b');
            b.innerHTML = txtstuff;
            range.insertNode(b);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.text = txtstuff;
    }
}

Altri suggerimenti

Read up on document.execCommand https://developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla

The syntax in your case would be:

document.execCommand('bold');

Even though it's Mozilla's documentation this is very cross-browser. It also doesn't rely on possibly buggy cursor selection.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top