LoginSignup
1
1

More than 3 years have passed since last update.

【javascript】 クリックイベント click  文字色変更 文字変更 innerHTML / classList / toggle

Posted at

【ゴール】

その① 文字色変化

画面収録 2020-07-07 18.26.59.mov.gif

その② 文字大きさ変化

画面収録 2020-07-07 18.29.16.mov.gif

【メリット】

■ javascript 理解度向上

【必要なもの】

■ HTML記述(ページ内容表示、文や、文字の表示)
■ CSS記述(ページの装飾、色変更等)
■ javascript記述(CSSでは実現できない動き、)

【コード】

その①文字色を変更

HTML

*id を付与。

index.html
<button id="button">文字色が変わるよ</button>
<h2 id="text">文字色が変わるよ</h2>

CSS

*クリックイベント後の処理

style.css
.font-color {
      color: pink;
    }

javascript

*button id がクリックされたらスコープ内を処理
toggleメソッドはクラスが存在していれば削除、なければ付与。超絶便利メソッド

script.js
const change = document.getElementById('button');

    change.addEventListener('click', () => {
     document.getElementById('text').classList.toggle('font-color');
    });

その② 文字を変更

HTML

*その①と同じ

index.html
<button id="button">文字が変わるよ</button>
<h2 id="text">文字色が変わるよ</h2>

CSS

今回は不要

javascript

*button id がクリックされたらスコープ内を処理
innerHtmlメソッドで文字を変更

script.js
const change = document.getElementById('button');

change.addEventListener('click', () => {
  document.getElementById('text').innerHTML = '<h2>変わったね</h2>';
});

【留意点】

■アロー関数を積極的に使う。推奨の為
■javascript取得するIDを間違えないようにする
■メソッド、基本的な物を覚える。

【合わせて読みたい】

■ 【Javascript】 メソッド まとめ 基礎基本コード メモ
https://qiita.com/tanaka-yu3/items/2438798d159fa402b1d5

■ 【アロー関数】 javascript () => {}  意味 一言で、 入門 
https://qiita.com/tanaka-yu3/items/e16d51280f647aa19a58

■ドットインストールカリキュラム javascript
https://dotinstall.com/lessons/basic_javascript_v4/50603

1
1
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
1