프로그램 언어/JavaScript Dom Part

[J.S_DOM] 4-1. 스타일 변경 예제 모음

알케이88 2025. 8. 8. 21:52

 

🧪 예제 1. .style로 배경색 바꾸기

<div id="box1" style="width: 100px; height: 100px; background-color: gray;"></div>
<button onclick="changeColor()">색 바꾸기</button>

<script>
  function changeColor() {
    const box = document.getElementById("box1");
    box.style.backgroundColor = "tomato";
  }
</script>

 

✅ 설명 

버튼 클릭시 박스의 배경색이 gray에서 tomato 로 변경

box.style.backgroundColor를 사용하여 직접 인라인 스타일을 수정

 

🧪 예제 2. .style로 여러 스타일 적용하기

<p id="text1">텍스트입니다.</p>
<button onclick="resizeText()">크기/색 변경</button>

<script>
  function resizeText() {
    const txt = document.getElementById("text1");
    txt.style.fontSize = "24px";
    txt.style.color = "blue";
    txt.style.fontWeight = "bold";
  }
</script>

 

✅ 설명 

버튼 클릭 시 글자 크기\, 색상, 굵기를 .style로 직접 지정

 

🧪 예제 3. .classList.add()로 클래스 적용하기

<style>
  .rounded {
    border-radius: 20px;
    background-color: skyblue;
  }
</style>

<div id="box2" style="width: 100px; height: 100px; background: gray;"></div>
<button onclick="applyClass()">클래스 적용</button>

<script>
  function applyClass() {
    document.getElementById("box2").classList.add("rounded");
  }
</script>

 

✅ 설명 

클릭 시 .rounded 클래스가 추가 되어 둥근 모서리와 배경색이 변경

 

🧪 예제 4. .classList.toggle()로 클래스 켜고 끄기

<style>
  .highlight {
    background-color: yellow;
  }
</style>

<p id="text2">이 문장을 클릭하면 강조됩니다.</p>

<script>
  const txt = document.getElementById("text2");
  txt.addEventListener("click", () => {
    txt.classList.toggle("highlight");
  });
</script>

 

✅ 설명 

클릭 마다 .highlight 클래스가 추가/제거되며 스타일이 변함

 

🧪 예제 5. .classList.replace()로 클래스 교체하기

<style>
  .on { background-color: green; }
  .off { background-color: red; }
</style>

<div id="box3" class="off" style="width: 100px; height: 100px;"></div>
<button onclick="switchState()">상태 전환</button>

<script>
  function switchState() {
    const box = document.getElementById("box3");
    if (box.classList.contains("off")) {
      box.classList.replace("off", "on");
    } else {
      box.classList.replace("on", "off");
    }
  }
</script>

 

✅ 설명 

클릭 시 .on과 .off 클래스가 서로 교체 되며 색상 전환

 

🧪 예제 6. .classList.contains()로 상태 확인

<style>
  .active { background-color: lightgreen; }
</style>

<div id="btnBox">활성 상태 확인</div>
<button onclick="checkActive()">상태 확인</button>

<script>
  function checkActive() {
    const el = document.getElementById("btnBox");
    if (el.classList.contains("active")) {
      alert("이미 활성화된 상태입니다.");
    } else {
      el.classList.add("active");
    }
  }
</script>

 

✅ 설명 

클래스가 있는지 체크, 없으면 추가, 있으면 알람창 표시