将光标放在空标签上

时间:2010-12-16 19:58:14

标签: javascript

我正在编写文本编辑器,具有一些特殊的格式化功能,在设计模式下使用iframe。将光标位置设置为空元素时出现问题,例如:

<p></p>

我想设置光标,因此当用户继续在<p>标签之间输入文字时。 这是我的代码:

<iframe id="editor"></iframe>

$(document).ready(function() {
    var iframe = $('#editor').contents().get(0);
    var iwin = $('#editor')[0].contentWindow;
    iwin.document.designMode = "on";
    $('body', iframe).html('<p>ppp1</p><p></p><p>ppp3</p>');

    $('#editor').focus();
    var start = $('p', iframe)[1];

    var rng = $('#editor')[0].contentDocument.createRange();
    rng.setStart(start, 0);
    rng.setEnd(start, 0);

    var sel = iframe.getSelection();
    sel.removeAllRanges();
    sel.addRange(rng);

});

JsFiddle http://jsfiddle.net/xbit/MGaTf/3/

1 个答案:

答案 0 :(得分:3)

这里有一些问题:

  • 在大多数浏览器中,空段落不会显示。你需要一些内容;
  • 您已在iframe的文档而不是iframe的getSelection()对象上调用了Window。您需要var sel = iwin.getSelection();;
  • 这一切都不适用于IE,其处理选择的方式完全不同。
  • WebKit无法将插入符号放在空元素中。请参阅https://bugs.webkit.org/show_bug.cgi?id=15256

还有一些其他小问题:对于iframe DOM元素,contentWindow是非标准的,contentDocument不受普遍支持。为了最大限度地使用标准,我建议使用以下内容:

var iframe = $('#editor')[0];
var idoc, iwin;
if (typeof iframe.contentDocument != "undefined") {
    idoc = iframe.contentDocument;
    iwin = idoc.defaultView;
} else if (typeof iframe.contentWindow != "undefined") {
    iwin = idoc.contentWindow;
    idoc = iwin.document;
}

我已更新您的示例(虽然不幸的是第二段不再为空):http://jsfiddle.net/timdown/MGaTf/6/