【发布时间】:2012-07-03 21:01:09
【问题描述】:
我正在尝试在 iframe 中处理 contenteditable 正文,以防止浏览器在按 Enter 时自行添加 br、p 或 div。但是在尝试重置焦点时会发生一些奇怪的事情,并且它只是在处理其余代码之前发出 alert() 时才起作用。我认为这是因为javascript需要一些时间来进行操作,但是必须有一种方法可以在不“休眠”脚本的情况下进行操作...
在这里我粘贴了我的代码(使用 Jquery),只有使用“魔法警报”才能完美运行:
//PREVENT DEFAULT STUFF
var iframewindow=document.getElementById('rte').contentWindow;
var input = iframewindow.document.body;
$( input ).keypress( function ( e ) {
var sel, node, offset, text, textBefore, textAfter, range;
// the Selection object
sel = iframewindow.getSelection();
alert(sel); //MAGIC ALERT
// the node that contains the caret
node = sel.anchorNode;
alert(node); //MAGIC ALERT
// if ENTER was pressed while the caret was inside the input field
if ( node.parentNode === input && e.keyCode === 13 ) {
// prevent the browsers from inserting <div>, <p>, or <br> on their own
e.preventDefault();
// the caret position inside the node
offset = sel.anchorOffset;
// insert a '\n' character at that position
text = node.textContent;
textBefore = text.slice( 0, offset );
textAfter = text.slice( offset ) || ' ';
node.textContent = textBefore + '\n' + textAfter;
SEEREF=SEEREF.replace(/\n/g, "<br>");
// position the caret after that newBR character
range = iframewindow.document.createRange();
range.setStart( node, offset + 4 );
range.setEnd( node, offset + 4 );
// update the selection
sel.removeAllRanges();
sel.addRange( range );
}
});
SEEREF = framewindow.document.body.innerHTML(太长了)
编辑 当我删除 Magic Alerts 时,它仍然适用于 Chrome,但在 FF 中,它专注于一切的开始! (就像它是 offset=0 一样)
更新
似乎问题是用br 标签替换换行符的行。如果我删除此行,即使没有警报,它也能正常工作。我需要保留这个br标签,还有其他方法吗?
【问题讨论】:
-
console.log也在做同样的事情吗? -
如果您忽略警报会发生什么?错误信息是什么?
-
@Mageek 我不知道这是什么...(这里我有答案,我会试试 - stackoverflow.com/questions/4743730/…)谢谢!
-
@Christoph 对不起!...我忘了说,但我的问题现在更新了。当我省略它们时,会出现任何错误消息,但它不能正常工作。
-
我认为
alert给代码执行时间。
标签: javascript alert