一、实现代码
<! DOCTYPE html >
< style> * { padding : 0; margin : 0; } body { display : flex; width : 100%; height : 100vh; justify-content : center; align-items : center; } .list { display : flex; width : 336px; flex-wrap : wrap} .list-item { width : 100px; height : 50px; margin-top : 10px; border : 1px solid gray; margin-right : 10px; background-color : gray; color : #fff; } .list-item.moving { color : transparent; background-color : transparent; border : 1px dashed gray !important ; }
</ style> < body>
< div class = " list" > < div draggable = " true" class = " list-item" > 1</ div> < div draggable = " true" class = " list-item" > 2</ div> < div draggable = " true" class = " list-item" > 3</ div> < div draggable = " true" class = " list-item" > 4</ div> < div draggable = " true" class = " list-item" > 5</ div> < div draggable = " true" class = " list-item" > 6</ div> < div draggable = " true" class = " list-item" > 7</ div> < div draggable = " true" class = " list-item" > 8</ div> < div draggable = " true" class = " list-item" > 9</ div>
</ div>
</ body>
< script type = " text/javascript" > let sourceNode; const list = document. querySelector ( ".list" ) ; list. ondragstart = ( e ) => { console. log ( "当前拖动的节点:" ) ; console. log ( e. target) ; e. target. classList. add ( "moving" ) ; sourceNode = e. target; } ; list. ondragenter = ( e ) => { if ( e. target === list || e. target === sourceNode) { return ; } console. log ( "拖拽到节点:" ) ; console. log ( e. target) ; const children = Array. from ( list. children) ; const sourceIndex = children. indexOf ( sourceNode) ; const targetIndex = children. indexOf ( e. target) ; if ( sourceIndex < targetIndex) { list. insertBefore ( sourceNode, e. target. nextElementSibling) ; } else { list. insertBefore ( sourceNode, e. target) ; } } ; list. ondragend = ( e ) => { e. target. classList. remove ( 'moving' ) ; } </ script> </ html>
二、实现效果