Tengo muchos elementos en la página. Necesito dibujar un rectángulo circunscrito que contenga todos los elementos DOM.
Para eso itero los elementos DOM y obtengo un rectángulo:
Array.from(firstChild.children).forEach((child: Element) => { const rect = child.getBoundingClientRect(); }); ¿Qué accesorios necesito de rect para hacer eso? Lógicamente, necesito obtener un mínimo de x, y de la esquina left-top y un máximo de la esquina bottom-right . ¿Pero cómo?
Para aplicar un borde, debe establecer 4 valores: top , left , width y height .
Llegar a top e left se puede hacer fácilmente encontrando los elementos superiores e izquierdos. Para obtener los otros valores, debe hacer algunos cálculos:
width = rightmost - leftmost y height = bottommost - topmost
Para obtener los puntos más a la rightmost y bottommost , debe recorrer todos los elementos y obtener sus puntos más a la derecha/más abajo con la misma fórmula, pero debe reorganizarlos. Aquí debes mantener los valores más grandes.
//select all elements that should be inside the rectangle const myElements = document.querySelectorAll("div#container *") //set initial values, I made sure they are always smaller/bigger than they will be let Top=Infinity, Left=Infinity, Bottom=-Infinity, Right=-Infinity; for(const i of myElements){ //loop through the elements const data = i.getBoundingClientRect() Top = Math.min(Top, data.top) Bottom = Math.max(Bottom, data.top+data.height) Left = Math.min(Left, data.left) Right = Math.max(Right, data.left+data.width) } console.log(Top, Left, Bottom, Right) // print out the coordinates //set the border //I subtract 1px bacuse of the border width const myBorder = document.querySelector("#border") myBorder.style.top=Top-1+"px" myBorder.style.left=Left-1+"px" myBorder.style.width=Right-Left+"px" myBorder.style.height=Bottom-Top+"px" #t1{ position: absolute; top: 20px; left: 40px; width: 60px; height: 40px; background-color: #000; } #t2{ position: absolute; top: 30px; left: 80px; width: 40px; height: 70px; background-color: #111; } #t3{ position: absolute; top: 50px; left: -40px; width: 60px; height: 40px; background-color: #800; } #t4{ position: absolute; top: 35px; left: 110px; width: 30px; height: 40px; background-color: #444; } #border{ border: solid red 1px; position: absolute; } <div id="container"> <div id="t1"></div> <div id="t2"> <div id="t3"></div> </div> <div id="t4"></div> </div> <div id="border"></div>