“execCommand” is not working with AngularJS

穿精又带淫゛_ 提交于 2019-12-31 05:08:05

问题


In the process of creating my own mini/simplified text editor I ran into the issue of using execCommand. I do not know why my code isn't working. I tried to prevent the mousedown event and used the attribute "unsetectable="on" " but it still doesn't seem to work.

Here's my code:

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

and

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

Any help is appreciated, thanks!


回答1:


execCommand applies to the current selection. When you click the button (in fact, anywhere outside your textinput), you unselect currently selected text. The purpose of this code is to restore the selection of your contentEditable. This is also true if there is currently nothing selected, then at least the caret position needs to be restored (which is a selection with a length of 0 characters).

First you need to store the selected ranges every time the user changed the selection (in my case, on keyup and mouseup):

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

Storing the selection ranges in an array for that purpose:

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

And before executing the command, restoring the selection:

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 is defined as (although admittedly a little bit rude):

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

I assume you have a contentEditable, not just a simple textarea.



来源:https://stackoverflow.com/questions/42624450/execcommand-is-not-working-with-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!