Html HTML5 UL LI 可拖动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12332403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:44:51  来源:igfitidea点击:

HTML5 UL LI Draggable

htmldrag-and-drophtml-listsdraggable

提问by Anand Chowdhary

I have an unordered list:

我有一个无序列表:

  • List item 1
  • List item 2
  • List item 3
  • List item 4
  • List item 5
  • 列出项目 1
  • 列出项目 2
  • 列出项目 3
  • 列出项目 4
  • 列出项目 5

Implemented with this code:

使用此代码实现:

<ul>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
  <li>List item 4</li>
  <li>List item 5</li>
</ul>

Now, I want it to be draggable. For example, if I drag "List item 5" upward, I can place it between "List item 2" and "List item 3", and it'll become third.

现在,我希望它是可拖动的。例如,如果我向上拖动“List item 5”,我可以将它放在“List item 2”和“List item 3”之间,它会变成第三个。

I want to do this without jQuery, just plain Javascript. Also, I'd like to use native HTML5 draggable="true". Any help would be appreciated.

我想在没有 jQuery 的情况下做到这一点,只是简单的 Javascript。另外,我想使用原生 HTML5 draggable="true"。任何帮助,将不胜感激。

回答by 18bytes

Attribute "draggable" only enables the element for dragging. You need to implement the DnD listener and implement the drop event to make the changes you want.

属性“draggable”只允许拖动元素。您需要实现 DnD 侦听器并实现 drop 事件以进行所需的更改。

You will find the same problem you want to solve in this example: http://www.html5rocks.com/en/tutorials/dnd/basics/

你会在这个例子中找到你想要解决的同样问题:http: //www.html5rocks.com/en/tutorials/dnd/basics/

In the example they implement drag-drop for columns A, B and C. User can change the order by DnD.

在示例中,他们为 A、B 和 C 列实现了拖放。用户可以通过 DnD 更改顺序。

回答by luke

Just add draggable="true" to your li-elements.

只需将 draggable="true" 添加到您的 li 元素。

<ol ondragstart="">
<li draggable="true" data-value="data1">List Item 1</li>
<li draggable="true" data-value="data2">List Item 2</li>
<li draggable="true" data-value="data3">List Item 3</li>
</ol>

回答by ?abojad

If you are testing with Firefox, note that it also requires some data be sent in the drag operation:

如果你用 Firefox 进行测试,请注意它也需要在拖动操作中发送一些数据:

function handleDragStart(e) {
  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/html', e.target.innerHTML);
}

myLi.addEventListener('dragstart', handleDragStart, false);

Otherwise, you wouldn't see the ghost image of the content being dragged...

否则,您将看不到被拖动内容的鬼影...

回答by Владимир Казак

This code will solve your problem. Redone example with MDNTry it this jsfiddle.net

此代码将解决您的问题。使用MDN重做示例 试试这个jsfiddle.net

HTML 5

HTML 5

<ul>
  <li class="dropzone" id='0' draggable="true">List item 1</li>
  <li class="dropzone" id='1' draggable="true">List item 2</li>
  <li class="dropzone" id='2' draggable="true">List item 3</li>
  <li class="dropzone" id='3' draggable="true">List item 4</li>
  <li class="dropzone" id='4' draggable="true">List item 5</li>
</ul>

pure JS

纯JS

let dragged;
let id;
let index;
let indexDrop;
let list;

  document.addEventListener("dragstart", ({target}) => {
      dragged = target;
      id = target.id;
      list = target.parentNode.children;
      for(let i = 0; i < list.length; i += 1) {
        if(list[i] === dragged){
          index = i;
        }
      }
  });

  document.addEventListener("dragover", (event) => {
      event.preventDefault();
  });

  document.addEventListener("drop", ({target}) => {
   if(target.className == "dropzone" && target.id !== id) {
       dragged.remove( dragged );
      for(let i = 0; i < list.length; i += 1) {
        if(list[i] === target){
          indexDrop = i;
        }
      }
      console.log(index, indexDrop);
      if(index > indexDrop) {
        target.before( dragged );
      } else {
       target.after( dragged );
      }
    }
  });

回答by Prem

<ul id="parent">

    <li class="parent">List item 1</li>

    <li class="parent">List item 2</li>

    <li class="parent">List item 3</li>

    <li class="parent">List item 4</li>

    <li class="parent">List item 5</li>
</ul>

try this js

试试这个js

    var dragSrcEl = null;

    function handleDragStart(e) {
        // Target (this) element is the source node.
        this.style.opacity = '0.4';

        dragSrcEl = this;

        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', this.innerHTML);
    }

    function handleDragOver(e) {
        if (e.preventDefault) {
            e.preventDefault(); // Necessary. Allows us to drop.
        }

        e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.

        return false;
    }

    function handleDragEnter(e) {
        // this / e.target is the current hover target.
        this.classList.add('over');
    }

    function handleDragLeave(e) {
        this.classList.remove('over');  // this / e.target is previous target element.
    }

    function handleDrop(e) {
        // this/e.target is current target element.

        if (e.stopPropagation) {
            e.stopPropagation(); // Stops some browsers from redirecting.
        }

        // Don't do anything if dropping the same column we're dragging.
        if (dragSrcEl != this) {
            // Set the source column's HTML to the HTML of the column we dropped on.
            dragSrcEl.innerHTML = this.innerHTML;
            this.innerHTML = e.dataTransfer.getData('text/html');
        }

        return false;
    }

    function handleDragEnd(e) {
        // this/e.target is the source node.

        [].forEach.call(cols, function (col) {
            col.classList.remove('over');
        });
    }

    var cols = document.querySelectorAll('#parent .parent');
    [].forEach.call(cols, function (col) {
        col.addEventListener('dragstart', handleDragStart, false);
        col.addEventListener('dragenter', handleDragEnter, false)
        col.addEventListener('dragover', handleDragOver, false);
        col.addEventListener('dragleave', handleDragLeave, false);
        col.addEventListener('drop', handleDrop, false);
        col.addEventListener('dragend', handleDragEnd, false);
    });