2017-03-06 102 views
0

在創建我自己的迷你/簡化文本編輯器的過程中,遇到了使用execCommand的問題。我不知道爲什麼我的代碼無法正常工作。我試圖阻止mousedown事件,並在「」上使用屬性「unsetectable =」,但它似乎仍然不起作用。「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適用於當前選擇。當你點擊按鈕(實際上,你的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,不僅僅是一個簡單的文本區域。

+0

對不起,我還是不太明白,如果你能介意說明一下嗎? –

+0

更新我的答案 – Psi

+0

感謝您的回覆,而不是使用contentEditable,而是最終使用了iframe。 –