`
+2. Escrever as propriedades diretamente no atributo `style`: `
`.
-JavaScript can modify both classes and `style` properties.
+O JavaScript pode modificar tanto as classes quanto a propriedade `style`.
-We should always prefer CSS classes to `style`. The latter should only be used if classes "can't handle it".
+Devemos sempre preferir classes CSS no lugar do atributo `style`. Este último só deve ser usado se as classes "não conseguirem lidar com a estilização".
-For example, `style` is acceptable if we calculate coordinates of an element dynamically and want to set them from JavaScript, like this:
+Por exemple, `style` é aceitável se calculamos as coordenadas de um elemento dinamicamente e queremos defini-las a partir do JavaScript, dessa maneira:
```js
-let top = /* complex calculations */;
-let left = /* complex calculations */;
+let top = /* cálculos complexos */;
+let left = /* cálculos complexos */;
-elem.style.left = left; // e.g '123px', calculated at run-time
-elem.style.top = top; // e.g '456px'
+elem.style.left = left; // por exemplo, '123px', calculado em tempo de execução
+elem.style.top = top; // por exemplo, '456px'
```
-For other cases, like making the text red, adding a background icon -- describe that in CSS and then add the class (JavaScript can do that). That's more flexible and easier to support.
+Em outros casos, como deixar o texto vermelho, adicionar um ícone de fundo, descreva isso usando CSS e então adicione a classe (o JavaScript pode fazer isso). Isso é mais flexível e mais fácil de manter.
-## className and classList
+## className e classList
-Changing a class is one of the most often used actions in scripts.
+Alterar uma classe é uma das ações mais utilizadas em scripts.
-In the ancient time, there was a limitation in JavaScript: a reserved word like `"class"` could not be an object property. That limitation does not exist now, but at that time it was impossible to have a `"class"` property, like `elem.class`.
+Antigamente, havia uma limitação no JavaScript: uma palavra reservada como `"class"` não poderia ser uma propriedade de objeto. Esta limitação não existe hoje, porém naquela época era impossível haver uma propriedade `"class"`, como `elem.class`.
-So for classes the similar-looking property `"className"` was introduced: the `elem.className` corresponds to the `"class"` attribute.
+Portanto, para classes, uma propriedade semelhante, `"className"`, foi introduzida: o `elem.className` corresponde ao atributo `"class"`.
-For instance:
+Por exemplo:
```html run
```
-If we assign something to `elem.className`, it replaces the whole string of classes. Sometimes that's what we need, but often we want to add/remove a single class.
+Se atribuirmos algo a `elem.className`, isto substituirá toda a sequência de classes. Às vezes é disso que precisamos, mas muitas vezes queremos adicionar ou remover uma única classe.
-There's another property for that: `elem.classList`.
+Existe outra propriedade para isso `elem.classList`.
-The `elem.classList` is a special object with methods to `add/remove/toggle` a single class.
+O `elem.classList` é um objeto especial com métodos para `adicionar/remover/alternar` uma única classe.
-For instance:
+Por exemplo:
```html run
```
-So we can operate both on the full class string using `className` or on individual classes using `classList`. What we choose depends on our needs.
+Então, podemos manipular tanto a string de classes completa usando `className` quanto classes individuais usando `classList`. A escolha depende das nossas necessidades.
-Methods of `classList`:
+Métodos de `classList`:
-- `elem.classList.add/remove("class")` -- adds/removes the class.
-- `elem.classList.toggle("class")` -- adds the class if it doesn't exist, otherwise removes it.
-- `elem.classList.contains("class")` -- checks for the given class, returns `true/false`.
+- `elem.classList.add/remove("class")` -- adiciona/remove a classe.
+- `elem.classList.toggle("class")` -- adiciona a classe se ela não existir, caso contrário a remove.
+- `elem.classList.contains("class")` -- verifica se a classe especificada existe, retorna `true/false`.
-Besides, `classList` is iterable, so we can list all classes with `for..of`, like this:
+Além disso, `classList` é iterável, então podemos listar todas as classes com `for..of`, assim:
```html run
```
-## Element style
+## Estilo do elemento
-The property `elem.style` is an object that corresponds to what's written in the `"style"` attribute. Setting `elem.style.width="100px"` works the same as if we had in the attribute `style` a string `width:100px`.
+A propriedade `elem.style` é um objeto que corresponde ao que está escrito no atributo `"style"`. Definir `elem.style.width="100px"` funciona da mesma maneira como se nós tivéssemos uma string `width:100px` no atributo `style`.
-For multi-word property the camelCase is used:
+Para propriedades de múltiplas palavras, o camelCase é utilizado:
```js no-beautify
background-color => elem.style.backgroundColor
@@ -94,16 +94,16 @@ z-index => elem.style.zIndex
border-left-width => elem.style.borderLeftWidth
```
-For instance:
+Por exemplo:
```js run
document.body.style.backgroundColor = prompt('background color?', 'green');
```
-````smart header="Prefixed properties"
-Browser-prefixed properties like `-moz-border-radius`, `-webkit-border-radius` also follow the same rule: a dash means upper case.
+````smart header="Propriedades pré-fixadas"
+Propriedades com prefixo de navegador como `-moz-border-radius`, `-webkit-border-radius` também segue a mesma regra: um traço indica uma letra maiúscula.
-For instance:
+Por exemplo:
```js
button.style.MozBorderRadius = '5px';
@@ -111,41 +111,39 @@ button.style.WebkitBorderRadius = '5px';
```
````
-## Resetting the style property
+## Redefinindo a propriedade de estilo
-Sometimes we want to assign a style property, and later remove it.
+Às vezes queremos atribuir uma propriedade de estilo, e depois removê-la.
-For instance, to hide an element, we can set `elem.style.display = "none"`.
+Por exemplo, para esconder um elemento, podemos definir `elem.style.display = "none"`.
-Then later we may want to remove the `style.display` as if it were not set. Instead of `delete elem.style.display` we should assign an empty string to it: `elem.style.display = ""`.
+Depois, podemos querer remover o `style.display` como se não estivesse sido definido. Em vez de `delete elem.style.display`, devemos atribuir uma string vazia a ele: `elem.style.display = ""`.
```js run
-// if we run this code, the will blink
-document.body.style.display = "none"; // hide
+// Se executarmos esse código o irá piscar.
+document.body.style.display = "none"; // esconder
-setTimeout(() => document.body.style.display = "", 1000); // back to normal
+setTimeout(() => document.body.style.display = "", 1000); // de volta ao normal
```
+Se definirmos `style.display` como uma string vazia o navegador aplicará classes CSS e seus estilos nativos normalmente, como se, de fato, não existisse nenhuma propriedade `style.display`.
-If we set `style.display` to an empty string, then the browser applies CSS classes and its built-in styles normally, as if there were no such `style.display` property at all.
-
-Also there is a special method for that, `elem.style.removeProperty('style property')`. So, We can remove a property like this:
+Também existe um método especial para isso, `elem.style.removeProperty('style property')`. Assim, podemos remover uma propriedade desta forma:
```js run
-document.body.style.background = 'red'; //set background to red
+document.body.style.background = 'red'; // define a cor de fundo para vermelho
-setTimeout(() => document.body.style.removeProperty('background'), 1000); // remove background after 1 second
+setTimeout(() => document.body.style.removeProperty('background'), 1000); // remove o fundo após um segundo
```
-````smart header="Full rewrite with `style.cssText`"
-Normally, we use `style.*` to assign individual style properties. We can't set the full style like `div.style="color: red; width: 100px"`, because `div.style` is an object, and it's read-only.
-
-To set the full style as a string, there's a special property `style.cssText`:
+````smart header="Reescrita completa com `style.cssText`"
+Normalmente, usamos `style.*` para atribuir propriedades de estilos individuais. Não podemos definir o estilo completo como `div.style="color: red; width: 100px"`, pois `div.style` é um objeto sendo somente para leitura.
+Para definir o estilo completo como uma string, existe uma propriedade especial `style.cssText`:
```html run
Button
```
+Esta propriedade é raramente usada, pois, a atribuição remove todos os estilos existentes: ela não adiciona, mas os substitui. Pode ocasionalmente deletar algo necessário. Mas podemos usá-la com segurança para elementos novos, quando sabemos que não vamos deletar um estilo existente.
-This property is rarely used, because such assignment removes all existing styles: it does not add, but replaces them. May occasionally delete something needed. But we can safely use it for new elements, when we know we won't delete an existing style.
-
-The same can be accomplished by setting an attribute: `div.setAttribute('style', 'color: red...')`.
+O mesmo pode ser alcançado definindo um atributo: `div.setAttribute('style', 'color: red...')`.
````
-## Mind the units
+## Fique atento às unidades
-Don't forget to add CSS units to values.
+Não se esqueça de adicionar as unidades CSS aos valores.
-For instance, we should not set `elem.style.top` to `10`, but rather to `10px`. Otherwise it wouldn't work:
+Por exemplo, não devemos definir `elem.style.top` como `10`, mas sim como `10px`. Caso contrário, não funcionará:
```html run height=100
```
+Repare: o navegador "descompacta" a propriedade `style.margin` nas últimas linhas e infere `style.marginLeft` e `style.marginTop` a partir dela.
-Please note: the browser "unpacks" the property `style.margin` in the last lines and infers `style.marginLeft` and `style.marginTop` from it.
-
-## Computed styles: getComputedStyle
+## Estilos computados: getComputedStyle
-So, modifying a style is easy. But how to *read* it?
+Portanto, modificar um estilo é fácil. Mas como lê-lo?
-For instance, we want to know the size, margins, the color of an element. How to do it?
+Por exemplo, queremos saber o tamanho, as margens e a cor de um elemento. Como fazer isso?
-**The `style` property operates only on the value of the `"style"` attribute, without any CSS cascade.**
+**A propriedade `style` opera apenas no valor do atributo `"style"`, sem qualquer cascata CSS.**
-So we can't read anything that comes from CSS classes using `elem.style`.
+Então, não podemos ler nada que venha de classes CSS usando `elem.style`.
-For instance, here `style` doesn't see the margin:
+Por exemplo, aqui `style` não consegue ver a margem:
```html run height=60 no-beautify
@@ -206,35 +202,34 @@ For instance, here `style` doesn't see the margin:
- The red text
+ O texto vermelho
```
+...Mas e se precisarmos, por exemplo, aumentar a margem em `20px`? Nós iriamos querer o valor atual dela.
-...But what if we need, say, to increase the margin by `20px`? We would want the current value of it.
+Existe um outro método para isso: `getComputedStyle`.
-There's another method for that: `getComputedStyle`.
-
-The syntax is:
+A sintaxe é:
```js
getComputedStyle(element, [pseudo])
```
element
-: Element to read the value for.
+: O elemento para ler o valor.
pseudo
-: A pseudo-element if required, for instance `::before`. An empty string or no argument means the element itself.
+: Um pseudo-elemento, se necessário, como por exemplo `::before`. Uma string vazia ou a ausência de argumento indica o próprio elemento.
-The result is an object with styles, like `elem.style`, but now with respect to all CSS classes.
+O resultado é um objeto com estilos, como `elem.style`, mas agora considerando todas as classes CSS.
-For instance:
+Por exemplo:
```html run height=100
@@ -245,7 +240,7 @@ For instance: