1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin:0; padding:0; } #ul{ width:1000px; border:1px solid red; margin:0 auto; position: relative; } ul,li{ list-style-type: none; } #ul>li{ width:200px; height:200px; position: absolute; font-size:60px; text-align: center; line-height: 200px; color:#fff; cursor: pointer; user-select: none; transition: all .5s cubic-bezier(0.395, 1.650, 0.525, 0.745); }
</style> </head> <body> <ul id="ul"> </ul> </body> </html>
<script> function createLi(){ var oUl = document.querySelector("#ul"); for(let i = 1;i<21;i++){ let tag = document.createElement("li"); let text = document.createTextNode(i); tag.draggable=true; tag.appendChild(text); oUl.appendChild(tag); } } function computedLiPostion(){ var oUl = document.querySelector("#ul"); var oLi = oUl.getElementsByTagName("li"); oUl.style.height = Math.ceil(oLi.length / 5) * oLi[0].offsetHeight+1 + 'px'; var left =0,top=0; for(var i=0,length = oLi.length;i<length;i++){ const bg = `rgb(${parseInt(Math.random() * 256)},${parseInt(Math.random() * 256)},${parseInt(Math.random() * 256)})`; oLi[i].style.cssText= `;left:${left}px;top:${top}px;background-color:${bg}`; left=left+oLi[0].offsetWidth; if(left >=1000){ left=0; top+=oLi[0].offsetHeight; } } } function getStyle(element,attr){ if(element.currentStyle){ return element.currentStyle[attr] }else{ console.log(window.getComputedStyle(element)); return window.getComputedStyle(element)[attr] } } function changePosition(){ var oUl = document.querySelector("#ul"); var oLi = oUl.getElementsByTagName("li"); for(var i=0,length=oLi.length;i<length;i++){ oLi[i].index= i; var startIndex=0,endIndex=0; oLi[i].ondragstart=function(e){ startIndex = this.index; } oLi[i].ondragend=function(e){ e.preventDefault(); } oLi[i].ondragover=function(e){ e.preventDefault(); } oLi[i].ondrop=function(e){ e.preventDefault(); endIndex = this.index; for(let j=0,length=oLi.length;j<length;j++){ oLi[j].style.zIndex = 1; } let fromX = getStyle(oLi[startIndex],'left'); let fromY = getStyle(oLi[startIndex],'top'); let toX = getStyle(oLi[endIndex],'left'); let toY = getStyle(oLi[endIndex],'top'); oLi[startIndex].style.cssText+=`;z-index:100;left:${toX};top:${toY}`; oLi[endIndex].style.cssText+=`;z-index:100;left:${fromX};top:${fromY}`; } } } createLi(); computedLiPostion(); changePosition(); </script>
|