execCommand適用於當前選擇。當你點擊按鈕(實際上,你的textinput以外的任何地方),你取消選擇當前選定的文本。此代碼的目的是恢復您的contentEditable的選擇。如果當前沒有選擇任何內容,則也是如此,則至少需要還原插入位置(這是長度爲0個字符的選擇)。
首先,你需要每一個用戶改變了選擇時間存儲選擇的範圍(在我的情況下,KEYUP和MouseUp):
this.textInput.onmouseup = this.textInput.onkeyup = function(){
this.updateSelection();
this.updateStatus();
}.bind(this);
存儲的選擇範圍中爲該目的數組:
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。 –