0
2

More than 3 years have passed since last update.

jQuery基礎メモその2

Last updated at Posted at 2021-05-02

jQueryの準備

jQueryを使用するには、jQueryライブラリを読み込む必要がある。
jQueryの読込

index.html
<head>
  <script src="https://...jQuery.min.js"></script>
</head>

jQueryファイルの読込

タグの中に書くことはできるが、の直前に書くことで、WEBページの表示速度をより早めることができる。
index.html
<head> 
  ・・・
</head>

<body>
  ・・・
  <script src="script.js"></script>
</body>

bodyの終了タグの直前で読み込む。

jQueryの型
基本的な型

script.js
$(document).ready(function() {
  // この中にjQueryを書く
});

readyイベントの省略

script.js
$(function() {
  // この中にjQueryを書く
});

モーダルを表示

①モーダルをcssで非表示にする。

stylesheet.css
.login-modal-wrapper {
  display: none;
}

②ログインボタンにクリックイベントを設定
③clickイベントでモーダルを表示

$('#login-show').click(function() {
  $('#login-modal').fadeIn();
});

モーダルを隠す

閉じるボタンをクリックした時に、モーダルが閉じるようにする。

$('.close-modal').click(function() {
  $('#login-modal').fadeOut();
});

addClass・removeClass

addCrassメソッドを用いるとクラスを追加することができ、removeClassメソッドは反対にクラスを取り除くことができる。
addClass

$('.text-contents').addCrass('text-active');
                          // クラス名の前にドットは不要

removeClass

$('.text-contents').removeCrass('text-active');
                          // クラス名の前にドットは不要

this find 復習

thisに.マウスが乗っているlesson-hoverクラスが入ってfindでその中の.text-contentsを取得している。

$('.lesson-hover').hover(
    function() {
      $(this).find('.text-contents').addClass('text-active');
    },
    function() {
      $(this).find('.text-contents').removeClass('text-active');
    }
  );

hasClassメソッド

hasClassメソッドは、引数に指定したクラスを、オブジェクトが持っているか判定する時に使用する。
オブジェクトがそのクラスを持っていればtrue、持っていなければfalseを返す。

index.html
<div class="answer">・・・</div>

<div class="answer open">・・・</div>
script.js
$('.answer').hasClass('open');
// 結果: false

$('.answer open').hasClass('open');
// 結果: true

hasClassを用いたアコーディオン

script.js
if ($('.answer').hasClass('open')) {
  // openクラスを外す処理
  // 答えを隠す処理
} else {
  // openクラスをつける処理
  // 答えを表示する処理
script.js
$('.faq-list').click(function() {
  var $answer = $(this).find('.answer');
  if ($('.answer').hasClass('open')) {
    // answerにopenがある場合
    $answer.slideUp();
    $answer.removeClass('open')
  } else {
    // そうでない場合
    $answer.slideDown();
    $answer.addClass('open');
  }
});
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