0
0

More than 1 year has passed since last update.

TinyMCE5で画像にクラス付与、親要素(figureタグなど)をつける方法

Last updated at Posted at 2022-02-22

デモ

See the Pen Wrap img by figure tag by tinyMCE 5 by qwe001 (@qwe001) on CodePen.

実装

function initTinyMCE(selector)
{
  var options = {
    selector : selector,
    language : 'ja',
    height : 500,
    plugins : 'image code',
    toolbar1 : 'image custom-button-img code',
    image_class_list : [
      { title : 'None', value : '' },
      { title : 'Some class', value : 'img_class_name_0' }
    ],
    setup: function(editor){
      editor.ui.registry.addButton("custom-button-img", {
        tooltip: "new class",
        icon: "edit-block", // look editor-icon-identifiers page
        onAction: function(api) {
          var $ = tinymce.dom.DomQuery;
          var elem = tinymce.activeEditor.selection.getNode();

          var isImg = $(elem).is('img');
          var hasClass = $(elem).hasClass('has-wrapper');

          if(isImg){
            if(hasClass){
              $(elem).removeClass('has-wrapper');
              $(elem).unwrap('<div class="figure-wrapper"></div>');
              $(elem).unwrap('<figure class="img-wrapper"></figure>');
            }
            else {
              $(elem).addClass('has-wrapper');
              $(elem).wrap('<div class="figure-wrapper"></div>');
              $(elem).wrap('<figure class="img-wrapper"></figure>');
            }
          }
        }
      });
    },
  };

  tinymce.init(options);
}

画像をアップロードした後、画像を選択した状態でカスタムボタンを押すと、以下のようにimgタグをdiv>figure>imgのような形でラッピングして出力します

もう一度ボタンを押せば、ラッピング要素を除去します

<div class="figure-wrapper">
<figure class="img-wrapper">
<img class="has-wrapper" src="/uploads/22b918d29723f2abca34fb6830907903.png" alt="" width="539" height="572" /></figure>
</div>

もっと良い実装方法知ってるヤツ、至急コメントくれや

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0