Javascript - 仅当我执行警报()时才有效

Javascript - Only works if I do an alert()

本文关键字:有效 执行 Javascript      更新时间:2023-09-26

我正在尝试处理iframe中的内容可编辑正文,以防止浏览器在按Enter键时自行添加brpdiv。但是在尝试重置焦点时会发生一些奇怪的事情,并且在处理其余代码之前发出 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 (它太长了)

编辑当我删除魔术警报时,它仍然可以在 Chrome 上运行,但在 FF 中,它专注于一切的开始!(就像偏移量=0)

更新

似乎问题是用br标签替换换行符的行。如果我删除此行,即使没有警报,它也能完美运行。我需要保留这个br标签,还有其他方法吗?

这个问题很

狭隘。所以你应该结合doc & win:

var idoc= iframe.contentDocument || iframe.contentWindow.document; // ie compatibility
var iwin= iframe.contentWindow || iframe.contentDocument.defaultView;
... idoc.getSelection() +(''+iwin.getSelection()) //firefox fix