“execCommand” is not working with AngularJS

余生颓废 提交于 2019-12-02 07:43:39

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.

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