LoginSignup
0
2

More than 5 years have passed since last update.

クリック後に背景色、文字色を固定させる方法

Last updated at Posted at 2019-03-22

サイドバーのメニュー項目をクリック後、そのメニューの背景、文字色を固定させるのに躓いたのでメモ。
クリックしたメニュー項目にクラスを付与する考えで、実装できた。
例えば、、以下のrubyコードを

view/ruby.html.erb
<ul>
  <li><%= link_to 'ホーム', sample_path(sample_id) %></li>
</ul>

次のようにcurrent_page?メソッドを使って、書き換える。

view/ruby.html.erb
<ul>
  <li class="<%= 'sample_selecting' if current_page?(sample_path) %>"><%= link_to 'ホーム', sample_path(sample_id) %></li>
</ul>

current_page?(オプション)で指定したURLが、現在表示されていればtrueを返す。
現在sample_pathで表示されるページが開かれていれば、sample_selectingクラスを付与する。
このsample_selectingクラスを用いてcssを書けば、任意に特定のページにのみcssを反映させることができる。

custom.scss
.sidebar-menu > li.sample_selecting > a {
  color: #fff;
  background-color: #a0a0a0;
}

また、別の方法として、jQueryでクラスを付与することもできる。

//現在のページにsampleクラス付与
$(function(){
    $('.sidebar-menu li a').each(function(){
      var $href = $(this).attr('href');
      if(location.href.match($href)) {
        $(this).parent().addClass('sample');
      } else {
        $(this).parent().removeClass('sample');
      }
    });
  });

このとき、sidebar-menuはulタグのクラスを意味する。
変数hrefに特定のhref属性を代入。現在位置と合っていれば、sampleクラスを付与する。
このsampleクラスを用いて、cssを上記と同じような形で書けば、任意に特定のページにのみcssを反映させることができる。

0
2
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
2