How to set the cursor inside a newly added empty s

2019-06-19 22:28发布

问题:

I have a contenteditable div that has formatting options. I would like to be able to click on, say the bold button, and insert <span class="bold"> and </span> to the left and right of my cursor respectively. I believe I have managed to do this. However, I do not know how to place the cursor inside the span so that the user might start typing in bold text.

The function I am currently working with:

function bold(text,clearSelection) {
    text = text.replace(/\r\n/g,"<br>");
    var sel, range, html;
    var tn = false;
    //Here i am adding the span element
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            tn = document.createElement("span");
            tn.className="bold";
            tn.innerHTML=text;
            range.insertNode(tn);           
        }
    }
    if(clearSelection){
        //if the selection length is longer than 0, move cursor to end of selection
        if(sel.toString().length >0){
            range = window.getSelection().getRangeAt(0);
            range.setStart(range.endContainer,range.endOffset);
            document.getElementById('text').focus();
        } else {  
            /*Do something if the selection length is zero to place the cursor inside the span?*/
        }
    }
}

Edit: The following ended up working

if(clearSelection){
    //if the selection length is longer than 0, move cursor to end of selection
    if(sel.toString().length >0){
        range = window.getSelection().getRangeAt(0);
        range.setStart(range.endContainer,range.endOffset);
        document.getElementById('text').focus();
    } else {
        if(tn!==false){
            range.selectNodeContents(tn);
            document.getElementById('text').focus();
        }
    }
}

回答1:

There is no fiddle to try but how about placing var tn = ... above first if statement and then use focus() on it, like

var tn = false;
if (window.getSelection) {
    sel = window.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
...
        tn = document.createElement("span");
...          
    }
}
if(clearSelection){
    if(sel.toString().length >0){

    } else {
    /*Do something if the selection length is zero to place the cursor inside the span?*/
        if (tn !== false) {
            tn.focus();
        }

    }
}