PC端元素拖拽功能的实现

一、实现思路
1、确定两个元素:triggerElement-触发元素,如标题区域;targetElement-需要移动元素;
2、监听triggerElement元素mousedown事件,触发事件后,根据鼠标移动的距离,动态计算targetElement偏移距离,并重新设置样式

代码如下:

/**  
 * 拖拽功能实现,拖拽标题,移动弹窗 
 * @param triggerElement [HTMLElement] 触发拖拽的元素  
 * @param targetElement [HTMLElement] 移动的目标元素  
 */
 drag(triggerElement, targetElement) {  
  // 设置targetElement样式为position: relative  
  targetElement.style.position = 'relative';  
  // 监听鼠标摁下事件  
  triggerElement.addEventListener('mousedown', (event) => {  
    let originMouseX, originMouseY, moveX, moveY;  
  originMouseX = event.clientX;  
  originMouseY = event.clientY;  
  document.addEventListener('mousemove', mouseMove, false);  
  document.addEventListener('mouseup', mouseUp, false);  
  
  // 鼠标移动触发函数  
  function mouseMove(moveEvent) {  
      moveX = moveEvent.clientX - originMouseX;  
  moveY = moveEvent.clientY - originMouseY;  
  originMouseX = moveEvent.clientX;  
  originMouseY = moveEvent.clientY;  
  targetElement.style.left = (+moveX + +targetElement.offsetLeft) + 'px';  
  targetElement.style.top = (+moveY + +targetElement.offsetTop) + 'px';  
  // 防止选取文字  
  event.preventDefault();  
  triggerElement.onselectstart = function () {  
        return false;  
  };  
  }  
  
    // 鼠标释放触发函数  
  function mouseUp(upEvent) {  
      document.removeEventListener('mousemove', mouseMove, false);  
  document.removeEventListener('mouseup', mouseUp, false);  
  }  
  }, false);  
}

你可能感兴趣的:(javascript,前端)