スタイルを変更する

css

jQueryObject.css('プロパティ','値');

《index.html》

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>jQuery 〜</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
</body>
</html>


《script.js》

$(function(){
  $('#div1').css('border', '3px solid red'); //3pxの赤い線がつく
  $('#div2').css('background', 'pink'); //背景色がピンクになる
  $('#div3').css('background', 'green'); //背景色が緑になる
  $('#div3').css('opacity', 0.5); //半透明になる
});


スタイル変更の優先順位
<style>
  #somediv p{ color:red; }
  .somediv p{ color:blue; }
</style>
<div id="somediv" class="somediv">
  <p>赤か青か</p>
</div>
スタイルをまとめて指定
$('#somediv').css({
  color: 'red',
  display: 'block',
  top: 120,
  left:100
});
  • css()のなか全体を{}で囲み、プロパティと値のペアを複数「,」で区切っていれます
  • {}で囲まれたもののことをオブジェクトといい、一連の値をまとめて渡すことができます

show/hide

  jQueryObject.show();
  jQueryObject.hide();


《index.html》

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>jQuery 〜</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div id="div1">最初は非表示になっているdiv</div>
<div id="div2">最初は表示されているdiv</div>
</body>
</html>


《style.css

  #div1{ display: none;}
  #div2{ display: block;}


《script.js》

$(function(){
  $('#div1').show();
  $('#div2').hide();
});


  • 「#div1」は、「display: none」で非表示になっていますが、ページの読み込みが完了した時点で「show()」としているため、ブラウザでは表示されています
  • 「#div2」は、「display: block」で表示になっていますが、ページの読み込みが完了した時点で「hide()」としているため、ブラウザでは表示されません


CSSメソッドの場合

  jQueryObject.css('display', 'block'); //show()とほぼ同じ
  jQueryObject.css('display', 'none'); //hide()とほぼ同じ
アニメーションする「show/hide」
$(function(){
  $('#div1').show(500); //0.5秒で表示させるアニメーション
  $('#div2').hide(500); //0.5秒で非表示にするアニメーション
});

width/height

  jQueryObject.width( 幅 );
  jQueryObject.height( 高さ );


《index.html》

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>jQuery 〜</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div id="div1">width</div>
<div id="div2">height</div>
</body>
</html>


《style.css

div {
  background: pink;
  margin: 10px;
}


《script.js》

$(function(){
  $('#div1').width(300);
  $('#div2').height(300);
});




CSSメソッドの場合

$(function(){
  $('#div1').css('width', 300);
  $('#div2').css('height', 300);
});