【问题标题】:How do you replace the selection in medium-editor once it's lost?一旦丢失,如何替换中编辑器中的选择?
【发布时间】:2015-04-21 04:32:44
【问题描述】:

我正在尝试添加一个扩展来替换medium editor 中的现有链接功能,以允许我拥有一个文件列表和其他自定义位。问题是,一旦我显示模态并且您对其进行了一些更改,原始选择就会丢失。插入代码的示例,看起来与主脚本使用的 is this 相同,我仅对其进行编辑,以允许将选择对象作为第二个参数传入。

我所做的是单击按钮显示模态,设置一些输入,从基础中获取选择(与 window.getSelection() 相同)将其保存到扩展对象。然后单击模态中的保存按钮,我使用代码插入示例中的函数,传递选择。但是选择已经改变,所以我猜它是一个参考或每次都计算,所以我不确定如何使它工作。

这是代码,我把不相关的部分删掉了:

function MediumLink() {
    var self = this;
    this.parent = true;
    //...button init

    this.modalSubmit.addEventListener('click', function () {
        //the linkSel is no longer what I set it to here
        console.log(self.linkSel);
        self.insertHtmlAtCaret('<a href="' + self.modalHref.value + '">' + self.modalName.value + '</a>', self.linkSel);
        //... hide and reset modal
    }, false);

    //https://github.com/jillix/medium-editor-custom-html
    this.insertHtmlAtCaret = function (html, sel) {
        if (sel === undefined) {
            sel = window.getSelection();
        }
        //..rest of this function is unchanged from example
    };
}
MediumLink.prototype.onClick = function () {
    var sel = this.base.selection;

    if (sel.type === 'Range') { //trying to keep sel from changing since an empty selection would have a different type
        //... set inputs in modal based on the selection

        // sel is what I want at this point, what should be passed 
        console.log(sel);
        this.linkSel = sel;
    }
};

【问题讨论】:

    标签: javascript medium-editor


    【解决方案1】:

    好的,我认为问题归结为:

    如果在执行其他操作时丢失了选择,我们如何保存选择并重新生成它。

    我不知道它是否有内置的媒体编辑器功能,但我遇到了同样的问题,简短的回答是使用 Ranges 和 X-path 来保存选择。

    需要范围来突出显示选择和 X 路径,以便在所有节点和文本中准确选择。

    参考这个: How to calculate the XPath position of an element using Javascript?

    【讨论】:

      【解决方案2】:

      medium-editor 确实支持这个内置:

      MediumEditor.saveSelection()  // Stores the selection internally
      MediumEditor.restoreSelection() // Re-applies the stored selection
      

      在您的扩展程序中,由于您设置了this.parent = true,您可以访问this.base 来调用这些方法:

      this.base.saveSelection()
      this.base.restoreSelection()
      

      只要您在保存选择和恢复选择之间不对 html(或更具体地说是文本值本身)进行大的更改,这些内置帮助程序应该可以正常工作。

      【讨论】:

      • 这正是我所需要的。
      猜你喜欢
      • 2016-09-05
      • 2021-11-07
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 2015-10-04
      • 2020-11-16
      相关资源
      最近更新 更多