From 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:50:24 +0100 Subject: unslug pt-pt: move --- files/pt-pt/web/guide/ajax/community/index.html | 22 ++ .../web/guide/ajax/como_come\303\247ar/index.html" | 305 ------------------ files/pt-pt/web/guide/ajax/comunidade/index.html | 22 -- .../web/guide/ajax/getting_started/index.html | 305 ++++++++++++++++++ files/pt-pt/web/guide/eventos/index.html | 133 -------- files/pt-pt/web/guide/events/index.html | 133 ++++++++ files/pt-pt/web/guide/graphics/index.html | 50 +++ "files/pt-pt/web/guide/gr\303\241ficos/index.html" | 50 --- .../guide/html/categorias_de_conteudo/index.html | 175 ----------- .../web/guide/html/content_categories/index.html | 175 +++++++++++ .../web/guide/html/html5/html5_parser/index.html | 58 ++++ files/pt-pt/web/guide/html/html5/index.html | 169 ++++++++++ .../html/html5/introduction_to_html5/index.html | 20 ++ .../using_html_sections_and_outlines/index.html | 343 +++++++++++++++++++++ .../index.html | 343 --------------------- 15 files changed, 1275 insertions(+), 1028 deletions(-) create mode 100644 files/pt-pt/web/guide/ajax/community/index.html delete mode 100644 "files/pt-pt/web/guide/ajax/como_come\303\247ar/index.html" delete mode 100644 files/pt-pt/web/guide/ajax/comunidade/index.html create mode 100644 files/pt-pt/web/guide/ajax/getting_started/index.html delete mode 100644 files/pt-pt/web/guide/eventos/index.html create mode 100644 files/pt-pt/web/guide/events/index.html create mode 100644 files/pt-pt/web/guide/graphics/index.html delete mode 100644 "files/pt-pt/web/guide/gr\303\241ficos/index.html" delete mode 100644 files/pt-pt/web/guide/html/categorias_de_conteudo/index.html create mode 100644 files/pt-pt/web/guide/html/content_categories/index.html create mode 100644 files/pt-pt/web/guide/html/html5/html5_parser/index.html create mode 100644 files/pt-pt/web/guide/html/html5/index.html create mode 100644 files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html create mode 100644 files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html delete mode 100644 files/pt-pt/web/guide/html/utilizar_estruturas_e_seccoes_de_html/index.html (limited to 'files/pt-pt/web/guide') diff --git a/files/pt-pt/web/guide/ajax/community/index.html b/files/pt-pt/web/guide/ajax/community/index.html new file mode 100644 index 0000000000..98a2936999 --- /dev/null +++ b/files/pt-pt/web/guide/ajax/community/index.html @@ -0,0 +1,22 @@ +--- +title: Comunidade +slug: Web/Guide/AJAX/Comunidade +tags: + - AJAX +translation_of: Web/Guide/AJAX/Community +--- +

Se conhece listas de discussão úteis, grupos de notícias, fóruns, ou outras comunidades relacionadas com AJAX, interligue-os aqui.

+ +

Recursos Ajax

+ +

Ajax - Conferências e Cursos

+ + + +

{{ languages( { "ja": "ja/AJAX/Community", "fr": "fr/AJAX/Communaut\u00e9" } ) }}

diff --git "a/files/pt-pt/web/guide/ajax/como_come\303\247ar/index.html" "b/files/pt-pt/web/guide/ajax/como_come\303\247ar/index.html" deleted file mode 100644 index f067252d2d..0000000000 --- "a/files/pt-pt/web/guide/ajax/como_come\303\247ar/index.html" +++ /dev/null @@ -1,305 +0,0 @@ ---- -title: Primeiros Passos -slug: Web/Guide/AJAX/Como_começar -tags: - - AJAX - - API - - Avançado - - JavaScript - - Mecânica da Web - - XMLHttpRequest -translation_of: Web/Guide/AJAX/Getting_Started ---- -

Este artigo guia-o através do essencial do AJAX e oferece-lhe dois exemplos práticos simples para poder começar.

- -

O que é AJAX?

- -

AJAX (JavaScript Assíncrono e XML) em poucas palavras, é a utilização do objeto XMLHttpRequest para comunicar com os servidores. Este pode enviar e receber informação em vários formatos, incluindo JSON, XML, HTML e ficheiros de texto. A característica mais atraente do AJAX é a sua natureza 'assíncrona', o que significa que este pode comunicar com o servidor, trocar dados, e atualizar a página sem ter que recarregar a página.

- -

As duas principais funcionalidades do AJAX são as seguintes:

- - - -

Passo 1 - Como efetuar um pedido de HTTP

- -

Para fazer uma requisição HTTP ao servidor usando JavaScript, você precisa de uma instância de uma classe que disponibilize essa funcionalidade. Tal classe foi primeiro introduzida no Internet Explorer sob a forma de um objecto ActiveX chamado XMLHTTP. Depois, o Mozilla, o Safari e outros browsers fizeram o mesmo, implementando uma classe de nome XMLHttpRequest que suporta os métodos e as propriedades do objecto ActiveX original da Microsoft.

- -

Por isso, para criar uma instância (objeto) da classe pretendida compatível com multiplos navegadores, você pode fazer:

- -
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
-    http_request = new XMLHttpRequest();
-} else if (window.ActiveXObject) { // IE
-    http_request = new ActiveXObject("Microsoft.XMLHTTP");
-}
-
-
- -

(só a título de exemplo, o código acima é uma versão simplificada do código a ser usado para a criação de uma instância XMLHTTP. Para um exemplo mais "vida real", dê uma olhada ao 3º passo deste artigo.)

- -

Algumas versões de alguns browsers Mozilla não irão funcionar bem se a resposta do servidor não possuir um cabeçalho mime-type XML. Para satisfazer isto, você pode usar uma chamada extra a um método para ultrapassar o cabeçalho enviado pelo servidor, só no caso de não ser no formato text/xml.

- -
http_request = new XMLHttpRequest();
-http_request.overrideMimeType('text/xml');
-
- -

A próxima coisa a ser feita é decidir o que quer fazer após receber a resposta do servidor ao seu pedido. Nesta etapa só precisa de dizer ao objecto pedido HTTP que função JavaScript irá processar a resposta. Isto é feito definindo a propriedade onreadystatechange do objeto ao nome da função JavaScript que pretende utilizar, por exemplo:

- -

http_request.onreadystatechange = NomedaFunção;

- -

Note-se que não existem chaves após o nome da função e não são passados parâmetros. Também, em vez de dar um nome a função, você pode usar a técnica JavaScript de definir funções na hora (chamadas funções anônimas) e definir as ações que vão processar a resposta logo, por exemplo:

- -
http_request.onreadystatechange = function(){
-    // processar resposta do servidor
-};
-
- -

Em seguida, após ter declarado o que vai acontecer mal receba a resposta, você precisa de consumar o pedido. Precisa de chamar os métodos open() e send() da classe pedido HTTP, por exemplo:

- -
http_request.open('GET', 'http://www.dominio.com.br/arquivo.extensao', true);
-http_request.send(null);
-
- - - -

O parâmetro do método send() pode ser costituido por quaisquer dados que pretenda enviar ao servidor ao enviar (POST) o pedido. Os dados devem estar sob a forma de uma linha de texto de pergunta, tipo:

- -

name=value&anothername=othervalue&so=on

- -

ou em vários outros formatos, incluindo JSON, SOAP, etc.

- -

Note-se que se pretende enviar (POST) dados, você deve alterar o tipo MIME do pedido usando a seguinte linha:

- -
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
-
- -

De outra forma o servidor irá ignorar os dados (post).

- -

Pode-se também colocar o charset desejado assim:

- -
http_request.setRequestHeader('Content-Type',
-                           "application/x-www-form-urlencoded; charset=iso-8859-1");
-
- -

Outro ponto importante é controle do cache, pois caso haja necessidadde de reenviar a consulta, pode ser que o objeto retorne o que está no cache do navegador. Para evitar esse tipo de transtorno as linhas abaixo eliminam essas possibilidades:

- -
 http_request.setRequestHeader("Cache-Control",
-                               "no-store, no-cache, must-revalidate");
-http_request.setRequestHeader("Cache-Control",
-                              "post-check=0, pre-check=0");
-http_request.setRequestHeader("Pragma", "no-cache");
-
- -

Passo 2 - Manipular a resposta do servidor

- -

Lembre-se que quando estava a enviar o pedido, você providenciou o nome de uma função JavaScript que é criada para lidar com a resposta.

- -

http_request.onreadystatechange = nameOfTheFunction;

- -

Vamos a ver o que é que esta função deve fazer. Primeiro, a função precisa de verificar o estado do pedido. Se o estado possui o valor 4, isso significa que a totalidade da resposta do servidor foi recebida e que pode continuar a processá-la à vontade.

- -
if (http_request.readyState == 4) {
-    // everything is good, the response is received
-} else {
-    // still not ready
-}
-
- -

A lista completa dos valores readyState é a seguinte:

- - - -

(Source)

- -

A próxima coisa a verificar é o código do estado da resposta HTTP do servidor. Todos os códigos possíveis estão listados na página W3C. Para os nossos objectivos nós só estamos interessados na resposta 200 OK.

- -
if (http_request.status == 200) {
-    // perfect!
-} else {
-    // there was a problem with the request,
-    // for example the response may be a 404 (Not Found)
-    // or 500 (Internal Server Error) response codes
-}
-
- -

Depois de verificar o estado do pedido e o código do estado HTTP da resposta, compete-lhe a si fazer aquilo que quer fazer com os dados que o servidor lhe enviou. Tem duas opções para aceder a esses dados:

- - - -

 

- -

Passo 3 – Um exemplo simples

- -

Vamos agora pôr tudo junto e efectuar um simples pedido HTTP. O nosso JavaScript vai pedir um documento HTML, teste.html, que contém o texto "Sou um teste." e então vamos alert() os conteúdos do ficheiro teste.html.

- -
<script type="text/javascript" language="javascript">
-
-    var http_request = false;
-
-    function makeRequest(url) {
-
-        http_request = false;
-
-        if (window.XMLHttpRequest) { // Mozilla, Safari,...
-            http_request = new XMLHttpRequest();
-            if (http_request.overrideMimeType) {
-                http_request.overrideMimeType('text/xml');
-                // See note below about this line
-            }
-        } else if (window.ActiveXObject) { // IE
-            try {
-                http_request = new ActiveXObject("Msxml2.XMLHTTP");
-            } catch (e) {
-                try {
-                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
-                } catch (e) {}
-            }
-        }
-
-        if (!http_request) {
-            alert('Giving up :( Cannot create an XMLHTTP instance');
-            return false;
-        }
-        http_request.onreadystatechange = alertContents;
-        http_request.open('GET', url, true);
-        http_request.send(null);
-
-    }
-
-    function alertContents() {
-
-        if (http_request.readyState == 4) {
-            if (http_request.status == 200) {
-                alert(http_request.responseText);
-            } else {
-                alert('There was a problem with the request.');
-            }
-        }
-
-    }
-</script>
-<span
-    style="cursor: pointer; text-decoration: underline"
-    onclick="makeRequest('test.html')">
-        Make a request
-</span>
-
- -

Neste exemplo:

- - - -

Você pode testar o exemplo aqui e pode ver o ficheiro de teste aqui.

- -
Nota: Se você está enviando uma solicitação para um pedaço de código que retornará XML, ao invés de um arquivo XML estático, é necessário definir alguns cabeçalhos de resposta se a sua página deve trabalhar com o Internet Explorer, além de Mozilla. Se você não definir cabeçalho Content-Type: application / xml, o IE irá lançar um erro JavaScript, "Objeto esperado", após a linha onde você tentar acessar um elemento XML..
- -
Nota 2: Se você não definir cabeçalho Cache-Control: no-cache o navegador armazenará em cache a resposta e jamais voltará a submeter o pedido, tornando a depuração "desafiadora". Também é possível acrescentar um parâmetro GET adicional sempre diferente, como o timestamp ou um número aleatório (veja bypassing the cache).
- -
Nota 3: Se a variável httpRequest é utilizada globalmente, funções concorrentes chamando makeRequest () podem sobrescrever o outro, causando uma condição de corrida. Declarando o httpRequest variável local para um closure contendo as funções AJAX impede a condição de corrida.
- -
Nota 4: Caso ocorra um erro de comunicação (tal como a queda de do servidor web), uma exceção será lançada no método onreadystatechange quando o campo status for acessado. Tenha a certeza de envolver sua declaração if..then dentro de um bloco try...catch. (Veja: {{ Bug(238559) }}).
- -

Passo 4 – Trabalhar com a resposta XML

- -

No exemplo anterior, após termos recebido a resposta ao pedido HTTP, nós usamos a propriedade reponseText do objecto de pedido e continha os conteúdos do ficheiro test.html. Agora vamos experimentar a propriedade responseXML.

- -

Antes de tudo, vamos criar um documento XML válido que vamos pedir mais à frente. O documento (test.xml) contém o seguinte:

- -

 

