LoginSignup
1
0

More than 3 years have passed since last update.

jQueryの基礎

Last updated at Posted at 2019-07-10

jQueryの基礎

jQueryの導入~テスト実行

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Progate</title>
  <link rel="stylesheet" type="text/css" href="stylesheet.css">
  <!-- jQueryの読み込み -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
  <h1>Hello, World</h1>
  <!-- script.jsの読み込み -->
  <script src="script.js"></script>
</body>
</html>
sample.js
$(function() {
  //hideメソッドを用いて<h1>要素を隠す
  $('h1').hide();  
});

イベント

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Progate</title>
  <link rel="stylesheet" type="text/css" href="stylesheet.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
  <!-- このボタンを押すと -->
  <div class="btn" id="hide-text">説明を隠す</div>
  <!-- この表示が隠れる -->
  <h1 id="text">Hello, World!</h1>
  <script src="script.js"></script>
</body>
</html>
sample.js
$(function(){
  $('#hide-text').click(function(){
    $('#text').slideUp();
  });  
});

メソッドの例

$('セレクタ').hide();:要素を隠す
$('セレクタ').fadeOut(1000);:アニメーション付きで要素を隠す(1000ミリ秒)
$('セレクタ').slideUp(1000);:アニメーション付きで下から上に要素を隠す
$('セレクタ').show();:隠れた要素の表示(要素はCSSでdisplay:none;をしておく)
$('セレクタ').fadeIn(1000);:アニメーション付きで要素を表示
$('セレクタ').slideDown(1000);:アニメーション付きで下から上に要素を表示
$('セレクタ').css('color', 'red');:CSSを変更
$('セレクタ').text('テキスト');:テキストを変更
$('セレクタ').html('<a href="#">リンク</a>');:HTMLを変更

イベントの例

$('セレクタ').click(function(){クリックしたときの処理});
$('セレクタ').hover(function(){マウスをのせたとき},function(){外したとき});

おまけ:変数の宣言とメソッドチェーン

sample.js
//変数の宣言
var $title = $('#title');
$title.css('color', 'red');
$title.fadeOut(1000);

//メソッドチェーン(メソッドを繋げる)
$('#text').css('color', 'blue').fadeOut(1000);

//findメソッド(子孫要素から指定したセレクタをもつ要素を取得)
$('セレクタ').find('a').css('color', 'blue');
1
0
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
1
0