Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Scrolling#330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
joaquinelio merged 23 commits intojavascript-tutorial:masterfromLeired7:Scrolling
Aug 1, 2020
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
23 commits
Select commitHold shift + click to select a range
78a2c32
Traducido
Leired7Jul 27, 2020
91310a9
Traducido
Leired7Jul 27, 2020
c17d015
Correciones
Leired7Jul 31, 2020
ac1313a
Traducido
Leired7Jul 31, 2020
7966e0b
Traducido
Leired7Jul 31, 2020
58c7f67
Traducido
Leired7Jul 31, 2020
3dbcac4
Traducido
Leired7Jul 31, 2020
e6dda83
Correciones
Leired7Jul 31, 2020
d5d58d1
Update 2-ui/3-event-details/8-onscroll/1-endless-page/solution.md
Leired7Aug 1, 2020
efdc7ac
Update 2-ui/3-event-details/8-onscroll/1-endless-page/solution.md
Leired7Aug 1, 2020
f39a7a4
Update 2-ui/3-event-details/8-onscroll/1-endless-page/solution.md
Leired7Aug 1, 2020
78a061c
Update 2-ui/3-event-details/8-onscroll/1-endless-page/task.md
Leired7Aug 1, 2020
b08da7f
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/task.md
Leired7Aug 1, 2020
db8261e
Update 2-ui/3-event-details/8-onscroll/article.md
Leired7Aug 1, 2020
75fafd5
Update 2-ui/3-event-details/8-onscroll/article.md
Leired7Aug 1, 2020
35717b6
Update 2-ui/3-event-details/8-onscroll/article.md
Leired7Aug 1, 2020
e2fc3bb
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/task.md
Leired7Aug 1, 2020
c4c3fbe
Update 2-ui/3-event-details/8-onscroll/1-endless-page/task.md
Leired7Aug 1, 2020
c695759
Update 2-ui/3-event-details/8-onscroll/2-updown-button/task.md
Leired7Aug 1, 2020
e434070
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.md
Leired7Aug 1, 2020
b9f812e
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.md
Leired7Aug 1, 2020
d4e2538
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/solution.md
Leired7Aug 1, 2020
e1c887a
Update 2-ui/3-event-details/8-onscroll/3-load-visible-img/task.md
Leired7Aug 1, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 24 additions & 24 deletions2-ui/3-event-details/8-onscroll/1-endless-page/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,63 @@
The core of the solution is a function that adds more dates to the page (or loads more stuff inreal-life) while we're at the page end.
El núcleo de la solución es una función que añade más fechas a la página (o carga más cosas en la vidareal) mientras estamos en el final de la página.

We can call it immediately and add as a `window.onscroll` handler.
Podemos llamarlo inmediatamente o agregarlo como un manejador de `window.onscroll`.

The most important question is: "How do we detect that the page is scrolled to bottom?"
La pregunta más importante es: "¿Cómo detectamos que la página se desplaza hasta el fondo?"

Let's use window-relative coordinates.
Usaremos las coordenadas de la ventana.

The document is represented (and contained) within`<html>` tag, that is `document.documentElement`.
El documento está representado (y contenido) dentro de la etiqueta`<html>`, que es `document.documentElement`.

We can get window-relative coordinates of the whole document as`document.documentElement.getBoundingClientRect()`,the`bottom`property will be window-relative coordinate of the document bottom.
Podemos obtener las coordenadas relativas a la ventana de todo el documento como`document.documentElement.getBoundingClientRect()`,la propiedad`bottom`será la coordenada relativa a la ventana del fondo del documento.

For instance, if the height of the whole HTML document is`2000px`,then:
Por ejemplo, si la altura de todo el documento es`2000px`,entonces:

```js
//when we're on the top of the page
// window-relative top = 0
//cuando estamos en la parte superior de la página
//window-relative top = 0 (relativo a la ventana, límite superior = 0 )
document.documentElement.getBoundingClientRect().top = 0

// window-relative bottom = 2000
//the document is long, so that is probably far beyond the window bottom
// window-relative bottom = 2000 (relativo a la ventana, límite inferior = 2000)
//el documento es largo, así que probablemente esté más allá del fondo de la ventana
document.documentElement.getBoundingClientRect().bottom = 2000
```

