前端学习笔记

时间:2024-06-09 07:10:57
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .outer { position: relative; } div { width: 100px; height: 100px; position: absolute; border-radius: 25%; line-height: 100px; text-align: center; } </style> </head> <body> <div class="outer"> <div>A</div> <div>B</div> <div>C</div> <div>D</div> <div>E</div> <div>F</div> <div>G</div> <div>H</div> <div>I</div> </div> <script> var mg = 10 var perWidth = 100 + mg function randomColor() { //随机颜色函数 let r = Math.floor(Math.random() * 255); let g = Math.floor(Math.random() * 255); let b = Math.floor(Math.random() * 255); return `rgb(${r},${g},${b})`; } var out = document.querySelector(".outer") var oDivs = out.querySelectorAll("div") //给div上色 oDivs.forEach(function (v, i) { v.style.backgroundColor = randomColor(); }); //放前三个div for (var i = 0; i < 3; i++) { oDivs[i].style.left = i * perWidth + "px" oDivs[i].style.top = 0 } //根据前三个div的top和left放剩下的div for (var i = 3; i < oDivs.length; i++) { oDivs[i].style.left = oDivs[i - 3].style.left oDivs[i].style.top = parseInt(oDivs[i - 3].style.top) + perWidth + "px" } function minindex(a) { var min = 0 for (var i = 1; i < a.length; i++) { if (a[min] > a[i]) { min = i } } return min } //实现拖拽 out.onmousedown = function (e) { //确定鼠标点的位置 var tag = e.target var a = e.clientX - parseInt(tag.style.left) var b = e.clientY - parseInt(tag.style.top) var kelong = tag.cloneNode(true)//克隆 out.replaceChild(kelong, tag) out.appendChild(tag) document.onmousemove = function (e) { //更新位置 e.preventDefault(); var x = e.clientX - a var y = e.clientY - b tag.style.left = x + "px"; tag.style.top = y + "px"; } document.onmouseup = function () { var arr = []; var oDivs = out.querySelectorAll("div") for (var i = 0; i < oDivs.length - 1; i++) { var a = tag.offsetLeft - oDivs[i].offsetLeft var b = tag.offsetTop - oDivs[i].offsetTop var c = Math.sqrt(a * a + b * b) arr.push(c) } console.log(arr); var min = minindex(arr) tag.style.left = oDivs[min].style.left tag.style.top = oDivs[min].style.top oDivs[min].style.left = kelong.style.left oDivs[min].style.top = kelong.style.top out.removeChild(kelong) document.onmouseup = null document.onmousemove = null; } } </script> </body>