4

brブラウザが追加されないようにするため、pまたはdivEnterキーを押したときに単独で、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タグを保持する必要がありますが、他に方法はありますか?

4

1 に答える 1

1

この質問 はあなたのものの狭いです。したがって、doc と win を組み合わせる必要があります。

var idoc= iframe.contentDocument || iframe.contentWindow.document; // ie compatibility
var iwin= iframe.contentWindow || iframe.contentDocument.defaultView;

... idoc.getSelection() +(''+iwin.getSelection()) //firefox fix
于 2012-07-03T11:26:42.427 に答える