LoginSignup
8
4

More than 5 years have passed since last update.

Bootstrapのpopoverに指定divのhtmlを表示する

Last updated at Posted at 2017-11-26

Bootstrapのpopoverに表示するhtml記述を別個所に切り出したい

Bootstrapのpopoverで本文として表示する内容は「data-html="true"」とすることで「data-content」にhtmlで記述することができます。

index.cshtml
<span class="fa fa-question-circle"
      aria-hidden="true"
      data-toggle="popover" 
      data-placement="top"
      data-container="body"
      data-html="true"
      data-content="ほげほげ<br />ふがふが<span class=""fa fa-warning"" aria-hidden = ""true""></span>
 "

data-contentに記述する内容が短い場合は直接記述でも良いのですが、少し込み入ったhtmlを表示したい場合は
エスケープ記述等が煩雑となるため別個所に記述して読み込むようにします。(別ファイル化までは行いません)

環境

ASP.NET MVC6(C#) + Bootstrap(ver3.37)

popover表示設定jsの変更

site.js

    // ポップオーバーの有効化

    //$('[data-toggle="popover"]').popover();

    $("[data-toggle=popover]").popover({
        html: true,
        container: 'body',
        content: function () {
            var contentDivId = '#' + $(this).data('content_div_id');
            return $(contentDivId).html();
        },
        trigger: 'hover'
    });
  • htmlの使用(html: true),
  • 表示領域の大型化(container: 'body')
  • ホバーによる表示(trigger: 'hover')

と共通設定を集約、合わせて

content: function () {
 var contentDivId = '#' + $(this).data('content_div_id');
 return $(contentDivId).html();
},

のようにcontentに「data-content_div_id」で指定したId要素のhtmlを適用する設定を行いました。

cshtmlの変更

index.cshtml(popover個所)
<span class="fa fa-question-circle"
      aria-hidden="true"
      data-toggle="popover" 
      data-placement="top"
      data-content_div_id="hogehoge_content">
</span>

data-contentの記述を書かない代わりにdata-content_div_idに読み込み対象となるhtml記述箇所のid(hogehoge_content)を指定します。

index.cshtml(popover表示htmlを記述する箇所)
<!--ポップオーバー内表示用html-->
<div id="hogehoge_content" class="hide">
  ほげほげ<br />
  ふがふが<span class="fa fa-warning" aria-hidden="true"></span>
</div>

ポップオーバー内表示用html記述箇所を囲むdiv等の要素に上記で指定したid(hogehoge_content)、ポップオーバー内表示以外では非表示とするためclass="hide"を設定します。

8
4
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
8
4