2017-03-06 66 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。 –