Summernote - 插入文本并保持格式样式

时间:2017-08-01 19:57:16

标签: javascript jquery html css summernote

我目前正在尝试将下拉列表中的一串文本插入到Summernote文本编辑器中。但是,插入后,字符串会关闭所有格式标记,例如<'strong'>,<'p'>等等。

这是我插入字符串“AND”

后的HTML示例

鲍勃 喜欢冰淇淋和蛋糕。你呢?

<p><span style="font-size: 12px;"><b>Bob </b></span>AND <span style="font-size: 12px;">
<b>I&nbsp;</b></span><span style="font-size: 12px;">
<b>Loves Ice Cream and Cake. &nbsp;How about You?</b></span>

我需要能够阻止光标所在位置右侧和左侧的标签自动关闭和自动打开。我正在研究使用insertNode()和insertText()函数,但这两个函数最终都做了同样的事情。

有什么想法吗?谢谢!

编辑:这是在光标处插入的代码示例。我目前正在使用UppercaseButton扩展Summernote的按钮。

 var UppercaseButton = function (context) {
    var ui = $.summernote.ui;

    // create button
    var button = ui.button({
        contents: '<i class="fa fa-child"/> Uppercase',
        tooltip: 'Highlight a data attribute that you would like to make uppercase',
        click: function () {

            var range = $('#taBody').summernote('createRange');
            var newText = range.toString();
            console.log("newText: " + newText);
            console.log(range);
            context.invoke("editor.insertText", newText.toUpperCase());
        }
    });

    return button.render();   // return button as jquery object
}

1 个答案:

答案 0 :(得分:1)

这是我的方法。这应该获取光标所在的当前节点上下文,然后将所需的文本附加到该节点中

function insertAtCaret(text) {
        // deleteContents() will replace any text that is currently highlighted, if any
        let newRange = $("#taBody").summernote("getLastRange").deleteContents();

        // Insert the desired text inside the formatted tag of the first part of the highlighted text. That way the formatting applies to the inserted text
        newRange.sc.textContent = newRange.sc.textContent.substring(0, newRange.so) + text + newRange.sc.textContent.substring(newRange.so, newRange.sc.textContent.length);

        // Update the cursor position to just after the inserted text
        $("#taBody").summernote('setLastRange', $.summernote.range.create(/* start container */newRange.sc, /* start offset */ newRange.so + text.length).select());
    }

var UppercaseButton = function (context) {
    var ui = $.summernote.ui;

    // create button
    var button = ui.button({
        contents: '<i class="fa fa-child"/> Uppercase',
        tooltip: 'Highlight a data attribute that you would like to make uppercase',
        click: function () {
            insertAtCaret(newText.toUpperCase())
        }
    });

    return button.render();   // return button as jquery object
}
相关问题