【问题标题】:How to drag & drop select -option element with Vanilla JS如何使用 Vanilla JS 拖放 select -option 元素
【发布时间】:2020-07-19 12:52:39
【问题描述】:

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

【问题讨论】:

    标签: javascript select drag-and-drop option


    【解决方案1】:

    使用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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2011-12-15
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多