Muscardinus
Rating UI 본문
728x90
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Rating UI</title>
<link rel="stylesheet" href="index.scss" />
</head>
<body>
<div id="app">
<span class="score">0</span>
<div class="stars"></div>
<button class="reset"></button>
</div>
<script src="index.js"></script>
</body>
</html>
// 필요한 Dom Selector
const $stars = document.querySelector('.stars')
const $score = document.querySelector('.score')
const $reset = document.querySelector('.reset')
// 별의 갯수 = Score
const MAX_SCORE = 5
// 별의 현재 점수 상태
const state = {
score: 0,
}
// 별의 갯수만큼 별 DOM 추가 (별은 empty, half, full 클래스를 가질수 있음)
Array(MAX_SCORE)
.fill()
.forEach(() => {
const star = document.createElement('div')
star.className = 'star empty'
$stars.appendChild(star)
})
// Write your solution here.
const setDisplayScore = (score) => {
const starList = [...$stars.children];
starList.forEach((star, i) => {
if (score > i) {
if (score - i === 0.5) star.className = "star half";
else star.className = "star full";
} else {
star.className = "star empty";
}
});
}
const setScore = (score) => {
setDisplayScore(score);
state.score = score;
$score.textContent = score;
}
const calculateScore = (e) => {
const { width, left } = e.currentTarget.getBoundingClientRect();
console.log({width,left});
const x = e.clientX - left;
const scale = width / MAX_SCORE / 2;
return Math.floor(x / scale + 1) / 2;
}
$stars.addEventListener("click", (e) => {
setScore(calculateScore(e));
setDisplayScore(calculateScore(e));
});
$stars.addEventListener("mousemove", (e) => {
const score = calculateScore(e);
$score.textContent = score;
setDisplayScore(score);
});
$stars.addEventListener("mouseleave", (e) => {
setScore(state.score);
});
$reset.addEventListener("click", (e) => {
setScore(0);
})
728x90
'FrontEnd > Basic Skills' 카테고리의 다른 글
Scroll Indicator (0) | 2022.03.20 |
---|---|
Modal Window (0) | 2022.03.19 |
Radio Box (0) | 2022.03.17 |
Dropdown Menu (0) | 2022.03.13 |
Auto Complete (0) | 2022.03.13 |
Comments