자바스크립트예제 counter

5o_hyun·2022년 10월 28일
0
increase 누르면 증가, decrease 누르면 감소, reset 누르면 초기화 되는 카운터를 만들어보았다. 또한 양수면 초록색, 음수면 빨간색으로 표시되게 했다.

깃허브소스클릭

html

<div class="container">
  <h1>counter</h1>
  <p class="count">0</p>
  <div class="btnGroup">
    <button class="btn decrease">decrease</button>
    <button class="btn reset">reset</button>
    <button class="btn increase">increase</button>
  </div>
</div>

css

body {
  width: 100%;
  height: 100%;
  background-color: aliceblue;
  display: flex;
  justify-content: center;
  align-items: center;
}
.container {
  width: 400px;
  height: 300px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
h1 {
  text-transform: uppercase;
}
p {
  font-size: 60px;
  font-weight: bold;
}
.btnGroup {
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 5px;
}
button {
  flex: 1;
  height: 40px;
  background-color: transparent;
  border: 1px solid #000;
  border-radius: 10px;
  cursor: pointer;
}
button:hover,
button:active {
  background-color: #333;
  color: #fff;
}

js

$(document).ready(function () {
  $(function () {
    const count = document.querySelector(".count");
    const decrease = document.querySelector(".decrease");
    const reset = document.querySelector(".reset");
    const increase = document.querySelector(".increase");

    decrease.addEventListener("click", function () {
      let num = count.textContent;
      num = Number(num - 1);
      count.textContent = num;
      colorChange();
    });
    increase.addEventListener("click", function () {
      let num = count.textContent;
      num = Number(num) + 1;
      count.textContent = num;
      colorChange();
    });
    reset.addEventListener("click", function () {
      count.textContent = 0;
      colorChange();
    });

    function colorChange() {
      if (Number(count.textContent) < 0) {
        count.style.color = "red";
      } else if (Number(count.textContent) > 0) {
        count.style.color = "green";
      } else if (Number(count.textContent) == 0) {
        count.style.color = "#000";
      }
    }
  });
});
profile
학생 점심 좀 차려

0개의 댓글