ピスタチオを食べながらrailsを楽しむ

ピスタチオ大好きな著者のrailsを使ったツール作成の日記です。

bootstrapでtooltipを使う

tooltipとは

特定の要素に吹き出し型のテキストを表示出来る。

# app/assets/javascripts/tooltips.js.coffee
jQuery ->
  $(".tooltip").tooltip()
# app/views/tooltips/index.html.erb
<div>
  <span class="tooltip">これ</span>がツールチップです。
</div>

この状態でこれにカーソルを合わせるとtooltipが表示される。

cssを弄る

デフォルトは以下の状態になっている。

.tooltip{
    position:absolute;
    z-index:1020;
    display:block;
    visibility:visible;
    padding:5px;
    font-size:11px;
    opacity:0;
    filter:alpha(opacity=0);
}
.tooltip.in{
    opacity:.8;
    filter:alpha(opacity=80);
}
.tooltip.top{
    margin-top:-2px;
}
.tooltip.right{
    margin-left:2px;
}
.tooltip.bottom{
    margin-top:2px;
}
.tooltip.left{
    margin-left:-2px;
}
.tooltip.top .tooltip-arrow{
    bottom:0;
    left:50%;
    margin-left:-5px;
    border-left:5px solid transparent;
    border-right:5px solid transparent;
    border-top:5px solid #000;
}
.tooltip.left .tooltip-arrow{
    top:50%;
    right:0;
    margin-top:-5px;
    border-top:5px solid transparent;
    border-bottom:5px solid transparent;
    border-left:5px solid #000;
}
.tooltip.bottom .tooltip-arrow{
    top:0;
    left:50%;
    margin-left:-5px;
    border-left:5px solid transparent;
    border-right:5px solid transparent;
    border-bottom:5px solid #000;
}
.tooltip.right .tooltip-arrow{
    top:50%;
    left:0;
    margin-top:-5px;
    border-top:5px solid transparent;
    border-bottom:5px solid transparent;
    border-right:5px solid #000;
}
.tooltip-inner{
    max-width:200px;
    padding:3px 8px;
    color:#fff;
    text-align:center;
    text-decoration:none;
    background-color:#000;
    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    border-radius:4px;
}
.tooltip-arrow{
    position:absolute;
    width:0;
    height:0;
}

これらを弄ることでcssを変更出来る。
例えばtooltip.topのbackgroundの色を変える。

# app/assets/stylesheets/tooltips.css.scss
.tooltip.top {
  .tooltip-inner {
    background: #ddd;
    color: #111;
  }
  .tooltip-arrow {
    bottom; 0;
    left: 50%;
    margin-left: -5px;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #ddd;
  }
}

他、jsでオプションを指定することも出来る。
例えば表示の際のアニメーションをオフにする。

# app/assets/javascripts/tooltips.js.coffee
jQuery ->
  $(".tooltip").tooltip({animation: false})