If we scroll `500px`below, then:
Si nos desplazamos `500px`abajo, entonces:

```js
//document top is above the window 500px
//la parte superior del documento está 500px por encima de la ventana
document.documentElement.getBoundingClientRect().top = -500
//document bottom is500pxcloser
//la parte inferior del documento está500pxmás cerca
document.documentElement.getBoundingClientRect().bottom = 1500
```

When we scroll till the end, assuming that the window height is `600px`:
Cuando nos desplazamos hasta el final, asumiendo que la altura de la venta es `600px`:


```js
//document top is above the window 1400px
//La parte superior del documento está 1400px sobre la ventana
document.documentElement.getBoundingClientRect().top = -1400
//document bottom is below the window600px
//la parte inferior del documento está a600px debajo de la ventana
document.documentElement.getBoundingClientRect().bottom = 600
```

Please note that the`bottom`can't be`0`,because it never reaches the window top. The lowest limit of the`bottom`coordinate is the window height (we assumed it to be`600`),we can't scroll it any more up.
Tened en cuenta que el fondo del documento`bottom`nunca puede ser`0`,porque nunca llega a la parte superior de la ventana. El límite más bajo de la coordenada`bottom`es la altura de la ventana (asumimos que es`600`),no podemos desplazarla más hacia arriba.

We can obtain the window height as `document.documentElement.clientHeight`.
Podemos obtener la altura de la ventana con `document.documentElement.clientHeight`.

For our task, we need to know when the document bottom is not no more than`100px`away from it (that is: `600-700px`,if the height is `600`).
Para nuestra tarea, necesitamos saber cuando tenemos el final del documento a unos`100px`(esto es: `600-700px`,si la altura es de `600`).

So here's the function:
Así que aquí está la función:

```js
function populate() {
while(true) {
//document bottom
//final del documento
let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;

//if the user scrolled far enough(<100pxto the end)
//si el usuario se desplaza lo suficiente(<100pxhasta el final)
if (windowRelativeBottom < document.documentElement.clientHeight + 100) {
//let's add more data
//vamos añadir más datos
document.body.insertAdjacentHTML("beforeend", `<p>Date: ${new Date()}</p>`);
}
}
Expand Down
16 changes: 8 additions & 8 deletions2-ui/3-event-details/8-onscroll/1-endless-page/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,19 +2,19 @@ importance: 5

---

#Endless page
#Página sin fin

Create an endless page. When a visitor scrolls it to the end, it auto-appends current date-time to the text (so that a visitor can scroll more).
Crear una página interminable. Cuando un visitante la desplace hasta el final, se auto-añadirá la fecha y hora actual al texto (así el visitante podrá seguir desplazándose)

Like this:
Así:

[iframe src="solution" height=200]

Please note two important features of the scroll:
Por favor tenga en cuenta dos características importantes del desplazamiento:

1. **The scrollis "elastic".**We can scroll a little beyond the document start or end in some browsers/devices (empty space below is shown, and then the document will automatically "bounces back" to normal).
2. **The scrollis imprecise.**When we scroll to page end, then we may be in fact like0-50pxaway from the real document bottom.
1. **El scrolles "elástico".**En algunos navegadores/dispositivos podemos desplazarnos un poco más allá del inicio o final del documento (se muestra un espacio vacío abajo, y luego el documento "rebota" automáticamente a la normalidad).
2. **El scrolles impreciso.**Cuando nos desplazamos hasta el final de la página, podemos estar de hecho como a0-50pxdel fondo del documento real.

So, "scrolling to the end" should mean that the visitor isnomore than 100px away from the document end.
Así que, "desplazarse hasta el final" debería significar que el visitantenoestá a más de 100px del final del documento.

P.S. In real life we may want to show "more messages" or "more goods".
P.D. En la vida real podemos querer mostrar "más mensajes" o "más bienes".
14 changes: 7 additions & 7 deletions2-ui/3-event-details/8-onscroll/2-updown-button/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,15 +2,15 @@ importance: 5

---

#Up/down button
#Botón para subir/bajar

Create a "to the top" button to help with page scrolling.
Crea un botón "ir arriba" para ayudar con el desplazamiento de la página.

It should work like this:
-While the page is not scrolled down at least for the window height -- it's invisible.
-When the page is scrolled down more than the window height--there appears an "upwards" arrow in the left-top corner. If the page is scrolled back, it disappears.
-When the arrow is clicked, the page scrolls to the top.
Debería funcionar así:
-Mientras que la página no se desplace hacia abajo al menos la altura de la ventana... es invisible.
-Cuando la página se desplaza hacia abajo más que la altura de la ventana--aparece una flecha "hacia arriba" en la esquina superior izquierda. Si la página se desplaza hacia atrás desaparece.
-Cuando se hace click en la flecha, la página se desplaza hacia arriba hasta el tope.

Like this (top-left corner, scroll to see):
Así (esquina superior izquierda, desplácese para ver):

[iframe border="1" height="200" link src="solution"]
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
The`onscroll`handler should check which images are visible and show them.
El manejador`onscroll`debería comprobar qué imágenes son visibles y mostrarlas.

We also want to run it when the page loads, to detect immediately visible images and load them.
También queremos que se ejecute cuando se cargue la página, para detectar las imágenes visibles inmediatamente y cargarlas.

The code should execute when the document is loaded, so that it has access to its content.
El código debería ejecutarse cuando se cargue el documento, para que tenga acceso a su contenido.

Or put it at the`<body>` bottom:
O ponerlo en la parte inferior del`<body>`:

```js
// ...the page content is above...
// ...el contenido de la página está arriba...

