[javascript] 드래그 앤 드롭 효과를 사용한 웹사이트용 그래프 구현 방법

웹사이트에서 드래그 앤 드롭(Drag and Drop) 효과를 사용하여 그래프를 구현하는 방법에 대해 알아보겠습니다.

HTML 구조

<div id="graph">
  <div class="bar"></div>
  <div class="bar"></div>
  <div class="bar"></div>
  <!-- 그래프 바 추가 -->
</div>

우선, 그래프 바를 감싸는 <div> 요소를 만들고, 그 안에 각각의 그래프 바를 나타내는 <div> 요소를 추가합니다.

CSS 스타일

#graph {
  display: flex;
  height: 300px;
  background-color: #f5f5f5;
}

.bar {
  flex: 1;
  margin: 0 10px;
  background-color: #3498db;
  cursor: grab;
}

.bar:active {
  cursor: grabbing;
}

#graph 요소에는 display: flex;를 설정하여 그래프 바가 가로로 나열되도록 합니다. 또한, 각각의 그래프 바에는 flex: 1; 속성을 주어 같은 크기로 설정하고, margin 값을 주어 그래프 바 사이의 간격을 조정합니다. 마지막으로, 그래프 바에 cursor 속성을 설정하여 드래그 가능한 상태를 나타내도록 합니다.

JavaScript 이벤트 처리

var bars = document.getElementsByClassName('bar');
var currentBar = null;

for(var i = 0; i < bars.length; i++) {
  bars[i].addEventListener('mousedown', function(e) {
    currentBar = this;
    currentBar.style.opacity = '0.5';
    currentBar.style.transition = 'none';
    currentBar.style.zIndex = '1';
  });
  
  bars[i].addEventListener('mouseup', function(e) {
    currentBar.style.opacity = '1';
    currentBar.style.transition = 'all 0.3s';
    currentBar.style.zIndex = '0';
    currentBar = null;
  });
  
  bars[i].addEventListener('mousemove', function(e) {
    if(currentBar !== null) {
      var mousePosition = e.clientX - document.getElementById('graph').offsetLeft;
      currentBar.style.width = mousePosition + 'px';
    }
  });
}

각각의 그래프 바에 대해 mousedown, mouseup, mousemove 이벤트를 감지하여 드래그 앤 드롭 효과를 구현합니다.

결과 확인

위의 코드를 HTML 파일에 추가하고 웹브라우저에서 열어 그래프를 확인해보세요. 그래프 바를 클릭하여 드래그 앤 드롭 효과가 적용되는지 확인할 수 있습니다.

이와 같은 드래그 앤 드롭 효과를 활용하면 웹사이트에서 그래프를 직접 조작할 수 있어 사용자 경험을 향상시킬 수 있습니다.

참고 자료