简体   繁体   English

“ execCommand”不适用于AngularJS

[英]“execCommand” is not working with AngularJS

In the process of creating my own mini/simplified text editor I ran into the issue of using execCommand. 在创建自己的小型/简化文本编辑器的过程中,我遇到了使用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. 我试图防止mousedown事件,并使用属性“ unsetectable =” on“”,但它似乎仍然无法正常工作。

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! 任何帮助表示赞赏,谢谢!

execCommand applies to the current selection. execCommand适用于当前选择。 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. 此代码的目的是还原对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). 如果当前未选择任何内容,那么也是如此,那么至少需要恢复插入符号的位置(这是一个长度为0个字符的选择)。

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): this.getSelection定义为(尽管公认有点粗鲁):

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

I assume you have a contentEditable, not just a simple textarea. 我假设您有一个contentEditable,而不仅仅是一个简单的textarea。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM