【问题标题】:"execCommand" is not working with AngularJS“execCommand”不适用于 AngularJS
【发布时间】:2017-07-26 06:05:03
【问题描述】:

在创建我自己的迷你/简化文本编辑器的过程中,我遇到了使用 execCommand 的问题。我不知道为什么我的代码不起作用。我试图阻止 mousedown 事件并使用属性 "unsetectable="on" " 但它似乎仍然不起作用。

这是我的代码:

<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);
};

感谢任何帮助,谢谢!

【问题讨论】:

    标签: javascript html css angularjs execcommand


    【解决方案1】:

    execCommand 适用于当前选择。当您单击按钮时(事实上,在您的文本输入之外的任何地方),您取消选择当前选定的文本。此代码的目的是恢复您对 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,而不仅仅是一个简单的文本区域。

    【讨论】:

    • 对不起,我还是不太明白,您介意详细说明一下吗?
    • 更新我的答案
    • 感谢您的回复,我最终没有使用 contentEditable,而是使用了 iframe。
    • 我想这也可以,但仅使用 DIV 并使其成为 contentEditable 可以让您避免很多问题
    猜你喜欢
    • 1970-01-01
    • 2017-09-08
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多