2016-03-20 15 views
0

コンテンツ編集可能なdivでexecCommandを実行するときにボタンをアクティブに保つ方法はありますか?execCommandをcontentEditable divに適用するボタンにクラスを適用する

例:

<input type="button" onclick="doRichEditCommand('bold');" value="B"/> 

function doRichEditCommand(command){ 
    document.execCommand(command, null, false); 
} 

私はcarretがdocument.execCommand(command, null, false);が適用されている何か内にあるとき、私のボタンがアクティブのままにしたいと思います。私はそれが親要素をチェックすることによって実行可能だと思うが、それが良い方法に組み込まれている場合。

つまり、大胆でなければならないカレットがどこかにあるときは、大胆なボタンがオレンジ色になるようにしたいと思います。

答えて

0
<head> 
<script type="text/javascript"> 
    var editorDoc; 
    function InitEditable() { 
     var editor = document.getElementById ("editor"); 
     editorDoc = editor.contentWindow.document;   
     var editorBody = editorDoc.body; 

      // turn off spellcheck 
     if ('spellcheck' in editorBody) { // Firefox 
      editorBody.spellcheck = false; 
     } 

     if ('contentEditable' in editorBody) { 
       // allow contentEditable 
      editorBody.contentEditable = true; 
     } 
     else { // Firefox earlier than version 3 
      if ('designMode' in editorDoc) { 
        // turn on designMode 
       editorDoc.designMode = "on";     
      } 
     } 
    } 

    function ToggleBold() { 
     editorDoc.execCommand ('bold', false, null); 
    } 
</script> 
</head> 

<body onload="InitEditable();"> 
    First, write and select some text in the editor. 
    <br /> 
    <iframe id="editor" src="editable.htm"></iframe> 
    <br /><br /> 
    You can toggle the bold/normal state of the selected text with this button: 
    <br /> 
    <button onclick="ToggleBold();">Bold</button> 
</body> 

editable.html:ここ

<!DOCTYPE html> 
<html> 
    <head> 
     <title>Editable content example</title> 
     <meta charset="utf-8" /> 
    </head> 
    <body> 
     Some text in the editor. 
    </body> 
</html> 

いくつかの可能な解決策:execCommand method examples

+0

私の質問を理解しているかどうかわからない、アクティブ時にボールドボタンがオレンジ色に変わるようにしたい – Ced

+0

http://jsbin.com/ebubop/7/edit?html,output –

+0

私を助けてくれてありがとうこれは私が求めていることではありません。たとえば、単語やgmailを使用している場合、太字の場所にカレットを置くと太字のボタンがアクティブになります(オレンジ色)。私は、ボタンをcontentEditableフィールドにリンクする組み込みの関数があるのか​​疑問に思っていました。私は誰もがそれはショットの価値があったとは思わない。 – Ced

0

それはなんとかだが、それは本当に迷惑なんです。

コンテンツ編集が変更されるたびに、document.queryCommandState()を呼び出して、キャレットがあるテキストの状態を見つけて、ボタンクラスを一致するように更新します。したがって、次のようなものがあります。

let div = document.getElementById("myContentEditable"); 
div.oninput =() => { 
    if (document.queryCommandState('bold')) { 
    console.log("bold!"); 
    } else { 
    console.log("not bold."); 
    } 
    return false; 
}; 

ここから太字のボタンにスタイルを適用または削除して、カーソルが太字のセクションにあるかどうかを示します。他のスタイルについても同じ手順を繰り返します。

厄介な部分は、いくつかの異なるイベントでボタンの状態を更新する必要があることです。これはかなり私に網羅的です:

div.oninput = div.onselect = div.onchange = div.onkeyup = eventhandler; 

...私は間違っている可能性があります。

関連する問題