我正在编写文本编辑器,具有一些特殊的格式化功能,在设计模式下使用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/
答案 0 :(得分:3)
这里有一些问题:
getSelection()
对象上调用了Window
。您需要var sel = iwin.getSelection();
; 还有一些其他小问题:对于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/