我正在尝试在 iframe 中处理可内容编辑的正文,以防止浏览器添加br
,p
or div
按 Enter 键时自行执行。但是当尝试重置焦点时会发生一些奇怪的事情,并且在处理其余代码之前发出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(太长了)
Edit当我删除 Magic Alerts 时,它仍然可以在 Chrome 上运行,但在 FF 中它专注于一切的开始! (就像 offset=0 一样)
UPDATE
问题似乎是用以下内容替换新行的行br
标签。如果我删除这条线,即使没有警报它也能完美工作。我需要保留这个br
标签,还有其他方法吗?