我有一个包含格式选项的内容可编辑的 div。我希望能够单击,说粗体按钮,然后分别插入光标的左侧<span class="bold">
和</span>
右侧。我相信我已经成功地做到了这一点。但是,我不知道如何将光标放在跨度内,以便用户可以开始输入粗体文本。
我目前正在使用的功能:
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?*/
}
}
}
编辑:以下最终工作
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();
}
}
}