Beispiel:JS-element.getBoundingClientRect.html

Aus SELFHTML-Wiki
Wechseln zu: Navigation, Suche

<!doctype html> <html lang="de"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./Beispiel:SELFHTML-Beispiel-Grundlayout.css">

   <title>Elementgrößen ermitteln - 3</title>  
<script>

'use strict'; document.addEventListener('DOMContentLoaded', function () {

const page = document.querySelector('body'); page.addEventListener('mouseover',getCSSValues); page.addEventListener('focus',getCSSValues);


 function getCSSValues(event) { 

const element = event.target; const name = element.nodeName; const rect = element.getBoundingClientRect(); let result = ` Elementname: ${name} \n x₁, y₁ : ${rect.left}px, ${rect.top}px (links oben) \n x₂, y₂: ${rect.right}px, ${rect.bottom}px (rechts unten) \n Höhe: ${rect.height}px \n Breite: ${rect.width}px `; console.log(result); result = result.replaceAll("\n", "
"); document.getElementById('info').innerHTML = result;

 }


}); </script>

<style>
  1. aussen {

height: 20em; width: 21em; margin: 1em; }

  1. innen1 {

width: 25em; }

  1. innen2 {

width: 100%; }

.box { background-color: #f5e6bc; border: 0.5em solid #337599; color:#866a00; padding: 1em; }

.box > * { background-color: #efd68f; border: thin solid; margin: 0; }

.box p { color: #866a00; background-color: #efd68f; border: thin solid; border-bottom-color: transparent; margin: 0; line-height: 2;

}

aside p { height: 7.5em; border-top-color: transparent; }

output { font-family: monospace;

} body { margin: 2em auto; padding: 0 2em; }

main, #aussen {

 border: thin dotted;

overflow: auto; /* muss gesetzt werden! */ resize: both; }

footer { color: white; padding: 2em; } footer p {border-color:#866a00;padding:1em;}

  1. container {
 display:grid;

grid-template-columns: 1fr 1fr; gap; 1em; border:thin dotted; } section {

grid-column: 1 /-!;

}

  • {
 box-sizing: border-box;

} </style>


</head> <body>

Elementgrößen ermitteln - 3
Seiteninspektor mit getBoundingClientRect()

 <main id="container">

Box, die kleiner als das Elternelement ist.

<img src="https://wiki.selfhtml.org/images/5/54/Landscape.svg" alt="Symbolbild mit einer Toskana-Landschaft"> </div> </div>

     <p>Box, die sich an das Elternelement anpasst.</p>
     <p><img src="https://wiki.selfhtml.org/images/5/54/Landscape.svg" alt="Symbolbild mit einer Toskana-Landschaft">
 <section>

Ausgabe

<p>Elementbox-Größe: <output id="info"></output>

 </section>

</main>

<footer id="footer" class="box">

made by <a class="externer link" href="https://selfhtml.org/">SELFHTML</a>

</footer>

</body>

</html>