본문 바로가기
JavaScript

[JavaScript] 별점 드래그 기능 만들기

by teamnova 2022. 12. 21.

안녕하세요. 오늘은 회색 별을 드래그 했을 때 노란색으로 채워지는 기능을 만들어 보겠습니다.

 

star.html

<!DOCTYPE html>

<html lang="en">

<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>별점</title>
  <script defer src="star.js"></script>
  <link rel="stylesheet" href="star.css">
</head>

<body>
  <div class="rating_box">
    <div class="rating">
      ★★★★★
      <span class="rating_star">★★★★★</span>
      <input type="range" value="1" step="1" min="0" max="10">
    </div>
  </div>

</body>

</html>

 

star.css

.rating_box {
  display: flex;
}

.rating {
  position: relative;
  color: #ddd;
  font-size: 30px;
  text-align: center;
}

.rating input {
  position: absolute;
  left: 0;
  right: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.rating_star {
  width: 0;
  color: #ffc107;
  position: absolute;
  left: 0;
  right: 0;
  overflow: hidden;
  pointer-events: none;
}

 

star.js

const rating_input = document.querySelector('.rating input');
const rating_star = document.querySelector('.rating_star');

// 별점 드래그 할 때
rating_input.addEventListener('input', () => {
  rating_star.style.width = `${rating_input.value * 10}%`;
});

 

결과