생계유지형 개발자/HTML+CSS+JS

[html/js] <input type=range> 를 div로 구현하기

이 가을 2021. 10. 6. 13:14

div로 슬라이더 구현했다가 input type=range로 바꾸면서  안 쓰게 되됨

근데 이거 자바스크립트로 슬라이더 직접 구현하는거 너무 개고생해가지고 고생이 아까워서 남겨놓음

 

HTML
<div class="control_light">
  <div class="light_line">
    <!-- width size == sliderValue -->
    <div class="line_indicator" style="width:{sliderValue}%">
	  <span class="figure_spot">
	  <span class="figure_desc">
        <strong class="num"> {sliderValue} <em class="sign_mark--bottom">%</em>
        </strong>
     </span>
   </span>
  </div>
</div>
CSS
.control_light .light_line {
  position: relative;
  width: 100%;
  height: 2px;
  background-color: #e7eff0;
}
.control_light .line_indicator {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  min-width: 24px;
  max-width: 100%;
  background-color: #177efb;
}
.control_light .line_indicator .figure_spot {
  display: block;
  width: 24px;
  height: 24px;
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  -ms-border-radius: 50%;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 2px 6px 0 #b8c0cc;
  cursor: pointer;
}
.control_light .line_indicator .figure_desc .num {
  display: block;
  line-height: 19px;
  font-size: 16px;
}
.control_light .line_indicator.type_default .figure_desc {
  top: -16px;
}
Js
let isMoving = false    	// 드래그 중인지 또는 놓은 상태인지
let leftEmptyWidth = 0		// 브라우저 좌측에서부터 slider 영역 시작지점까지 가로 길이
let indicatorWidth = 0
let minValue = 0, maxValue = 100, sliderValue = 초기값

/* slider 단추 영역 */
let spots = document.getElementById("figure_spot")	

/* slider 단추 누름. 이동 시작. (모바일의 경우, ontouchstart 사용) */
spots.onmousedown = function (event) {        
	isMoving = true				// 드래그 중인 상태로 변경
	let controlLight = event.target.parentElement.parentElement.parentElement
	let bound = controlLight.getBoundingClientRect()
	indicatorWidth = bound.width		// slider 영역 길이
	leftEmptyWidth = bound.x - 5		// 화면 좌측에서 slider 시작 부분까지의 길이
	
    /* slider 이동하면서 값 변경됨 (모바일의 경우, ontouchmove 사용) */
    document.onmousemove = function (event) {
	  event.preventDefault()
	  if (!isMoving) return;
	  let _sliderValue = Math.floor(((event.pageX - leftEmptyWidth) / indicatorWidth) * 100)
	  if (_sliderValue >= minValue && _sliderValue <= maxValue) {
      		// Do somthing with _sliderValue ..
      		sliderValue = _sliderValue
	  }
    }
}

/* slider에서 마우스 또는 터치 해제함 (모바일의 경우, ontouchend 사용) */
document.onmouseup = function () {
	if (!isMoving) return;
	isMoving = false
	document.onmousemove = null    // slider 이동 멈춤 (터치 제거)
	// commitValue(sliderValue)    
}