Come determinare le coordinate di un elemento in JavaScript?

February 18

Le coordinate dello schermo di un elemento sono specificati nella sua dichiarazione di stile e memorizzati dal browser all'interno del Document Object Model (DOM) della pagina HTML visualizzata. Ogni elemento all'interno del DOM è data una stringa di identità (ID). Un codice JavaScript può accedere ad un particolare elemento con questa stringa di identità come punto di riferimento e può ottenere i valori specifici per le coordinate e 'top' 'sinistra' degli elementi all'interno della finestra del browser.

istruzione

1 Aprire un nuovo file nell'editor di testo e salvarlo come "coordinates.HTML." Scrivere o copiare il codice di dichiarazione documento HTML nel file:

<! DOCTYPE HTML PUBLIC "- // W3C // DTD XHTML 1.0 Strict // EN"

"Http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<Html xmlns = "http://www.w3.org/1999/xhtml">

2 Scrivere o copiare questo HTML <head> del codice nel file:

<Head>

&lt;title>Element Coordinates.&lt;/title>

& Lt; meta content = "text / html; charset = utf-8" http-equiv = "Content-Type" />

<Style type = "text / css">

scatola

{

position: absolute;

z-index: 1;

Visibilità: visibile;

Larghezza: 10.0em;

altezza: 5.0em;

top: 1.0em;

sinistra: 1.0em;

border: 2px #ccc solido;

-moz-border-radius: 0.5em;

-webkit-border-radius: 0.5em;

text-align: center;

padding: 1.0em;

}

p {

font-size: 1.2em;

font-weight: 900;

color: # 000000;

}

</ Style>

<Script type = "text / javascript">

var x;

var y;

getCoordinates function ()

{

x = Math.floor(Math.random()*40);

y = Math.floor (Math.random () * 30);

. Document.getElementById ( "box") style.left = x + "em";

. Document.getElementById ( "box") style.top = y + "em";

. X = document.getElementById ( "box") style.left;

y = document.getElementById ( "box") style.top.;

alert ( "sinistra =" + x);

alert ( "top =" + y);

}

</ Script>

</ Head>

3 Scrivere o copiare questo HTML <body> codice nel file:

<Body>

<Div id = "box" onmouseover = "getCoordinates ()">

<P>

Toccami!

</ P>

</ Div>

</ Body>

</ Html>

4 Salvare il file e aprirlo nel browser web. Toccare l'elemento ed esso si sposterà in una nuova posizione all'interno della finestra del browser e visualizzare l 'e' top '' sinistra 'valori delle coordinate.