首页 > 解决方案 > 如何使用 Vanilla JS 拖放 select -option 元素

问题描述

我最近尝试在选择元素中拖动选项框内容。似乎无法完成 - 拖动根本不会触发。我考虑完全重新设计这个元素,让它看起来像 Select。此处描述了 jQuery 的其他选项: https : //stackoverflow.com/questions/ask 在我的情况下,它必须使用 Vanilla.JS 完成。我当然可以对上面的代码进行反向工程,但是也许有人知道其他可行的解决方案?

标签: javascriptselectdrag-and-dropoption

解决方案


使您希望拖动的元素成为绝对元素并将其放置在使用z-index. 然后获取元素的xy坐标。将元素直接移动到正文中,将元素放在指针的中心。添加事件侦听器以mousemove使用函数将元素置于页面x/y坐标的中心。释放鼠标按钮时删除元素的功能.onmouseup,这将删除与元素移动相关的所有事件侦听器。

注意: 这是非常基本的,如果用户将元素拖出页面边界,则必须使用更多代码来确定页面约束。

let drag = document.getElementById('draggableSpan');

drag.onmousedown = function(event) {
  // make element absolute and place it on top with z-index
  drag.style.position = 'absolute';
  drag.style.zIndex = 1000;
  
  let shiftX = event.clientX - drag.getBoundingClientRect().left;
  let shiftY = event.clientY - drag.getBoundingClientRect().top;

  // move it out of any current parents directly into body
  // to make it positioned relative to the body
  document.body.append(drag);

  // function that centers the element at (pageX, pageY) coordinates
  function moveTo(pageX, pageY) {
    drag.style.left = pageX - shiftX + 'px';
    drag.style.top = pageY - shiftY + 'px';
  }

  // move the absolutely positioned element under the pointer
  moveTo(event.pageX, event.pageY);

  function onMouseMove(event) {
    moveTo(event.pageX, event.pageY);
  }

  // move the element on mousemove with event  listener
  document.addEventListener('mousemove', onMouseMove);

  // drop the element on the page by removing eventlisteners that 
  // are relavent to the moving of the element
  drag.onmouseup = function() {
    document.removeEventListener('mousemove', onMouseMove);
    drag.onmouseup = null;
  };

};
<div class='parent'>
  <span id='draggableSpan'>
      draggable
  </span>
</div>


推荐阅读