开发者

How do i set the cursor in a html editor using IE (7-8)

Actually i am trying to set the cursor to a specific node inside a html edi开发者_StackOverflow社区tor (which uses a contenteditable iframe). For example i have several paragraphs and want the cursor to move to the start of the previous paragraph. Unfortunatly, the Internet Explorers range object does not support setStartBefore and setStartAfter. The ierange project is not an option - the solution i am looking for needs to work with IE out of the box.

How do i set the cursor in IE?

In Firefox the solution is straight forward:

// sets the cursor position (start defines, if cursor is needed at the start or end of the node)
function setCursor(editor, node, start){

var tn = editor.getDoc().createTextNode("."); // gets the editors document
  if (start){
    node.insertBefore(tn, node.firstChild);
  } 
  else node.appendChild(tn);

  rng = editor.selection.getRng();  // gets the browsers range object for the users selection
  rng.selectNode(tn);
  rng.setStartBefore(tn);
  rng.setStartAfter(tn);

  ed.selection.setRng(rng);
  node.removeChild(tn);  // removes the caret node - curser is placed now
}


You could use my Rangy project for this. The code would then be the same in all browsers:

function setCursor(element, start) {
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;

    rangy.init();
    var range = rangy.createRange(doc);
    range.selectNodeContents(element);
    range.collapse(start);
    rangy.getSelection(win).setSingleRange(range);
}

Alternatively, this particular case isn't too tricky without a library:

function setCursor(element, start) {
    var doc = element.ownerDocument || element.document;
    if (typeof doc.createRange != "undefined") {
        var range = doc.createRange();
        range.selectNodeContents(element);
        range.collapse(start);
        var win = doc.defaultView || doc.parentWindow;
        var sel = win.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof doc.body.createTextRange != "undefined") {
        var textRange = doc.body.createTextRange();
        if (start) {
            textRange.moveToElementText(element);
            textRange.collapse(start);
        } else {
            var markerEl = doc.createElement("span");
            markerEl.innerHTML = "\u00A0";
            element.appendChild(markerEl);
            textRange.moveToElementText(markerEl);
            element.removeChild(markerEl);
        }
        textRange.select();
    }
}


Working with the Cursor Position (This solution works for me in IE, Firefox and Opera)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