- -
<?xml version="1.0" ?>
-<root>
-    I'm a test.
-</root>
-
- -

No guião só precisamos de alterar a linha do pedido com:

- -
...
-onclick="makeRequest('test.xml')">
-...
-
- -

Então em alertContents() nós precisamos de substituir a linha de alerta (alert(http_request.responseText);) com:

- -
var xmldoc = http_request.responseXML;
-var root_node = xmldoc.getElementsByTagName('root').item(0);
-alert(root_node.firstChild.data);
-
- -

Este código pega o objeto XMLDocument obtido por responseXML e utiliza métodos DOM para acessar alguns dados contidos no documento XML. Você pode ver o test.xml aqui e o script de teste atualizado aqui.

- -

Categorias

- -

Interwiki Language Links

- -

Passo 5 – Tabalhar com dados

- -

Finalmente, vamos enviar algum dado para o servidor e obter a resposta. Desta vez, nosso JavaScript solicitará um página dinâmica (test.php)  que receberá os dados que enviamos e retornará um string computada - "Hello, [user data]!" - visualizada através de alert().

- -

Primeiro, vamos adicionar uma text box em nosso HTML de modo que o usuário possa digitar o seu nome:

- -
<label>Your name:
-  <input type="text" id="ajaxTextbox" />
-</label>
-<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
-  Make a request
-</span>
- -

Vamos, também, adicionar uma linha para nosso manipulador de eventos obter os dados do usuário da text box e enviá-lo para função makeRequest() juntamente com a URL do nosso script do lado do servidor (server-side):

- -
document.getElementById("ajaxButton").onclick = function() {
-      var userName = document.getElementById("ajaxTextbox").value;
-      makeRequest('test.php',userName);
-  };
- -

Precisamos modificar makeRequest () para aceitar os dados do usuário e passá-lo para o servidor. Vamos mudar o método de requisição de GET para POST, e incluir nossos dados como um parâmetro na chamada para httpRequest.send():

- -
function makeRequest(url, userName) {
-
-    ...
-
-    httpRequest.onreadystatechange = alertContents;
-    httpRequest.open('POST', url);
-    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
-    httpRequest.send('userName=' + encodeURIComponent(userName));
-  }
-
- -

A função alertContents() pode ser escrita da mesma forma que se encontrava no Passo 3 para alertar (alert()) nossa string computada,  se isso for tudo o que o servidor retorna. No entanto, vamos dizer que  o servidor irá retornar tanto a sequência computada como o dados original do usuário. Portanto, se o usuário digitou "Jane" na text box, a resposta do servidor ficaria assim:

- -

{"userData":"Jane","computedString":"Hi, Jane!"}

- -

Para utilizar estes dados dentro de alertContents(), nós não podemos simplesmente exibir com alert()  a propriedade responseText. Temos que analisar (parse it)  computedString a propriedade que queremos:

- -
function alertContents() {
-    if (httpRequest.readyState === 4) {
-      if (httpRequest.status === 200) {
-        var response = JSON.parse(httpRequest.responseText);
-        alert(response.computedString);
-    } else {
-      alert('There was a problem with the request.');
-    }
-}
- -

Para mais métodos DOM, certifique-se que consulta os documentos sobre a implementação de DOM da Mozilla

diff --git a/files/pt-pt/web/guide/ajax/comunidade/index.html b/files/pt-pt/web/guide/ajax/comunidade/index.html deleted file mode 100644 index 98a2936999..0000000000 --- a/files/pt-pt/web/guide/ajax/comunidade/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Comunidade -slug: Web/Guide/AJAX/Comunidade -tags: - - AJAX -translation_of: Web/Guide/AJAX/Community ---- -

Se conhece listas de discussão úteis, grupos de notícias, fóruns, ou outras comunidades relacionadas com AJAX, interligue-os aqui.

- -

Recursos Ajax

- -

Ajax - Conferências e Cursos

- - - -

{{ languages( { "ja": "ja/AJAX/Community", "fr": "fr/AJAX/Communaut\u00e9" } ) }}

diff --git a/files/pt-pt/web/guide/ajax/getting_started/index.html b/files/pt-pt/web/guide/ajax/getting_started/index.html new file mode 100644 index 0000000000..f067252d2d --- /dev/null +++ b/files/pt-pt/web/guide/ajax/getting_started/index.html @@ -0,0 +1,305 @@ +--- +title: Primeiros Passos +slug: Web/Guide/AJAX/Como_começar +tags: + - AJAX + - API + - Avançado + - JavaScript + - Mecânica da Web + - XMLHttpRequest +translation_of: Web/Guide/AJAX/Getting_Started +--- +

Este artigo guia-o através do essencial do AJAX e oferece-lhe dois exemplos práticos simples para poder começar.

+ +

O que é AJAX?

+ +

AJAX (JavaScript Assíncrono e XML) em poucas palavras, é a utilização do objeto XMLHttpRequest para comunicar com os servidores. Este pode enviar e receber informação em vários formatos, incluindo JSON, XML, HTML e ficheiros de texto. A característica mais atraente do AJAX é a sua natureza 'assíncrona', o que significa que este pode comunicar com o servidor, trocar dados, e atualizar a página sem ter que recarregar a página.

+ +

As duas principais funcionalidades do AJAX são as seguintes:

+ + + +

Passo 1 - Como efetuar um pedido de HTTP

+ +

Para fazer uma requisição HTTP ao servidor usando JavaScript, você precisa de uma instância de uma classe que disponibilize essa funcionalidade. Tal classe foi primeiro introduzida no Internet Explorer sob a forma de um objecto ActiveX chamado XMLHTTP. Depois, o Mozilla, o Safari e outros browsers fizeram o mesmo, implementando uma classe de nome XMLHttpRequest que suporta os métodos e as propriedades do objecto ActiveX original da Microsoft.

+ +

Por isso, para criar uma instância (objeto) da classe pretendida compatível com multiplos navegadores, você pode fazer:

+ +
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
+    http_request = new XMLHttpRequest();
+} else if (window.ActiveXObject) { // IE
+    http_request = new ActiveXObject("Microsoft.XMLHTTP");
+}
+
+
+ +

(só a título de exemplo, o código acima é uma versão simplificada do código a ser usado para a criação de uma instância XMLHTTP. Para um exemplo mais "vida real", dê uma olhada ao 3º passo deste artigo.)

+ +

Algumas versões de alguns browsers Mozilla não irão funcionar bem se a resposta do servidor não possuir um cabeçalho mime-type XML. Para satisfazer isto, você pode usar uma chamada extra a um método para ultrapassar o cabeçalho enviado pelo servidor, só no caso de não ser no formato text/xml.

+ +
http_request = new XMLHttpRequest();
+http_request.overrideMimeType('text/xml');
+
+ +

A próxima coisa a ser feita é decidir o que quer fazer após receber a resposta do servidor ao seu pedido. Nesta etapa só precisa de dizer ao objecto pedido HTTP que função JavaScript irá processar a resposta. Isto é feito definindo a propriedade onreadystatechange do objeto ao nome da função JavaScript que pretende utilizar, por exemplo:

+ +

http_request.onreadystatechange = NomedaFunção;

+ +

Note-se que não existem chaves após o nome da função e não são passados parâmetros. Também, em vez de dar um nome a função, você pode usar a técnica JavaScript de definir funções na hora (chamadas funções anônimas) e definir as ações que vão processar a resposta logo, por exemplo:

+ +
http_request.onreadystatechange = function(){
+    // processar resposta do servidor
+};
+
+ +

Em seguida, após ter declarado o que vai acontecer mal receba a resposta, você precisa de consumar o pedido. Precisa de chamar os métodos open() e send() da classe pedido HTTP, por exemplo:

+ +
http_request.open('GET', 'http://www.dominio.com.br/arquivo.extensao', true);
+http_request.send(null);
+
+ + + +

O parâmetro do método send() pode ser costituido por quaisquer dados que pretenda enviar ao servidor ao enviar (POST) o pedido. Os dados devem estar sob a forma de uma linha de texto de pergunta, tipo:

+ +

name=value&anothername=othervalue&so=on

+ +

ou em vários outros formatos, incluindo JSON, SOAP, etc.

+ +

Note-se que se pretende enviar (POST) dados, você deve alterar o tipo MIME do pedido usando a seguinte linha:

+ +
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+
+ +

De outra forma o servidor irá ignorar os dados (post).

+ +

Pode-se também colocar o charset desejado assim:

+ +
http_request.setRequestHeader('Content-Type',
+                           "application/x-www-form-urlencoded; charset=iso-8859-1");
+
+ +

Outro ponto importante é controle do cache, pois caso haja necessidadde de reenviar a consulta, pode ser que o objeto retorne o que está no cache do navegador. Para evitar esse tipo de transtorno as linhas abaixo eliminam essas possibilidades:

+ +
 http_request.setRequestHeader("Cache-Control",
+                               "no-store, no-cache, must-revalidate");
+http_request.setRequestHeader("Cache-Control",
+                              "post-check=0, pre-check=0");
+http_request.setRequestHeader("Pragma", "no-cache");
+
+ +

Passo 2 - Manipular a resposta do servidor

+ +

Lembre-se que quando estava a enviar o pedido, você providenciou o nome de uma função JavaScript que é criada para lidar com a resposta.

+ +

http_request.onreadystatechange = nameOfTheFunction;

+ +

Vamos a ver o que é que esta função deve fazer. Primeiro, a função precisa de verificar o estado do pedido. Se o estado possui o valor 4, isso significa que a totalidade da resposta do servidor foi recebida e que pode continuar a processá-la à vontade.

+ +
if (http_request.readyState == 4) {
+    // everything is good, the response is received
+} else {
+    // still not ready
+}
+
+ +

A lista completa dos valores readyState é a seguinte:

+ + + +

(Source)

+ +

A próxima coisa a verificar é o código do estado da resposta HTTP do servidor. Todos os códigos possíveis estão listados na página W3C. Para os nossos objectivos nós só estamos interessados na resposta 200 OK.

+ +
if (http_request.status == 200) {
+    // perfect!
+} else {
+    // there was a problem with the request,
+    // for example the response may be a 404 (Not Found)
+    // or 500 (Internal Server Error) response codes
+}
+
+ +

Depois de verificar o estado do pedido e o código do estado HTTP da resposta, compete-lhe a si fazer aquilo que quer fazer com os dados que o servidor lhe enviou. Tem duas opções para aceder a esses dados:

+ + + +

 

+ +

Passo 3 – Um exemplo simples

+ +

Vamos agora pôr tudo junto e efectuar um simples pedido HTTP. O nosso JavaScript vai pedir um documento HTML, teste.html, que contém o texto "Sou um teste." e então vamos alert() os conteúdos do ficheiro teste.html.

+ +
<script type="text/javascript" language="javascript">
+
+    var http_request = false;
+
+    function makeRequest(url) {
+
+        http_request = false;
+
+        if (window.XMLHttpRequest) { // Mozilla, Safari,...
+            http_request = new XMLHttpRequest();
+            if (http_request.overrideMimeType) {
+                http_request.overrideMimeType('text/xml');
+                // See note below about this line
+            }
+        } else if (window.ActiveXObject) { // IE
+            try {
+                http_request = new ActiveXObject("Msxml2.XMLHTTP");
+            } catch (e) {
+                try {
+                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
+                } catch (e) {}
+            }
+        }
+
+        if (!http_request) {
+            alert('Giving up :( Cannot create an XMLHTTP instance');
+            return false;
+        }
+        http_request.onreadystatechange = alertContents;
+        http_request.open('GET', url, true);
+        http_request.send(null);
+
+    }
+
+    function alertContents() {
+
+        if (http_request.readyState == 4) {
+            if (http_request.status == 200) {
+                alert(http_request.responseText);
+            } else {
+                alert('There was a problem with the request.');
+            }
+        }
+
+    }
+</script>
+<span
+    style="cursor: pointer; text-decoration: underline"
+    onclick="makeRequest('test.html')">
+        Make a request
+</span>
+
+ +

Neste exemplo:

+ + + +

Você pode testar o exemplo aqui e pode ver o ficheiro de teste aqui.

+ +
Nota: Se você está enviando uma solicitação para um pedaço de código que retornará XML, ao invés de um arquivo XML estático, é necessário definir alguns cabeçalhos de resposta se a sua página deve trabalhar com o Internet Explorer, além de Mozilla. Se você não definir cabeçalho Content-Type: application / xml, o IE irá lançar um erro JavaScript, "Objeto esperado", após a linha onde você tentar acessar um elemento XML..
+ +
Nota 2: Se você não definir cabeçalho Cache-Control: no-cache o navegador armazenará em cache a resposta e jamais voltará a submeter o pedido, tornando a depuração "desafiadora". Também é possível acrescentar um parâmetro GET adicional sempre diferente, como o timestamp ou um número aleatório (veja bypassing the cache).
+ +
Nota 3: Se a variável httpRequest é utilizada globalmente, funções concorrentes chamando makeRequest () podem sobrescrever o outro, causando uma condição de corrida. Declarando o httpRequest variável local para um closure contendo as funções AJAX impede a condição de corrida.
+ +
Nota 4: Caso ocorra um erro de comunicação (tal como a queda de do servidor web), uma exceção será lançada no método onreadystatechange quando o campo status for acessado. Tenha a certeza de envolver sua declaração if..then dentro de um bloco try...catch. (Veja: {{ Bug(238559) }}).
+ +

