버튼을 클릭하면 랜덤으로 배경색이 바뀌는 기능
container
: backgroundcontenst
안에 배경색을 나타내는 p
와 클릭 버튼 button
생성...
<body>
<div class="container">
<div class="contents">
<p>Background Color: <span class="color">mint</span></p>
<button class="button">Click Me!</button>
</div>
</div>
</body>
...
querySelector
를 이용하여 특정 요소를 찾는다.colors
에 배열 형태로 집어 넣는다.handleClick
: 버튼이 클릭되었을 때 실행할 동작 정의randomNumber
: colors 경우만큼의 랜덤 숫자background.style.backgroundColor
: colors
의 color
로 색상 변경colorText.style.color
: colors
의 color
로 텍스트 색상 변경colorText.textContent
: colors
의 name
으로 텍스트 변경$(document).ready(function () {
$(function () {
const background = document.querySelector(".container");
const colorText = document.querySelector(".color");
const btn = document.querySelector("button");
const colors = [
{ id: 1, name: "red", color: "#ff0000" },
{ id: 2, name: "orange", color: "#FFA500" },
{ id: 3, name: "yellow", color: "#ffff00" },
{ id: 4, name: "lime green", color: "#32cd32" },
{ id: 5, name: "skyblue", color: "#87CEEB" },
];
const handleClick = () => {
const randomNumber = Math.floor(Math.random() * colors.length);
background.style.backgroundColor = colors[randomNumber].color;
colorText.style.color = colors[randomNumber].color;
colorText.textContent = colors[randomNumber].name;
};
btn.addEventListener("click", handleClick);
});
});
특정 name
,id
,class
를 제한하지 않고 css선택자를 사용하여 요소를 찾는다.
- querySelector(#id) => id 값 id를 가진 요소를 찾는다.
- querySelector(.class) => class 값 class를 가진 요소를 찾는다.
괄호 안에 id
값을 집어넣어 사용한다.
<button id="test-btn">바뀌기 전 text</button>
test-btn
이라는 id
값을 가진 버튼 요소를 찾고, 해당 버튼을 click
했을 때, 텍스트를 변경하는 코드const mode = document.getElementById("test-btn");
mode.addEventListener("click", function() {
if (mode.innerText === "바뀌기 전 text") {
mode.innerText = "바뀐 text!";
} else {
mode.innerText = "바뀌기 전 text";
}
});
body 요소의 배경색을 설정하거나 가져온다.
document.body.style.backgroundColor = 'lightblue';
소수 부분을 버림하여 정수 부분만 남긴다.
let number = 5.78;
console.log(Math.floor(number)); // 5
0 이상 1 미만의 난수를 반환한다.
// 0부터 5까지의 랜덤 숫자를 얻기
const randomNumber = Math.floor(Math.random() * 6);
// 1부터 5까지의 랜덤 숫자를 얻기
const randomNumber = Math.floor(Math.random() * 5) + 1;