2017-03-06 15 views
0

私自身のミニ/シンプルなテキストエディタを作成する過程で、execCommandの使用に関する問題が発生しました。なぜ私のコードが動作していないのかわかりません。私はmousedownイベントを防止しようとし、 "unsetectable =" on ""属性を使用しましたが、それでも動作していないようです。すべてのヘルプは高く評価され"execCommand"がAngularJSと連携していません

<button type="button" class="btn btn-default" ng-click="makeBold()" unselectable="on" ng-mousedown="$event.stopPropagation()">B</button> 

$scope.makeBold = function(){ 
    document.execCommand('bold',false,null); 
}; 

、感謝:

は、ここに私のコードです!

答えて

0

execCommandは、現在の選択範囲に適用されます。ボタンをクリックすると(実際には、テキスト入力の外のどこでも)、現在選択されているテキストの選択が解除されます。このコードの目的は、あなたのcontentEditableの選択を元に戻すことです。もし現在何も選択されていなければ、少なくともキャレットの位置を復元する必要があります(これは長さ0の選択です)。

this.textInput.onmouseup = this.textInput.onkeyup = function(){ 
    this.updateSelection(); 
    this.updateStatus(); 
}.bind(this); 

は、その目的のために、アレイ内の選択範囲を保存する:

まずあなたが(keyUpイベントとのmouseupに、私の場合には)選択した範囲にユーザーが選択を変更するたびに格納する必要があります

this.updateSelection = function(){ 
    this.selection = []; 
    var sel = this.getSelection(); 
    for(var i=0; i<sel.rangeCount; i++) 
     this.selection.push(sel.getRangeAt(i).cloneRange()); 
}; 

と選択を復元し、コマンドを実行する前に:

this.reselect = function(){ 
    var sel = this.getSelection(); 
    sel.removeAllRanges(); 
    for(var i=0; i<this.selection.length; i++) 
     sel.addRange(this.selection[i].cloneRange()); 
}; 

this.reselect(); 
document.execCommand("bold"); 

this.getSelectionは(確かに少し失礼ではあるが)のように定義されます。

return window.getSelection ? window.getSelection() : 
(document.getSelection ? document.getSelection() : 
document.documentElement.getSelection()); 

私はあなたがのcon​​tentEditable、だけではなく、単純なテキストエリアを持っていると仮定します。

+0

申し訳ありませんまだ精巧ではありませんか? –

+0

私の答えを更新する – Psi

+0

返信いただきありがとうございます.contentEditableを使用する代わりに、代わりにiframeを使用しました。 –

関連する問題