function isVisible(elem) {

let coords = elem.getBoundingClientRect();

let windowHeight = document.documentElement.clientHeight;

//top elem edge is visible?
//¿El borde superior del elemento es visible?
let topVisible = coords.top > 0 && coords.top < windowHeight;

//bottom elem edge is visible?
//¿El borde inferior del elemento es visible?
let bottomVisible = coords.bottom < windowHeight && coords.bottom > 0;

return topVisible || bottomVisible;
}
```

The`showVisible()`function uses the visibility check, implemented by `isVisible()`,to load visible images:
La función`showVisible()`utiliza el control de visibilidad, implementado por `isVisible()`,para cargar imágenes visibles:

```js
function showVisible() {
Expand All@@ -46,4 +46,4 @@ window.onscroll = showVisible;
*/!*
```

P.S. The solution also has a variant of`isVisible`that "preloads" images that are within 1 page above/below the current document scroll.
P.D. La solución tiene una variante de`isVisible`que "precarga" imágenes que están dentro de 1 página por encima/debajo del desplazamiento del documento actual.
24 changes: 12 additions & 12 deletions2-ui/3-event-details/8-onscroll/3-load-visible-img/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,29 +2,29 @@ importance: 4

---

#Load visible images
#Cargar imágenes visibles

Let's say we have a slow-speed client and want to save their mobile traffic.
Digamos que tenemos un cliente con baja velocidad de conexión y queremos cuidar su tarifa de datos.

For that purpose we decide not to show images immediately, but rather replace them with placeholders, like this:
Para ello decidimos no mostrar las imágenes inmediatemente, sino sustituirlas por marcadores de posición, como este:

```html
<img *!*src="placeholder.svg"*/!* width="128" height="128" *!*data-src="real.jpg"*/!*>
```

So, initially all images are`placeholder.svg`.When the page scrolls to the position where the user can see the image--we change`src`to the one in`data-src`,and so the image loads.
Así que, inicialmente todas las imágenes son`placeholder.svg`.Cuando la página se desplaza a la posición donde el usuario puede ver la imagen--cambiamos`src`a`data-src`,y así la imagen se carga.

Here's an example in `iframe`:
Aquí hay un ejemplo en `iframe`:

[iframe src="solution"]

Scroll it to see images load "on-demand".
Desplázate para ver las imagenes cargadas "bajo demanda".

Requirements:
-When the page loads, those images that are on-screen should load immediately, prior to any scrolling.
-Some images may be regular, without `data-src`.The code should not touch them.
-Once an image is loaded, it should not reload any more when scrolled in/out.
Requerimientos:
-Cuando la página se carga, las imágenes que están en pantalla deben cargarse inmediatamente, antes de cualquier desplazamiento.
-Algunas imágenes pueden ser regulares, sin `data-src`.El código no debe tocarlas.
-Una vez que una imagen se carga, no debe recargarse más cuando haya desplazamiento arriba/abajo.

P.S. If you can, make a more advanced solution that would "preload" images that are one page below/after the current position.
P.D. Si puedes, haz una solución más avanzada para "precargar" las imágenes que están más abajo/después de la posición actual.

P.P.S. Only vertical scroll is to be handled, nohorizontal scrolling.
Post P.D. Sólo se debe manejar el desplazamiento vertical, noel horizontal.
30 changes: 15 additions & 15 deletions2-ui/3-event-details/8-onscroll/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
#Scrolling
#Desplazamiento

The`scroll`event allows to react on a page or element scrolling. There are quite a few good things we can do here.
El evento`scroll`permite reaccionar al desplazamiento de una página o elemento. Hay bastantes cosas buenas que podemos hacer aquí.

For instance:
-Show/hide additional controls or information depending on where in the document the user is.
-Load more data when the user scrolls down till the end of the page.
Por ejemplo:
-Mostrar/ocultar controles o información adicional según el lugar del documento en el que se encuentre el/la usuario/a.
-Cargar más datos cuando el/la usuario/a se desplaza hacia abajo hasta el final del documento.

Here's a small function to show the current scroll:
Aquí hay una pequeña función para mostrar el desplazamiento actual:

```js autorun
window.addEventListener('scroll', function() {
Expand All@@ -17,21 +17,21 @@ window.addEventListener('scroll', function() {
```online
In action:

Current scroll = <b id="showScroll">scroll the window</b>
Desplazamiento actual = <b id="showScroll">Desplazamiento de la ventana</b>
```

The`scroll`event works both on the`window`and on scrollable elements.
El evento`scroll`funciona tanto en`window`como en los elementos desplazables.

##Prevent scrolling
##Evitar el desplazamiento

How do we make something unscrollable?
¿Qué hacemos para que algo no se pueda desplazar?

We can't prevent scrolling by using `event.preventDefault()`in`onscroll` listener, because it triggers *after* the scroll has already happened.
No podemos evitar el desplazamiento utilizando `event.preventDefault()`oyendo al evento`onscroll`, porque este se activa *después* de que el desplazamiento haya ocurrido.

But we can prevent scrolling by `event.preventDefault()`on an event that causes the scroll, for instance`keydown`event for`key:pageUp`and `key:pageDown`.
Pero podemos prevenir el desplazamiento con `event.preventDefault()`en un evento que cause el desplazamiento, por ejemplo en el evento`keydown`para`key:pageUp`y `key:pageDown`.

If we add an event handler to these events and`event.preventDefault()`in it, then the scroll won't start.
Si añadimos un manejador de eventos a estos eventos y un`event.preventDefault()`en el manejador, entonces el desplazamiento no se iniciará.

There are many ways to initiate a scroll, so it's more reliable to useCSS, `overflow` property.
Hay muchas maneras de iniciar un desplazamiento, la más fiable es usarCSS,la propiedad`overflow`.

Here are few tasks that you can solve or look through to see the applications on `onscroll`.
Aquí hay algunas tareas que puedes resolver o mirar para ver las aplicaciones de `onscroll`.

[8]ページ先頭

©2009-2025 Movatter.jp