【予備】なまのJSのサンプル

なまのHTML,CSSのサンプル - 2017年度 新人研修を利用する。

+JS

クリックされたらタイトルのスタイルが適用されるようにする

  • idをつける
  • 要素を取得する
  • クリックイベントを定義する
  • リンクさせる
<!DOCTYPE html>
<html>
<head>
  <title>Sample</title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="sample.css">
</head>
<body>
  <h1 class="red" id="title">Hello</h1>
  <div>
    <p>This is a paragraph.</p>
  </div>
  <script src="sample.js"></script>
</body>
</html>
そのまま
(function(){
  var title = document.getElementById("title");

  title.addEventListener("click", function(){
    this.className = "blue";
  })

})();

+JS(切り替え)

クリックされるごとにスタイルが切り替わるようにする

  • CSSのスタイルを増やす
  • JSでクラス名の切り替えを行うように実装する(if文で分岐する)
そのまま
@charset 'UTF-8';

.red{
  color: red;
}

.blue{
  color: blue;
}
(function(){
  var title = document.getElementById("title");

  title.addEventListener("click", function(){
    if(this.className === "red"){
      this.className = "blue";
    }else if(this.className === "blue"){
      this.className = "red";
    }
  })

})();

ポイント

  • Javascriptは、ブラウザ上で実行されるプログラム言語である(PHPも)
  • WEBサイトに動きを付けている(クリックしたときの変化とか)はjavascriptで実現している