Froala add custom pre code button

纵然是瞬间 提交于 2020-01-05 06:07:07

问题


I'm trying to create a code button with the Froala editor which can basicly do the same thing as here on SO by pressing CNTRL+K. Now I think I have two choices.

The first one is to edit the froala-editor.js file, because Froala already has a 'code' button which only adds the <pre> tags. If I could somehow get it to also add the <code> tag, problem solved. Unfortunately I didn't get this to work.

The second option is to create a custom button, so far I have this piece of code:

$('textarea[name="description"]').editable({
    //Settings here
    customButtons: {
        insertCode: {
            title: 'Insert code',
            icon: {
                type: 'font',
                value: 'fa fa-code'
            },
            callback: function() {
                this.saveSelection();

                if (!this.selectionInEditor()) {
                    this.$element.focus(); // Focus on editor if it's not.
                }

                var html = '<pre><code>' + this.text() + ' </code></pre>';

                this.restoreSelection();
                this.insertHTML(html);
                this.saveUndoStep();
            }
        }
    }
});

It works somehow, but it's buggy and produces strange html like so:

<p><code></code>
  <pre><code>asdasdasdasd
</code></pre>
</p>

Any help with getting this done for either option one or two would be greatly appreciated.


回答1:


If you upgrade to version 1.2.3 that is available on Github your code should work https://github.com/froala/wysiwyg-editor. It's not necessary to save/restore selection.


LATER EDIT: Here is a jsFiddle for it http://jsfiddle.net/9pmmg1jk/.

customButtons: {
  insertCode: {
    title: 'Insert code',
      icon: {
        type: 'font',
          value: 'fa fa-code'
      },
        callback: function() {
          if (!this.selectionInEditor()) {
            this.$element.focus(); // Focus on editor if it's not.
          }

          var html = '<code>' + (this.text() || '&#8203;') + '<span class="f-marker" data-type="false" data-id="0" data-fr-verified="true"></span><span class="f-marker" data-type="true" data-id="0" data-fr-verified="true"></span></code>';

          this.insertHTML(html);
          this.restoreSelectionByMarkers();
          this.saveUndoStep();
        }
  }
}


来源:https://stackoverflow.com/questions/26392277/froala-add-custom-pre-code-button

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