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

Introduction to browser events#392

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
maksumi merged 7 commits intojavascript-tutorial:masterfrommaksumi:browser-events
Oct 2, 2020
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,13 @@

<body>

<input type="button" id="hider" value="Click to hide the text"/>
<input type="button" id="hider" value="Haz click para desaparecer el texto"/>

<div id="text">Text</div>
<div id="text">Texto</div>

<script>
//Here it doesn't matter how we hide the text,
//could also use style.display:
//Aquí no importa cómo escondamos el texto
//podríamos usar style.display:
document.getElementById('hider').onclick = function() {
document.getElementById('text').hidden = true;
}
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,12 +7,12 @@

<body>

<input type="button" id="hider" value="Click to hide the text"/>
<input type="button" id="hider" value="Haz click para desaparecer el texto"/>

<div id="text">Text</div>
<div id="text">Texto</div>

<script>
/*your code */
/*Tu código */
</script>

</body>
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,10 +2,10 @@ importance: 5

---

#Hide on click
#Ocultar con un click

Add JavaScriptto the`button`to make`<div id="text">`disappear when we click it.
Agrega JavaScriptal`button`para hacer que`<div id="text">`desaparezca al clickearlo.

The demo:
El demo:

[iframe border=1 src="solution" height=80]
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
Can use `this`in the handlerto reference "the element itself" here:
Podemos usar `this`en el handlerpara referenciar "al propio elemento" aquí:

