2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jQueryを使ったスライダーメニューの実装

Posted at

はじめに

ヘッダーバーに、マウスオーバーした際に出現するスライドメニューを作ります。
(自分自身の備忘録として記します)

完成イメージ

dropDownMenu.gif

環境

MacOS 10.15.7
ruby 2.6.5
Ruby on Rails 6.0.0

前提条件

jQueryの導入が完了済みであること。

作業していきましょう!

①htmlを作成

html.erb
<%# ログインユーザーの名前・アイコン表示 %>
      <div class="loginUser">
        <div class="loginUserInfo">
          <div class="loginUserInfo__Avatar">
            <%= image_tag current_user.image.url, class: "loginUserInfo__Avatar--image" %>
          </div>
          <span class=loginUserName>
            <%= current_user.name %>
          </span>
          <i class="fas fa-caret-down"></i>
        </div>
        <%# スライドメニューバー(マウスオーバー時出現) %>
        <ul class="dropDownMenu">
          <li>
            <i class="fas fa-user"></i>
            <%= link_to "マイページ", "/users/#{current_user.id}", class:"loginMenu" %>
          </li>
          <li>
            <i class="fas fa-plus-square"></i>
            <%= link_to  "投稿する", new_post_path, class: "loginMenu" %>
          </li>
          <li>
            <i class="fas fa-sign-out-alt"></i>
            <%= link_to "ログアウト", destroy_user_session_path, class:"loginMenu", method: :delete %>
          </li>
        </ul>
      </div>

scssは次の通りです。

scss
// ログインユーザーのアイコン・名前
.loginUser {
  width: 200px;
  height: 50px;
  margin-left: 5%;
}
.loginUserInfo {
  display: flex;
  align-items: center;
  &__Avatar {
    width: 40px;
    height: 40px;
    &--image {
      height: 100%;
      width: 100%;
      border-radius: 50%;
    }
  }
}
.loginUserName {
  font-size: 0.7em;
  margin-right: 5px;
}

.dropDownMenu {
  width: 200px;
  display: none;
  margin-left: -5px;
  margin-top: 5px;
  padding: 0;
  text-align: center;
  background-color: rgba($color: #222222, $alpha: 0.95);
}
.dropDownMenu li {
  cursor: pointer;
  width: 100%;
  padding: 2vh 0;
}
.dropDownMenu li a:hover {
  text-decoration: none;
  color: #00bfff;
}

以上です。

②jsファイルにjQueryにて処理を記述

usermenu.jsというファイルを新規作成して、そこにスライダー処理の記述を行います。

usermenu.js
$(function() {
  // loginUser上にオンマウスした時に発動するイベント
  $(".loginUser").hover(function(){
    //slideToggleメソッドを使ってスライドメニューを表示させる。
    $(this).children(".dropDownMenu").stop().slideToggle();
  });
});

hoverメソッドを使って、loginUserクラス上にマウスが乗った時に、slideToggleメソッドを使って、
スライドメニュー(.dropDownMenu)を呼び出します。

stopメソッドはhoverするたびに同じ処理が発動しないようにするための記述となります。

以上となります!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?