Passo 4 – Trabalhar com a resposta XML

+ +

No exemplo anterior, após termos recebido a resposta ao pedido HTTP, nós usamos a propriedade reponseText do objecto de pedido e continha os conteúdos do ficheiro test.html. Agora vamos experimentar a propriedade responseXML.

+ +

Antes de tudo, vamos criar um documento XML válido que vamos pedir mais à frente. O documento (test.xml) contém o seguinte:

+ +

 

+ +
<?xml version="1.0" ?>
+<root>
+    I'm a test.
+</root>
+
+ +

No guião só precisamos de alterar a linha do pedido com:

+ +
...
+onclick="makeRequest('test.xml')">
+...
+
+ +

Então em alertContents() nós precisamos de substituir a linha de alerta (alert(http_request.responseText);) com:

+ +
var xmldoc = http_request.responseXML;
+var root_node = xmldoc.getElementsByTagName('root').item(0);
+alert(root_node.firstChild.data);
+
+ +

Este código pega o objeto XMLDocument obtido por responseXML e utiliza métodos DOM para acessar alguns dados contidos no documento XML. Você pode ver o test.xml aqui e o script de teste atualizado aqui.

+ +

Categorias

+ +

Interwiki Language Links

+ +

Passo 5 – Tabalhar com dados

+ +

Finalmente, vamos enviar algum dado para o servidor e obter a resposta. Desta vez, nosso JavaScript solicitará um página dinâmica (test.php)  que receberá os dados que enviamos e retornará um string computada - "Hello, [user data]!" - visualizada através de alert().

+ +

Primeiro, vamos adicionar uma text box em nosso HTML de modo que o usuário possa digitar o seu nome:

+ +
<label>Your name:
+  <input type="text" id="ajaxTextbox" />
+</label>
+<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
+  Make a request
+</span>
+ +

Vamos, também, adicionar uma linha para nosso manipulador de eventos obter os dados do usuário da text box e enviá-lo para função makeRequest() juntamente com a URL do nosso script do lado do servidor (server-side):

+ +
document.getElementById("ajaxButton").onclick = function() {
+      var userName = document.getElementById("ajaxTextbox").value;
+      makeRequest('test.php',userName);
+  };
+ +

Precisamos modificar makeRequest () para aceitar os dados do usuário e passá-lo para o servidor. Vamos mudar o método de requisição de GET para POST, e incluir nossos dados como um parâmetro na chamada para httpRequest.send():

+ +
function makeRequest(url, userName) {
+
+    ...
+
+    httpRequest.onreadystatechange = alertContents;
+    httpRequest.open('POST', url);
+    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+    httpRequest.send('userName=' + encodeURIComponent(userName));
+  }
+
+ +

A função alertContents() pode ser escrita da mesma forma que se encontrava no Passo 3 para alertar (alert()) nossa string computada,  se isso for tudo o que o servidor retorna. No entanto, vamos dizer que  o servidor irá retornar tanto a sequência computada como o dados original do usuário. Portanto, se o usuário digitou "Jane" na text box, a resposta do servidor ficaria assim:

+ +

{"userData":"Jane","computedString":"Hi, Jane!"}

+ +

Para utilizar estes dados dentro de alertContents(), nós não podemos simplesmente exibir com alert()  a propriedade responseText. Temos que analisar (parse it)  computedString a propriedade que queremos:

