0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

8.2 基本構文(変数とは、if文, switch文, for文, while文について)補足

Last updated at Posted at 2022-09-14

基本構文を使用して表示を制御してみよう

if文、for文

if文やfor文を使用して、ボタンを押下することで表示、非表示の切り替わる文字列を実装していきます。

index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>8.3</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <p>visibilityプロパティを使用して表示を切り替える</p>
    <p id="test1">あいうえお</p>
    <button onClick="hide()">非表示にする</button>
    <button onClick="show()">表示する</button>
    <button onClick="showHide()">表示/非表示</button>

    <p>displayプロパティを使用して表示を切り替える</p>
    <p id="test2">かきくけこ</p>
    <button onClick="displayHide()">非表示にする</button>
    <button onClick="displayShow()">表示する</button>
    <button onClick="displayShowHide()">表示/非表示</button>

    <p>渡された引数の数分の数値を表示</p>
    <p id="test3"></p>
    <button onClick="repetitionShowNum(5)">数値を表示</button>
  </body>
  <script src="script.js"></script>
</html>
script.js
/** visibilityを使用して非表示 */
const hide = () => {
  let element = document.getElementById("test1");
  element.style.visibility = "hidden";
};

/** visibilityを使用して表示 */
const show = () => {
  let element = document.getElementById("test1");
  element.style.visibility = "visible";
};

/** visibilityを使用して表示/非表示 */
const showHide = () => {
  let element = document.getElementById("test1");
  if (element.style.visibility === "hidden") {
    element.style.visibility = "visible";
  } else {
    element.style.visibility = "hidden";
  }
};

/** displayを使用して非表示 */
const displayHide = () => {
  let element = document.getElementById("test2");
  element.style.display = "none";
};
/** displayを使用して表示 */
const displayShow = () => {
  let element = document.getElementById("test2");
  element.style.display = "block";
};

/** displayを使用して表示/非表示 */
const displayShowHide = () => {
  let element = document.getElementById("test2");
  if (element.style.display === "none") {
    element.style.display = "block";
  } else {
    element.style.display = "none";
  }
};

/** 渡された引数の数分の数値を表示 */
const repetitionShowNum = (num) => {
  let element = document.getElementById("test3");
  for (let i = 1; i <= num; i++) {
    element.textContent += i;
  }
};

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?