需要先设置拖拽元素的draggable属性为true。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> * { margin: 0; padding: 0; } li { list-style: none; float: left; width: 50px; height: 50px; line-height: 50px; text-align: center; border-radius: 50%; background-color: yellow; } .a, .b { width: 300px; height: 300px; border: 1px solid red; } </style> </head> <body> <ul class="a"> <li draggable="true">1</li> <li draggable="true">2</li> <li draggable="true">3</li> <li draggable="true">4</li> </ul> <div class="b"> </div> <!--javascript--> <script> var lis = document.querySelectorAll("li"); var b = document.querySelector(".b"); var srcEle; lis.forEach(function (element, index) { //拖动就会触发 // element.ondrag = function () { // console.log("拖拽元素drag"); // } //拖动开始的时候 element.ondragstart = function () { srcEle = index; console.log("拖拽元素dragstart"); } //离开自己的时候 element.ondragleave = function () { console.log("拖拽元素dragleave"); } //手放下的那一刻 element.ondragend = function () { console.log("拖拽元素dragend"); } } ) //拖动元素时,鼠标进入目标元素后会触发一次! b.ondragenter = function () { console.log("目标元素ondragenter"); } //拖动元素时,鼠标进入目标元素后会一直触发 b.ondragover = function (e) { e = e || window.event; e.preventDefault(); console.log("目标元素ondragover"); } b.ondragleave = function () { console.log("目标元素ondragleave"); } //拖动元素在目标元素上面放下的时候触发 b.ondrop = function () { this.appendChild(lis[srcEle]); console.log("目标元素ondrop"); } </script> </body> </html>