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());
私はあなたがのcontentEditable、だけではなく、単純なテキストエリアを持っていると仮定します。
出典
2017-03-06 11:44:47
Psi
申し訳ありませんまだ精巧ではありませんか? –
私の答えを更新する – Psi
返信いただきありがとうございます.contentEditableを使用する代わりに、代わりにiframeを使用しました。 –