```html run height=50
<input type="button" onclick="this.hidden=true" value="Clickto hide">
<input type="button" onclick="this.hidden=true" value="Clickpara ocultar">
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,11 @@ importance: 5

---

#Hide self
#Ocultarse

Create a button that hides itself on click.
Crea un botón que se oculte a sí mismo al darle un click.

```online
Like this:
<input type="button" onclick="this.hidden=true" value="Clickto hide">
Así:
<input type="button" onclick="this.hidden=true" value="Clickpara esconder">
```
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
The answer: `1`and `2`.
La respuesta: `1`y `2`.

The first handlertriggers, because it's not removed by`removeEventListener`.To remove the handlerwe need to pass exactly the function that was assigned. And in the code a new function is passed, that looks the same, but is still another function.
El primer handlerse activa porque no es removido por`removeEventListener`.Para remover el handlernecesitamos pasar exactamente la función que fue asignada. Y en el código se pasa una función que luce igual pero es otra función.

To remove a function object, we need to store a reference to it, like this:
Para remover un objeto de función necesitamos almacenar una referencia a él, así:

```js
function handler() {
Expand All@@ -13,4 +13,4 @@ button.addEventListener("click", handler);
button.removeEventListener("click", handler);
```

The handler `button.onclick`works independently and in addition to `addEventListener`.
El handler `button.onclick`funciona independientemente y en adición a `addEventListener`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,11 @@ importance: 5

---

#Which handlersrun?
#¿Qué handlersse ejecutan?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Correcto, pero tengo una duda ¿no hemos traducido handler en anteriores artículos? Creo que es mejor mantener esa consistencia. No importa si se traduce como manejador o controlador, pero creo que es mejor traducirlo.


There's a button in the variable.There are nohandlerson it.
Hay un botón en la variable.No hayhandlersen él.

Which handlersrun onclickafter the following code? Which alerts show up?
¿Qué handlersse ejecutan con elclickdespués del siguiente código? ¿Qué alertas se muestran?

```js no-beautify
button.addEventListener("click", () => alert("1"));
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@

First we need to choose a method of positioning the ball.
Primero necesitamos elegir un método para posicionar el balón.

We can't use `position:fixed`for it, because scrolling the page would move the ball from the field.
No podemos usar `position:fixed`para ello, porque al desplazar la página se movería el balón del campo.

So we should use `position:absolute`and, to make the positioning really solid, make`field`itself positioned.
Así que deberíamos usar `position:absolute`y, para que el posicionamiento sea realmente sólido, hacer que`field`sea posicione a sí mismo.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

entendemos "solido" ?

en ingles "solid" es una persona confiable, ¿el ruso lo esta usando asi? seria medio rebuscado

la cosa que no "posicionamiento solido" que se refiere a coordenadas relativass al contenido no al browser
aunque quizaas sea equivalente a decir :absolute y np lo entiendo...

ok no importa


Then the ball will be positioned relatively to the field:
Entonces el balón se posicionará en relación al campo:

```css
#field {
Expand All@@ -16,36 +16,36 @@ Then the ball will be positioned relatively to the field:

#ball {
position: absolute;
left: 0; /*relative to the closest positioned ancestor (field) */
left: 0; /*relativo al predecesor más cercano (field) */
top: 0;
transition: 1s all; /* CSSanimation for left/topmakes the ball fly */
transition: 1s all; /*AnimaciónCSSpara que left/tophagan al balón volar */
}
```

Next we need to assign the correct`ball.style.left/top`. They contain field-relative coordinates now.
Lo siguiente es asignar el`ball.style.left/top` correcto. Ahora contienen coordenadas relativas al campo.

Here's the picture:
Aquí está la imagen:

![](move-ball-coords.svg)

We have`event.clientX/clientY` -- window-relative coordinates of theclick.
Tenemos`event.clientX/clientY`, las cuales son las coordenadas delclick relativas a la ventana.

To get field-relative`left`coordinate of the click, we can substract the field left edge and the border width:
Para obtener la coordenada`left`del click relativa al campo necesitamos restar el limite izquierdo del campo y el ancho del borde:

```js
let left = event.clientX - fieldCoords.left - field.clientLeft;
```

Normally, `ball.style.left`means the "left edge of the element" (the ball).So if we assign that`left`,then the ball edge, not center, would be under the mousecursor.
Normalmente `ball.style.left`significa el "borde izquierdo del elemento" (el balón).Por lo que si asignamos ese`left`,entonces el borde del balón, no el centro, es el que se encontraría debajo delcursor del mouse.

We need to move the ball half-width left and half-height up to make it center.
Necesitamos mover la mitad del ancho del balón a la izquierda y la mitad del alto hacia arriba para que quede en el centro.

So the final`left`would be:
Por lo que el`left`final debería ser:

```js
let left = event.clientX - fieldCoords.left - field.clientLeft - ball.offsetWidth/2;
```

Theverticalcoordinate is calculated using the same logic.
La coordenadaverticales calculada usando la misma lógica.

Please note that the ball width/height must be known at the time we access`ball.offsetWidth`.Should be specified in HTMLor CSS.
Por favor, nota que el ancho/alto del balón se debe conocer al momento que accedemos a`ball.offsetWidth`.Se debe especificar en HTMLo CSS.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -27,7 +27,7 @@

<body style="height:2000px">

Click on a field to move the ball there.
Haz click en un lugar del campo para mover el balón allí.
<br>


Expand All@@ -39,29 +39,29 @@
<script>
field.onclick = function(event) {

//window-relative field coordinates
//Coordenadas del campo relativas a la ventana
let fieldCoords = this.getBoundingClientRect();

//the ball has position:absolute,the field: position:relative
//so ball coordinates are relative to the field inner left-upper corner
//El balón tiene position:absolute,el campo: position:relative
//por lo que las coordenadas de la bola son relativas a la esquina superior izquierda interna del campo
let ballCoords = {
top: event.clientY - fieldCoords.top - field.clientTop - ball.clientHeight / 2,
left: event.clientX - fieldCoords.left - field.clientLeft - ball.clientWidth / 2
};

//prevent crossing the top field boundary
//previniendo el cruce del limite superior del campo
if (ballCoords.top < 0) ballCoords.top = 0;

//prevent crossing the left field boundary
//previniendo el cruce del limite izquierdo del campo
if (ballCoords.left < 0) ballCoords.left = 0;


// //prevent crossing the right field boundary
// //previniendo el cruce del limite derecho del campo
if (ballCoords.left + ball.clientWidth > field.clientWidth) {
ballCoords.left = field.clientWidth - ball.clientWidth;
}

//prevent crossing the bottom field boundary
//previniendo el cruce del limite inferior del campo
if (ballCoords.top + ball.clientHeight > field.clientHeight) {
ballCoords.top = field.clientHeight - ball.clientHeight;
}
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -16,8 +16,8 @@

<body style="height:2000px">

Click on a field to move the ball there.
<br>The ball should never leave the field.
Haz click en un lugar del campo para mover el balón allí.
<br>El balón nunca debe abandonar el campo.


<div id="field">
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,20 +2,20 @@ importance: 5

---

#Move the ball across the field
#Mueve el balón por el campo

Move the ball across the field to a click.Like this:
Mueve el balón por el campo con un click.Así:

[iframe src="solution" height="260" link]

Requirements:
Requerimientos:

-The ball center should come exactly under the pointer onclick (if possible without crossing the field edge).
- CSS-animation is welcome.
-The ball must not cross field boundaries.
-When the page is scrolled, nothing should break.
-El centro del balón debe quedar exactamente bajo el cursor al hacerclick (sin atravesar el borde del campo si es posible).
-Las animacionesCSS son bienvenidas.
-El balón no debe cruzar los límites del campo.
-Cuando la página se desplace nada se debe romper.

Notes:
Notas:

-The code should also work with different ball and field sizes, not be bound to any fixed values.
-Use properties`event.clientX/event.clientY`for click coordinates.
-El código también debe funcionar con medidas diferentes de campo y balón, no debe estar asociado a ningún valor fijo.
-Usa las propiedades`event.clientX/event.clientY`para las coordenadas del click.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@

# HTML/CSS
First let's createHTML/CSS.
Primero hay que crear elHTML yCSS.

A menu is a standalone graphical component on the page, so it's better to put it into a single DOM element.
Un menú es un componente gráfico independiente en la página, por lo que es mejor colocarlo en un solo elemento del DOM.

A list of menu items can be laid out as a list `ul/li`.
Una lista de elementos del menú se puede diseñar como una lista `ul/li`.

Here's the example structure:
Aquí está la estructura de ejemplo:

```html
<div class="menu">
Expand All@@ -19,29 +19,29 @@ Here's the example structure:
</div>
```

We use`<span>`for the title, because `<div>`has an implicit`display:block`on it, and it will occupy 100%of the horizontal width.
Usamos`<span>`para el título, porque `<div>`tiene un`display:block`implícito en él, y va a ocupar 100%del ancho horizontal.

Like this:
Así:

```html autorun height=50
<div style="border: solid red 1px" onclick="alert(1)">Sweeties (click me)!</div>
```

So if we set`onclick`on it, then it will catch clicks to the right of the text.
Entonces si establecemos`onclick`en él, detectará los clics a la derecha del texto.

As `<span>`has an implicit`display: inline`, it occupies exactly enough place to fit all the text:
Como `<span>`tiene un`display: inline` implícito, ocupa exactamente el lugar suficiente para que quepa todo el texto:

```html autorun height=50
<span style="border: solid red 1px" onclick="alert(1)">Sweeties (click me)!</span>
```

#Toggling the menu
#Alternar el menú

Toggling the menu should change the arrow and show/hide the menu list.
Alternar el menú debería cambiar la flecha y mostrar/ocultar la lista del menú.

All these changes are perfectly handled by CSS.In JavaScriptwe should label the current state of the menu by adding/removing the class `.open`.
Todos estos cambios son perfectamente controlados con CSS.En JavaScriptdebemos etiquetar el estado actual del menú agregando/eliminando la clase `.open`.

Without it, the menu will be closed:
Sin él, el menú se cerrará:

```css
.menu ul {
Expand All@@ -58,7 +58,7 @@ Without it, the menu will be closed:
}
```

...And with `.open`the arrow changes and the list shows up:
...Y con `.open`la flecha cambia y aparece la lista:

```css
.menu.open .title::before {
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,10 +2,10 @@ importance: 5

---

#Create a sliding menu
#Crear un menú deslizante

Create a menu that opens/collapses on click:
Crea un menú que se abra/colapse al hacer click:

[iframe border=1 height=100 src="solution"]

P.S.HTML/CSSof the source document is to be modified.
P.D. ElHTML/CSSdel documento fuente se debe modificar.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@

To add the button we can use either`position:absolute` (and make the pane `position:relative`)or `float:right`.The `float:right`has the benefit that the button never overlaps the text, but`position:absolute`gives more freedom. So the choice is yours.
Para agregar el botón podemos usar cualquiera de las opciones`position:absolute` (y hacer el panel `position:relative`)o `float:right`.El `float:right`tiene la ventaja de que el botón no se encima con el texto, pero`position:absolute`da más libertad. Entonces la elección es tuya.

Then for each pane the code can be like:
Luego, para cada panel, el código puede ser así:
```js
pane.insertAdjacentHTML("afterbegin", '<button class="remove-button">[x]</button>');
```

Then the `<button>`becomes`pane.firstChild`,so we can add a handler to it like this:
Luego el `<button>`se convierte en`pane.firstChild`,por lo que podemos agregarle un controlador como este:

```js
pane.firstChild.onclick = () => pane.remove();
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@ <h3>Cat</h3>

for(let pane of panes) {
pane.insertAdjacentHTML("afterbegin", '<button class="remove-button">[x]</button>');
// buttonbecomes the firstchildof pane
// buttondebe convertirse en el primerchildde pane
pane.firstChild.onclick = () => pane.remove();
}
</script>
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,12 +2,12 @@ importance: 5

---

#Add a closing button
#Agregar un botón de cierre

There's a list of messages.
Hay una lista de mensajes.

Use JavaScriptto add a closing button to the right-upper corner of each message.
Usa JavaScriptpara agregar un botón de cierre en la esquina superior derecha de cada mensaje.

The result should look like this:
El resultado debería verse algo así:

[iframe src="solution" height=450]
Loading

[8]ページ先頭

©2009-2025 Movatter.jp