13

Firefox は<br />Enter キーを押すとタグを挿入しますが、他のブラウザーは a<p>または<div>. chrome と safari が contentEditable div の firstchild に同じタグを挿入していることはわかっています。ただし、Firefox も同様です。ただし、最初のタグの innerHTML が空の場合、Firefox はタグを無視し、2 行目のデフォルト ノードをプッシュして新しい行を作成し、子ノード内ではなくエディター内に直接書き込みます。したがって、基本的には、Firefox が指定されたタグ内に書き込み、Enter キーを押すたびにその種類のノードを挿入し続けるようにしたいと考えています。どうすればそれができますか?助言がありますか?

4

3 に答える 3

4

私は解決策を見つけました:)これを機能させるには、キャレットの親要素にIDを指定する必要があります。次に、次のコードを使用できます。C# から browsernName を取得し、それを隠しフィールドに入れることに注意してください。そのため、「firefox」と同等にしました。次のコードは FF 3.6 でテストされており、完全に動作します。唯一のことは、キャレットの親要素を確認する必要があり、それが現在の行の id と等しくない場合は、選択関数を使用して現在の行内にキャレットを配置する必要があることです。また、keyup イベントでこのコードを実行し、keyup イベントで他のコードを実行する場合は、必ずこのコードを最後に配置してください。とにかく、楽しんでください:)

// The code works good in the following cases:
// 1) If there is text inside the editor and the user selects the whole text
//    and replace it with a single character, the <p> tag will be placed and the
//    text will place inside the p tag
// 2) If the user selects the whole code and deletes it and begins to type again
// 3) If the user types normally and press enter 
// NB: Please note me if you find any bug

if (browserName == "firefox") {
    //remove all br tags
    var brs = txteditor.getElementsByTagName("br");
    for (var i = 0; i < brs.length; i++) { brs[i].parentNode.removeChild(brs[i]); }
    //check whether there is a p tag inside
    var para = txteditor.getElementsByTagName("p");
    if (para.length == 0) {
        var inner = txteditor.innerHTML.replace(/^\s+|\s+$/g, '');
        var str = (inner == "") ? "&#8203;" : txteditor.innerHTML;
        var nText = "<p id=\"" + cRow + "\">" + str + "</p>";
        // in order to prevent a dublicate row clear inside the text editor
        txteditor.innerHTML = "";
        document.execCommand('insertHTML', false, nText);
    } else {
        // always make sure that the current row's innerHTML is never empty
        if (document.getElementById(cRow).innerHTML == "")
            document.getElementById(cRow).innerHTML = "&#8203;";
    }
}
于 2011-04-19T19:26:57.263 に答える
2

要素内にa を挿入してみてください<p></p>。次に、ほぼ確実にすべての改行が新しい段落になります。

于 2011-04-18T15:58:44.600 に答える