diff --git a/2-ui/1-document/10-size-and-scroll-window/article.md b/2-ui/1-document/10-size-and-scroll-window/article.md index 08a2f6576..7e29d0e54 100644 --- a/2-ui/1-document/10-size-and-scroll-window/article.md +++ b/2-ui/1-document/10-size-and-scroll-window/article.md @@ -1,50 +1,50 @@ -# Window sizes and scrolling +# Tamanhos e rolagem da janela -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? +Como encontramos a largura e a altura da janela do navegador? Como obtemos a largura e a altura completas do documento, incluindo a parte rolada para fora? Como rolamos a página usando JavaScript? -For this type of information, we can use the root document element `document.documentElement`, that corresponds to the `` tag. But there are additional methods and peculiarities to consider. +Para esse tipo de informação, podemos usar o elemento raiz do documento `document.documentElement`, que corresponde à tag ``. Mas há métodos adicionais e peculiaridades a considerar. -## Width/height of the window +## Largura/altura da janela -To get window width and height, we can use the `clientWidth/clientHeight` of `document.documentElement`: +Para obter a largura e a altura da janela, podemos usar `clientWidth/clientHeight` de `document.documentElement`:  ```online -For instance, this button shows the height of your window: +Por exemplo, este botão mostra a altura da sua janela: ``` -````warn header="Not `window.innerWidth/innerHeight`" -Browsers also support properties like `window.innerWidth/innerHeight`. They look like what we want, so why not to use them instead? +````warn header="Não `window.innerWidth/innerHeight`" +Os navegadores também suportam propriedades como `window.innerWidth/innerHeight`. Elas parecem ser o que queremos, então por que não usá-las? -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 the width/height of the visible part of the document, available for the content. +Se existe uma barra de rolagem, e ela ocupa algum espaço, `clientWidth/clientHeight` fornecem a largura/altura sem ela (subtraindo-a). Em outras palavras, elas retornam a largura/altura da parte visível do documento, disponível para o conteúdo. -`window.innerWidth/innerHeight` includes the scrollbar. +`window.innerWidth/innerHeight` inclui a barra de rolagem. -If there's a scrollbar, and it occupies some space, then these two lines show different values: +Se há uma barra de rolagem, e ela ocupa algum espaço, então essas duas linhas mostram valores diferentes: ```js run -alert( window.innerWidth ); // full window width -alert( document.documentElement.clientWidth ); // window width minus the scrollbar +alert( window.innerWidth ); // largura completa da janela +alert( document.documentElement.clientWidth ); // largura da janela menos a barra de rolagem ``` -In most cases, we need the *available* window width in order to draw or position something within scrollbars (if there are any), so we should use `documentElement.clientHeight/clientWidth`. +Na maioria dos casos, precisamos da largura *disponível* da janela para desenhar ou posicionar algo dentro das barras de rolagem (se houver alguma), então devemos usar `documentElement.clientHeight/clientWidth`. ```` -```warn header="`DOCTYPE` is important" -Please note: top-level geometry properties may work a little bit differently when there's no `` in HTML. Odd things are possible. +```warn header="`DOCTYPE` é importante" +Note: as propriedades de geometria de nível superior podem funcionar de forma um pouco diferente quando não há `` no HTML. Coisas estranhas são possíveis. -In modern HTML we should always write `DOCTYPE`. +No HTML moderno devemos sempre escrever o `DOCTYPE`. ``` -## Width/height of the document +## Largura/altura do documento -Theoretically, as the root document element is `document.documentElement`, and it encloses all the content, we could measure the document's full size as `document.documentElement.scrollWidth/scrollHeight`. +Teoricamente, como o elemento raiz do documento é `document.documentElement`, e ele envolve todo o conteúdo, poderíamos medir o tamanho completo do documento como `document.documentElement.scrollWidth/scrollHeight`. -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`! Weird, right? +Mas nesse elemento, para a página como um todo, essas propriedades não funcionam como esperado. No Chrome/Safari/Opera, se não houver rolagem, então `documentElement.scrollHeight` pode ser até menor que `documentElement.clientHeight`! Estranho, não é? -To reliably obtain the full document height, we should take the maximum of these properties: +Para obter de forma confiável a altura completa do documento, devemos pegar o máximo entre essas propriedades: ```js run let scrollHeight = Math.max( @@ -53,110 +53,110 @@ let scrollHeight = Math.max( document.body.clientHeight, document.documentElement.clientHeight ); -alert('Full document height, with scrolled out part: ' + scrollHeight); +alert('Altura completa do documento, com a parte rolada para fora: ' + scrollHeight); ``` -Why so? Better don't ask. These inconsistencies come from ancient times, not a "smart" logic. +Por que isso acontece? Melhor nem perguntar. Essas inconsistências vêm de tempos antigos, não de uma lógica "inteligente". -## Get the current scroll [#page-scroll] +## Obtenha a rolagem atual [#page-scroll] -DOM elements have their current scroll state in their `scrollLeft/scrollTop` properties. +Os elementos do DOM têm seu estado de rolagem atual em suas propriedades `scrollLeft/scrollTop`. -For document scroll, `document.documentElement.scrollLeft/scrollTop` 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`. +Para a rolagem do documento, `document.documentElement.scrollLeft/scrollTop` funciona na maioria dos navegadores, exceto nos mais antigos baseados em WebKit, como o Safari (bug [5991](https://bugs.webkit.org/show_bug.cgi?id=5991)), onde devemos usar `document.body` em vez de `document.documentElement`. -Luckily, we don't have to remember these peculiarities at all, because the scroll is available in the special properties, `window.pageXOffset/pageYOffset`: +Felizmente, não precisamos lembrar dessas peculiaridades, porque a rolagem está disponível nas propriedades especiais `window.pageXOffset/pageYOffset`: ```js run -alert('Current scroll from the top: ' + window.pageYOffset); -alert('Current scroll from the left: ' + window.pageXOffset); +alert('Rolagem atual a partir do topo: ' + window.pageYOffset); +alert('Rolagem atual a partir da esquerda: ' + window.pageXOffset); ``` -These properties are read-only. +Essas propriedades são apenas leitura. -```smart header="Also available as `window` properties `scrollX` and `scrollY`" -For historical reasons, both properties exist, but they are the same: -- `window.pageXOffset` is an alias of `window.scrollX`. -- `window.pageYOffset` is an alias of `window.scrollY`. +```smart header="Também disponível como as propriedades `scrollX` e `scrollY` de `window`" +Por razões históricas, ambas as propriedades existem, mas são a mesma coisa: +- `window.pageXOffset` é outro nome para `window.scrollX`. +- `window.pageYOffset` é outro nome para `window.scrollY`. ``` -## Scrolling: scrollTo, scrollBy, scrollIntoView [#window-scroll] +## Rolagem: scrollTo, scrollBy, scrollIntoView [#window-scroll] ```warn -To scroll the page with JavaScript, its DOM must be fully built. +Para rolar a página com JavaScript, seu DOM deve estar completamente construído. -For instance, if we try to scroll the page with a script in `
`, it won't work. +Por exemplo, se tentarmos rolar a página com um script no ``, não vai funcionar. ``` -Regular elements can be scrolled by changing `scrollTop/scrollLeft`. +Elementos comuns podem ser rolados alterando `scrollTop/scrollLeft`. -We can do the same for the page using `document.documentElement.scrollTop/scrollLeft` (except Safari, where `document.body.scrollTop/Left` should be used instead). +Podemos fazer o mesmo para a página usando `document.documentElement.scrollTop/scrollLeft` (exceto no Safari, onde `document.body.scrollTop/Left` deve ser usado em vez disso). -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). +Alternativamente, há uma solução mais simples e universal: os métodos especiais [window.scrollBy(x,y)](mdn:api/Window/scrollBy) e [window.scrollTo(pageX,pageY)](mdn:api/Window/scrollTo). -- The method `scrollBy(x,y)` scrolls the page *relative to its current position*. For instance, `scrollBy(0,10)` scrolls the page `10px` down. +- O método `scrollBy(x,y)` rola a página *em relação à sua posição atual*. Por exemplo, `scrollBy(0,10)` rola a página `10px` para baixo. ```online - The button below demonstrates this: + O botão abaixo demonstra isso: ``` -- 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`. +- O método `scrollTo(pageX,pageY)` rola a página *para coordenadas absolutas*, de forma que o canto superior esquerdo da parte visível tenha coordenadas `(pageX, pageY)` em relação ao canto superior esquerdo do documento. É como definir `scrollLeft/scrollTop`. - To scroll to the very beginning, we can use `scrollTo(0,0)`. + Para rolar até o início, podemos usar `scrollTo(0,0)`. ```online ``` -These methods work for all browsers the same way. +Esses métodos funcionam da mesma forma em todos os navegadores. ## scrollIntoView -For completeness, let's cover one more method: [elem.scrollIntoView(top)](mdn:api/Element/scrollIntoView). +Para completar, vamos abordar mais um método: [elem.scrollIntoView(top)](mdn:api/Element/scrollIntoView). -The call to `elem.scrollIntoView(top)` scrolls the page to make `elem` visible. It has one argument: +A chamada a `elem.scrollIntoView(top)` rola a página para fazer `elem` ficar visível. Ela tem um argumento: -- 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 will be aligned with the window top. -- If `top=false`, then the page scrolls to make `elem` appear at the bottom. The bottom edge of the element will be aligned with the window bottom. +- Se `top=true` (esse é o padrão), então a página será rolada para fazer `elem` aparecer no topo da janela. A borda superior do elemento será alinhada com o topo da janela. +- Se `top=false`, então a página rola para fazer `elem` aparecer na parte de baixo. A borda inferior do elemento será alinhada com a parte de baixo da janela. ```online -The button below scrolls the page to position itself at the window top: +O botão abaixo rola a página para se posicionar no topo da janela: -And this button scrolls the page to position itself at the bottom: +E este botão rola a página para se posicionar na parte de baixo: ``` -## Forbid the scrolling +## Impedindo a rolagem -Sometimes we need to make the document "unscrollable". For instance, when we need to cover the page with a large message requiring immediate attention, and we want the visitor to interact with that message, not with the document. +Às vezes precisamos tornar o documento "não rolável". Por exemplo, quando precisamos cobrir a página com uma mensagem grande que requer atenção imediata, e queremos que o visitante interaja com essa mensagem, não com o documento. -To make the document unscrollable, it's enough to set `document.body.style.overflow = "hidden"`. The page will "freeze" at its current scroll position. +Para tornar o documento não rolável, basta definir `document.body.style.overflow = "hidden"`. A página vai "congelar" na sua posição de rolagem atual. ```online -Try it: +Tente: -The first button freezes the scroll, while the second one releases it. +O primeiro botão congela a rolagem, enquanto o segundo a libera. ``` -We can use the same technique to freeze the scroll for other elements, not just for `document.body`. +Podemos usar a mesma técnica para congelar a rolagem de outros elementos, não só de `document.body`. -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. +A desvantagem desse método é que a barra de rolagem desaparece. Se ela ocupava algum espaço, então esse espaço fica livre e o conteúdo "salta" para preenchê-lo. -That looks a bit odd, but can be worked around if we compare `clientWidth` before and after the freeze. If it increased (the scrollbar disappeared), then add `padding` to `document.body` in place of the scrollbar to keep the content width the same. +Isso parece um pouco estranho, mas pode ser contornado se compararmos `clientWidth` antes e depois do congelamento. Se ele aumentou (a barra de rolagem desapareceu), então adicione `padding` a `document.body` no lugar da barra de rolagem para manter a largura do conteúdo a mesma. -## Summary +## Resumo -Geometry: +Geometria: -- Width/height of the visible part of the document (content area width/height): `document.documentElement.clientWidth/clientHeight` -- Width/height of the whole document, with the scrolled out part: +- Largura/altura da parte visível do documento (largura/altura da área de conteúdo): `document.documentElement.clientWidth/clientHeight` +- Largura/altura de todo o documento, com a parte rolada para fora: ```js let scrollHeight = Math.max( @@ -166,11 +166,11 @@ Geometry: ); ``` -Scrolling: +Rolagem: -- Read the current scroll: `window.pageYOffset/pageXOffset`. -- Change the current scroll: +- Ler a rolagem atual: `window.pageYOffset/pageXOffset`. +- Alterar a rolagem atual: - - `window.scrollTo(pageX,pageY)` -- absolute coordinates, - - `window.scrollBy(x,y)` -- scroll relative the current place, - - `elem.scrollIntoView(top)` -- scroll to make `elem` visible (align with the top/bottom of the window). + - `window.scrollTo(pageX,pageY)` -- coordenadas absolutas, + - `window.scrollBy(x,y)` -- rola em relação ao local atual, + - `elem.scrollIntoView(top)` -- rola para fazer `elem` ficar visível (alinhando com o topo/a parte de baixo da janela).