+ +
function alertContents() {
+    if (httpRequest.readyState === 4) {
+      if (httpRequest.status === 200) {
+        var response = JSON.parse(httpRequest.responseText);
+        alert(response.computedString);
+    } else {
+      alert('There was a problem with the request.');
+    }
+}
+ +

Para mais métodos DOM, certifique-se que consulta os documentos sobre a implementação de DOM da Mozilla

diff --git a/files/pt-pt/web/guide/eventos/index.html b/files/pt-pt/web/guide/eventos/index.html deleted file mode 100644 index 99e7f2f492..0000000000 --- a/files/pt-pt/web/guide/eventos/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: Guia do programador de eventos -slug: Web/Guide/Eventos -tags: - - DOM - - Evento - - Guía - - Precisa de Atualização -translation_of: Web/Guide/Events ---- -

{{draft()}}

- -

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

- -

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

- -

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

- -

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

- -

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

- -

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

- -

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

- -

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

- - - -

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

- -

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

- -

The network requests made by a web page might trigger some events.

- -

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

- -
-

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

-
- -

Documentos

- -

{{LandingPageListSubpages}}

- -
- - - - - -
diff --git a/files/pt-pt/web/guide/events/index.html b/files/pt-pt/web/guide/events/index.html new file mode 100644 index 0000000000..99e7f2f492 --- /dev/null +++ b/files/pt-pt/web/guide/events/index.html @@ -0,0 +1,133 @@ +--- +title: Guia do programador de eventos +slug: Web/Guide/Eventos +tags: + - DOM + - Evento + - Guía + - Precisa de Atualização +translation_of: Web/Guide/Events +--- +

{{draft()}}

+ +

Events refers both to a design pattern used for the asynchronous handling of various incidents which occur in the lifetime of a web page and to the naming, characterization, and use of a large number of incidents of different types.

+ +

The overview page provides an introduction to the design pattern and a summary of the types of incidents which are defined and reacted to by modern web browsers.

+ +

The custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.

+ +

The remaining pages describe how to use events of different kinds defined by web browsers. Unfortunately, these events have been defined piece by piece as web browsers have evolved so that there is no satisfying systematic characterization of the events built-in or defined by modern web browsers.

+ +

The device on which the web browser is running can trigger events, for example due to a change in its position and orientation in the real world, as discussed partially by the page on orientation coordinate systems and the page on the use of 3D transforms. That is different, but similar, to the change in device vertical orientation. 

+ +

The window in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.

+ +

The process loading of a web page can trigger events in response to the completion of different steps in the downloading, parsing, and rendering of the web page for display to the user.

+ +

The user interaction with the web page contents can trigger events. The events triggered by user interaction evolved during the early years of browser design and include a complicated system defining the sequence in which events will be called and the manner in which that sequence can be controlled. The different types of user interaction-driven events include:

+ + + +

The modification of the web page in structure or content might trigger some events, as explained in the mutation events page, but the use of these events has been deprecated in favour of the lighter Mutation Observer approach.

+ +

The media streams embedded in the HTML documents might trigger some events, as explained in the media events page.

+ +

The network requests made by a web page might trigger some events.

+ +

There are many other sources of events defined by web browsers for which pages are not yet available in this guide.

+ +
+

Note: This Event Developer Guide needs substantial work. The structure needs to be reorganized and the pages rewritten. Our hope is that everything you need to know about events will go under here.

+
+ +

Documentos

+ +

{{LandingPageListSubpages}}

+ +
+ + + + + +
diff --git a/files/pt-pt/web/guide/graphics/index.html b/files/pt-pt/web/guide/graphics/index.html new file mode 100644 index 0000000000..c18d703bc5 --- /dev/null +++ b/files/pt-pt/web/guide/graphics/index.html @@ -0,0 +1,50 @@ +--- +title: Gráficos na Web +slug: Web/Guide/Gráficos +tags: + - 2D + - 3D + - Canvas + - HTML5 + - SVG + - Tela + - Web + - WebGL + - WebRTC + - graficos +translation_of: Web/Guide/Graphics +--- +

Web sites e aplicações necessitam frequentemente de apresentar gráficos. Imagens estáticas podem ser facilmente mostradas usado o elemento {{HTMLElement("img")}}, ou definindo o fundo do elemento HTML com a propriedade {{cssxref("background-image")}}. É ainda possivel construir gráficos no momento, ou manipular imagens. Este artigo disponibiliza toda a informação necessária.  

+ +
+
+

Gráficos 2D

+ +
+
Canvas
+
O elemento {{HTMLElement("canvas")}} fornece APIs para desenhar gráficos em 2D com recurso a JavaScript.
+
SVG
+
Scalable Vector Graphics (SVG) utiliza linhas, curvas, e outras formas geometricas para criar gráficos. Com vetores, pode ainda criar imagens que escalam para qualquer tamanho.
+
+ +

View All...

+
+ +
+

Gráficos 3D

+ +
+
WebGL
+
Um guia para iniciar com WebGL, o API de gráficos 3D para a Web. Esta tecnologia permite o uso do standard OpenGL ES em conteúdos Web.
+
+ +

Vídeo

+ +
+
Utilizar áudio e vídeo em HTML5
+
Incorporar video e/ou audio numa página web e controlar a sua reprodução.
+
WebRTC
+
O RTC em WebRTC significa Real-Time Communications (Comunicação em Tempo Real), é a tecnologia que permite o streaming the audio/video e partilha de informação entre clientes de browser (peers).
+
+
+
diff --git "a/files/pt-pt/web/guide/gr\303\241ficos/index.html" "b/files/pt-pt/web/guide/gr\303\241ficos/index.html" deleted file mode 100644 index c18d703bc5..0000000000 --- "a/files/pt-pt/web/guide/gr\303\241ficos/index.html" +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Gráficos na Web -slug: Web/Guide/Gráficos -tags: - - 2D - - 3D - - Canvas - - HTML5 - - SVG - - Tela - - Web - - WebGL - - WebRTC - - graficos -translation_of: Web/Guide/Graphics ---- -

Web sites e aplicações necessitam frequentemente de apresentar gráficos. Imagens estáticas podem ser facilmente mostradas usado o elemento {{HTMLElement("img")}}, ou definindo o fundo do elemento HTML com a propriedade {{cssxref("background-image")}}. É ainda possivel construir gráficos no momento, ou manipular imagens. Este artigo disponibiliza toda a informação necessária.  

- -
-
-

Gráficos 2D

- -
-
Canvas
-
O elemento {{HTMLElement("canvas")}} fornece APIs para desenhar gráficos em 2D com recurso a JavaScript.
-
SVG
-
Scalable Vector Graphics (SVG) utiliza linhas, curvas, e outras formas geometricas para criar gráficos. Com vetores, pode ainda criar imagens que escalam para qualquer tamanho.
-
- -

View All...

-
- -
-

Gráficos 3D

- -
-
WebGL
-
Um guia para iniciar com WebGL, o API de gráficos 3D para a Web. Esta tecnologia permite o uso do standard OpenGL ES em conteúdos Web.
-
- -

Vídeo

- -
-
Utilizar áudio e vídeo em HTML5
-
Incorporar video e/ou audio numa página web e controlar a sua reprodução.
-
WebRTC
-
O RTC em WebRTC significa Real-Time Communications (Comunicação em Tempo Real), é a tecnologia que permite o streaming the audio/video e partilha de informação entre clientes de browser (peers).
-
-
-
diff --git a/files/pt-pt/web/guide/html/categorias_de_conteudo/index.html b/files/pt-pt/web/guide/html/categorias_de_conteudo/index.html deleted file mode 100644 index 9a7c08ee9a..0000000000 --- a/files/pt-pt/web/guide/html/categorias_de_conteudo/index.html +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: Categorias de conteúdo -slug: Web/Guide/HTML/Categorias_de_conteudo -tags: - - Avançado - - Guía - - HTML - - HTML5 - - Web -translation_of: Web/Guide/HTML/Content_categories ---- -

Every HTML element is a member of one or more content categories, which group elements that share characteristics. This is a loose grouping (it doesn't actually create a relationship among elements of these categories), but they help define and describe the categories' shared behavior and their associated rules, especially when you come upon their intricate details. It's also possible for elements to not be a member of any of these categories.

- -

There are three types of content categories:

- - - -
-

Nota: A more detailed discussion of these content categories and their comparative functionalities is beyond the scope of this article; for that, you may wish to read the relevant portions of the HTML specification.

-
- -

A Venn diagram showing how the various content categories interrelate. The following sections explain these relationships in text.

- -

Main content categories

- -

Metadata content

- -

Elements belonging to the metadata content category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other out of band information.

- -

Elements belonging to this category are {{HTMLElement("base")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("link")}}, {{HTMLElement("meta")}}, {{HTMLElement("noscript")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} and {{HTMLElement("title")}}.

- -

Flow content

- -

Elements belonging to the flow content category typically contain text or embedded content. They are: {{HTMLElement("a")}}, {{HTMLElement("abbr")}}, {{HTMLElement("address")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("audio")}}, {{HTMLElement("b")}},{{HTMLElement("bdo")}}, {{HTMLElement("bdi")}}, {{HTMLElement("blockquote")}}, {{HTMLElement("br")}}, {{HTMLElement("button")}}, {{HTMLElement("canvas")}}, {{HTMLElement("cite")}}, {{HTMLElement("code")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("data")}}, {{HTMLElement("datalist")}}, {{HTMLElement("del")}}, {{HTMLElement("details")}}, {{HTMLElement("dfn")}}, {{HTMLElement("div")}}, {{HTMLElement("dl")}}, {{HTMLElement("em")}}, {{HTMLElement("embed")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figure")}}, {{HTMLElement("footer")}}, {{HTMLElement("form")}}, {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}, {{HTMLElement("header")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("hr")}}, {{HTMLElement("i")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{HTMLElement("input")}}, {{HTMLElement("ins")}}, {{HTMLElement("kbd")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("main")}}, {{HTMLElement("map")}}, {{HTMLElement("mark")}}, {{MathMLElement("math")}}, {{HTMLElement("menu")}}, {{HTMLElement("meter")}}, {{HTMLElement("nav")}}, {{HTMLElement("noscript")}}, {{HTMLElement("object")}}, {{HTMLElement("ol")}}, {{HTMLElement("output")}}, {{HTMLElement("p")}}, {{HTMLElement("pre")}}, {{HTMLElement("progress")}}, {{HTMLElement("q")}}, {{HTMLElement("ruby")}}, {{HTMLElement("s")}}, {{HTMLElement("samp")}}, {{HTMLElement("script")}}, {{HTMLElement("section")}}, {{HTMLElement("select")}}, {{HTMLElement("small")}}, {{HTMLElement("span")}}, {{HTMLElement("strong")}}, {{HTMLElement("sub")}}, {{HTMLElement("sup")}}, {{SVGElement("svg")}}, {{HTMLElement("table")}}, {{HTMLElement("template")}}, {{HTMLElement("textarea")}}, {{HTMLElement("time")}}, {{HTMLElement("ul")}}, {{HTMLElement("var")}}, {{HTMLElement("video")}}, {{HTMLElement("wbr")}} and Text.

- -

A few other elements belong to this category, but only if a specific condition is fulfilled:

- - - -

Sectioning content

- -

Elements belonging to the sectioning content model create a section in the current outline that defines the scope of {{HTMLElement("header")}} elements, {{HTMLElement("footer")}} elements, and heading content.

- -

Elements belonging to this category are {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("nav")}} and {{HTMLElement("section")}}.

- -
-

Do not confuse this content model with the sectioning root category, which isolates its content from the regular outline.

-
- -

Heading content

- -

Heading content defines the title of a section, whether marked by an explicit sectioning content element, or implicitly defined by the heading content itself.

- -

Elements belonging to this category are {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}} and {{HTMLElement("hgroup")}}.

- -
-

Though likely to contain heading content, the {{HTMLElement("header")}} is not heading content itself.

-
- -
-

Note: The {{HTMLElement("hgroup")}} element was removed from the W3C HTML specification prior to HTML 5 being finalized, but is still part of the WHATWG specification and is at least partially supported by most browsers.

-
- -

Phrasing content

- -

Phrasing content defines the text and the mark-up it contains. Runs of phrasing content make up paragraphs.

- -

Elements belonging to this category are {{HTMLElement("abbr")}}, {{HTMLElement("audio")}}, {{HTMLElement("b")}}, {{HTMLElement("bdo")}}, {{HTMLElement("br")}}, {{HTMLElement("button")}}, {{HTMLElement("canvas")}}, {{HTMLElement("cite")}}, {{HTMLElement("code")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("data")}}, {{HTMLElement("datalist")}}, {{HTMLElement("dfn")}}, {{HTMLElement("em")}}, {{HTMLElement("embed")}}, {{HTMLElement("i")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{HTMLElement("input")}}, {{HTMLElement("kbd")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("mark")}}, {{MathMLElement("math")}}, {{HTMLElement("meter")}}, {{HTMLElement("noscript")}}, {{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("q")}}, {{HTMLElement("ruby")}}, {{HTMLElement("samp")}}, {{HTMLElement("script")}}, {{HTMLElement("select")}}, {{HTMLElement("small")}}, {{HTMLElement("span")}}, {{HTMLElement("strong")}}, {{HTMLElement("sub")}}, {{HTMLElement("sup")}}, {{SVGElement("svg")}}, {{HTMLElement("textarea")}}, {{HTMLElement("time")}}, {{HTMLElement("var")}}, {{HTMLElement("video")}}, {{HTMLElement("wbr")}} and plain text (not only consisting of white spaces characters).

- -

A few other elements belong to this category, but only if a specific condition is fulfilled:

- - - -

Embedded content

- -

Embedded content imports another resource or inserts content from another mark-up language or namespace into the document. Elements that belong to this category include: {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("embed")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{MathMLElement("math")}}, {{HTMLElement("object")}}, {{SVGElement("svg")}}, {{HTMLElement("video")}}.

- -

Interactive content

- -

Interactive content includes elements that are specifically designed for user interaction. Elements that belong to this category include: {{HTMLElement("a")}}, {{HTMLElement("button")}}, {{HTMLElement("details")}}, {{HTMLElement("embed")}}, {{HTMLElement("iframe")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
- Some elements belong to this category only under specific conditions:

- - - -

Palpable content

- -

Content is palpable when it's neither empty or hidden; it is content that is rendered and is substantive. Elements whose model is flow content or phrasing content should have at least one node which is palpable.

- -

Form-associated content

- -

Form-associated content comprises elements that have a form owner, exposed by a form attribute. A form owner is either the containing {{HTMLElement("form")}} element or the element whose id is specified in the form attribute.

- - - -

This category contains several sub-categories:

- -
-
listed
-
Elements that are listed in the form.elements and fieldset.elements IDL collections. Contains {{HTMLElement("button")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
-
labelable
-
Elements that can be associated with {{HTMLElement("label")}} elements. Contains {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("meter")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
-
submittable
-
Elements that can be used for constructing the form data set when the form is submitted. Contains {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("object")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
-
resettable
-
Elements that can be affected when a form is reset. Contains {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("output")}},{{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
-
- -

Secondary categories

- -

There are some secondary classifications of elements that can be useful to be aware of as well.

- -

Script-supporting elements

- -

Script-supporting elements are elements which don't directly contribute to the rendered output of a document. Instead, they serve to support scripts, either by containing or specifying script code directly, or by specifying data that will be used by scripts.

- -

The script-supporting elements are:

- - - -

Transparent content model

- -

If an element has a transparent content model, then its contents must be structured such that they would be valid HTML 5, even if the transparent element were removed and replaced by the child elements.

- -

For example, the {{HTMLElement("del")}} and {{HTMLELement("ins")}} elements are transparent:

- -
<p>We hold these truths to be <del><em>sacred &amp; undeniable</em></del> <ins>self-evident</ins>.</p>
-
- -

If those elements were removed, this fragment would still be valid HTML (if not correct English).

- -
<p>We hold these truths to be <em>sacred &amp; undeniable</em> self-evident.</p>
-
- -

Outros modelos de conteúdo

- -

Seção raiz.

diff --git a/files/pt-pt/web/guide/html/content_categories/index.html b/files/pt-pt/web/guide/html/content_categories/index.html new file mode 100644 index 0000000000..9a7c08ee9a --- /dev/null +++ b/files/pt-pt/web/guide/html/content_categories/index.html @@ -0,0 +1,175 @@ +--- +title: Categorias de conteúdo +slug: Web/Guide/HTML/Categorias_de_conteudo +tags: + - Avançado + - Guía + - HTML + - HTML5 + - Web +translation_of: Web/Guide/HTML/Content_categories +--- +

Every HTML element is a member of one or more content categories, which group elements that share characteristics. This is a loose grouping (it doesn't actually create a relationship among elements of these categories), but they help define and describe the categories' shared behavior and their associated rules, especially when you come upon their intricate details. It's also possible for elements to not be a member of any of these categories.

+ +

There are three types of content categories:

+ + + +
+

Nota: A more detailed discussion of these content categories and their comparative functionalities is beyond the scope of this article; for that, you may wish to read the relevant portions of the HTML specification.

+
+ +

A Venn diagram showing how the various content categories interrelate. The following sections explain these relationships in text.

+ +

Main content categories

+ +

Metadata content

+ +

Elements belonging to the metadata content category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other out of band information.

+ +

Elements belonging to this category are {{HTMLElement("base")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("link")}}, {{HTMLElement("meta")}}, {{HTMLElement("noscript")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}} and {{HTMLElement("title")}}.

+ +

Flow content

+ +

Elements belonging to the flow content category typically contain text or embedded content. They are: {{HTMLElement("a")}}, {{HTMLElement("abbr")}}, {{HTMLElement("address")}}, {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("audio")}}, {{HTMLElement("b")}},{{HTMLElement("bdo")}}, {{HTMLElement("bdi")}}, {{HTMLElement("blockquote")}}, {{HTMLElement("br")}}, {{HTMLElement("button")}}, {{HTMLElement("canvas")}}, {{HTMLElement("cite")}}, {{HTMLElement("code")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("data")}}, {{HTMLElement("datalist")}}, {{HTMLElement("del")}}, {{HTMLElement("details")}}, {{HTMLElement("dfn")}}, {{HTMLElement("div")}}, {{HTMLElement("dl")}}, {{HTMLElement("em")}}, {{HTMLElement("embed")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figure")}}, {{HTMLElement("footer")}}, {{HTMLElement("form")}}, {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}, {{HTMLElement("header")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("hr")}}, {{HTMLElement("i")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{HTMLElement("input")}}, {{HTMLElement("ins")}}, {{HTMLElement("kbd")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("main")}}, {{HTMLElement("map")}}, {{HTMLElement("mark")}}, {{MathMLElement("math")}}, {{HTMLElement("menu")}}, {{HTMLElement("meter")}}, {{HTMLElement("nav")}}, {{HTMLElement("noscript")}}, {{HTMLElement("object")}}, {{HTMLElement("ol")}}, {{HTMLElement("output")}}, {{HTMLElement("p")}}, {{HTMLElement("pre")}}, {{HTMLElement("progress")}}, {{HTMLElement("q")}}, {{HTMLElement("ruby")}}, {{HTMLElement("s")}}, {{HTMLElement("samp")}}, {{HTMLElement("script")}}, {{HTMLElement("section")}}, {{HTMLElement("select")}}, {{HTMLElement("small")}}, {{HTMLElement("span")}}, {{HTMLElement("strong")}}, {{HTMLElement("sub")}}, {{HTMLElement("sup")}}, {{SVGElement("svg")}}, {{HTMLElement("table")}}, {{HTMLElement("template")}}, {{HTMLElement("textarea")}}, {{HTMLElement("time")}}, {{HTMLElement("ul")}}, {{HTMLElement("var")}}, {{HTMLElement("video")}}, {{HTMLElement("wbr")}} and Text.

+ +

A few other elements belong to this category, but only if a specific condition is fulfilled:

+ + + +

Sectioning content

+ +

Elements belonging to the sectioning content model create a section in the current outline that defines the scope of {{HTMLElement("header")}} elements, {{HTMLElement("footer")}} elements, and heading content.

+ +

Elements belonging to this category are {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("nav")}} and {{HTMLElement("section")}}.

+ +
+

Do not confuse this content model with the sectioning root category, which isolates its content from the regular outline.

+
+ +

Heading content

+ +

Heading content defines the title of a section, whether marked by an explicit sectioning content element, or implicitly defined by the heading content itself.

+ +

Elements belonging to this category are {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}} and {{HTMLElement("hgroup")}}.

+ +
+

Though likely to contain heading content, the {{HTMLElement("header")}} is not heading content itself.

+
+ +
+

Note: The {{HTMLElement("hgroup")}} element was removed from the W3C HTML specification prior to HTML 5 being finalized, but is still part of the WHATWG specification and is at least partially supported by most browsers.

+
+ +

Phrasing content

+ +

Phrasing content defines the text and the mark-up it contains. Runs of phrasing content make up paragraphs.

+ +

Elements belonging to this category are {{HTMLElement("abbr")}}, {{HTMLElement("audio")}}, {{HTMLElement("b")}}, {{HTMLElement("bdo")}}, {{HTMLElement("br")}}, {{HTMLElement("button")}}, {{HTMLElement("canvas")}}, {{HTMLElement("cite")}}, {{HTMLElement("code")}}, {{ Obsolete_inline() }}{{HTMLElement("command")}}, {{HTMLElement("data")}}, {{HTMLElement("datalist")}}, {{HTMLElement("dfn")}}, {{HTMLElement("em")}}, {{HTMLElement("embed")}}, {{HTMLElement("i")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{HTMLElement("input")}}, {{HTMLElement("kbd")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("mark")}}, {{MathMLElement("math")}}, {{HTMLElement("meter")}}, {{HTMLElement("noscript")}}, {{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("q")}}, {{HTMLElement("ruby")}}, {{HTMLElement("samp")}}, {{HTMLElement("script")}}, {{HTMLElement("select")}}, {{HTMLElement("small")}}, {{HTMLElement("span")}}, {{HTMLElement("strong")}}, {{HTMLElement("sub")}}, {{HTMLElement("sup")}}, {{SVGElement("svg")}}, {{HTMLElement("textarea")}}, {{HTMLElement("time")}}, {{HTMLElement("var")}}, {{HTMLElement("video")}}, {{HTMLElement("wbr")}} and plain text (not only consisting of white spaces characters).

+ +

A few other elements belong to this category, but only if a specific condition is fulfilled:

+ + + +

Embedded content

+ +

Embedded content imports another resource or inserts content from another mark-up language or namespace into the document. Elements that belong to this category include: {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("embed")}}, {{HTMLElement("iframe")}}, {{HTMLElement("img")}}, {{MathMLElement("math")}}, {{HTMLElement("object")}}, {{SVGElement("svg")}}, {{HTMLElement("video")}}.

+ +

Interactive content

+ +

Interactive content includes elements that are specifically designed for user interaction. Elements that belong to this category include: {{HTMLElement("a")}}, {{HTMLElement("button")}}, {{HTMLElement("details")}}, {{HTMLElement("embed")}}, {{HTMLElement("iframe")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("label")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
+ Some elements belong to this category only under specific conditions:

+ + + +

Palpable content

+ +

Content is palpable when it's neither empty or hidden; it is content that is rendered and is substantive. Elements whose model is flow content or phrasing content should have at least one node which is palpable.

+ +

Form-associated content

+ +

Form-associated content comprises elements that have a form owner, exposed by a form attribute. A form owner is either the containing {{HTMLElement("form")}} element or the element whose id is specified in the form attribute.

+ + + +

This category contains several sub-categories:

+ +
+
listed
+
Elements that are listed in the form.elements and fieldset.elements IDL collections. Contains {{HTMLElement("button")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
+
labelable
+
Elements that can be associated with {{HTMLElement("label")}} elements. Contains {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("meter")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
+
submittable
+
Elements that can be used for constructing the form data set when the form is submitted. Contains {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("object")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
+
resettable
+
Elements that can be affected when a form is reset. Contains {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("output")}},{{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
+
+ +

Secondary categories

+ +

There are some secondary classifications of elements that can be useful to be aware of as well.

+ +

Script-supporting elements

+ +

Script-supporting elements are elements which don't directly contribute to the rendered output of a document. Instead, they serve to support scripts, either by containing or specifying script code directly, or by specifying data that will be used by scripts.

+ +

The script-supporting elements are:

+ + + +

Transparent content model

+ +

If an element has a transparent content model, then its contents must be structured such that they would be valid HTML 5, even if the transparent element were removed and replaced by the child elements.

+ +

For example, the {{HTMLElement("del")}} and {{HTMLELement("ins")}} elements are transparent:

+ +
<p>We hold these truths to be <del><em>sacred &amp; undeniable</em></del> <ins>self-evident</ins>.</p>
+
+ +

If those elements were removed, this fragment would still be valid HTML (if not correct English).

+ +
<p>We hold these truths to be <em>sacred &amp; undeniable</em> self-evident.</p>
+
+ +

Outros modelos de conteúdo

+ +

Seção raiz.

diff --git a/files/pt-pt/web/guide/html/html5/html5_parser/index.html b/files/pt-pt/web/guide/html/html5/html5_parser/index.html new file mode 100644 index 0000000000..eff96db73f --- /dev/null +++ b/files/pt-pt/web/guide/html/html5/html5_parser/index.html @@ -0,0 +1,58 @@ +--- +title: Parser HTML5 +slug: Web/HTML/HTML5/Parser_HTML5 +translation_of: Web/Guide/HTML/HTML5/HTML5_Parser +--- +

{{ gecko_minversion_header("2") }}

+

O Gecko 2 introduz um novo analizador (parser), baseado no HTML5. O analizador (parser) HTML é uma das peças mais sensíveis e complicadas de um navegador. Ele controla como o código fonte HTML é transformado em páginas web e, também, mudanças para alguns casos de exceções. O novo analisador (parser) é mais rápido, cumpre com o padrão do HTML5, e habilita também várias novas funcionalidades.

+

O novo analisador (parser) introduz estas melhorias maiores:

+ +

A especificação do HTML5 (en) fornece descrições mais detalhadas do que os padrões anteriores do HTML de como transformar um fluxo de bytes em uma árvore DOM. Isto resultará em implementações mais consistentes do navegador. Em outras palavras, o suporte ao HTML5 no Gecko, WebKit e Internet Explorer (IE) se tornará mais consistente um com o outro.

+

Changed parser behaviors

+

Some changes to the way that the Gecko 2 parser behaves, as compared to earlier versions of Gecko, may affect web developers, depending on how you've written your code in the past and what browsers you've tested it on.

+

Tokenization of left angle-bracket within a tag

+

Given the string <foo<bar>, the new parser reads it as one tag named foo<bar. This behavior is consistent with IE and Opera, and is different from Gecko 1.x and WebKit, which read it as two tags, foo and bar. If you previously tested your code in IE and Opera, then you probably don't have any tags like this. If you tested your site only with Gecko 1.x or WebKit (for example, Firefox-only intranets or WebKit-oriented mobile sites), then you might have tags that match this pattern, and they will behave differently with Gecko 2.

+

Calling document.write() during parsing

+

Prior to HTML5, Gecko and WebKit allowed calls to document.write() during parsing to insert content into the source stream. This behavior was inherently racy, as the content was inserted into a timing-dependent point in the source stream. If the call happened after the parser was done, the inserted content replaced the document. In IE, such calls are either ignored or imply a call to document.open(), replacing the document. In HTML5, document.write() can only be called from a script that is created by a {{ HTMLElement("script") }} tag that does not have the async or defer attributes set. With the HTML5 parser, calls to document.write() in any other context either are ignored or replace the document.

+

Some contexts from which you should not call document.write() include:

+ +

If you use the same mechanism for loading script libraries for all browsers including IE, then your code probably will not be affected by this change. Scripts that serve racy code to Firefox, perhaps while serving safe code to IE, will see a difference due to this change. Firefox writes a warning to the JavaScript console when it ignores a call to document.write().

+

Lack of Reparsing

+

Prior to HTML5, parsers reparsed the document if they hit the end of the file within certain elements or within comments. For example, if the document lacked a </title> closing tag, the parser would reparse to look for the first '<' in the document, or if a comment was not closed, it would look for the first '>'. This behavior created a security vulnerability. If an attacker could force a premature end-of-file, the parser might change which parts of the document it considered to be executable scripts. In addition, supporting reparsing led to unnecessarily complex parsing code.

+

With HTML5, parsers no longer reparse documents. This change has the following consequences for web developers:

+ +

Performance improvement with speculative parsing

+

Unrelated to the requirements of HTML5 specification, the Gecko 2 parser uses speculative parsing, in which it continues parsing a document while scripts are being downloaded and executed. This results in improved performance compared to older parsers, because most of the time, Gecko can complete these tasks in parallel.

+

To best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call document.write(), you write a balanced sub-tree within that chunk of script. A balanced sub-tree is HTML code in which any elements that are opened are also closed, so that after the script, the elements left open are the same ones that were open before the script. The open and closing tags do not need to be written by the same document.write() call, as long as they are within the same <script> tag.

+

Please note that you shouldn't use end tags for void elements that don't have end tags: {{ HTMLElement('area') }}, {{ HTMLElement('base') }}, {{ HTMLElement('br') }}, {{ HTMLElement('col') }}, {{ HTMLElement('command') }}, {{ HTMLElement('embed') }}, {{ HTMLElement('hr') }}, {{ HTMLElement('img') }}, {{ HTMLElement('input') }}, {{ HTMLElement('keygen') }}, {{ HTMLElement('link') }}, {{ HTMLElement('meta') }}, {{ HTMLElement('param') }}, {{ HTMLElement('source') }} and {{ HTMLElement('wbr') }}. (There are also some element whose end tags can be omitted in some cases, such as {{ HTMLElement('p') }} in the example below, but it's simpler to always use end tags for those elements than to make sure that the end tags are only omitted when they aren't necessary.)

+

For example, the following code writes a balanced sub-tree:

+
<script>
+  document.write("<div>");
+  document.write("<p>Some content goes here.</p>");
+  document.write("</div>");
+</script>
+<!-- Non-script HTML goes here. -->
+
+

In contrast, the following code contains two scripts with unbalanced sub-trees, which causes speculative parsing to fail and therefore the time to parse the document is longer.

+
<script>document.write("<div>");</script>
+<p>Some content goes here.</p>
+<script>document.write("</div>");</script>
+
+

For more information, see Optimizing your pages for speculative parsing.

+

 

diff --git a/files/pt-pt/web/guide/html/html5/index.html b/files/pt-pt/web/guide/html/html5/index.html new file mode 100644 index 0000000000..87e542c8c8 --- /dev/null +++ b/files/pt-pt/web/guide/html/html5/index.html @@ -0,0 +1,169 @@ +--- +title: HTML5 +slug: Web/HTML/HTML5 +tags: + - Desenvolvimento da Web + - Guía + - HTML + - HTML5 + - Resumo + - Sinopse + - Web +translation_of: Web/Guide/HTML/HTML5 +--- +

HTML5 é a última evolução no padrão que define o HTML. O termo representa dois conceitos diferentes. Esta é uma nova versão da linguagem HTML, com novos elementos, atributos e comportamentos, e um conjunto maior de tecnologias que permite a criação de sites e aplicações da Web mais diversos e poderosos. Este conjunto às vezes é chamado de HTML5 e amigos e, muitas vezes, abreviado apenas para HTML5.

+ +

Desenhado para ser utilizado por todos os programadores da Web Aberta, esta página de referência interliga para inúmeros recursos sobre as tecnologias em HTML5, classificadas em vários grupos com base nas suas funções.

+ + + +
+
+

SemÂntIcA

+ +
+
Sections and outlines in HTML5
+
A look at the new outlining and sectioning elements in HTML5: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} and {{HTMLElement("aside")}}.
+
Using HTML5 audio and video
+
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
+
Forms improvements
+
A look at the constraint validation API, several new attributes, new values for the {{HTMLElement("input")}} attribute {{htmlattrxref("type", "input")}} and the new {{HTMLElement("output")}} element.
+
New semantic elements
+
Beside sections, media and forms elements, there are numerous new elements, like {{HTMLElement("mark")}}, {{HTMLElement("figure")}}, {{HTMLElement("figcaption")}}, {{HTMLElement("data")}}, {{HTMLElement("time")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, or {{HTMLElement("meter")}} and {{HTMLElement("main")}}, increasing the number of valid HTML5 elements.
+
Improvement in {{HTMLElement("iframe")}}
+
Using the {{htmlattrxref("sandbox", "iframe")}} and {{htmlattrxref("srcdoc", "iframe")}} attributes, authors can now be precise about the level of security and the wished rendering of an {{HTMLElement("iframe")}} element.
+
MathML
+
Allows directly embedding mathematical formulas.
+
Introduction to HTML5
+
This article introduces how to indicate to the browser that you are using HTML5 in your web design or web application.
+
HTML5 Cheat Sheet
+
A handy HTML 5 cheat sheet for beginners who want to master HTML 5, its elements, event attributes and compatibility.
+
HTML5-compliant parser
+
The parser, which turns the bytes of an HTML document into a DOM, has been extended and now precisely defines the behavior to use in all cases, even when faced with invalid HTML. This leads to far greater predictability and interoperability between HTML5-compliant browsers.
+
+ +

ConetiviDADE

+ +
+
Web Sockets
+
Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means.
+
Server-sent events
+
Allows a server to push events to a client, rather than the classical paradigm where the server could send data only in response to a client's request.
+
WebRTC
+
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
+
+ +

Off-line e ARMAZENAMENTO

+ +
+
Offline resources: The application cache
+
Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level.
+
Online and offline events
+
Firefox 3 supports WHATWG online and offline events, which let applications and extensions detect whether or not there's an active Internet connection, as well as to detect when the connection goes up and down.
+
WHATWG client-side session and persistent storage (aka DOM storage)
+
Client-side session and persistent storage allows web applications to store structured data on the client side.
+
IndexedDB
+
IndexedDB is a web standard for the storage of significant amounts of structured data in the browser and for high performance searches on this data using indexes.
+
Using files from web applications
+
Support for the new HTML5 File API has been added to Gecko, making it possible for web applications to access local files selected by the user. This includes support for selecting multiple files using the {{HTMLElement("input")}} of type file HTML element's new multiple attribute. There also is FileReader.
+
+ +

MultimÉdia

+ +
+
Using HTML5 audio and video
+
The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.
+
WebRTC
+
This technology, where RTC stands for Real-Time Communication, allows connecting to other people and controlling videoconferencing directly in the browser, without the need for a plugin or an external application.
+
Using the Camera API
+
Allows using, manipulating, and storing an image from the computer's camera.
+
Track and WebVTT
+
The {{HTMLElement("track")}} element allows subtitles and chapters. WebVTT is a text track format.
+
+ +

GRÁFICOS E EFEITOS 3D

+ +
+
Canvas tutorial
+
Learn about the new {{HTMLElement("canvas")}} element and how to draw graphs and other objects in Firefox.
+
HTML5 Text API for <canvas> elements
+
The HTML5 text API is now supported by {{HTMLElement("canvas")}} elements.
+
WebGL
+
WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0 that can be used in HTML5 {{HTMLElement("canvas")}} elements.
+
SVG
+
An XML-based format of vectorial images that can directly be embedded in the HTML.
+
+
+ +
+

DESEMPENHO E IntegraÇÃO

+ +
+
Web Workers
+
Allows delegation of JavaScript evaluation to background threads, allowing these activities to prevent slowing down interactive events.
+
XMLHttpRequest level 2
+
Allows fetching asynchronously some parts of the page, allowing it to display dynamic content, varying according to the time and user actions. This is the technology behind Ajax.
+
JIT-compiling JavaScript engines
+
The new generation of JavaScript engines is much more powerful, leading to greater performance.
+
History API
+
Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information.
+
The contentEditable Attribute: Transform your website to a wiki!
+
HTML5 has standardized the contentEditable attribute. Learn more about this feature.
+
Drag and drop
+
The HTML5 drag and drop API allows support for dragging and dropping items within and between web sites. This also provides a simpler API for use by extensions and Mozilla-based applications.
+
Focus management in HTML
+
The new HTML5 activeElement and hasFocus attributes are supported.
+
Web-based protocol handlers
+
You can now register web applications as protocol handlers using the navigator.registerProtocolHandler() method.
+
requestAnimationFrame
+
Allows control of animations rendering to obtain optimal performance.
+
Fullscreen API
+
Controls the usage of the whole screen for a Web page or application, without the browser UI displayed.
+
Pointer Lock API
+
Allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit.
+
Online and offline events
+
In order to build a good offline-capable web application, you need to know when your application is actually offline. Incidentally, you also need to know when your application has returned to an online status again.
+
+ +

ACESSO AO DISPOSITIVO

+ +
+
Using the Camera API
+
Allows using, manipulating, and storing an image from the computer's camera.
+
Touch events
+
Handlers to react to events created by a user pressing touch screens.
+
Using geolocation
+
Let browsers locate the position of the user using geolocation.
+
Detecting device orientation
+
Get the information when the device on which the browser runs changes orientation. This can be used as an input device (e.g., to make games that react to the position of the device) or to adapt the layout of a page to the orientation of the screen (portrait or landscape).
+
Pointer Lock API
+
Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.
+
+ +

ESTILIZAÇÃO

+ +

CSS has been extended to be able to style elements in a much more complex way. This is often referred as CSS3, though CSS is not a monolithic specification any more and the different modules are not all at level 3: some are at level 1 and others at level 4, with all the intermediate levels covered.

+ +
+
New background styling features
+
It is now possible to put a shadow to a box, using {{cssxref("box-shadow")}} and multiple backgrounds can be set.
+
More fancy borders
+
Not only it is now possible to use images to style borders, using {{cssxref("border-image")}} and its associated longhand properties, but rounded borders are supported via the {{cssxref("border-radius")}} property.
+
Animating your style
+
Using CSS Transitions to animate between different states or using CSS Animations to animate parts of the page without a triggering event, you can now control mobile elements on your page.
+
Typography improvement
+
Authors have better control to reach better typography. They can control {{cssxref("text-overflow")}} and hyphenation, but also can add a shadow to it or control more precisely its decorations. Custom typefaces can be downloaded and applied thanks to the new {{cssxref("@font-face")}} at-rule.
+
New presentational layouts
+
In order to improve the flexibility of designs, two new layouts have been added: the CSS multi-column layouts and CSS flexible box layout.
+
+
+
diff --git a/files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html b/files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html new file mode 100644 index 0000000000..7a30759282 --- /dev/null +++ b/files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html @@ -0,0 +1,20 @@ +--- +title: Introdução ao HTML5 +slug: Web/HTML/HTML5/Introdução_ao_HTML5 +tags: + - HTML + - HTML5 +translation_of: Web/Guide/HTML/HTML5/Introduction_to_HTML5 +--- +

O HTML5 (en), cujas novidades começaram a ser implementadas no Gecko 1.8.1, é a mais nova versão do padrão HTML. Ela oferece novas características para proporcionar não somente um rico suporte à mídia, mas também para melhorar o suporte à criação de aplicações web que podem interagir com o usuário, seus dados locais e servidores de maneira mais fácil e efetiva.

+ +

Como o HTML5 ainda está em estágio de projeto, mudanças às especificações são inevitáveis. Por causa disso, nem todas as características são suportadas por todos os navegadores ainda. Entretanto, o Gecko (e por extensão, o Firefox) possui um suporte inicial ao HTML5 muito bom e o trabalho continua no caminho de suportar cada vez mais características. Você pode encontrar uma lista das características do HTML5 suportadas pelo Gecko na página principal do HTML5.

+ +

O doctype do HTML5

+ +

O doctype para o HTML5 é muito simples. Para indicar que seu conteúdo HTML usa HTML5, simplesmente use:

+ +
<!DOCTYPE html>
+
+ +

Este doctype tão simples, permitirá que mesmo os navegadores que atualmente não suportam o HTML5, o considerem como o modo padrão, o que significa que eles irão interpretar as partes do HTML já estabelecidas em um modo complacente do HTML5, ignorando as novas características do HTML5 não suportadas pelos mesmos.

diff --git a/files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html b/files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html new file mode 100644 index 0000000000..fd11f62887 --- /dev/null +++ b/files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html @@ -0,0 +1,343 @@ +--- +title: Utilizar estruturas e secções de HTML +slug: Web/Guide/HTML/Utilizar_estruturas_e_seccoes_de_HTML +tags: + - Avançado + - Estruturas + - Exemplo + - Guía + - HTML + - HTML5 + - Resumo + - Secções + - Sinopse + - Web +translation_of: Web/Guide/HTML/Using_HTML_sections_and_outlines +--- +
+

Importante: atualmente, não existem implementações conhecidas do algoritmo de estrutura nos navegadores gráficos ou agentes de utilizador da tecnologia assistiva, embora o algoritmo esteja implementado noutro software, tal como verificadores de conformidade . Assim, o algoritmo de estrutura não pode ser invocado para transmitir a estrutura do documento aos utilizadores. Recomenda-se que os autores utilizem rank (h1-h6) para transmitir a estrutura do documento.

+
+ +

The HTML5 specification brings several new elements to web developers allowing them to describe the structure of a web document with standard semantics. This document describes these elements and how to use them to define the desired outline for any document.

+ +

Estrutura de um documento em HTML 4

+ +

A estrutura de um documento, por exemplo, a estrutura de semântica do que está entre <body> e </body>, é fundamental para apresentar a página ao utilizador. HTML4 uses the notion of sections and sub-sections of a document to describe its structure. A section is defined by a ({{HTMLElement("div")}}) element with heading elements ({{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, or {{HTMLElement("h6")}}) within it, defining its title. The relationships of these elements leads to the structure of the document and its outline.

+ +

So the following mark-up:

+ +
+
<div class="section" id="forest-elephants" >
+  <h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <div class="subsection" id="forest-habitat" >
+    <h2>Habitat</h2>
+    <p>Forest elephants do not live in trees but among them.
+     ...this subsection continues...
+  </div>
+</div>
+
+
+ +

leads to the following outline (without the implicit level numbers displayed):

+ +
1. Forest elephants
+   1.1 Habitat
+
+ +

The {{HTMLElement("div")}} elements aren't mandatory to define a new section. The mere presence of a heading element is enough to imply a new section. Therefore,

+ +
<h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <h2>Habitat</h2>
+  <p>Forest elephants do not live in trees but among them.
+    ...this subsection continues...
+  <h2>Diet</h2>
+<h1>Mongolian gerbils</h1>
+
+ +

leads to the following outline:

+ +
1. Forest elephants
+   1.1 Habitat
+   1.2 Diet
+2. Mongolian gerbils
+
+ +

Problemas resolvidos pelo HTML5

+ +

The HTML 4 definition of the structure of a document and its implied outlining algorithm is very rough and leads to numerous problems:

+ +
    +
  1. Usage of {{HTMLElement("div")}} for defining semantic sections, without defining specific values for the class attributes makes the automation of the outlining algorithm impossible ("Is that {{HTMLElement("div")}} part of the outline of the page, defining a section or a subsection?" Or "is it only a presentational {{HTMLElement("div")}}, only used for styling?"). In other terms, the HTML4 spec is very imprecise on what is a section and how its scope is defined. Automatic generation of outlines is important, especially for assistive technology, that are likely to adapt the way they present information to the users according to the structure of the document. HTML5 removes the need for {{HTMLElement("div")}} elements from the outlining algorithm by introducing a new element, {{HTMLElement("section")}}, the HTML Section Element.
  2. +
  3. Merging several documents is hard: inclusion of a sub-document in a main document means changing the level of the HTML Headings Element so that the outline is kept. This is solved in HTML5 as the newly introduced sectioning elements ({{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("nav")}} and {{HTMLElement("aside")}}) are always subsections of their nearest ancestor section, regardless of what sections are created by internal headings.
  4. +
  5. In HTML4, every section is part of the document outline. But documents are often not that linear. A document can have special sections containing information that is not part of, though it is related to, the main flow, like an advertisement block or an explanation box. HTML5 introduces the {{HTMLElement("aside")}} element allowing such sections to not be part of the main outline.
  6. +
  7. Again, in HTML4, because every section is part of the document outline, there is no way to have sections containing information related not to the document but to the whole site, like logos, menus, table of contents, or copyright information and legal notices. For that purpose, HTML5 introduces three new elements: {{HTMLElement("nav")}} for collections of links, such as a table of contents, {{HTMLElement("footer")}} and {{HTMLElement("header")}} for site-related information. Note that {{HTMLElement("header")}} and {{HTMLElement("footer")}} are not sectioning content like {{HTMLElement("section")}}, rather, they exist to semantically mark up parts of a section.
  8. +
+ +

More generally, HTML5 brings precision to the sectioning and heading features, allowing document outlines to be predictable and used by the browser to improve the user experience.

+ +

O algoritmo de estrutura de HTML5

+ +

Let's consider the algorithms  underlying the way HTML handles sections and outlines.

+ +

Definir secções

+ +

All content lying inside the {{HTMLElement("body")}} element is part of a section. Sections in HTML5 can be nested. Beside the main section, defined by the {{HTMLElement("body")}} element, section limits are defined either explicitly or implicitly. Explicitly-defined sections are the content within {{HTMLElement("body")}},  {{HTMLElement("section")}},  {{HTMLElement("article")}},  {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} tags. 

+ +
Each section can have its own heading hierarchy. Therefore, even a nested section can have an {{HTMLElement("h1")}}. See {{anch("Defining headings")}}
+ +

Let's look at an example — here we have a document with a top level section and a footer defined. Inside the top level section we have three subsections, defined by two {{htmlelement("section")}} elements and an {{htmlelement("aside")}} element:

+ +
<section>
+
+  <h1>Forest elephants</h1>
+
+  <section>
+    <h1>Introduction</h1>
+    <p>In this section, we discuss the lesser known forest elephants.</p>
+  </section>
+
+  <section>
+    <h1>Habitat</h1>
+    <p>Forest elephants do not live in trees but among them.</p>
+  </section>
+
+  <aside>
+    <p>advertising block</p>
+  </aside>
+
+</section>
+
+<footer>
+  <p>(c) 2010 The Example company</p>
+</footer>
+ +

This leads to the following outline:

+ +
1. Forest elephants
+   1.1 Introduction
+   1.2 Habitat
+
+ +

Definir cabeçalhos

+ +

While the HTML Sectioning elements define the structure of the document, an outline also needs headings to be useful. The basic rule is simple: the first HTML heading element (one of {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}) defines the heading of the current section.

+ +

The heading elements have a rank given by the number in the element name, where {{HTMLElement("h1")}} has the highest rank, and {{HTMLElement("h6")}} has the lowest rank. Relative ranking matters only within a section; the structure of the sections determines the outline, not the heading rank of the sections. For example, consider this code:

+ +
<section>
+  <h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <section>
+    <h2>Habitat</h2>
+    <p>Forest elephants do not live in trees but among them.
+        ...this subsection continues...
+  </section>
+</section>
+<section>
+  <h3>Mongolian gerbils</h3>
+  <p>In this section, we discuss the famous mongolian gerbils.
+     ...this section continues...
+</section>
+ +

This creates the following outline:

+ +
1. Forest elephants
+   1.1 Habitat
+2. Mongolian gerbils
+ +

Note that the rank of the heading element (in the example {{HTMLElement("h1")}} for the first top-level section, {{HTMLElement("h2")}} for the subsection and {{HTMLElement("h3")}} for the second top-level section) is not important. (Any rank can be used as the heading of an explicitly-defined section, although this practice is not recommended.)

+ +

Implicit sectioning

+ +

Because the HTML5 Sectioning Elements aren't mandatory to define an outline, to keep compatibility with the existing web dominated by HTML4, there is a way to define sections without them. This is called implicit sectioning.

+ +

The heading elements ({{HTMLElement("h1")}} to {{HTMLElement("h6")}}) define a new, implicit section when they aren't the first heading of their parent, explicit, sections. The way this implicit section is positioned in the outline is defined by its relative rank with the previous heading in its parent section. If it is of a lower rank than the previous heading, it opens an implicit sub-section of the section. This code:

+ +
<section>
+  <h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <h3 class="implicit subsection">Habitat</h3>
+  <p>Forest elephants do not live in trees but among them.
+    ...this subsection continues...
+</section>
+ +

leading to the following outline:

+ +
1. Forest elephants
+   1.1 Habitat (implicitly defined by the h3 element)
+
+ +

If it is of the same rank as the previous heading, it closes the previous section (which may have been explicit!) and opens a new implicit one at the same level: 

+ +
<section>
+  <h1>Forest elephants</h1>
+  <p>In this section, we discuss the lesser known forest elephants.
+    ...this section continues...
+  <h1 class="implicit section">Mongolian gerbils</h1>
+  <p>Mongolian gerbils are cute little mammals.
+    ...this section continues...
+</section>
+ +

leading to the following outline: 

+ +
1. Forest elephants
+2. Mongolian gerbils (implicitly defined by the h1 element, which closed the previous section at the same time)
+
+ +

If it is of a higher rank than the previous heading, it closes the previous section and opens a new implicit one at the higher level:

+ +
<body>
+  <h1>Mammals</h1>
+  <h2>Whales</h2>
+  <p>In this section, we discuss the swimming whales.
+    ...this section continues...
+  <section>
+    <h3>Forest elephants</h3>
+    <p>In this section, we discuss the lesser known forest elephants.
+      ...this section continues...
+    <h3>Mongolian gerbils</h3>
+      <p>Hordes of gerbils have spread their range far beyond Mongolia.
+         ...this subsection continues...
+    <h2>Reptiles</h2>
+      <p>Reptiles are animals with cold blood.
+          ...this section continues...
+  </section>
+</body>
+ +

leading to the following outline:

+ +
1. Mammals
+   1.1 Whales (implicitly defined by the h2 element)
+   1.2 Forest elephants (explicitly defined by the section element)
+   1.3 Mongolian gerbils (implicitly defined by the h3 element, which closes the previous section at the same time)
+2. Reptiles (implicitly defined by the h2 element, which closes the previous section at the same time)
+
+ +

This is not the outline that one might expect by quickly glancing at the heading tags. To make your markup human-understandable, it is a good practice to use explicit tags for opening and closing sections, and to match the heading rank to the intended section nesting level. However, this is not required by the HTML5 specification. If you find that browsers are rendering your document outline in unexpected ways, check whether you have sections that are implicitly closed by heading elements.

+ +

An exception to the rule of thumb that heading rank should match the section nesting level is for sections that may be reused in multiple documents. For example, a section might be stored in a content-management system and assembled into documents at run time. In this case, a good practice is to start at {{HTMLElement("h1")}} for the top heading level of the reusable section. The nesting level of the reusable section will be determined by the section hierarchy of the document in which it appears. Explicit section tags are still helpful in this case.

+ +

Sectioning roots

+ +

 A sectioning root is an HTML element that can have its own outline, but the sections and headings inside it do not contribute to the outline of its ancestor. Beside {{HTMLElement("body")}} which is the logical sectioning root of a document, these are often elements that introduce external content to the page: {{HTMLElement("blockquote")}}, {{HTMLElement("details")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figure")}} and {{HTMLElement("td")}}.

+ +

Example:

+ +
<section>
+  <h1>Forest elephants</h1>
+  <section>
+    <h2>Introduction</h2>
+    <p>In this section, we discuss the lesser known forest elephants</p>
+  </section>
+  <section>
+    <h2>Habitat</h2>
+    <p>Forest elephants do not live in trees but among them. Let's
+       look what scientists are saying in "<cite>The Forest Elephant in Borneo</cite>":</p>
+    <blockquote>
+       <h1>Borneo</h1>
+       <p>The forest element lives in Borneo...</p>
+    </blockquote>
+  </section>
+</section>
+
+ +

This example results in the following outline:

+ +
1. Forest elephants
+   1.1 Introduction
+   1.2 Habitat
+ +

This outline doesn't contain the internal outline of the {{HTMLElement("blockquote")}} element, which, being an external citation, is a sectioning root and isolates its internal outline.

+ +

Sections outside the outline

+ +

 HTML5 introduces two new elements that allow defining sections that don't belong to the main outline of a web document:

+ +
    +
  1. The HTML Aside Section Element ({{HTMLElement("aside")}}) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. It has its own outline, but doesn't belong to the main one.
  2. +
  3. The HTML Navigational Section Element ({{HTMLElement("nav")}}) defines a section that contains navigation links. There can be several of them in a document, for example one with page internal links like a table of contents, and another with site navigational links. These links are not part of the main document flow and outline, and are generally not initially rendered by screen readers and similar assistive technologies.
  4. +
+ +

Cabeçalhos e Rodapés

+ +

HTML5 also introduces two new elements that can be used to mark up the header and the footer of a section:

+ +
    +
  1. The HTML Header Element ({{HTMLElement("header")}}) defines a page header — typically containing the logo and name of the site and possibly a horizontal menu — or section header, containing perhaps the section's heading, author name, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("header")}}. Despite its name, it is not necessarily positioned at the beginning of the page or section.
  2. +
  3. The HTML Footer Element ({{HTMLElement("footer")}}) defines a page footer — typically containing the copyright and legal notices and sometimes some links — or section footer, containing perhaps the section's publication date, license information, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("footer")}}. Despite its name, it is not necessarily positioned at the end of the page or section.
  4. +
+ +

These do not create new sections in the outline, rather, they mark up content inside sections of the page.

+ +

Addresses in sectioning elements

+ +

The author of a document often wants to publish some contact information, such as the author's name and address. HTML4 allowed this via the {{HTMLElement("address")}} element, which has been extended in HTML5.

+ +

A document can be made of different sections from different authors. A section from another author than the one of the main page is defined using the {{HTMLElement("article")}} element. Consequently, the {{HTMLElement("address")}} element is now linked to its nearest {{HTMLElement("body")}} or {{HTMLElement("article")}} ancestor.

+ +

Utilizar elementos de HTML5 nos navegadores não HTML5

+ +

Sections and headings elements should work in most non-HTML5 browsers. Though unsupported, they don't need a special DOM interface and they only need a specific CSS styling as unknown elements are styled as display:inline by default:

+ +
article, aside, footer, header, hgroup, nav, section {
+  display:block;
+}
+
+ +

Of course the web developer can style them differently, but keep in mind that in a non-HTML5 browser, the default styling is different from what is expected for such elements. Also note that the {{HTMLElement("time")}} element has not been included, because the default styling for it in a non-HTML5 browser is the same as the one in an HTML5-compatible one.

+ +

This method has its limitation though, as some browsers do not allow styling of unsupported elements. That is the case of the Internet Explorer (version 8 and earlier), which need a specific script to allow this:

+ +
<!--[if lt IE 9]>
+  <script>
+    document.createElement("article");
+    document.createElement("aside");
+    document.createElement("footer");
+    document.createElement("header");
+    document.createElement("hgroup");
+    document.createElement("nav");
+    document.createElement("section");
+    document.createElement("time");
+  </script>
+<![endif]-->
+
+ +

This script means that, in the case of Internet Explorer (8 and earlier), scripting should be enabled in order to display HTML5 sectioning and headings elements properly. If not, they won't be displayed, which may be problematic as these elements are likely defining the structure of the whole page. That's why an explicit {{HTMLElement("noscript")}} element should be added inside the {{HTMLElement("head")}} element for this case:

+ +
<noscript>
+  <p><strong>This web page requires JavaScript to be enabled.</strong></p>
+  <p>JavaScript is an object-oriented computer programming language
+    commonly used to create interactive effects within web browsers.</p>
+  <p><a href="https://goo.gl/koeeaJ">How to enable JavaScript?</a></p>
+</noscript>
+
+ +

This leads to the following code to allow the support of the HTML5 sections and headings elements in non-HTML5 browsers, even for Internet Explorer (8 and older), with a proper fallback for the case where this latter browser is configured not to use scripting:

+ +
<!--[if lt IE 9]> <script>
+  document.createElement("article");
+    document.createElement("aside");
+    document.createElement("footer");
+    document.createElement("header");
+    document.createElement("hgroup");
+    document.createElement("nav");
+    document.createElement("section");
+    document.createElement("time");   </script> <![endif]--> <noscript>
+  <p><strong>This web page requires JavaScript to be enabled.</strong></p>
+  <p>JavaScript is an object-oriented computer programming language
+    commonly used to create interactive effects within web browsers.</p>
+  <p><a href="https://goo.gl/koeeaJ">How to enable JavaScript?</a></p>
+</noscript> <![endif]-->
+
+ +

Conclusão

+ +

The new semantic elements introduced in HTML5 bring the ability to describe the structure and the outline of a web document in a standard way. They bring a big advantage for people having HTML5 browsers and needing the structure to help them understand the page, for instance people needing the help of some assistive technology. These new semantic elements are simple to use and, with very few burdens, can be made to work also in non-HTML5 browsers. Therefore they should be used without restrictions.

+ +
{{HTML5ArticleTOC()}}
diff --git a/files/pt-pt/web/guide/html/utilizar_estruturas_e_seccoes_de_html/index.html b/files/pt-pt/web/guide/html/utilizar_estruturas_e_seccoes_de_html/index.html deleted file mode 100644 index fd11f62887..0000000000 --- a/files/pt-pt/web/guide/html/utilizar_estruturas_e_seccoes_de_html/index.html +++ /dev/null @@ -1,343 +0,0 @@ ---- -title: Utilizar estruturas e secções de HTML -slug: Web/Guide/HTML/Utilizar_estruturas_e_seccoes_de_HTML -tags: - - Avançado - - Estruturas - - Exemplo - - Guía - - HTML - - HTML5 - - Resumo - - Secções - - Sinopse - - Web -translation_of: Web/Guide/HTML/Using_HTML_sections_and_outlines ---- -
-

Importante: atualmente, não existem implementações conhecidas do algoritmo de estrutura nos navegadores gráficos ou agentes de utilizador da tecnologia assistiva, embora o algoritmo esteja implementado noutro software, tal como verificadores de conformidade . Assim, o algoritmo de estrutura não pode ser invocado para transmitir a estrutura do documento aos utilizadores. Recomenda-se que os autores utilizem rank (h1-h6) para transmitir a estrutura do documento.

-
- -

The HTML5 specification brings several new elements to web developers allowing them to describe the structure of a web document with standard semantics. This document describes these elements and how to use them to define the desired outline for any document.

- -

Estrutura de um documento em HTML 4

- -

A estrutura de um documento, por exemplo, a estrutura de semântica do que está entre <body> e </body>, é fundamental para apresentar a página ao utilizador. HTML4 uses the notion of sections and sub-sections of a document to describe its structure. A section is defined by a ({{HTMLElement("div")}}) element with heading elements ({{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, or {{HTMLElement("h6")}}) within it, defining its title. The relationships of these elements leads to the structure of the document and its outline.

- -

So the following mark-up:

- -
-
<div class="section" id="forest-elephants" >
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <div class="subsection" id="forest-habitat" >
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them.
-     ...this subsection continues...
-  </div>
-</div>
-
-
- -

leads to the following outline (without the implicit level numbers displayed):

- -
1. Forest elephants
-   1.1 Habitat
-
- -

The {{HTMLElement("div")}} elements aren't mandatory to define a new section. The mere presence of a heading element is enough to imply a new section. Therefore,

- -
<h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h2>Habitat</h2>
-  <p>Forest elephants do not live in trees but among them.
-    ...this subsection continues...
-  <h2>Diet</h2>
-<h1>Mongolian gerbils</h1>
-
- -

leads to the following outline:

- -
1. Forest elephants
-   1.1 Habitat
-   1.2 Diet
-2. Mongolian gerbils
-
- -

Problemas resolvidos pelo HTML5

- -

The HTML 4 definition of the structure of a document and its implied outlining algorithm is very rough and leads to numerous problems:

- -
    -
  1. Usage of {{HTMLElement("div")}} for defining semantic sections, without defining specific values for the class attributes makes the automation of the outlining algorithm impossible ("Is that {{HTMLElement("div")}} part of the outline of the page, defining a section or a subsection?" Or "is it only a presentational {{HTMLElement("div")}}, only used for styling?"). In other terms, the HTML4 spec is very imprecise on what is a section and how its scope is defined. Automatic generation of outlines is important, especially for assistive technology, that are likely to adapt the way they present information to the users according to the structure of the document. HTML5 removes the need for {{HTMLElement("div")}} elements from the outlining algorithm by introducing a new element, {{HTMLElement("section")}}, the HTML Section Element.
  2. -
  3. Merging several documents is hard: inclusion of a sub-document in a main document means changing the level of the HTML Headings Element so that the outline is kept. This is solved in HTML5 as the newly introduced sectioning elements ({{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("nav")}} and {{HTMLElement("aside")}}) are always subsections of their nearest ancestor section, regardless of what sections are created by internal headings.
  4. -
  5. In HTML4, every section is part of the document outline. But documents are often not that linear. A document can have special sections containing information that is not part of, though it is related to, the main flow, like an advertisement block or an explanation box. HTML5 introduces the {{HTMLElement("aside")}} element allowing such sections to not be part of the main outline.
  6. -
  7. Again, in HTML4, because every section is part of the document outline, there is no way to have sections containing information related not to the document but to the whole site, like logos, menus, table of contents, or copyright information and legal notices. For that purpose, HTML5 introduces three new elements: {{HTMLElement("nav")}} for collections of links, such as a table of contents, {{HTMLElement("footer")}} and {{HTMLElement("header")}} for site-related information. Note that {{HTMLElement("header")}} and {{HTMLElement("footer")}} are not sectioning content like {{HTMLElement("section")}}, rather, they exist to semantically mark up parts of a section.
  8. -
- -

More generally, HTML5 brings precision to the sectioning and heading features, allowing document outlines to be predictable and used by the browser to improve the user experience.

- -

O algoritmo de estrutura de HTML5

- -

Let's consider the algorithms  underlying the way HTML handles sections and outlines.

- -

Definir secções

- -

All content lying inside the {{HTMLElement("body")}} element is part of a section. Sections in HTML5 can be nested. Beside the main section, defined by the {{HTMLElement("body")}} element, section limits are defined either explicitly or implicitly. Explicitly-defined sections are the content within {{HTMLElement("body")}},  {{HTMLElement("section")}},  {{HTMLElement("article")}},  {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} tags. 

- -
Each section can have its own heading hierarchy. Therefore, even a nested section can have an {{HTMLElement("h1")}}. See {{anch("Defining headings")}}
- -

Let's look at an example — here we have a document with a top level section and a footer defined. Inside the top level section we have three subsections, defined by two {{htmlelement("section")}} elements and an {{htmlelement("aside")}} element:

- -
<section>
-
-  <h1>Forest elephants</h1>
-
-  <section>
-    <h1>Introduction</h1>
-    <p>In this section, we discuss the lesser known forest elephants.</p>
-  </section>
-
-  <section>
-    <h1>Habitat</h1>
-    <p>Forest elephants do not live in trees but among them.</p>
-  </section>
-
-  <aside>
-    <p>advertising block</p>
-  </aside>
-
-</section>
-
-<footer>
-  <p>(c) 2010 The Example company</p>
-</footer>
- -

This leads to the following outline:

- -
1. Forest elephants
-   1.1 Introduction
-   1.2 Habitat
-
- -

Definir cabeçalhos

- -

While the HTML Sectioning elements define the structure of the document, an outline also needs headings to be useful. The basic rule is simple: the first HTML heading element (one of {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}) defines the heading of the current section.

- -

The heading elements have a rank given by the number in the element name, where {{HTMLElement("h1")}} has the highest rank, and {{HTMLElement("h6")}} has the lowest rank. Relative ranking matters only within a section; the structure of the sections determines the outline, not the heading rank of the sections. For example, consider this code:

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <section>
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them.
-        ...this subsection continues...
-  </section>
-</section>
-<section>
-  <h3>Mongolian gerbils</h3>
-  <p>In this section, we discuss the famous mongolian gerbils.
-     ...this section continues...
-</section>
- -

This creates the following outline:

- -
1. Forest elephants
-   1.1 Habitat
-2. Mongolian gerbils
- -

Note that the rank of the heading element (in the example {{HTMLElement("h1")}} for the first top-level section, {{HTMLElement("h2")}} for the subsection and {{HTMLElement("h3")}} for the second top-level section) is not important. (Any rank can be used as the heading of an explicitly-defined section, although this practice is not recommended.)

- -

Implicit sectioning

- -

Because the HTML5 Sectioning Elements aren't mandatory to define an outline, to keep compatibility with the existing web dominated by HTML4, there is a way to define sections without them. This is called implicit sectioning.

- -

The heading elements ({{HTMLElement("h1")}} to {{HTMLElement("h6")}}) define a new, implicit section when they aren't the first heading of their parent, explicit, sections. The way this implicit section is positioned in the outline is defined by its relative rank with the previous heading in its parent section. If it is of a lower rank than the previous heading, it opens an implicit sub-section of the section. This code:

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h3 class="implicit subsection">Habitat</h3>
-  <p>Forest elephants do not live in trees but among them.
-    ...this subsection continues...
-</section>
- -

leading to the following outline:

- -
1. Forest elephants
-   1.1 Habitat (implicitly defined by the h3 element)
-
- -

If it is of the same rank as the previous heading, it closes the previous section (which may have been explicit!) and opens a new implicit one at the same level: 

- -
<section>
-  <h1>Forest elephants</h1>
-  <p>In this section, we discuss the lesser known forest elephants.
-    ...this section continues...
-  <h1 class="implicit section">Mongolian gerbils</h1>
-  <p>Mongolian gerbils are cute little mammals.
-    ...this section continues...
-</section>
- -

leading to the following outline: 

- -
1. Forest elephants
-2. Mongolian gerbils (implicitly defined by the h1 element, which closed the previous section at the same time)
-
- -

If it is of a higher rank than the previous heading, it closes the previous section and opens a new implicit one at the higher level:

- -
<body>
-  <h1>Mammals</h1>
-  <h2>Whales</h2>
-  <p>In this section, we discuss the swimming whales.
-    ...this section continues...
-  <section>
-    <h3>Forest elephants</h3>
-    <p>In this section, we discuss the lesser known forest elephants.
-      ...this section continues...
-    <h3>Mongolian gerbils</h3>
-      <p>Hordes of gerbils have spread their range far beyond Mongolia.
-         ...this subsection continues...
-    <h2>Reptiles</h2>
-      <p>Reptiles are animals with cold blood.
-          ...this section continues...
-  </section>
-</body>
- -

leading to the following outline:

- -
1. Mammals
-   1.1 Whales (implicitly defined by the h2 element)
-   1.2 Forest elephants (explicitly defined by the section element)
-   1.3 Mongolian gerbils (implicitly defined by the h3 element, which closes the previous section at the same time)
-2. Reptiles (implicitly defined by the h2 element, which closes the previous section at the same time)
-
- -

This is not the outline that one might expect by quickly glancing at the heading tags. To make your markup human-understandable, it is a good practice to use explicit tags for opening and closing sections, and to match the heading rank to the intended section nesting level. However, this is not required by the HTML5 specification. If you find that browsers are rendering your document outline in unexpected ways, check whether you have sections that are implicitly closed by heading elements.

- -

An exception to the rule of thumb that heading rank should match the section nesting level is for sections that may be reused in multiple documents. For example, a section might be stored in a content-management system and assembled into documents at run time. In this case, a good practice is to start at {{HTMLElement("h1")}} for the top heading level of the reusable section. The nesting level of the reusable section will be determined by the section hierarchy of the document in which it appears. Explicit section tags are still helpful in this case.

- -

Sectioning roots

- -

 A sectioning root is an HTML element that can have its own outline, but the sections and headings inside it do not contribute to the outline of its ancestor. Beside {{HTMLElement("body")}} which is the logical sectioning root of a document, these are often elements that introduce external content to the page: {{HTMLElement("blockquote")}}, {{HTMLElement("details")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("figure")}} and {{HTMLElement("td")}}.

- -

Example:

- -
<section>
-  <h1>Forest elephants</h1>
-  <section>
-    <h2>Introduction</h2>
-    <p>In this section, we discuss the lesser known forest elephants</p>
-  </section>
-  <section>
-    <h2>Habitat</h2>
-    <p>Forest elephants do not live in trees but among them. Let's
-       look what scientists are saying in "<cite>The Forest Elephant in Borneo</cite>":</p>
-    <blockquote>
-       <h1>Borneo</h1>
-       <p>The forest element lives in Borneo...</p>
-    </blockquote>
-  </section>
-</section>
-
- -

This example results in the following outline:

- -
1. Forest elephants
-   1.1 Introduction
-   1.2 Habitat
- -

This outline doesn't contain the internal outline of the {{HTMLElement("blockquote")}} element, which, being an external citation, is a sectioning root and isolates its internal outline.

- -

Sections outside the outline

- -

 HTML5 introduces two new elements that allow defining sections that don't belong to the main outline of a web document:

- -
    -
  1. The HTML Aside Section Element ({{HTMLElement("aside")}}) defines a section that, though related to the main element, doesn't belong to the main flow, like an explanation box or an advertisement. It has its own outline, but doesn't belong to the main one.
  2. -
  3. The HTML Navigational Section Element ({{HTMLElement("nav")}}) defines a section that contains navigation links. There can be several of them in a document, for example one with page internal links like a table of contents, and another with site navigational links. These links are not part of the main document flow and outline, and are generally not initially rendered by screen readers and similar assistive technologies.
  4. -
- -

Cabeçalhos e Rodapés

- -

HTML5 also introduces two new elements that can be used to mark up the header and the footer of a section:

- -
    -
  1. The HTML Header Element ({{HTMLElement("header")}}) defines a page header — typically containing the logo and name of the site and possibly a horizontal menu — or section header, containing perhaps the section's heading, author name, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("header")}}. Despite its name, it is not necessarily positioned at the beginning of the page or section.
  2. -
  3. The HTML Footer Element ({{HTMLElement("footer")}}) defines a page footer — typically containing the copyright and legal notices and sometimes some links — or section footer, containing perhaps the section's publication date, license information, etc. {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, and {{HTMLElement("nav")}} can have their own {{HTMLElement("footer")}}. Despite its name, it is not necessarily positioned at the end of the page or section.
  4. -
- -

These do not create new sections in the outline, rather, they mark up content inside sections of the page.

- -

Addresses in sectioning elements

- -

The author of a document often wants to publish some contact information, such as the author's name and address. HTML4 allowed this via the {{HTMLElement("address")}} element, which has been extended in HTML5.

- -

A document can be made of different sections from different authors. A section from another author than the one of the main page is defined using the {{HTMLElement("article")}} element. Consequently, the {{HTMLElement("address")}} element is now linked to its nearest {{HTMLElement("body")}} or {{HTMLElement("article")}} ancestor.

- -

Utilizar elementos de HTML5 nos navegadores não HTML5

- -

Sections and headings elements should work in most non-HTML5 browsers. Though unsupported, they don't need a special DOM interface and they only need a specific CSS styling as unknown elements are styled as display:inline by default:

- -
article, aside, footer, header, hgroup, nav, section {
-  display:block;
-}
-
- -

Of course the web developer can style them differently, but keep in mind that in a non-HTML5 browser, the default styling is different from what is expected for such elements. Also note that the {{HTMLElement("time")}} element has not been included, because the default styling for it in a non-HTML5 browser is the same as the one in an HTML5-compatible one.

- -

This method has its limitation though, as some browsers do not allow styling of unsupported elements. That is the case of the Internet Explorer (version 8 and earlier), which need a specific script to allow this:

- -
<!--[if lt IE 9]>
-  <script>
-    document.createElement("article");
-    document.createElement("aside");
-    document.createElement("footer");
-    document.createElement("header");
-    document.createElement("hgroup");
-    document.createElement("nav");
-    document.createElement("section");
-    document.createElement("time");
-  </script>
-<![endif]-->
-
- -

This script means that, in the case of Internet Explorer (8 and earlier), scripting should be enabled in order to display HTML5 sectioning and headings elements properly. If not, they won't be displayed, which may be problematic as these elements are likely defining the structure of the whole page. That's why an explicit {{HTMLElement("noscript")}} element should be added inside the {{HTMLElement("head")}} element for this case:

- -
<noscript>
-  <p><strong>This web page requires JavaScript to be enabled.</strong></p>
-  <p>JavaScript is an object-oriented computer programming language
-    commonly used to create interactive effects within web browsers.</p>
-  <p><a href="https://goo.gl/koeeaJ">How to enable JavaScript?</a></p>
-</noscript>
-
- -

This leads to the following code to allow the support of the HTML5 sections and headings elements in non-HTML5 browsers, even for Internet Explorer (8 and older), with a proper fallback for the case where this latter browser is configured not to use scripting:

- -
<!--[if lt IE 9]> <script>
-  document.createElement("article");
-    document.createElement("aside");
-    document.createElement("footer");
-    document.createElement("header");
-    document.createElement("hgroup");
-    document.createElement("nav");
-    document.createElement("section");
-    document.createElement("time");   </script> <![endif]--> <noscript>
-  <p><strong>This web page requires JavaScript to be enabled.</strong></p>
-  <p>JavaScript is an object-oriented computer programming language
-    commonly used to create interactive effects within web browsers.</p>
-  <p><a href="https://goo.gl/koeeaJ">How to enable JavaScript?</a></p>
-</noscript> <![endif]-->
-
- -

Conclusão

- -

The new semantic elements introduced in HTML5 bring the ability to describe the structure and the outline of a web document in a standard way. They bring a big advantage for people having HTML5 browsers and needing the structure to help them understand the page, for instance people needing the help of some assistive technology. These new semantic elements are simple to use and, with very few burdens, can be made to work also in non-HTML5 browsers. Therefore they should be used without restrictions.

- -
{{HTML5ArticleTOC()}}
-- cgit v1.2.3-54-g00ecf