Skip to content

Commit 326527e

Browse files
authored
Merge pull request #328 from vplentinax/scrolling
Window sizes and scrolling
2 parents e26b59e + c27b7c0 commit 326527e

File tree

1 file changed

+65
-65
lines changed
  • 2-ui/1-document/10-size-and-scroll-window

1 file changed

+65
-65
lines changed
Lines changed: 65 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,50 @@
1-
# Window sizes and scrolling
1+
# Tamaño de ventana y desplazamiento
22

3-
How do we find the width and height of the browser window? How do we get the full width and height of the document, including the scrolled out part? How do we scroll the page using JavaScript?
3+
¿Cómo encontramos el ancho y el alto de la ventana del navegador? ¿Cómo obtenemos todo el ancho y la altura del documento, incluida la parte desplazada? ¿Cómo desplazamos la página usando JavaScript?
44

5-
For most such requests, we can use the root document element `document.documentElement`, that corresponds to the `<html>` tag. But there are additional methods and peculiarities important enough to consider.
5+
Para la mayoría de estas cuestiones, podemos usar el elemento de documento raíz `document.documentElement`, que corresponde a la etiqueta `<html>`. Pero hay métodos y peculiaridades adicionales lo suficientemente importantes para considerar.
66

7-
## Width/height of the window
7+
## Ancho/alto de la ventana
88

9-
To get window width and height we can use `clientWidth/clientHeight` of `document.documentElement`:
9+
Para obtener el ancho y alto de la ventana, podemos usar `clientWidth / clientHeight` de `document.documentElement`:
1010

1111
![](document-client-width-height.svg)
1212

1313
```online
14-
For instance, this button shows the height of your window:
14+
Por ejemplo, este botón muestra la altura de su ventana:
1515
1616
<button onclick="alert(document.documentElement.clientHeight)">alert(document.documentElement.clientHeight)</button>
1717
```
1818

19-
````warn header="Not `window.innerWidth/Height`"
20-
Browsers also support properties `window.innerWidth/innerHeight`. They look like what we want. So why not to use them instead?
19+
````warn header="No *window.innerWidth/Height*"
20+
Los navegadores también admiten propiedades `window.innerWidth / innerHeight`. Se parecen a lo que queremos. Entonces, ¿por qué no usarlos?
2121
22-
If there exists a scrollbar, and it occupies some space, `clientWidth/clientHeight` provide the width/height without it (subtract it). In other words, they return width/height of the visible part of the document, available for the content.
22+
Si existe una barra de desplazamiento, y ocupa algo de espacio, `clientWidth / clientHeight` proporciona el ancho / alto sin ella (resta el espacio desplazado). En otras palabras, devuelven ancho / alto de la parte visible del documento, disponible para el contenido.
2323
24-
...And `window.innerWidth/innerHeight` include the scrollbar.
24+
... Y `window.innerWidth / innerHeight` incluye la barra de desplazamiento.
2525
26-
If there's a scrollbar, and it occupies some space, then these two lines show different values:
26+
Si hay una barra de desplazamiento y ocupa algo de espacio, estas dos líneas muestran valores diferentes:
2727
```js run
28-
alert( window.innerWidth ); // full window width
29-
alert( document.documentElement.clientWidth ); // window width minus the scrollbar
28+
alert( window.innerWidth ); // ancho de la ventana completa
29+
alert( document.documentElement.clientWidth ); // ancho de ventana menos el desplazamiento.
3030
```
3131
32-
In most cases we need the *available* window width: to draw or position something. That is: inside scrollbars if there are any. So we should use `documentElement.clientHeight/Width`.
32+
En la mayoría de los casos, necesitamos el ancho de ventana *disponible*, para dibujar o colocar algo. Es decir: el espacio del desplazamiento si hay alguno. Entonces deberíamos usar `documentElement.clientHeight/Width`.
3333
````
3434

35-
```warn header="`DOCTYPE` is important"
36-
Please note: top-level geometry properties may work a little bit differently when there's no `<!DOCTYPE HTML>` in HTML. Odd things are possible.
35+
```warn header="*DOCTYPE* es importante"
36+
Tenga en cuenta que las propiedades de geometría de nivel superior pueden funcionar de manera un poco diferente cuando no hay `<!DOCTYPE HTML>` en HTML. Pueden suceder cosas extrañas.
3737
38-
In modern HTML we should always write `DOCTYPE`.
38+
En HTML moderno siempre debemos escribir `DOCTYPE`.
3939
```
4040

41-
## Width/height of the document
41+
## Ancho/Alto del documento
4242

43-
Theoretically, as the root document element is `document.documentElement`, and it encloses all the content, we could measure document full size as `document.documentElement.scrollWidth/scrollHeight`.
43+
Teóricamente, como el elemento del documento raíz es `document.documentElement`, e incluye todo el contenido, podríamos medir el tamaño completo del documento con `document.documentElement.scrollWidth / scrollHeight`.
4444

45-
But on that element, for the whole page, these properties do not work as intended. In Chrome/Safari/Opera if there's no scroll, then `documentElement.scrollHeight` may be even less than `documentElement.clientHeight`! Sounds like a nonsense, weird, right?
45+
Pero en ese elemento, para toda la página, estas propiedades no funcionan según lo previsto. ¡En Chrome / Safari / Opera si no hay desplazamiento, entonces `documentElement.scrollHeight` puede ser incluso menor que `documentElement.clientHeight`! Suena como una tontería, raro, ¿verdad?
4646

47-
To reliably obtain the full document height, we should take the maximum of these properties:
47+
Para obtener de manera confiable la altura completa del documento, debemos tomar el máximo de estas propiedades:
4848

4949
```js run
5050
let scrollHeight = Math.max(
@@ -53,104 +53,104 @@ let scrollHeight = Math.max(
5353
document.body.clientHeight, document.documentElement.clientHeight
5454
);
5555

56-
alert('Full document height, with scrolled out part: ' + scrollHeight);
56+
alert('Altura completa del documento, con parte desplazada: ' + scrollHeight);
5757
```
5858

59-
Why so? Better don't ask. These inconsistencies come from ancient times, not a "smart" logic.
59+
¿Por qué? Mejor no preguntes. Estas inconsistencias provienen de tiempos antiguos, no una lógica "inteligente".
6060

61-
## Get the current scroll [#page-scroll]
61+
## Obtener el desplazamiento actual [#page-scroll]
6262

63-
DOM elements have their current scroll state in `elem.scrollLeft/scrollTop`.
63+
Los elementos DOM tienen su estado de desplazamiento actual en `elem.scrollLeft/scrollTop`.
6464

65-
For document scroll `document.documentElement.scrollLeft/Top` works in most browsers, except older WebKit-based ones, like Safari (bug [5991](https://bugs.webkit.org/show_bug.cgi?id=5991)), where we should use `document.body` instead of `document.documentElement`.
65+
El desplazamiento de documentos, `document.documentElement.scrollLeft / Top` funciona en la mayoría de los navegadores, excepto los más antiguos basados en WebKit, como Safari (bug [5991](https://bugs.webkit.org/show_bug.cgi?id=5991)), donde deberíamos usar `document.body` en lugar de `document.documentElement`.
6666

67-
Luckily, we don't have to remember these peculiarities at all, because the scroll is available in the special properties `window.pageXOffset/pageYOffset`:
67+
Afortunadamente, no tenemos que recordar estas peculiaridades en absoluto, porque el desplazamiento está disponible en las propiedades especiales `window.pageXOffset/pageYOffset`:
6868

6969
```js run
70-
alert('Current scroll from the top: ' + window.pageYOffset);
71-
alert('Current scroll from the left: ' + window.pageXOffset);
70+
alert('Desplazamiento actual desde la parte superior: ' + window.pageYOffset);
71+
alert('Desplazamiento actual desde la parte izquierda: ' + window.pageXOffset);
7272
```
7373

74-
These properties are read-only.
74+
Estas propiedades son de solo lectura.
7575

76-
## Scrolling: scrollTo, scrollBy, scrollIntoView [#window-scroll]
76+
## Desplazamiento: scrollTo, scrollBy, scrollIntoView [#window-scroll]
7777

7878
```warn
79-
To scroll the page from JavaScript, its DOM must be fully built.
79+
para desplazar la página desde JavaScript, su DOM debe estar completamente construido.
8080
81-
For instance, if we try to scroll the page from the script in `<head>`, it won't work.
81+
Por ejemplo, si intentamos desplazar la página desde el script en `<head>`, no funcionará.
8282
```
8383

84-
Regular elements can be scrolled by changing `scrollTop/scrollLeft`.
84+
Los elementos regulares se pueden desplazar cambiando `scrollTop/scrollLeft`.
8585

86-
We can do the same for the page using `document.documentElement.scrollTop/Left` (except Safari, where `document.body.scrollTop/Left` should be used instead).
86+
Nosotros podemos hacer lo mismo para la página usando `document.documentElement.scrollTop/Left` (excepto Safari, donde `document.body.scrollTop/Left` debería usarse en su lugar).
8787

88-
Alternatively, there's a simpler, universal solution: special methods [window.scrollBy(x,y)](mdn:api/Window/scrollBy) and [window.scrollTo(pageX,pageY)](mdn:api/Window/scrollTo).
88+
Alternativamente, hay una solución más simple y universal: métodos especiales [window.scrollBy(x,y)](mdn:api/Window/scrollBy) y [window.scrollTo(pageX,pageY)](mdn:api/Window/scrollTo).
8989

90-
- The method `scrollBy(x,y)` scrolls the page *relative to its current position*. For instance, `scrollBy(0,10)` scrolls the page `10px` down.
90+
- El método `scrollBy(x, y)` desplaza la página *en relación con su posición actual*. Por ejemplo, `scrollBy(0,10)` desplaza la página `10px` hacia abajo.
9191

9292
```online
93-
The button below demonstrates this:
93+
El siguiente botón demuestra esto:
9494
9595
<button onclick="window.scrollBy(0,10)">window.scrollBy(0,10)</button>
9696
```
97-
- The method `scrollTo(pageX,pageY)` scrolls the page *to absolute coordinates*, so that the top-left corner of the visible part has coordinates `(pageX, pageY)` relative to the document's top-left corner. It's like setting `scrollLeft/scrollTop`.
97+
- El método `scrollTo(pageX, pageY)` desplaza la página *a coordenadas absolutas*, de modo que la esquina superior izquierda de la parte visible tiene coordenadas `(pageX, pageY)` en relación con la esquina superior izquierda del documento. Es como configurar `scrollLeft / scrollTop`.
9898
99-
To scroll to the very beginning, we can use `scrollTo(0,0)`.
99+
Para desplazarnos hasta el principio, podemos usar `scrollTo(0,0)`.
100100
101101
```online
102102
<button onclick="window.scrollTo(0,0)">window.scrollTo(0,0)</button>
103103
```
104104
105-
These methods work for all browsers the same way.
105+
Estos métodos funcionan para todos los navegadores de la misma manera.
106106
107107
## scrollIntoView
108108
109-
For completeness, let's cover one more method: [elem.scrollIntoView(top)](mdn:api/Element/scrollIntoView).
109+
Para completar, cubramos un método más: [elem.scrollIntoView(top)](mdn:api/Element/scrollIntoView).
110110
111-
The call to `elem.scrollIntoView(top)` scrolls the page to make `elem` visible. It has one argument:
111+
La llamada a `elem.scrollIntoView(top)` desplaza la página para hacer visible `elem`. Tiene un argumento:
112112
113-
- if `top=true` (that's the default), then the page will be scrolled to make `elem` appear on the top of the window. The upper edge of the element is aligned with the window top.
114-
- if `top=false`, then the page scrolls to make `elem` appear at the bottom. The bottom edge of the element is aligned with the window bottom.
113+
- si `top=true` (ese es el valor predeterminado), la página se desplazará para que aparezca `element` en la parte superior de la ventana. El borde superior del elemento está alineado con la parte superior de la ventana.
114+
- si `top=false`, la página se desplaza para hacer que `element` aparezca en la parte inferior. El borde inferior del elemento está alineado con la parte inferior de la ventana.
115115
116116
```online
117-
The button below scrolls the page to make itself show at the window top:
117+
El botón a continuación desplaza la página para mostrarse en la parte superior de la ventana:
118118
119119
<button onclick="this.scrollIntoView()">this.scrollIntoView()</button>
120120
121-
And this button scrolls the page to show it at the bottom:
121+
Y este botón desplaza la página para mostrarla en la parte inferior:
122122
123123
<button onclick="this.scrollIntoView(false)">this.scrollIntoView(false)</button>
124124
```
125125

126-
## Forbid the scrolling
126+
## Prohibir el desplazamiento
127127

128-
Sometimes we need to make the document "unscrollable". For instance, when we need to cover it with a large message requiring immediate attention, and we want the visitor to interact with that message, not with the document.
128+
A veces necesitamos hacer que el documento sea "inescrutable". Por ejemplo, cuando necesitamos cubrirlo con un mensaje grande que requiere atención inmediata, y queremos que el visitante interactúe con ese mensaje, no con el documento.
129129

130-
To make the document unscrollable, it's enough to set `document.body.style.overflow = "hidden"`. The page will freeze on its current scroll.
130+
Para hacer que el documento sea inescrutable, es suficiente establecer `document.body.style.overflow="hidden"`. La página se congelará en su desplazamiento actual.
131131

132132
```online
133-
Try it:
133+
Prueba esto:
134134
135135
<button onclick="document.body.style.overflow = 'hidden'">document.body.style.overflow = 'hidden'</button>
136136
137137
<button onclick="document.body.style.overflow = ''">document.body.style.overflow = ''</button>
138138
139-
The first button freezes the scroll, the second one resumes it.
139+
El primer botón congela el desplazamiento, el segundo lo reanuda.
140140
```
141141

142-
We can use the same technique to "freeze" the scroll for other elements, not just for `document.body`.
142+
Podemos usar la misma técnica para "congelar" el desplazamiento para otros elementos, no solo para `document.body`.
143143

144-
The drawback of the method is that the scrollbar disappears. If it occupied some space, then that space is now free, and the content "jumps" to fill it.
144+
El inconveniente del método es que la barra de desplazamiento desaparece. Si ocupaba algo de espacio, entonces ese espacio ahora es libre y el contenido "salta" para llenarlo.
145145

146-
That looks a bit odd, but can be worked around if we compare `clientWidth` before and after the freeze, and if it increased (the scrollbar disappeared) then add `padding` to `document.body` in place of the scrollbar, to keep the content width the same.
146+
Eso parece un poco extraño, pero puede solucionarse si comparamos `clientWidth` antes y después del congelamiento, y si aumentó (la barra de desplazamiento desapareció) luego agregue `padding` a `document.body` en lugar de la barra de desplazamiento, para que mantenga el ancho del contenido igual.
147147

148-
## Summary
148+
## Resumen
149149

150-
Geometry:
150+
Geometría:
151151

152-
- Width/height of the visible part of the document (content area width/height): `document.documentElement.clientWidth/Height`
153-
- Width/height of the whole document, with the scrolled out part:
152+
- Ancho/alto de la parte visible del documento (área de contenido ancho / alto): `document.documentElement.clientWidth/Height`
153+
- Ancho/alto de todo el documento, con la parte desplazada:
154154

155155
```js
156156
let scrollHeight = Math.max(
@@ -160,11 +160,11 @@ Geometry:
160160
);
161161
```
162162

163-
Scrolling:
163+
Desplazamiento:
164164

165-
- Read the current scroll: `window.pageYOffset/pageXOffset`.
166-
- Change the current scroll:
165+
- Lee el desplazamiento actual: `window.pageYOffset/pageXOffset`.
166+
- Cambia el desplazamiento actual:
167167

168-
- `window.scrollTo(pageX,pageY)` -- absolute coordinates,
169-
- `window.scrollBy(x,y)` -- scroll relative the current place,
170-
- `elem.scrollIntoView(top)` -- scroll to make `elem` visible (align with the top/bottom of the window).
168+
- `window.scrollTo(pageX,pageY)` -- coordenadas absolutas
169+
- `window.scrollBy(x,y)` -- desplazamiento relativo al lugar actual,
170+
- `elem.scrollIntoView(top)` -- desplácese para hacer visible el `elem` (alineación con la parte superior / inferior de la ventana).

0 commit comments

Comments
 (0)