Javascript/GMA(2302~)
230530 자바스크립트 예제 - 버튼클릭시 색상변경 (*setProperty / Math.random / hsl)
hyerin1201
2023. 5. 30. 16:15
- 색상변경 버튼 클릭시 배경 컬러 변경
html
<body class="chapter-2">
<main>
<!-- 버튼 -->
<button class="button">색상 변경</button>
<!-- 그라데이션이 표시되는 직사각형 -->
<div class="rectangle"></div>
</main>
</body>
Css
.button {
margin-bottom: 10px;
background-color: rgba(0, 0, 0, 0.1);
padding: 10px;
color: #fff;
cursor: pointer;
width: 120px;
}
.rectangle {
width: 100%;
height: calc(100% - 50px);
--start: hsl(0, 100%, 50%);
--end: hsl(322, 100%, 50%);
background-image: linear-gradient(-135deg, var(--start), var(--end));
}
Javascript
//색상변경되는 공간 지정
//버튼 정의 및 클릭이벤트 부여->함수실행
//색조 : hue, 채도: saturation, 명도: lightness (최대값 360)
//setProperty 자바스크립트에서 스타일을 변경하고자 할때
const rectangle = document.querySelector(".rectangle");
document.querySelector(".button").addEventListener("click", changeColor);
function changeColor() {
const randomHue = Math.ceil(Math.random() * 360);
const randomStart = `hsl(${randomHue}, 100%, 50%)`;
const randomEnd = `hsl(${randomHue + 40}, 100%, 50%)`;
rectangle.style.setProperty("--start", randomStart);
rectangle.style.setProperty("--end", randomEnd);
}