LoginSignup
0
1

More than 3 years have passed since last update.

サイドナビのリンクを開くと、そのナビだけ色が変わる。

Last updated at Posted at 2020-02-19

サイドナビの色を変化させる。

サイドナビでナビをクリックすると、ナビの色が変化して、今開いているナビがわかるようにする。

処理の作成

application_helper.rb

module ApplicationHelper
  def active_class(link_path) # (link_path)にrake routeの_pathを記載する。
    "active" if request.fullpath == link_path
    # もしも開いたページのURL(request.fullpath)が、指定の(link_path)と同じ場合、"active"になる。
  end
end

classを付与させる

html.haml
%li{class: "#{active_class(users_path)}"}
// application_helper.rbで作成した処理により、activeが付与する。
// 指定したリンク以外では、activeは付与しない。
// この例の場合、users_pathのため、users#showのページを開くとナビの色が変化する

これで、完成

おまけにHTMLとSCSS

haml

%ul.list-group
  %li{class: "list-group-item #{active_class(user_path)}"}
    = link_to "", user_path, class: "nav-list__link"
    %p マイページ
  %li{class: "list-group-item #{active_class(new_product_path)}"}
    = link_to "", new_product_path, class: "nav-list__link"
    %p コンテンツ
scss
.list-group{
  width: 250px;
  &-item{
    position: relative;
    /* li全体をaタグにする。 */
    a{
      text-decoration: none;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    &::after{
        /* 矢印 */
        position: absolute;
        top: 40%;
        right: 13px;
        content: '';
        width: 8px;
        height: 8px;
        border-top: 2px solid #ccc;
        border-right: 2px solid #ccc;
        -webkit-transform: rotate( -50%);
        -webkit-transform: rotate( -50%);
        transform: rotate(45deg);
        transition: all .2s;
      }
      &:hover{
        background: #fafafa;
        &::after{
          right: 9px;
          border-color: #333;
        }
      }
    /* 今開いているページのナビは、色を変化 */
    &.active{
      background: #EEEEEE;
      font-weight: bold;
      border-color: #3333;
      color: #212529;
      &::after{
        border-top: 2px solid #333333;
        border-right: 2px solid #333333;
      }
      .nav-list{
        &__link{
          text-decoration: none;
          font-weight: bold;
          color: #333333;
          font-size: 14px;
        }
      }
      &:hover{
        background: #EEEEEE;
      }
    }
  }
}
0
1
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
1