我试图在iframe中处理一个可信的主体,以防止浏览器在按Enter键时自行添加 br
, p
或 div
. 但是在尝试重置焦点时发生了一些奇怪的事情,它只是在处理其余代码之前制作alert()时才起作用 . 我认为这是因为javascript需要一些时间来进行操作,但必须有一种方法可以在没有"sleeping"脚本的情况下完成...
在这里,我粘贴我的代码(使用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 当我删除魔法警报时,它仍可在Chrome上运行,但在FF中它专注于所有内容的开头! (如果偏移= 0)
UPDATE
似乎问题是用 br
标签替换换行符的行 . 如果我删除此行,即使没有警报,它也能完美运行 . 我需要保留这个 br
标签,有没有其他方法可以做到这一点?
1 回答
这个question是你的一个 . 所以你应该结合doc&win: