일단 해보는 코딩/Java Script

[Java Script] JS로 HTML 제어해보기 (간단 예제)

eun_zoey2 2023. 4. 30. 19:57
728x90

1. 기본 구조 만들기 

 

<!DOCTYPE html>
<html lang="ko">
<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>Document</title>
  <link rel="stylesheet" href="./main.css">
  <script defer src="./main.js"></script>
</head>
<body>
  <div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
</div>
<div class="btn">클릭하세요~</div>
</body>
</html>
.btn {
  width: 150px;
  height: 40px;
  background-color: royalblue;
  border-radius: 10px;
  color: aliceblue;
  display: flex;  
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: 0,5s;
}
.btn:hover {
  background-color: blue;
}
.btn span {
  font-size: 22px;
  font-weight: 700;
}

 

2. Java Script 이용해서 제어하기

 

 

const itemEls = document.querySelectorAll('.item') 
const btnEl = document.querySelector('.btn')
const colors = ['royalblue','orange','tomato']

btnEl.addEventListener('click', function() {
    itemEls.forEach(function (itemEl, index) {
      console.log(index, itemEl)
        itemEl.style.backgroundColor = colors[2]
    })
  }) //클릭이벤트

 

 

const itemEls = document.querySelectorAll('.item') 
const btnEl = document.querySelector('.btn')
const colors = ['royalblue','orange','tomato']

btnEl.addEventListener('click', function() {
    itemEls.forEach(function (itemEl, index) {
      console.log(index, itemEl)
        itemEl.style.backgroundColor = colors[index]
    })
  }) //클릭이벤트
 

const itemEls = document.querySelectorAll('.item') 
const btnEl = document.querySelector('.btn')
const colors = ['royalblue','orange','tomato']

btnEl.addEventListener('click', function() {
    itemEls.forEach(function (itemEl, index) { 
    //els.forEach(함수)-찾은 HTML요소의 개수만큼 함수를 실행
      console.log(index, itemEl)
        itemEl.style.backgroundColor = colors[index]
    })
    btnEl.innerHTML = "클릭했어요!"
  }) //클릭이벤트