br
ブラウザが追加されないようにするため、p
またはdiv
Enterキーを押したときに単独で、iframe内のコンテンツ編集可能な本文を処理しようとしています。しかし、フォーカスをリセットしようとすると何か奇妙なことが起こり、残りのコードを処理する前に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(長すぎました)
編集 MagicAlertsを削除しても、Chromeでも機能しますが、FFではすべての最初に焦点が当てられます。(offset = 0の場合のように)
アップデート
ポーブレムは、改行をbr
タグに置き換える行のようです。この行を削除すると、アラートがなくても完全に機能します。このbr
タグを保持する必要がありますが、他に方法はありますか?