diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pt-pt/web | |
parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip |
initial commit
Diffstat (limited to 'files/pt-pt/web')
392 files changed, 74821 insertions, 0 deletions
diff --git a/files/pt-pt/web/accessibility/aria/aria_techniques/index.html b/files/pt-pt/web/accessibility/aria/aria_techniques/index.html new file mode 100644 index 0000000000..34fa824f8c --- /dev/null +++ b/files/pt-pt/web/accessibility/aria/aria_techniques/index.html @@ -0,0 +1,215 @@ +--- +title: 'Using ARIA: Roles, states, and properties' +slug: Web/Accessibility/ARIA/ARIA_Techniques +tags: + - ARIA + - Accessibility + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/Accessibility/ARIA/ARIA_Techniques +--- +<p class="summary">ARIA defines semantics that can be applied to elements, with these divided into <strong>roles</strong> (defining a type of user interface element) and <strong>states</strong> and <strong>properties</strong> that are supported by a role. Authors must assign an ARIA role and the appropriate states and properties to an element during its life-cycle, unless the element already has appropriate ARIA semantics (via use of an appropriate HTML element). Addition of ARIA semantics only exposes extra information to a browser's accessibility API, and does not affect a page's DOM.</p> + +<h2 id="Roles">Roles</h2> + +<h3 id="Widget_roles">Widget roles</h3> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/button_role" title="Using the button role">button</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/checkbox_role" title="Using the checkbox role">checkbox</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Gridcell_Role">gridcell</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_link_role" title="Using the Link role">link</a></li> + <li>menuitem</li> + <li>menuitemcheckbox </li> + <li>menuitemradio</li> + <li>option</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_progressbar_role" title="en/ARIA/ARIA_Techniques/Using_the_progressbar_role">progressbar</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_radio_role" title="en/ARIA/ARIA_Techniques/Using_the_radio_role">radio</a></li> + <li>scrollbar</li> + <li>searchbox</li> + <li>separator (when focusable)</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_slider_role" title="en/ARIA/ARIA_Techniques/Using_the_slider_role">slider</a></li> + <li>spinbutton</li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Switch_role">switch</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Tab_Role">tab</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Tabpanel_Role">tabpanel</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_textbox_role" title="en/ARIA/ARIA_Techniques/Using_the_textbox_role">textbox</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Treeitem_Role">treeitem</a></li> +</ul> +</div> + +<h3 id="Composite_roles">Composite roles</h3> + +<p>The techniques below describe each composite role as well as their required and optional child roles.</p> + +<div class="index"> +<ul> + <li>combobox</li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Grid_Role">grid</a> (including <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Row_Role">row</a>, <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Gridcell_Role">gridcell</a>, rowheader, columnheader roles)</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_listbox_role" title="en/ARIA/ARIA_Techniques/Using_the_listbox_role">listbox</a> (including option role)</li> + <li>menu</li> + <li>menubar</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_radio_role" title="en/ARIA/ARIA_Techniques/Using_the_radio_role">radiogroup (see radio role)</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Tablist_Role">tablist</a> (including <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Tab_Role">tab</a> and <a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Tabpanel_Role">tabpanel</a> roles)</li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Tree_Role">tree</a></li> + <li>treegrid</li> +</ul> +</div> + +<h3 id="Document_structure_roles">Document structure roles</h3> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Application_Role">application</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Article_Role" title="en/Accessibility/ARIA/ARIA_Techniques/Using_the_article_role">article</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Cell_Role">cell</a></li> + <li>columnheader</li> + <li>definition</li> + <li>directory</li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Document_Role">document</a></li> + <li>feed</li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Figure_Role">figure</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_group_role" title="en/ARIA/ARIA_Techniques/Using_the_group_role">group</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/heading_role">heading</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Role_Img">img</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/List_role">list</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Listitem_role">listitem</a></li> + <li>math</li> + <li>none</li> + <li>note</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_presentation_role" title="en/ARIA/ARIA_Techniques/Using_the_presentation_role">presentation</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Row_Role">row</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Rowgroup_Role">rowgroup</a></li> + <li>rowheader</li> + <li>separator</li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Table_Role">table</a></li> + <li>term</li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/textbox_role">textbox</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_toolbar_role" title="en/ARIA/ARIA_Techniques/Using_the_toolbar_role">toolbar</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Tooltip_Role">tooltip</a></li> +</ul> +</div> + +<h3 id="Landmark_roles">Landmark roles</h3> + +<div class="index"> +<ul> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_banner_role" title="en/ARIA/ARIA_Techniques/Using_the_banner_role">banner</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Complementary_role">complementary</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Contentinfo_role">contentinfo</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Form_Role">form</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Main_role">main</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Navigation_Role">navigation</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Region_role">region</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Search_role">search</a></li> +</ul> +</div> + +<h3 id="Live_Region_Roles">Live Region Roles</h3> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/Alert_Role">alert</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_log_role" title="Using the Log role">log</a></li> + <li>marquee</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_status_role" title="Using the link role">status</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/ARIA_timer_role">timer</a></li> +</ul> +</div> + +<h3 id="Window_Roles">Window Roles</h3> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_alertdialog_role">alertdialog</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Roles/dialog_role">dialog</a></li> +</ul> +</div> + +<h2 id="States_and_properties">States and properties</h2> + +<h3 id="Widget_attributes">Widget attributes</h3> + +<div class="index"> +<ul> + <li>aria-autocomplete</li> + <li>aria-checked</li> + <li>aria-current</li> + <li>aria-disabled</li> + <li>aria-errormessage</li> + <li>aria-expanded</li> + <li>aria-haspopup</li> + <li>aria-hidden</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-invalid_attribute" title="Using the aria-invalid attribute">aria-invalid</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute" title="Using the aria-labelledby attribute">aria-label</a></li> + <li>aria-level</li> + <li>aria-modal</li> + <li>aria-multiline</li> + <li>aria-multiselectable</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-orientation_attribute" title="en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-orientation_attribute">aria-orientation</a></li> + <li>aria-placeholder</li> + <li>aria-pressed</li> + <li>aria-readonly</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-required_attribute" title="Using the aria-required property">aria-required</a></li> + <li>aria-selected</li> + <li>aria-sort</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-valuemax_attribute" title="Using the aria-required attribute">aria-valuemax</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-valuemin_attribute" title="en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-valuemin_attribute">aria-valuemin</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-valuenow_attribute" title="en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-valuenow_attribute">aria-valuenow</a></li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-valuetext_attribute" title="en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-valuetext_attribute">aria-valuetext</a></li> +</ul> +</div> + +<h3 id="Live_region_attributes">Live region attributes</h3> + +<div class="index"> +<ul> + <li>aria-live</li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-relevant_attribute" title="en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-relevant_attribute">aria-relevant</a></li> + <li>aria-atomic</li> + <li>aria-busy</li> +</ul> +</div> + +<h3 id="Drag_drop_attributes">Drag & drop attributes</h3> + +<div class="index"> +<ul> + <li>aria-dropeffect</li> + <li>aria-dragged</li> +</ul> +</div> + +<h3 id="Relationship_attributes">Relationship attributes</h3> + +<div class="index"> +<ul> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-activedescendant_attribute" title="Role">aria-activedescendant</a></li> + <li>aria-colcount</li> + <li>aria-colindex</li> + <li>aria-colspan</li> + <li>aria-controls</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-describedby_attribute" title="Using the aria-labelledby attribute">aria-describedby</a></li> + <li><a href="/en-US/docs/Web/Accessibility/ARIA/Annotations#Associating_annotated_elements_with_their_details">aria-details</a></li> + <li>aria-errormessage</li> + <li>aria-flowto</li> + <li><a href="/en/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-labelledby_attribute" title="en/ARIA/ARIA_Techniques/Using_the_aria-labelledby_attribute">aria-labelledby</a></li> + <li>aria-owns</li> + <li>aria-posinset</li> + <li>aria-rowcount</li> + <li>aria-rowindex</li> + <li>aria-rowspan</li> + <li>aria-setsize</li> +</ul> +</div> + +<h3 id="MicrosoftEdge-specific_properties">MicrosoftEdge-specific properties</h3> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Web/API/x-ms-aria-flowfrom">x-ms-aria-flowfrom</a> {{Non-standard_Inline}}</li> +</ul> +</div> diff --git a/files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html b/files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html new file mode 100644 index 0000000000..23374a0329 --- /dev/null +++ b/files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html @@ -0,0 +1,82 @@ +--- +title: Utilizar o role status +slug: Web/Accessibility/ARIA/ARIA_Techniques/Usando_o_role_status +tags: + - ARIA + - Acessibilidade + - RequerConteúdo +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_status_role +--- +<h3 id="Descrição">Descrição</h3> + +<p class="p1">Esta técnica demonstra como usar o <em>role</em> <em><a class="external" href="https://www.w3.org/TR/wai-aria-1.1/#status">status</a>,</em> e descreve ainda o seu impacto em browsers e tecnologia assistiva.</p> + +<p class="p1">O <em>role</em> <em>status </em>é um tipo de <em><a class="external" href="http://www.w3.org/WAI/PF/aria/terms#def_liveregion">live region</a></em> para avisos que não são suficientemente importantes para constarem de um <em><a class="external" href="https://www.w3.org/TR/wai-aria-practices/#alert">alert</a>.</em> Tais avisos são normalmente apresentados como uma barra de estado. Quando o <em>role</em> é adicionado ao elemento, o <em>browser</em> envia um evento de estado para produtos de tecnologia assitiva, que por sua vez podem alertar o utilizador.</p> + +<p class="p1">Informação de <em>status</em> tem de ser fornecida num objeto de <em>status</em>, objeto este que não deve poder ser focado. Se outra parte da página controla o que aparece como <em>status</em>, deve-se utilizar o atributo <a class="external" href="http://www.w3.org/TR/wai-aria/states_and_properties#aria-controls">aria-controls</a> para relacionar essa parte da página com o objeto de <em>status</em>.</p> + +<p class="p1">Produtos de tecnologias assistiva podem reservar determinadas células de uma tela Braille para exibir o <em>status</em>.</p> + +<h3 id="Possível_impacto_em_user_agents_e_tecnologia_assistiva">Possível impacto em <em>user agents</em> e tecnologia assistiva </h3> + +<p class="p1">Quando o <em>role status </em>é adicionado a um elemento, ou quando esse elemento fica visível, o <em>user agent</em> deve:</p> + +<ul class="ul1"> + <li class="li2">Expôr o elemento como tendo um <em>role</em> de <em>status</em> através da API de acessibilidade do sistema operativo. </li> + <li class="li2">Emitir um evento <em>status</em> acessível através da API de acessibilidade do sistema operativo, se possível.</li> +</ul> + +<p class="p1">Produtos de tecnologia assistiva devem captar o evento de estado e notificar o utilizador adequadamente:</p> + +<ul class="ul1"> + <li class="li2">Leitores de ecrã (<em>screen readers</em>) podem implementar uma tecla especial para anunciar o <em>status</em> atual, apresentando assim o conteúdo de uma <em>live region</em> de <em>status</em>. Estes devem ser anunciados apenas quando o utilizador está inativo, a menos que se tenha definido o atributo <em><span class="s1">aria-live=”assertive”</span></em><span class="s1">,</span> caso em que o utilizador pode ser interrompido. </li> + <li class="li2">Ampliadores de ecrã (<em>screen magnifiers</em>) poderão aumentar o tamanho do <em>status</em>.</li> +</ul> + +<div class="note"><strong>Nota:</strong> Opiniões sobre como produtos de tecnologia assistiva lidam com esta técnica podem variar. A informação acima é apenas uma dessas opiniões, pelo que não pode ser considerada normativa.</div> + +<h3 id="Exemplos">Exemplos</h3> + +<h4 id="Exemplo_1_Adicionar_o_role_status_em_HTML">Exemplo 1: Adicionar o <em>role</em> <em>status</em> em HTML</h4> + +<p class="p1">O <em>snippet</em> em baixo mostra como se pode adicionar o <em>role </em>de <em>status</em> diretamente em código HTML. </p> + +<pre class="brush: html notranslate"><p role="status">Your changes were automatically saved.</p> </pre> + +<h4 id="Exemplos_a_Correr">Exemplos a Correr:</h4> + +<ul> +</ul> + +<h3 id="Notas">Notas </h3> + +<h3 id="Atribuos_ARIA_utilizados">Atribuos ARIA utilizados</h3> + +<ul> + <li class="p1"><a class="external" href="https://www.w3.org/TR/wai-aria-1.1/#status">status</a></li> +</ul> + +<h3 id="Técnicas_ARIA_relacionadas">Técnicas ARIA relacionadas </h3> + +<ul> + <li class="p1"><a class="external" href="https://www.w3.org/TR/wai-aria-practices/#alert">o <em>role alert</em></a></li> + <li class="p1"><a href="https://www.w3.org/TR/wai-aria-1.1/#live_region_roles"><em>Roles </em>de <em>Live Region</em></a></li> + <li class="p1"><a href="https://www.w3.org/TR/wai-aria-1.1/#attrs_liveregions">Atributos de <em>Live Region</em></a></li> +</ul> + +<h3 id="Compatibilidade">Compatibilidade</h3> + +<ul> + <li class="comment"> + <p>The Paciello Group publicou dados sobre da compatibilidade deste <em>role</em> num artigo de 2014: <em><a href="https://developer.paciellogroup.com/blog/2014/03/screen-reader-support-aria-live-regions/">Screen reader support for ARIA live regions</a></em></p> + </li> + <li class="comment"> + <p>A determinar: Adicionar informação atualizada sobre combinações comuns de produtos de tecnologia assistiva com<em>user agents</em></p> + </li> +</ul> + +<h3 id="Mais_recursos">Mais recursos</h3> + +<ul> + <li class="p1">Recomendações anteriores da <a href="https://www.w3.org/TR/wai-aria-1.1/#status">WAI-ARIA 1.0 (2014)</a> para o <em>role</em> <em>status</em></li> +</ul> diff --git a/files/pt-pt/web/acessibilidade/aria/index.html b/files/pt-pt/web/acessibilidade/aria/index.html new file mode 100644 index 0000000000..d49bc53276 --- /dev/null +++ b/files/pt-pt/web/acessibilidade/aria/index.html @@ -0,0 +1,122 @@ +--- +title: ARIA +slug: Web/Acessibilidade/ARIA +tags: + - ARIA + - Acessibilidade + - Web +translation_of: Web/Accessibility/ARIA +--- +<p><span class="seoSummary"><em>Accessible Rich Internet Applications</em> <strong>(ARIA)</strong> </span> define as maneiras para tornar o conteúdo da Web e aplicações da Web (especialmente aqueles desenvolvidos com Ajax e JavaScript) mais acessíveis para as pessoas com deficiência. Por exemplo, ARIA permite marcos de navegação acessíveis, widgets de JavaScript, dicas de formulário e mensagens de erro, atualizações de conteúdo <em>live</em> e muito mais.</p> + +<p>ARIA é um conjunto de atributos de acessibilidade especiais que podem ser adicionados a qualquer marcação, mas é especialmente adequado para HTML. . O atributo <code>role</code> define que tipo geral de objeto é (tais como um artigo, alerta, ou cursor). Os atributos ARIA adicionais fornecem outras propriedades úteis, tais como uma descrição para um formulário ou o valor atual de uma barra de progresso.</p> + +<p>ARIA é implementado na maioria dos navegadores populares e leitores de ecrã. No entanto, as implementações variam e as tecnologias mais antigas não o suportam bem (se for o caso). Utilize ARIA 'seguro' que se degrada graciosamente, ou peça aos utilizadores que atualizem para a nova tecnologia.</p> + +<div class="note"> +<p><strong>Nota</strong>: por favor, contribua e melhore ARIA para a próxima pessoa! Não tem tempo? Envie as sugestões para a <a href="https://lists.mozilla.org/listinfo/accessibility">lista de endereços de acessibilidade da </a> Mozilla, ou canal <a href="https://wiki.mozilla.org/IRC">IRC</a> #accessibility.</p> +</div> + +<div class="row topicpage-table"> +<div class="section"> +<h3 id="Iniciação_com_ARIA">Iniciação com ARIA</h3> + +<dl> + <dt><a href="/en-US/docs/Accessibility/An_overview_of_accessible_web_applications_and_widgets">Introduction to ARIA</a></dt> + <dd>A quick introduction to making dynamic content accessible with ARIA. See also the classic <a class="external" href="http://dev.opera.com/articles/view/introduction-to-wai-aria/">ARIA intro by Gez Lemon</a>, from 2008.</dd> + <dt><a href="/en-US/docs/Accessibility/ARIA/Web_applications_and_ARIA_FAQ">Web Applications and ARIA FAQ</a></dt> + <dd>Answers common questions about WAI-ARIA and why it's needed to make web applications accessible.</dd> + <dt><a class="external" href="http://zomigi.com/blog/videos-of-screen-readers-using-aria-updated/">Videos of Screen Readers Using ARIA</a></dt> + <dd>See both real and simplified examples from around the web, including "before" and "after" ARIA videos.</dd> + <dt><a class="external" href="https://w3c.github.io/using-aria/">Using ARIA</a></dt> + <dd>A practical guide for developers. It suggests what ARIA attributes to use on HTML elements. Suggestions are based on implementation realities.</dd> +</dl> + +<h3 id="Melhoramentos_ARIA_Simples">Melhoramentos ARIA Simples</h3> + +<dl> + <dt><a class="external" href="https://www.paciellogroup.com/blog/2013/02/using-wai-aria-landmarks-2013/">Enhancing Page Navigation with ARIA Landmarks</a></dt> + <dd>A nice intro to using ARIA landmarks to improve web page navigation for screen reader users. <a class="external" href="http://www.paciellogroup.com/blog/2011/07/html5-accessibility-chops-aria-landmark-support/">See also, ARIA landmark implementation notes</a> and examples on real sites (updated as of July 2011).</dd> + <dt><a href="/en-US/docs/ARIA/forms">Improving Form Accessibility</a></dt> + <dd>ARIA is not just for dynamic content! Learn how to improve accessibility of HTML forms using additional ARIA attributes.</dd> + <dt><a href="/en-US/docs/Accessibility/ARIA/ARIA_Live_Regions" title="Live Regions">Live regions (work-in-progress)</a></dt> + <dd>Live regions provide suggestions to screen readers about how to handle changes to the contents of a page.</dd> + <dt><a class="external" href="http://www.freedomscientific.com/Training/Surfs-up/AriaLiveRegions.htm">Using ARIA Live Regions to Announce Content Changes</a></dt> + <dd>A quick summary of live regions, by the makers of JAWS screen reader software. Live regions are also supported by NVDA with Firefox, and VoiceOver with Safari.</dd> +</dl> + +<h3 id="ARIA_para_Widgets_Scripted">ARIA para <em>Widgets Scripted</em></h3> + +<dl> + <dt><a class="external" href="/en-US/docs/Accessibility/Keyboard-navigable_JavaScript_widgets">Keyboard Navigation and Focus for JavaScript Widgets</a></dt> + <dd>The first step in developing an accessible JavaScript widget is to make it keyboard navigable. This article steps through the process. The <a class="external" href="http://www.yuiblog.com/blog/2009/02/23/managing-focus/">Yahoo! focus management article</a> is a great resource as well.</dd> + <dt><a class="external" href="http://access.aol.com/dhtml-style-guide-working-group/">Style Guide for Keyboard Navigation</a></dt> + <dd>A challenge with ARIA is getting developers to implement consistent behavior — clearly best for users. This style guide describes the keyboard interface for common widgets.</dd> +</dl> + +<h3 id="ARIA_-_Recursos">ARIA - Recursos</h3> + +<dl> + <dd>Need a slider, a menu, or another kind of widget? Find resources here.</dd> + <dt><a class="external" href="http://www.paciellogroup.com/blog/2009/07/wai-aria-implementation-in-javascript-ui-libraries/" title="http://www.paciellogroup.com/blog/2009/07/wai-aria-implementation-in-javascript-ui-libraries/">ARIA-Enabled JavaScript UI Libraries</a></dt> + <dd>If you're starting a new project, choose a UI widget library with ARIA support already built-in. Warning: this is from 2009 — content should be moved to an MDN page where it can be updated.</dd> +</dl> +</div> + +<div class="section"> +<h3 id="Lista_de_Endereços">Lista de Endereços</h3> + +<dl> + <dt><a class="link-https" href="https://groups.google.com/forum/#!forum/free-aria">Free ARIA Google Group</a></dt> + <dd>A place to ask questions about ARIA, as well as make suggestions for improving the ARIA documentation found on these pages.</dd> +</dl> + +<h3 id="Blogues">Blogues</h3> + +<p>ARIA information on blogs tends to get out of date quickly. Still, there is some great info out there from other developers making ARIA work today.</p> + +<p><a class="external" href="https://www.paciellogroup.com/blog/">Paciello Group</a></p> + +<p><a class="external" href="http://www.accessibleculture.org/tag/wai-aria/">Accessible Culture</a></p> + +<h3 id="Comunicar_Erros_(Bugs)">Comunicar Erros (<em>Bugs</em>)</h3> + +<p><a href="/en/Accessibility/ARIA/How_to_file_ARIA-related_bugs" title="https://developer.mozilla.org/en/ARIA/How_to_file_ARIA-related_bugs">File ARIA bugs on browsers, screen readers, and JavaScript libraries.</a></p> + +<h3 id="Exemplos">Exemplos</h3> + +<dl> + <dt><a class="external" href="/en-US/docs/Accessibility/ARIA/ARIA_Test_Cases">ARIA Examples Library</a></dt> + <dd>A set of barebones example files which are easy to learn from.</dd> + <dt>Accessible JS Widget Library Demos</dt> + <dd><a class="external" href="http://hanshillen.github.com/jqtest/">jQuery</a>, <a class="external" href="http://yuilibrary.com/gallery/">YUI</a></dd> + <dt><a class="external" href="http://mail.yahoo.com">Yahoo! Mail</a></dt> + <dd>Yahoo! puts it all together with Yahoo! Mail, a web app that almost looks like a native app. It works very well. As a <a class="external" href="http://www.marcozehe.de/2011/09/21/review-the-all-new-yahoo-mail-web-application/">review of Yahoo! Mail</a> by screen reader Marco Zehe says, "Keep up the good work!".</dd> + <dt><a class="external" href="http://search.yahoo.com">Yahoo! Search</a></dt> + <dd>Yahoo! has done an amazing job of advancing ARIA here, by exercising ARIA's full capabilities and <a class="external" href="http://ycorpblog.com/2011/03/23/searchdirect/">sharing their techniques</a>. Yahoo! Search uses a combination of ARIA landmarks, live regions, and widgets.</dd> +</dl> + +<h3 id="Esforços_de_Uniformização">Esforços de Uniformização</h3> + +<dl> + <dt><a class="external" href="http://www.w3.org/WAI/intro/aria.php">WAI-ARIA Activities Overview at W3C</a></dt> + <dd>Authoritative Overview of WAI-ARIA Standardization efforts by the Web Accessibility Initiative (WAI)</dd> + <dt><a class="external" href="https://www.w3.org/TR/wai-aria-1.1/">WAI-ARIA Specification</a></dt> + <dd>The W3C specification itself, useful as a reference. Note that, at this stage, it is important to test compatibility, as implementations are still inconsistent.</dd> + <dt><a class="external" href="https://www.w3.org/TR/wai-aria-practices-1.1/">WAI-ARIA Authoring Practices</a></dt> + <dd> + <p>Like the W3C WAI-ARIA specification, the official best practices represents a future ideal — a day when authors can rely on consistent ARIA support across browsers and screen readers. The W3C documents provide an in-depth view of ARIA.</p> + + <p>For now, web developers implementing ARIA should maximize compatibility. Use best practices docs and examples based on current implementations.</p> + </dd> + <dt><a class="external" href="http://www.openajax.org/member/wiki/Accessibility">Open AJAX Accessibility Task Force</a></dt> + <dd>The Open AJAX effort centers around developing tools, sample files, and automated tests for ARIA.</dd> + <dt><a href="/en-US/docs/Accessibility/ARIA/ARIA_Techniques" title="ARIA Techniques">Under Construction: WCAG 2.0 ARIA Techniques</a></dt> + <dd>The community needs a complete set of WCAG techniques for WAI-ARIA + HTML, so that organizations can be comfortable claiming their ARIA-enabled content is WCAG compliant. This is important when regulations or policies are based on WCAG.</dd> +</dl> +</div> +</div> + +<h3 id="Related_Topics" name="Related_Topics">Tópicos Relacionados</h3> + +<p><a href="/pt-PT/docs/Web/Acessibilidade">Acessibilidade</a>, <a href="/pt-PT/docs/Web/Guide/AJAX">AJAX</a>, <a href="/pt-PT/docs/Web/JavaScript">JavaScript</a></p> diff --git a/files/pt-pt/web/acessibilidade/index.html b/files/pt-pt/web/acessibilidade/index.html new file mode 100644 index 0000000000..0bf23a4fc9 --- /dev/null +++ b/files/pt-pt/web/acessibilidade/index.html @@ -0,0 +1,71 @@ +--- +title: Acessibilidade +slug: Web/Acessibilidade +tags: + - Acessibilidade +translation_of: Web/Accessibility +--- +<p>A acessibilidade no desenvolvimento da <em>Web</em> significa habilitar o maior número possível de pessoas para usar sites da <em>Web</em>, mesmo quando as habilidades dessas pessoas são limitadas de alguma forma. Aqui, fornecemos informações sobre o desenvolvimento de conteúdo para serem acessíveis<span class="seoSummary">.</span></p> + +<p>" A acessibilidade é mais usada para descrever instalações ou amenidades para ajudar as pessoas com deficiência, como em 'acessível para cadeiras de rodas'. Isso pode se estender a sinalização de Braille, rampas para cadeiras de rodas, sinais de áudio em passagens para pedestres, contornos de passarelas, design de sites, e assim por diante ." <a class="external" href="https://pt.wikipedia.org/wiki/Acessibilidade">Entrada da Wikipédia para 'Acessibilidade'</a></p> + +<p>"<strong>A Web é fundamentalmente projetada para trabalhar para todas as pessoas</strong>, seja qual for seu hardware, software, idioma, cultura, localização ou habilidade física ou mental. Quando a Web atende esse objetivo, é acessível para pessoas com uma diversidade de audiência, movimento, visão e capacidade cognitiva ." <a href="http://www.w3.org/standards/webdesign/accessibility" title="http://www.w3.org/standards/webdesign/accessibility">W3C - Acessibilidade </a>(inglês)</p> + +<div class="cleared topicpage-table"> +<div class="section"> +<h2 class="Key_accessibility_tutorials" id="Key_accessibility_tutorials" name="Key_accessibility_tutorials">Key tutorials</h2> + +<p>The MDN <a href="/en-US/docs/Learn/Accessibility">Accessibility Learning Area</a> contains modern, up-to-date tutorials covering accessibility essentials:</p> + +<dl> + <dt><a href="/en-US/docs/Learn/Accessibility/What_is_accessibility">What is accessibility?</a></dt> + <dd>This article starts off the module with a good look at what accessibility actually is — this includes what groups of people we need to consider and why, what tools different people use to interact with the Web, and how we can make accessibility part of our web development workflow.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/HTML">HTML: A good basis for accessibility</a></dt> + <dd>A great deal of web content can be made accessible just by making sure the correct HTML elements are used for the correct purpose at all times. This article looks in detail at how HTML can be used to ensure maximum accessibility.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/CSS_and_JavaScript">CSS and JavaScript accessibility best practices</a></dt> + <dd>CSS and JavaScript, when used properly, also have the potential to allow for accessible web experiences ... or they can significantly harm accessibility if misused. This article outlines some CSS and JavaScript best practices that should be considered to ensure even complex content is as accessible as possible.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/WAI-ARIA_basics">WAI-ARIA basics</a></dt> + <dd>Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/Multimedia">Accessible multimedia</a></dt> + <dd>Another category of content that can create accessibility problems is multimedia — video, audio, and image content need to be given proper textual alternatives so they can be understood by assistive technologies and their users. This article shows how.</dd> + <dt><a href="/en-US/docs/Learn/Accessibility/Mobile">Mobile accessibility</a></dt> + <dd>With web access on mobile devices being so popular, and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Other_documentation" id="Other_documentation" name="Other_documentation">Other documentation</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Accessibility/Understanding_WCAG">Understanding the Web Content Accessibility Guidelines</a></dt> + <dd> + <p>This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 (WCAG 2.0 or just WCAG, for the purposes of this writing).</p> + </dd> + <dt><a href="/en/Accessibility/Keyboard-navigable_JavaScript_widgets" title="en/Accessibility/Keyboard-navigable JavaScript widgets">Keyboard-navigable JavaScript widgets</a></dt> + <dd>Until now, web developers who want to make their styled <div> and <span> based widgets have lacked the proper techniques. <strong>Keyboard accessibility</strong> is part of the minimum accessibility requirements which a developer should be aware of.</dd> + <dt><a href="/en-US/docs/Accessibility/ARIA" title="/en-US/docs/Accessibility/ARIA">ARIA</a></dt> + <dd>A collection of articles to learn how to use ARIA to make your HTML documents more accessible.</dd> + <dt><a href="/en-US/docs/Accessibility/AT_Development" title="AT Development">Assistive technology (AT) development</a></dt> + <dd>A collection of articles intended for AT developers</dd> + <dt><a href="/en-US/docs/Web/Accessibility/Mobile_accessibility_checklist">Mobile accessibility checklist</a></dt> + <dd>This document provides a concise checklist of accessibility requirements for mobile app developers.</dd> + <dt><a href="/en-US/docs/Web/Accessibility/Cognitive_accessibility">Cognitive accessibility</a></dt> + <dd>When creating web content, be aware of how you can ensure that it is accessible to people cognitive impairments.</dd> + <dt><a href="/en-US/docs/Web/Accessibility/Seizure_disorders">Accessibility for seizure disorders</a></dt> + <dd>Some types of visual web content can induce seizures in people with certain brain disorders. Understand the types of content that can be problematic, and find tools and strategies to help you avoid them.</dd> + <dt></dt> +</dl> + +<p><span class="alllinks"><a href="/en-US/docs/tag/Accessibility" title="/en-US/docs/tag/Accessibility">View all articles about Accessibility...</a></span></p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://lists.mozilla.org/listinfo/accessibility">Mozilla mailing list about accessibility</a></li> + <li><a href="http://www.w3.org/WAI/IG/">WAI Interest Group</a></li> + <li><a href="https://mozillians.org/en-US/group/1-accessibility">Mozillians group about accessibility</a></li> + <li><a href="/en-US/docs/Web/Guide" title="REDIRECT Web">Developer guides</a></li> + <li><a href="/en-US/docs/Mozilla/Accessibility" title="Accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. Mozilla strives to make its software accessible; the documents below cover the ways in which we do so.">Accessibility and Mozilla</a></li> +</ul> +</div> diff --git a/files/pt-pt/web/api/animation/index.html b/files/pt-pt/web/api/animation/index.html new file mode 100644 index 0000000000..3921533613 --- /dev/null +++ b/files/pt-pt/web/api/animation/index.html @@ -0,0 +1,142 @@ +--- +title: Animation +slug: Web/API/Animation +tags: + - API + - Animations + - Animações da Web + - Experimental + - Interface + - Referencia + - api de animações da web + - waapi +translation_of: Web/API/Animation +--- +<div>{{ APIRef("Web Animations") }}{{SeeCompatTable}}</div> + +<p>The <strong><code>Animation</code></strong> interface of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> represents a single animation player and provides playback controls and a timeline for an animation node or source.</p> + +<h2 id="Construtor">Construtor</h2> + +<dl> + <dt>{{domxref("Animation.Animation()", "Animation()")}}</dt> + <dd>Creates a new <code>Animation</code> object instance.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{domxref("Animation.currentTime")}}</dt> + <dd>The current time value of the animation in milliseconds, whether running or paused. If the animation lacks a {{domxref("AnimationTimeline", "timeline")}}, is inactive or hasn't been played yet, its value is <code>null</code>.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.effect")}}</dt> + <dd>Gets and sets the {{domxref("AnimationEffectReadOnly")}} associated with this animation. This will usually be a {{domxref("KeyframeEffect")}} object.</dd> + <dt>{{domxref("Animation.finished")}} {{readOnlyInline}}</dt> + <dd>Returns the current finished Promise for this animation.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.id")}}</dt> + <dd>Gets and sets the <code>String</code> used to identify the animation.</dd> + <dt>{{domxref("Animation.pending")}} {{readonlyinline}}</dt> + <dd>Indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.</dd> + <dt>{{domxref("Animation.playState")}} {{readOnlyInline}}</dt> + <dd>Returns an enumerated value describing the playback state of an animation.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.playbackRate")}}</dt> + <dd>Gets or sets the playback rate of the animation.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.ready")}} {{readOnlyInline}}</dt> + <dd>Returns the current ready Promise for this animation.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.startTime")}}</dt> + <dd>Gets or sets the scheduled time when an animation's playback should begin.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.timeline")}}</dt> + <dd>Gets or sets the {{domxref("AnimationTimeline", "timeline")}} associated with this animation.</dd> +</dl> + +<h3 id="Manipuladores_de_evento">Manipuladores de evento</h3> + +<dl> + <dt>{{domxref("Animation.oncancel")}}</dt> + <dd>Gets and sets the event handler for the <code>cancel</code> event.</dd> + <dt>{{domxref("Animation.onfinish")}}</dt> + <dd>Gets and sets the event handler for the <code>finish</code> event.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("Animation.cancel()")}}</dt> + <dd>Clears all {{domxref("KeyframeEffect", "keyframeEffects")}} caused by this animation and aborts its playback.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.finish()")}}</dt> + <dd>Seeks either end of an animation, depending on whether the animation is playing or reversing.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.pause()")}}</dt> + <dd>Suspends playing of an animation.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.play()")}}</dt> + <dd>Starts or resumes playing of an animation, or begins the animation again if it previously finished.</dd> +</dl> + +<dl> + <dt>{{domxref("Animation.reverse()")}}</dt> + <dd>Reverses playback direction, stopping at the start of the animation. If the animation is finished or unplayed, it will play from end to beginning.</dd> + <dt>{{domxref("Animation.updatePlaybackRate()")}}</dt> + <dd>Sets the speed of an animation after first synchronizing its playback position.</dd> +</dl> + +<h2 id="Preocupações_de_acessibilidade">Preocupações de acessibilidade</h2> + +<p>Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine and Scotopic sensitivity.</p> + +<p>Consider providing a mechanism for pausing or disabling animation, as well as using the <a href="/en-US/docs/Web/CSS/@media/prefers-reduced-motion">Reduced Motion Media Query</a> to create a complimentary experience for users who have expressed a preference for no animated experiences.</p> + +<ul> + <li><a href="https://alistapart.com/article/designing-safer-web-animation-for-motion-sensitivity">Designing Safer Web Animation For Motion Sensitivity · An A List Apart Article </a></li> + <li><a href="https://css-tricks.com/introduction-reduced-motion-media-query/">An Introduction to the Reduced Motion Media Query | CSS-Tricks</a></li> + <li><a href="https://webkit.org/blog/7551/responsive-design-for-motion/">Responsive Design for Motion | WebKit</a></li> + <li><a href="/en-US/docs/Web/Accessibility/Understanding_WCAG/Operable#Guideline_2.2_%E2%80%94_Enough_Time_Provide_users_enough_time_to_read_and_use_content">MDN Understanding WCAG, Guideline 2.2 explanations</a></li> + <li><a href="https://www.w3.org/TR/UNDERSTANDING-WCAG20/time-limits-pause.html">Understanding Success Criterion 2.2.2 | W3C Understanding WCAG 2.0</a></li> +</ul> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName("Web Animations", "#the-animation-interface", "Animation")}}</td> + <td>{{Spec2("Web Animations")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("api.Animation")}}</p> diff --git a/files/pt-pt/web/api/api_armazenamento/index.html b/files/pt-pt/web/api/api_armazenamento/index.html new file mode 100644 index 0000000000..434cee963d --- /dev/null +++ b/files/pt-pt/web/api/api_armazenamento/index.html @@ -0,0 +1,128 @@ +--- +title: API de armazenamento +slug: Web/API/API_armazenamento +tags: + - API + - API de armazenamento + - Armazenamento + - Contextod e segurança + - Quotas + - Referencia + - Resumo + - Sinopse + - Utilização +translation_of: Web/API/Storage_API +--- +<p>{{securecontext_header}}{{DefaultAPISidebar("Storage")}}</p> + +<p>The Storage Standard defines a common, shared storage system to be used by all APIs and technologies that store content-accessible data for individual Web sites. The Storage API gives sites' code the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the {{Glossary("user agent")}} disposes of site data in order to make room for other things.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>Site storage—the data stored for a Web site which is managed by the Storage Standard—includes:</p> + +<ul> + <li><a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB databases</a></li> + <li><a href="/en-US/docs/Web/API/Cache">Cache API data</a></li> + <li><a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker registrations</a></li> + <li><a href="/en-US/docs/Web/API/Web_Storage_API">Web Storage API data</a> managed using {{domxref("window.localStorage")}}</li> + <li>History state information saved using {{domxref("History.pushState()")}}</li> + <li><a href="/pt-PT/docs/Web/HTML/Utilizar_a_cache_de_aplicacao">Caches de aplicação</a></li> + <li><a href="/en-US/docs/Web/API/Notifications_API">Notification data</a></li> + <li>Other kinds of site-accessible, site-specific data that may be maintained</li> +</ul> + +<h2 id="Unidades_de_armazenamento_de_site">Unidades de armazenamento de site</h2> + +<p>The site storage system described by the Storage Standard and interacted with using the Storage API consists of a single <strong>site storage unit</strong> for each {{Glossary("origin")}}. In essence, every Web site or Web application has its own storage unit into which its data gets placed. The diagram below shows a site storage pool with three storage units within, showing how storage units can have different data types stored within and may have different quotas (maximum storage limits).</p> + +<p><img alt="A diagram showing how the site storage pool consists of multiple storage units that contain data from various APIs as well as possible unused space left before the quota is reached." src="https://mdn.mozillademos.org/files/14379/StorageUnits.png" style="height: 412px; width: 600px;"></p> + +<ul> + <li>Origin 1 has some Web Storage data as well as some IndexedDB data, but also has some free space left; its current usage hasn't yet reached its quota.</li> + <li>Origin 2 has no data stored in it yet; it's just an empty box waiting for content. This origin, however, has a lower quota than the other two do. It may be a less-visited site, or one known to have lower data storage requirements.</li> + <li>Origin 3's storage unit is completely full; it's reached its quota and can't store any more data without some existing material being removed.</li> +</ul> + +<p>{{Glossary("User agent", "User agents")}} are likely to use various techniques to determine the quota for various origins. One of the most likely methods—one which the specification specifically encourages, in fact—would be to consider the popularity and/or usage levels of individual sites to determine what their quotas should be. It's also conceivable that the browser might offer a user interface to customize these quotas.</p> + +<h2 id="Modos_de_caixa_(Box)">Modos de caixa (Box)</h2> + +<p>The actual data storage within each site storage unit is called its <strong>box</strong>. Each site storage unit has exactly one box into which all of its data is placed, and has a <strong>box mode</strong> that describes the data retention policy for that box. There are two modes:</p> + +<dl> + <dt><code>"best-effort"</code></dt> + <dd>The user agent will try to retain the data contained in the box for as long as it can, <em>but will not warn users</em> if storage space runs low and it becomes necessary to clear the box in order to relieve the storage pressure.</dd> + <dt><code>"persistent"</code></dt> + <dd>The user agent will retain the data as long as possible, clearing all <code>"best-effort"</code> boxes before considering clearing a box marked <code>"persistent"</code>. If it becomes necessary to consider clearing persistent boxes, the user agent will notify the user and provide a way to clear one or more persistent boxes as needed.</dd> +</dl> + +<p>To change an origin's box mode requires permission to use the <code>"persistent-storage"</code> feature.</p> + +<h2 id="Persistência_de_dados_e_limpeza">Persistência de dados e limpeza</h2> + +<p>If the site or app has the <strong><code>"persistent-storage"</code></strong> feature permission, it can use the {{domxref("StorageManager.persist()")}} method to request that its box be made persistent. It's also possible for the user agent to decide to make the site's storage unit persistent due to usage characteristics or other metrics. The <code>"persistent-storage"</code> feature's permission-related flags, algorithms, and types are all set to the standard defaults for a permission, except that the <strong>permission state</strong> must be the same across the entire origin, and that if the permission state isn't <code>"granted"</code> (meaning that for whatever reason, access to the persistent storage feature was denied), the origin's site storage unit's box mode is always <code>"best-effort"</code>.</p> + +<div class="note"> +<p><strong>Nota</strong>: Consulte <a href="/en-US/docs/Web/API/Permissions_API/Using_the_Permissions_API">Using the Permissions API</a> para mais detalhes sobre como obter e gerir as permissões.</p> +</div> + +<p>When clearing site storage units, an origin's box is treated as a single entity; if the user agent needs to clear it and the user approves, the entire data store is cleared rather than providing some means of clearing only data from individual APIs.</p> + +<p>If a box is marked as <code>"persistent"</code>, the contents won't be cleared by the user agent without either the data's origin itself or the user specifically doing so. This includes scenarios such as the user selecting a "Clear Caches" or "Clear Recent History" option. The user will be asked specifically for permission to remove persistent site storage units.</p> + +<h2 id="Quotas_e_estimativas_de_utilização">Quotas e estimativas de utilização</h2> + +<p>The user agent determines, using whatever mechanism it chooses, the maximum amount of storage a given site can use. This maximum is the origin's <strong>quota</strong>. The amount of this space which is in use by the site is called its <strong>usage</strong>. Both of these values are estimates; there are several reasons why they're not precise:</p> + +<ul> + <li>User agents are encouraged to obscure the exact size of the data used by a given origin, to prevent these values from being used for fingerprinting purposes.</li> + <li>De-duplication, compression, and other methods to reduce the physical size of the stored data may be used.</li> + <li>Quotas are conservative estimates of the space available for the origin's use, and should be less than the available space on the device to help prevent overruns.</li> +</ul> + +<p>User agents may use any method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space.</p> + +<p>To determine the estimated quota and usage values for a given origin, use the {{domxref("StorageManager.estimate", "navigator.storage.estimate()")}} method, which returns a promise that, when resolved, receives a {{domxref("StorageEstimate")}} that contains these figures. For example:</p> + +<pre class="brush: js">navigator.storage.estimate().then(estimate => { + // estimate.quota is the estimated quota + // estimate.usage is the estimated number of bytes used +});</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('Storage')}}</td> + <td>{{Spec2('Storage')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div> +<h3 id="StorageManager"><code>StorageManager</code></h3> + +<div> + + +<p>{{Compat("api.StorageManager")}}</p> +</div> +</div> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li>{{domxref("NavigatorStorage.storage", "navigator.storage")}}</li> + <li>{{domxref("StorageManager")}} (the object returned by <code>navigator.storage</code>)</li> + <li><a href="/en-US/docs/Web/API/Permissions_API/Using_the_Permissions_API">Using the Permissions API</a></li> +</ul> diff --git a/files/pt-pt/web/api/api_autenticacao_web/index.html b/files/pt-pt/web/api/api_autenticacao_web/index.html new file mode 100644 index 0000000000..ecc97dd5c0 --- /dev/null +++ b/files/pt-pt/web/api/api_autenticacao_web/index.html @@ -0,0 +1,149 @@ +--- +title: APi de Autenticação da Web +slug: Web/API/API_Autenticacao_Web +tags: + - API + - API de Autenticação da Web + - Landing + - Referencia +translation_of: Web/API/Web_Authentication_API +--- +<div>{{draft}}{{SeeCompatTable}}{{securecontext_header}}{{DefaultAPISidebar("Web Authentication API")}}</div> + +<p class="summary">A "API de Autenticação da Web" é uma extensão de <a href="/en-US/docs/Web/API/Credential_Management_API">Credential Management API</a> que permite uma autenticação forte com a criptografia de chave pública, permitindo a autenticação sem palavra-passe e/ou autenticação de segundo fator segura sem textos de SMS.</p> + +<h2 id="Conceitos_e_utilização_da_autenticação_da_Web">Conceitos e utilização da autenticação da Web</h2> + +<p>The Web Authtentication API (also referred to as WebAuthn) uses <a href="https://en.wikipedia.org/wiki/Public-key_cryptography">asymmetric (public-key) cryptography</a> instead of passwords or SMS texts for registering, authenticating, and <a href="https://en.wikipedia.org/wiki/Multi-factor_authentication">second-factor authentication</a> with websites. This resolves significant security problems related to <a href="https://en.wikipedia.org/wiki/Phishing">phishing</a>, <a href="https://en.wikipedia.org/wiki/Data_breach">data breaches</a>, and attacks against SMS texts or other second-factor authentication methods while at the same time significantly increasing ease of use (since users don't have to manage dozens of increasingly complicated passwords).</p> + +<p>Many websites already have pages that allow users to register new accounts or sign in to an existing account, and WebAuthn acts as a replacement or suppliment to those on those existing webpages. Similar to the other forms of the <a href="/en-US/docs/Web/API/Credential_Management_API">Credential Management API</a>, the Web Authentication API has two basic methods that correspond to register and login:</p> + +<ul> + <li><a href="/en-US/docs/Web/API/CredentialsContainer/create">navigator.credentials.create()</a> - when used with the publicKey option, creates new credentials, either for registering a new account or for associating a new asymmetric key pair credentials with an existing account.</li> + <li><a href="/en-US/docs/Web/API/CredentialsContainer/get">navigator.credentials.get()</a> - when used with the publicKey option, uses an existing set of credentials to authenticate to a service, either logging a user in or as a form of second-factor authentication.</li> +</ul> + +<p><strong>Por favor, note:</strong> both create() and get() require a <a href="/en-US/docs/Web/Security/Secure_Contexts">Secure Context</a> (e.g. - the server is connected by https or is the localhost), and will not be available for use if the browser is not operating in a secure context.</p> + +<p>In their most basic forms, both create() and get() receive a very large random number called a challenge from the server and they return the challenge signed by the private key back to the server. This proves to the server that a user is in possession of the private key required for authentication without revealing any secrets over the network.</p> + +<p>In order to understand how the create() and get() methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser:</p> + +<ol> + <li><strong>Servidor</strong> - the WebAuthn API is intended to register new credentials on a server (also referred to as a service or a <a href="https://en.wikipedia.org/wiki/Relying_party">relying party</a>) and later use those same credentials on that same server to authenticate a user.</li> + <li><strong>Autenticador</strong> - the credentials are created and stored in a device called an authenticator. This is a new concept in authentication: when authenticating using passwords, the password is stored in a user's brain and no other device is needed; when authenticating using WebAuthn, the password is replaced with a key pair that is stored in an authenticator. The authenticator may be embedded into an operating system, such as Windows Hello, or may be a physical token, such as a USB or Bluetooth Security Key.</li> +</ol> + +<h3 id="Registo">Registo</h3> + +<p>A typical registration process has six steps, as illustrated in Figure 1 and described further below. This is a simplification of the data required for the registration process that is only intended to provide an overview. The full set of required fields, optional fields, and their meanings for creating a registration request can be found in the {{domxref("PublicKeyCredentialCreationOptions")}} dictionary. Likewise, the full set of response fields can be found in the {{domxref("PublicKeyCredential")}} interface (where {{domxref("PublicKeyCredential.response")}} is the {{domxref("AuthenticatorAttestationResponse")}} interface). Note most JavaScript programmers that are creating an application will only really care about steps 1 and 5 where the create() function is called and subsequently returns; however, steps 2, 3, and 4 are essential to understanding the processing that takes place in the browser and authenticator and what the resulting data means.</p> + +<p><img alt="WebAuthn registration component and dataflow diagram" src="https://mdn.mozillademos.org/files/15801/MDN%20Webauthn%20Registration%20(r3).png" style="height: 546px; width: 1118px;"></p> + +<p><em>Figura 1 - a diagram showing the sequence of actions for a WebAuthn registration and the essential data associated with each action.</em></p> + +<p>Os passos de registo são:</p> + +<ol start="0"> + <li><strong>Registo de Pedidos da Aplicação</strong> - The application makes the initial registration request. The protocol and format of this request is outside of the scope of WebAuthn.</li> + <li><strong>Servidor Envia Desafio, Informação do Utilziador, e Envio de Informação de Confiança </strong>- The server sends a challenge, user information, and relying party information to the JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be <a href="/en-US/docs/Glossary/REST">REST</a> over https (probably using <a href="/en-US/docs/User:maybe/webidl_mdn/XMLHttpRequest_API">XMLHttpRequest</a> or <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a>), but they could also be <a href="/en-US/docs/Glossary/SOAP">SOAP</a>, <a href="https://tools.ietf.org/html/rfc2549">RFC 2549</a> or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the <a href="/en-US/docs/Web/API/CredentialsContainer/create">create()</a> call, typically with little or no modification and returns a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> that will resolve to a {{domxref("PublicKeyCredential")}} containing an {{domxref("AuthenticatorAttestationResponse")}}. <strong>Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the registration process.</strong></li> + <li><strong>Navegador Chama o authenticatorMakeCredential() no Autenticador</strong> - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).</li> + <li><strong>Autenticador Cria Novo Par de Chave e Certificação </strong>- Before doing anything, the authenticator will typically ask for some form of user verficiation. This could be entering a PIN, using a fingerprint, doing an iris scan, etc. to prove that the user is present and consenting of the registration. After the user verification, the authenticator will create a new asymmetric key pair and safely store the private key for future reference. The public key will become part of the attestation, which the authtenticator will sign over with a private key that was burned into the authenticator during its manufacturing process and that has a certificate chain that can be validated back to a root of trust.</li> + <li><strong>Autenticador Devolve os Dados para o Navegador </strong>- The new public key, a globally unique credential id, and other attestation data are returned to the browser where they become the attestationObject.</li> + <li><strong>Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor</strong> - The create() Promise resolves to an {{domxref("PublicKeyCredential")}}, which has a {{domxref("PublicKeyCredential.rawId")}} that is the globally unique credential id along with a response that is the {{domxref("AuthenticatorAttestationResponse")}} containing the {{domxref("AuthenticatorResponse.clientDataJSON")}} and {{domxref("AuthenticatorAttestationResponse.attestationObject")}}. The {{domxref("PublicKeyCredential")}} is sent back to the server using any desired formatting and protocol (note that the ArrayBuffer properties need to be be base64 encoded or similar).</li> + <li><strong>Servidor Valida e Finaliza o Registo</strong> - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. These include: + <ol> + <li>Verifying that the challenge is the same as the challenge that was sent</li> + <li>Ensuring that the origin was the origin expected</li> + <li>Validating that the signature over the clientDataHash and the attestation using the certificate chain for that specific model of authenticator</li> + </ol> + A complete list of validation steps <a href="https://w3c.github.io/webauthn/#registering-a-new-credential">can be found in the WebAuthn specification</a>. Assuming that the checks pan out, the server will store the new public key associated with the user's account for future use -- that is, whenever the user desires to use the public key for authentication.</li> +</ol> + +<h3 id="Autenticação">Autenticação</h3> + +<p>After a user has registered with WebAuthn, they can subsequently authenticate (a.k.a. - login or sign-in) with the service. The authentication flow looks similar to the registration flow, and the illustration of actions in Figure 2 may be recognizable as being similar to the illustration of registration actions in Figure 1. The primary differences between registration and authentication are that: 1) authentication doesn't require user or relying party information; and 2) authentication creates an assertion using the previously generated key pair for the service rather than creating an attestation with the key pair that was burned into the authenticator during manufacturing. Again, the discription of authentication below is a broad overview rather than getting into all the options and features of WebAuthn. The specific options for authenticating can be found in the {{domxref("PublicKeyCredentialRequestOptions")}} dictionary, and the resulting data can be found in the {{domxref("PublicKeyCredential")}} interface (where {{domxref("PublicKeyCredential.response")}} is the {{domxref("AuthenticatorAssertionResponse")}} interface) .</p> + +<p><img alt="WebAuthn authentication component and dataflow diagram" src="https://mdn.mozillademos.org/files/15802/MDN%20Webauthn%20Authentication%20(r1).png" style="height: 527px; width: 1067px;"></p> + +<p><em>Figure 2 - similar to Figure 1, a diagram showing the sequence of actions for a WebAuthn authentication and the essential data associated with each action.</em></p> + +<ol start="0"> + <li><strong>Auyenticação dos Pedidos da Aplicação</strong> - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of WebAuthn.</li> + <li><strong>Servidor Envia Desafio </strong>- The server sends a challenge JavaScript program. The protocol for communicating with the server is not specified and is outside of the scope of WebAuthn. Typically, server communications would be <a href="/en-US/docs/Glossary/REST">REST</a> over https (probably using <a href="/en-US/docs/User:maybe/webidl_mdn/XMLHttpRequest_API">XMLHttpRequest</a> or <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a>), but they could also be <a href="/en-US/docs/Glossary/SOAP">SOAP</a>, <a href="https://tools.ietf.org/html/rfc2549">RFC 2549</a> or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the <a href="/en-US/docs/Web/API/CredentialsContainer/get">get()</a> call, typically with little or no modification. <strong>Note that it is absolutely critical that the challenge be a large buffer of random information (e.g. - more than 100 bytes) and it MUST be generated on the server in order to ensure the security of the authentication process.</strong></li> + <li><strong>Navegador Chama o authenticatorGetCredential() no Autenticador</strong> - Internally, the browser will validate the parameters and fill in any defaults, which become the {{domxref("AuthenticatorResponse.clientDataJSON")}}. One of the most important parameters is the origin, which recorded as part of the clientData so that the origin can be verified by the server later. The parameters to the create() call are passed to the authenticator, along with a SHA-256 hash of the clientDataJSON (only a hash is sent because the link to the authenticator may be a low-bandwidth NFC or Bluetooth link and the authenticator is just going to sign over the hash to ensure that it isn't tampered with).</li> + <li><strong>Autenticador Cria uma Certificação </strong> - The authenticator finds a credential for this service that matches the Relying Party ID and prompts a user to consent to the authentication. Assuming both of those steps are successful, the authenticator will create a new assertion by signing over the clientDataHash and authenticatorData with the private key generated for this account during the registration call.</li> + <li><strong>Autenticador Devolve os Dados para o Navegador</strong> - The authenticator returns the authenticatorData and assertion signature back to the browser.</li> + <li><strong>Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor </strong>- The browser resolves the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> to a {{domxref("PublicKeyCredential")}} with a {{domxref("PublicKeyCredential.response")}} that contains the {{domxref("AuthenticatorAssertionResponse")}}. It is up to the JavaScript application to transmit this data back to the server using any protocol and format of its choice.</li> + <li><strong>Servidor Valida e Finaliza a Autenticação </strong>- Upon receiving the result of the authentication request, the server performs validation of the response such as: + <ol> + <li>Using the public key that was stored during the registration request to validate the signature by the authenticator.</li> + <li>Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.</li> + <li>Checking that the Relying Party ID is the one expected for this service.</li> + </ol> + A full list of the <a href="https://w3c.github.io/webauthn/#verifying-assertion">steps for validating an assertion can be found in the WebAuthn specification</a>. Assuming the validation is successful, the server will note that the user is now authenticated. This is outside the scope of the WebAuthn specification, but one option would be to drop a new cookie for the user session.</li> +</ol> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("CredentialsContainer")}}</dt> + <dd>WebAuthn extends the <a href="/en-US/docs/Web/API/Credential_Management_API">Credential Management API</a>'s <a href="/en-US/docs/Web/API/CredentialsContainer/create">create()</a> and <a href="/en-US/docs/Web/API/CredentialsContainer/get">get()</a> methods to take a new option: publicKey. When the publicKey option is passed to create() and / or get(), the Credential Management API will create a new public key pair or get an authentication for a key pair, respectively.</dd> + <dt>{{domxref("PublicKeyCredential")}}</dt> + <dd>A credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.</dd> + <dt>{{domxref("AuthenticatorResponse")}}</dt> + <dd>Part of the PublicKeyCredential, the AuthenticatorResponse includes information from the browser (such as the challenge and origin); as well as information from the authenticator such as an AuthenticatorAttestationResponse (for new credentials) or an AuthenticatorAssertionResponse (when authenticating with existing credentials).</dd> + <dt>{{domxref("AuthenticatorAttestationResponse")}}</dt> + <dd>When a PublicKeyCredential has been created with the <a href="/en-US/docs/Web/API/CredentialsContainer/create">create()</a> call, it will include an AuthenticatorAttestationResponse. This is the authenticator's way of providing a cryptographic root of trust for the new key pair that has been generated.</dd> + <dt>{{domxref("AuthenticatorAssertionResponse")}}</dt> + <dd>When a PublicKeyCredential is the result of a <a href="/en-US/docs/Web/API/CredentialsContainer/get">get()</a> call, it will include an AuthenticatorAssertionResponse. This is the authenticator's way of proving to a service that it has the key pair and that the authentication request is valid and approved.</dd> +</dl> + +<h2 id="Opções">Opções</h2> + +<dl> + <dt>{{domxref("PublicKeyCredentialCreationOptions")}}</dt> + <dd>The options for creating a credential via <a href="/en-US/docs/Web/API/CredentialsContainer/create">navigator.credentials.create() </a></dd> + <dt>{{domxref("PublicKeyCredentialRequestOptions")}}</dt> + <dd>The options for using a credential via <a href="/en-US/docs/Web/API/CredentialsContainer/get">navigator.credentials.get() </a></dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<ul> + <li><a class="external" href="https://webauthn.bin.coffee/">Mozilla Demo</a> website and it's <a href="https://github.com/jcjones/webauthn.bin.coffee">source code</a>.</li> + <li><a class="external" href="http://webauthndemo.appspot.com/">Google Demo</a> website and it's <a href="https://github.com/google/webauthndemo">source code</a>.</li> +</ul> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('WebAuthn')}}</td> + <td>{{Spec2('WebAuthn')}}</td> + <td>Definção inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_do_Navegador">Compatibilidade do Navegador</h2> + +<div> +<div> + + +<p>{{Compat("api.PublicKeyCredential")}}</p> +</div> +</div> + +<h2 id="Consulte_também">Consulte também:</h2> + +<ul> + <li><a href="https://www.youtube.com/watch?v=UNI_Ad-9gX8">WebAuthentication and WebPayment demo</a> num dispositivo Android</li> +</ul> diff --git a/files/pt-pt/web/api/api_de_armazenamento_da_web/index.html b/files/pt-pt/web/api/api_de_armazenamento_da_web/index.html new file mode 100644 index 0000000000..192a51ee66 --- /dev/null +++ b/files/pt-pt/web/api/api_de_armazenamento_da_web/index.html @@ -0,0 +1,156 @@ +--- +title: API de Armazenamento da Web +slug: Web/API/API_de_Armazenamento_da_Web +tags: + - API + - Armazenamento + - Armazenamento Local + - Armazenamento da Sessão + - Armazenamento da Web + - Referencia +translation_of: Web/API/Web_Storage_API +--- +<p>{{DefaultAPISidebar("Web Storage API")}}</p> + +<p>A <strong>API de Armazenamento da Web</strong> fornece mecanismos pelos quais os navegadores podem armazenar pares chave/valor, de uma maneira muito mais intuitiva do que utilizar cookies.</p> + +<h2 id="Armazenamento_da_Web_-_conceitos_e_utilização">Armazenamento da Web - conceitos e utilização</h2> + +<p>The two mechanisms within Web Storage are as follows:</p> + +<ul> + <li><code>sessionStorage</code> maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores)</li> + <li><code>localStorage</code> does the same thing, but persists even when the browser is closed and reopened.</li> +</ul> + +<p>These mechanisms are available via the {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} properties (to be more precise, in supporting browsers the <code>Window</code> object implements the <code>WindowLocalStorage</code> and <code>WindowSessionStorage</code> objects, which the <code>localStorage</code> and <code>sessionStorage</code> properties hang off) — invoking one of these will create an instance of the {{domxref("Storage")}} object, through which data items can be set, retrieved and removed. A different Storage object is used for the <code>sessionStorage</code> and <code>localStorage</code> for each origin — they function and are controlled separately.</p> + +<div class="note"> +<p><strong>Nota</strong>: From Firefox 45 onwards, when the browser crashes/restarts, the amount of data saved per origin is limited to 10MB. This has been done to avoid memory issues caused by excessive usage of web storage.</p> +</div> + +<div class="note"> +<p><strong>Nota</strong>: Access to Web Storage from third-party IFrames is denied if the user has <a href="https://support.mozilla.org/en-US/kb/disable-third-party-cookies">disabled third-party cookies</a> (Firefox implements this behaviour from <a href="/en-US/docs/Mozilla/Firefox/Releases/43">version 43</a> onwards.)</p> +</div> + +<div class="note"> +<p><strong>Nota:</strong> Web Storage is not the same as <a href="/en-US/docs/Storage" title="Storage">mozStorage</a> (Mozilla's XPCOM interfaces to SQLite) or the <a href="/en-US/docs/Session_store_API" title="Session_store_API">Session store API</a> (an <a href="/en-US/docs/XPCOM" title="XPCOM">XPCOM</a> storage utility for use by extensions).</p> +</div> + +<h2 id="Armazenamento_da_Web_-_Interfaces">Armazenamento da Web - Interfaces</h2> + +<dl> + <dt>{{domxref("Storage")}}</dt> + <dd>Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)</dd> + <dt>{{domxref("Window")}}</dt> + <dd>The Web Storage API extends the {{domxref("Window")}} object with two new properties — {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} — which provide access to the current domain's session and local {{domxref("Storage")}} objects respectively, and a {{domxref("Window.onstorage")}} event handler that fires when a storage area changes (e.g. a new item is stored.)</dd> + <dt>{{domxref("StorageEvent")}}</dt> + <dd>The <code title="event-storage">storage</code> event is fired on a document's <code>Window</code> object when a storage area changes.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>To illustrate some typical web storage usage, we have created a simple example, imaginatively called <a href="https://github.com/mdn/dom-examples/tree/master/web-storage">Web Storage Demo</a>. The <a href="https://mdn.github.io/dom-examples/web-storage/">landing page</a> provides controls that can be used to customize the colour, font and decorative image. When you choose different options, the page is instantly updated; in addition your choices are stored in <code>localStorage</code>, so that when you leave the page then load it again later on your choices are remembered.</p> + +<p>In addition, we have provided an <a href="https://mdn.github.io/dom-examples/web-storage/event.html">event output page</a> — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as the {{domxref("StorageEvent")}} is fired.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Armazenamento local</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>3.5</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + <tr> + <td>Armazenamento da sessão</td> + <td>5</td> + <td>{{CompatVersionUnknown}}</td> + <td>2</td> + <td>8</td> + <td>10.50</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>2.1</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatUnknown }}</td> + <td>8</td> + <td>11</td> + <td>iOS 3.2</td> + </tr> + </tbody> +</table> +</div> + +<p>All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a <a class="external" href="http://dev-test.nemikor.com/web-storage/support-test/" title="http://dev-test.nemikor.com/web-storage/support-test/">detailed rundown of all the storage capacities for various browsers</a>.</p> + +<div class="note"> +<p><strong>Nota: </strong>since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short.</p> +</div> + +<h2 id="Modos_Incógnito_Navegação_Privada">Modos Incógnito / Navegação Privada</h2> + +<p>Most modern browsers support a privacy option called 'Incognito', 'Private Browsing' or something similar that doesn't store data like history and cookies. This is fundamentally incompatible with Web Storage for obvious reasons. As such, browser vendors are experimenting with different scenarios for how to deal with this incompatibility.</p> + +<p>Most browsers have opted for a strategy where storage APIs are still available and seemingly fully functional, with the one big difference that all stored data is wiped after the browser is closed. For these browsers there are still different interpretations of what should be done with existing stored data (from a regular browsing session). Should it be available to read when in Private mode? Then there are some browsers, most notably Safari, that have opted for a solution where storage is available, but is empty and has a quota of 0 bytes assigned, effectively making it impossible to write data to it.</p> + +<p>Developers should be aware of these different implementations and take them into account when developing websites depending on Web Storage APIs. For more information please have a look at <a href="https://blog.whatwg.org/tag/localstorage">this WHATWG blog post</a> that specifically deals with this topic.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Using the Web Storage API</a></li> + <li><a href="https://medium.com/@ramsunvtech/onfocus-html5-storage-apis-b45d92aa424b">HTML5 Storage API By Venkatraman</a></li> +</ul> diff --git a/files/pt-pt/web/api/api_de_canvas/index.html b/files/pt-pt/web/api/api_de_canvas/index.html new file mode 100644 index 0000000000..17971de4ee --- /dev/null +++ b/files/pt-pt/web/api/api_de_canvas/index.html @@ -0,0 +1,247 @@ +--- +title: API de Canvas +slug: Web/API/API_de_canvas +translation_of: Web/API/Canvas_API +--- +<div>{{CanvasSidebar}}</div> + +<p class="summary">Added in <a href="/en-US/docs/HTML/HTML5">HTML5</a>, the <strong>HTML {{HTMLElement("canvas")}} element</strong> can be used to draw graphics via scripting in <a href="/en-US/docs/Web/JavaScript">JavaScript</a>. For example, it can be used to draw graphs, make photo compositions, create animations, or even do real-time video processing or rendering.</p> + +<p>Mozilla applications gained support for <code><canvas></code> starting with Gecko 1.8 (i.e. <a href="/en-US/docs/Mozilla/Firefox/Releases/1.5">Firefox 1.5</a>). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <code><canvas></code> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <code><canvas></code> by including a script from Google's <a href="https://github.com/arv/explorercanvas">Explorer Canvas</a> project. Google Chrome and Opera 9 also support <code><canvas></code>.</p> + +<p>The <code><canvas></code> element is also used by <a href="/en-US/docs/Web/WebGL">WebGL</a> to draw hardware-accelerated 3D graphics on web pages.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<p>This is just a simple code snippet which uses the {{domxref("CanvasRenderingContext2D.fillRect()")}} method.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><canvas id="canvas"></canvas> +</pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext('2d'); + +ctx.fillStyle = 'green'; +ctx.fillRect(10, 10, 100, 100); +</pre> + +<p>Edit the code below and see your changes update live in the canvas:</p> + +<div class="hidden"> +<h6 id="Playable_code">Playable code</h6> + +<pre class="brush: html"><canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> +<div class="playable-buttons"> + <input id="edit" type="button" value="Edit" /> + <input id="reset" type="button" value="Reset" /> +</div> +<textarea id="code" class="playable-code"> +ctx.fillStyle = 'green'; +ctx.fillRect(10, 10, 100, 100);</textarea> +</pre> + +<pre class="brush: js">var canvas = document.getElementById('canvas'); +var ctx = canvas.getContext("2d"); +var textarea = document.getElementById('code'); +var reset = document.getElementById('reset'); +var edit = document.getElementById('edit'); +var code = textarea.value; + +function drawCanvas() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + eval(textarea.value); +} + +reset.addEventListener('click', function() { + textarea.value = code; + drawCanvas(); +}); + +edit.addEventListener('click', function() { + textarea.focus(); +}) + +textarea.addEventListener('input', drawCanvas); +window.addEventListener('load', drawCanvas); +</pre> +</div> + +<p>{{ EmbedLiveSample('Playable_code', 700, 360) }}</p> + +<h2 id="Referência">Referência</h2> + +<div class="index"> +<ul> + <li>{{domxref("HTMLCanvasElement")}}</li> + <li>{{domxref("CanvasRenderingContext2D")}}</li> + <li>{{domxref("CanvasGradient")}}</li> + <li>{{domxref("CanvasImageSource")}}</li> + <li>{{domxref("CanvasPattern")}}</li> + <li>{{domxref("ImageBitmap")}}</li> + <li>{{domxref("ImageData")}}</li> + <li>{{domxref("RenderingContext")}}</li> + <li>{{domxref("TextMetrics")}}</li> + <li>{{domxref("OffscreenCanvas")}}{{experimental_inline}}</li> + <li>{{domxref("Path2D")}} {{experimental_inline}}{{domxref("ImageBitmapRenderingContext")}}{{experimental_inline}}</li> +</ul> +</div> + +<p>The interfaces related to the <code>WebGLRenderingContext</code> are referenced under <a href="/en-US/docs/Web/WebGL" title="/en-US/docs/Web/WebGL">WebGL</a>.</p> + +<p>{{domxref("CanvasCaptureMediaStream")}} is related.</p> + +<h2 id="Guias_e_tutoriais">Guias e tutoriais</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Tutorial">Canvas tutorial</a></dt> + <dd>A comprehensive tutorial covering both the basic usage of <code><canvas></code> and its advanced features.</dd> + <dt><a href="/en-US/Add-ons/Code_snippets/Canvas">Code snippets: Canvas</a></dt> + <dd>Some extension developer-oriented code snippets involving <code><canvas></code>.</dd> + <dt><a href="/en-US/docs/Web/API/Canvas_API/A_basic_ray-caster">Demo: A basic ray-caster</a></dt> + <dd>A demo of ray-tracing animation using canvas.</dd> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas">Drawing DOM objects into a canvas</a></dt> + <dd>How to draw DOM content, such as HTML elements, into a canvas.</dd> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Manipulating_video_using_canvas">Manipulating video using canvas</a></dt> + <dd>Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} to manipulate video data in real time.</dd> +</dl> + +<h2 id="Recursos">Recursos</h2> + +<h3 id="Genérico">Genérico</h3> + +<ul> + <li><a href="http://joshondesign.com/p/books/canvasdeepdive/title.html">HTML5 Canvas Deep Dive</a></li> + <li><a href="http://bucephalus.org/text/CanvasHandbook/CanvasHandbook.html">Canvas Handbook</a></li> +</ul> + +<h3 id="Bibliotecas">Bibliotecas</h3> + +<ul> + <li><a href="http://fabricjs.com">Fabric.js</a> is an open-source canvas library with SVG parsing capabilities.</li> + <li><a href="https://github.com/ericdrowell/KineticJS">Kinetic.js</a> is an open-source canvas library focused on interactivity for desktop and mobile applications.</li> + <li><a href="http://paperjs.org/">Paper.js</a> is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas.</li> + <li><a href="http://origamijs.com/docs/">Origami.js</a> is an open source lightweight canvas library.</li> + <li><a href="http://libcanvas.github.com/">libCanvas</a> is powerful and lightweight canvas framework.</li> + <li><a href="http://processingjs.org">Processing.js</a> is a port of the Processing visualization language.</li> + <li><a href="https://playcanvas.com/">PlayCanvas</a> is an open source game engine.</li> + <li><a href="http://www.pixijs.com/">Pixi.js</a> is an open source game engine.</li> + <li><a href="http://www.liquidx.net/plotkit/">PlotKit</a> is a charting and graphing library.</li> + <li><a class="link-https" href="https://github.com/jeremyckahn/rekapi">Rekapi</a> is an animation key-framing API for Canvas.</li> + <li><a href="http://senchalabs.github.com/philogl/">PhiloGL</a> is a WebGL framework for data visualization, creative coding and game development.</li> + <li><a href="http://thejit.org/">JavaScript InfoVis Toolkit</a> creates interactive 2D Canvas data visualizations for the Web.</li> + <li><a href="http://www.createjs.com/easeljs">EaselJS</a> is a free/open source library to make it easier to use canvas for games and art</li> + <li><a href="http://scrawl.rikweb.org.uk/">Scrawl-canvas</a> is another open-source javascript library for creating and manipulating 2d canvas elements</li> + <li><a href="https://www.patrick-wied.at/static/heatmapjs/">heatmap.js</a> is an open source library to create canvas based heatmaps</li> +</ul> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Epecificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/WebGL_API">WebGL </a> (Biblioteca de Gráficos da Web)</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/api_de_canvas/tutorial/index.html b/files/pt-pt/web/api/api_de_canvas/tutorial/index.html new file mode 100644 index 0000000000..b93457336d --- /dev/null +++ b/files/pt-pt/web/api/api_de_canvas/tutorial/index.html @@ -0,0 +1,60 @@ +--- +title: Tutorial de Canvas +slug: Web/API/API_de_canvas/Tutorial +tags: + - Canvas + - Guía + - HTML + - HTML5 + - Intermediário + - Web + - graficos +translation_of: Web/API/Canvas_API/Tutorial +--- +<div>{{CanvasSidebar}}</div> + +<div><a href="/en-US/docs/HTML/Canvas" title="HTML/Canvas"><img alt="" src="https://mdn.mozillademos.org/files/257/Canvas_tut_examples.jpg" style="float: right; height: 450px; width: 200px;"></a></div> + +<div class="summary"> +<p><a href="/en-US/docs/Web/HTML/Element/canvas" title="HTML/Canvas"><strong><code><canvas></code></strong></a> is an <a href="/en-US/docs/Web/HTML" title="HTML">HTML</a> element which can be used to draw graphics via scripting (usually <a href="/en-US/docs/Glossary/JavaScript" title="JavaScript">JavaScript</a>). This can, for instance, be used to draw graphs, make photo composition or simple (and <a href="/en-US/docs/Web/API/Canvas_API/A_basic_ray-caster" title="A_Basic_RayCaster">not so simple</a>) animations. The images on this page show examples of <a href="/en-US/docs/Web/HTML/Element/canvas" title="HTML/Canvas"><strong><code><canvas></code></strong></a> implementations which will be created in this tutorial.</p> +</div> + +<p><span class="seoSummary">This tutorial describes how to use the <code><canvas></code> element to draw 2D graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with canvas and will provide code snippets that may get you started in building your own content.</span></p> + +<p>First introduced in WebKit by Apple for the OS X Dashboard, <code><canvas></code> has since been implemented in browsers. Today, all major browsers support it.</p> + +<h2 id="Before_you_start" name="Before_you_start">Antes de começar</h2> + +<p>Using the <code><canvas></code> element is not very difficult, but you do need a basic understanding of <a href="/en-US/docs/Web/HTML" title="HTML">HTML</a> and <a href="/en-US/docs/Web/JavaScript" title="JavaScript">JavaScript</a>. The <code><canvas></code> element is not supported in some older browsers, but is supported in recent versions of all major browsers. The default size of the canvas is 300 px × 150 px (width × height). But custom sizes can be defined using the HTML <code>height</code> and <code>width</code> property. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.</p> + +<h2 id="In_this_tutorial" name="In_this_tutorial">Neste tutorial</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage" title="Canvas_tutorial/Basic_usage">Basic usage</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes" title="Canvas_tutorial/Drawing_shapes">Drawing shapes</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Applying_styles_and_colors" title="Canvas_tutorial/Applying_styles_and_colors">Applying styles and colors</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text">Drawing text</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images" title="Canvas_tutorial/Using_images">Using images</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Transformations" title="Canvas_tutorial/Transformations">Transformations</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Compositing" title="Canvas_tutorial/Compositing">Compositing and clipping</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_animations" title="Canvas_tutorial/Basic_animations">Basic animations</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Advanced_animations">Advanced animations</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas">Pixel manipulation</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility">Hit regions and accessibility</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Optimizing_canvas" title="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Optimizing_canvas">Optimizing the canvas</a></li> + <li><a href="/en-US/docs/Web/API/Canvas_API/Tutorial/Finale">Finale</a></li> +</ul> + +<h2 id="See_also" name="See_also">Consulte também:</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Canvas_API" title="HTML/Canvas">Canvas topic page</a></li> + <li><a class="external" href="http://visitmix.com/labs/ai2canvas/" title="http://visitmix.com/labs/ai2canvas/">Adobe Illustrator to Canvas plug-in</a></li> + <li><a class="external" href="http://www.html5canvastutorials.com/" title="http://www.html5canvastutorials.com/">HTML5CanvasTutorials</a></li> +</ul> + +<h2 id="Uma_nota_para_os_colaboradores">Uma nota para os colaboradores</h2> + +<p>Due to an unfortunate technical error that occurred the week of June 17, 2013, we lost the history of this tutorial, including attributions to all past contributors to its content. We apologize for this, and hope you'll forgive this unfortunate mishap.</p> + +<div>{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}</div> diff --git a/files/pt-pt/web/api/api_do_estado_da_bateria/index.html b/files/pt-pt/web/api/api_do_estado_da_bateria/index.html new file mode 100644 index 0000000000..4805a71bc6 --- /dev/null +++ b/files/pt-pt/web/api/api_do_estado_da_bateria/index.html @@ -0,0 +1,169 @@ +--- +title: API do Estado da Bateria +slug: Web/API/API_do_Estado_da_Bateria +tags: + - API + - API de Bateria + - API do Estado da Bateria + - Aplicações + - Apps + - Firefox OS + - Guía + - Movel + - Resumo + - Sinopse +translation_of: Web/API/Battery_Status_API +--- +<div>{{obsolete_header}}</div> + +<div>{{DefaultAPISidebar("Battery API")}}</div> + +<p>A <em>API do Estado da Bateria</em>, mais conhecida como <strong>API de Bateria</strong>, fornece informação sobre o nível de carga da bateria do sistema e permite-lhe que seja notificado por eventos que são enviados quando o nível da bateria ou o estado de carregamento é alterado. Isto pode ser utilizado para ajustar a utilização de recursos da aplicação para reduzir o consumo de bateria quando a bateria estiver fraca ou para guardar as alterações antes que a bateria acabe para evitar a perda de dados.</p> + +<p>The Battery Status API extends {{domxref("window.navigator")}} with a {{domxref("navigator.getBattery()")}} method returning a battery promise, which is resolved in a {{domxref("BatteryManager")}} object providing also some new events you can handle to monitor the battery status.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<p>In this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level and timing. This is done by listening for the {{event("chargingchange")}}, {{event("levelchange")}}, {{event("chargingtimechange")}}, {{event("dischargingtimechange")}} events.</p> + +<pre class="brush: js">navigator.getBattery().then(function(battery) { + function updateAllBatteryInfo(){ + updateChargeInfo(); + updateLevelInfo(); + updateChargingInfo(); + updateDischargingInfo(); + } + updateAllBatteryInfo(); + + battery.addEventListener('chargingchange', function(){ + updateChargeInfo(); + }); + function updateChargeInfo(){ + console.log("Battery charging? " + + (battery.charging ? "Yes" : "No")); + } + + battery.addEventListener('levelchange', function(){ + updateLevelInfo(); + }); + function updateLevelInfo(){ + console.log("Battery level: " + + battery.level * 100 + "%"); + } + + battery.addEventListener('chargingtimechange', function(){ + updateChargingInfo(); + }); + function updateChargingInfo(){ + console.log("Battery charging time: " + + battery.chargingTime + " seconds"); + } + + battery.addEventListener('dischargingtimechange', function(){ + updateDischargingInfo(); + }); + function updateDischargingInfo(){ + console.log("Battery discharging time: " + + battery.dischargingTime + " seconds"); + } + +}); +</pre> + +<p>See also <a class="external" href="http://www.w3.org/TR/battery-status/#examples">the example in the specification</a>.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Battery API")}}</td> + <td>{{Spec2("Battery API")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_do_navegador">Compatibilidade do navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(39.0)}}</td> + <td>{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop("16")}}<sup>[1]</sup><br> + {{CompatGeckoDesktop("43")}}<sup>[3]</sup><br> + {{CompatGeckoDesktop("52")}}<sup>[4]</sup></td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(40.0)}}</td> + <td> + <p>{{CompatGeckoMobile("10")}} {{property_prefix("moz")}}<br> + {{CompatGeckoMobile("16")}}<sup>[1]</sup><br> + {{CompatGeckoMobile("43")}}<sup>[3]</sup><br> + {{CompatGeckoMobile("52")}}<sup>[3]</sup></p> + </td> + <td>{{CompatNo}}</td> + <td>25<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(42.0)}}<sup>[2]</sup></td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Disabled by default in Firefox 10.0, but can be enabled setting the preference <code>dom.battery.enabled</code> to <code>true</code>. Starting with Firefox 11.0, <code>mozBattery</code> is enabled by default. The Battery API is currently supported on Android, Windows, and Linux with UPower installed. Support for MacOS is available starting with Gecko 18.0 {{geckoRelease("18.0")}}. Firefox also provides support for the deprecated {{domxref("navigator.battery")}}.</p> + +<p>[2] Values for {{domxref("BatteryManager.chargingTime")}} and {{domxref("BatteryManager.dischargingTime")}} are always equal to <code>Infinity</code>.</p> + +<p>[3] The new promise-based syntax for {{domxref("Navigator.getBattery()")}} is supported from Firefox 43 onwards.</p> + +<p>[4] From Firefox 52 onwards, the Battery Status API is only available in chrome/privileged code.</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/en-US/Apps/Build/gather_and_modify_data/retrieving_battery_status_information">Retrieving battery status information - demo & article</a></li> + <li><a class="external" href="http://hacks.mozilla.org/2012/02/using-the-battery-api-part-of-webapi/">Hacks blog post - Using the Battery API</a></li> +</ul> diff --git a/files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html b/files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html new file mode 100644 index 0000000000..26e56945ee --- /dev/null +++ b/files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html @@ -0,0 +1,191 @@ +--- +title: API Entradas de Diretoria e Ficheiro +slug: Web/API/API_Entradas_de_Diretoria_e_Ficheiro +tags: + - API + - API Entradas de Diretoria e Ficheiro + - API Sistema de Ficheiros + - Ficheiros + - Não Padrão + - Referencia + - Resuno + - Sinopse +translation_of: Web/API/File_and_Directory_Entries_API +--- +<p>{{DefaultAPISidebar("File System API")}}{{Non-standard_header}}</p> + +<p>API Entradas de Diretoria e Ficheiro simula um sistema de ficheiros local em que as páginas da Web podem navegar dentro e aceder aos ficheiros na mesma. Pode desenvolver aplicações que lêem, escrevem e criam ficheiros e/ou diretorias num sistema de ficheiros virtual e ambiente de testes (sandbox).</p> + +<div class="note"> +<p>Because this is a non-standard API, whose specification is not currently on a standards track, it's important to keep in mind that not all browsers implement it, and those that do may implement only small portions of it. Check the {{anch("Browser compatibility")}} section for details.</p> +</div> + +<p>Two very similar APIs exist depending on whether you desire asynchronous or synchronous behavior. The synchronous API is indended to be used inside a {{domxref("Worker")}} and will return the values you desire. The asynchronous API will not block and functions and the API will not return values; instead, you will need to supply a callback function to handle the response whenever it arrives.</p> + +<div class="warning"> +<p>The Firefox implementation of the File and Directory Entries API is very limited; there is no support for creating files. Only for accessing files which are selected by the user in a file {{HTMLElement("input")}} element (see {{domxref("HTMLInputElement")}} as well) or when a file or directory is provided to the Web site or app using <a href="/en-US/docs/Web/API/HTML_Drag_and_Drop_API">drag and drop</a>. Firefox also does not implement the synchronous API. Check the browser compatibility for any part of the API you use carefully, and see <a href="/en-US/docs/Web/API/File_and_Directory_Entries_API/Firefox_support">File and Directory Entries API support in Firefox</a> for more details.</p> +</div> + +<h2 id="Obter_acesso_a_um_sistema_de_ficheiros">Obter acesso a um sistema de ficheiros</h2> + +<p>There are two ways to get access to file systems defined in the current specification draft:</p> + +<ul> + <li>When handling a {{event("drop")}} event for drag and drop, you can call {{domxref("DataTransferItem.webkitGetAsEntry()")}} to get the {{domxref("FileSystemEntry")}} for a dropped item. If the result isn't <code>null</code>, then it's a dropped file or directory, and you can use file system calls to work with it.</li> + <li>The {{domxref("HTMLInputElement.webkitEntries")}} property lets you access the {{domxref("FileSystemFileEntry")}} objects for the currently selected files, but only if they are dragged-and-dropped onto the file chooser ({{bug(1326031)}}). If {{domxref("HTMLInputElement.webkitdirectory")}} is <code>true</code>, the {{HTMLElement("input")}} element is instead a directory picker, and you get {{domxref("FileSystemDirectoryEntry")}} objects for each selected directory.</li> +</ul> + +<h2 id="API_Assíncrona">API Assíncrona</h2> + +<p>The asynchronous API should be used for most operations, to prevent file system accesses from blocking the entire browser if used on the main thread. It includes the following interfaces:</p> + +<dl> + <dt>{{domxref("FileSystem")}}</dt> + <dd>Represents a file system.</dd> + <dt>{{domxref("FileSystemEntry")}}</dt> + <dd>The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories.</dd> + <dt>{{domxref("FileSystemFileEntry")}}</dt> + <dd>Represents a single file in a file system.</dd> + <dt>{{domxref("FileSystemDirectoryEntry")}}</dt> + <dd>Represents a single directory in a file system.</dd> + <dt>{{domxref("FileSystemDirectoryReader")}}</dt> + <dd>Created by calling {{domxref("FileSystemDirectoryEntry.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.</dd> + <dt>{{domxref("FileSystemFlags")}}</dt> + <dd>Defines a set of values which are used when specifying option flags when calling certain methods in the <a href="https://developer.mozilla.org/en-US/docs/Web/API/File_and_Directory_Entries_API">File and Directory Entries API</a>.</dd> + <dt>{{domxref("FileError")}}</dt> + <dd>Represents an error which is generated by asynchronous file system calls.</dd> +</dl> + +<p>There are also two global functions (which are not part of the specification at this time and are implemented only by Google Chrome). They're available on the {{domxref("Window")}} object and implemented in {{domxref("LocalFileSystem")}}: <code>requestFileSystem()</code> and <code>resolveLocalFileSystemURL()</code>.</p> + +<h2 id="API_Síncrona">API Síncrona</h2> + +<p>The synchronous API is should only be used in {{domxref("Worker")}}s; these calls block until they're finished executing, and simply return the results instead of using callbacks. Using them on the main thread will block the browser, which is naughty. The interfaces below otherwise mirror the ones from the asynchronous API.</p> + +<dl> + <dt>{{domxref("FileSystemSync")}}</dt> + <dd>Represents a file system.</dd> + <dt>{{domxref("FileSystemEntrySync")}}</dt> + <dd>The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories. {{domxref("EntrySync")}}</dd> + <dt>{{domxref("FileSystemFileEntrySync")}}</dt> + <dd>Represents a single file in a file system.</dd> + <dt>{{domxref("FileSystemDirectoryEntrySync")}}</dt> + <dd>Represents a single directory in a file system.</dd> + <dt>{{domxref("FileSystemDirectoryReaderSync")}}</dt> + <dd>Created by calling {{domxref("FileSystemDirectoryEntrySync.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.</dd> + <dt>{{domxref("FileException")}}</dt> + <dd>Represents an error which is generated by synchronous file system calls.</dd> +</dl> + +<p>There are also two global functions (which are not part of the specification at this time and are implemented only by Google Chrome). They're available on the {{domxref("Worker")}} object and implemented in {{domxref("LocalFileSystemSync")}}: <code>requestFileSystemSync()</code> and <code>resolveLocalFileSystemSyncURL()</code>.</p> + +<h2 id="Outras_Interfaces">Outras Interfaces</h2> + +<dl> + <dt>{{domxref("LocalFileSystem")}}</dt> + <dd>Gives you access to a sandboxed file system.</dd> + <dt>{{domxref("LocalFileSystemSync")}}</dt> + <dt> </dt> + <dt>{{domxref("LockedFile")}}</dt> + <dd>Provides tools to deal with a given file with all the necessary locks.</dd> + <dt>{{domxref("Metadata")}}{{experimental_inline}}</dt> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File System API')}}</td> + <td>{{Spec2('File System API')}}</td> + <td>Draft of proposed API</td> + </tr> + </tbody> +</table> + +<p>This API has no official W3C or WHATWG specification.</p> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Asynchronous API</td> + <td>13 {{ property_prefix("webkit") }}</td> + <td>{{ CompatGeckoDesktop(50) }}<sup>[1]</sup></td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + </tr> + <tr> + <td>Synchronous API</td> + <td>13 {{ property_prefix("webkit") }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Asynchronous API</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}</td> + <td>{{ CompatGeckoMobile(50) }}<sup>[1]</sup></td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + </tr> + <tr> + <td>Synchronous API</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Firefox 50 introduces partial support for the File and Directory Entries API. Be sure to check the compatibility tables for individual interfaces and methods before using them, to ensure that they're supported, before you use them. The API can be disabled by setting the value of the preference <code>dom.webkitBlink.filesystem.enabled</code> to <code>false</code>.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction">Introdução às API Entradas de diretoria e Ficheiro </a>(inglês)</li> + <li><a href="/en-US/docs/Web/API/File_and_Directory_Entries_API/Firefox_support">File and Directory Entries API support in Firefox </a>(inglês)</li> +</ul> diff --git a/files/pt-pt/web/api/api_transmissoes_multimedia/index.html b/files/pt-pt/web/api/api_transmissoes_multimedia/index.html new file mode 100644 index 0000000000..399945ab71 --- /dev/null +++ b/files/pt-pt/web/api/api_transmissoes_multimedia/index.html @@ -0,0 +1,211 @@ +--- +title: API de Captura de Transmissões de Multimédia (Media Streams) +slug: Web/API/API_transmissoes_multimedia +tags: + - API + - API de Transmissão de Multimédia + - Audio + - Avançado + - Guía + - Introdução + - Media + - Multimedia + - Video +translation_of: Web/API/Media_Streams_API +--- +<div>{{DefaultAPISidebar("Media Capture and Streams")}}</div> + +<p>A API de <em><strong>Media Capture and Streams</strong></em>, muitas vezes chamada de <em>Media Stream API</em> ou <em>Stream API</em>, é uma API relacionada com <a href="/pt-PT/docs/Web/API/API_WebRTC" title="/en-US/docs/WebRTC">WebRTC</a> que suporta transmissões de dados de áudio ou vídeo, os métodos para trabalhar com eles, as restrições associadas com o tipo de dados, as devoluções de retorno de sucesso e erro quando utilizar os dados de forma assíncrona, e os eventos que foram ativados durante o processo.</p> + +<h2 id="Conceitos_básicos">Conceitos básicos</h2> + +<p>The API is based on the manipulation of a {{domxref("MediaStream")}} object representing a flux of audio- or video-related data. See an example in <a href="/docs/Web/API/API_WebRTC/Tirar_fotografias" title="/en-US/docs/WebRTC/taking_webcam_photos#Get_the_video">Get the video</a>.</p> + +<p>A <code>MediaStream</code> consists of zero or more {{domxref("MediaStreamTrack")}} objects, representing various audio or video <strong>tracks</strong>. Each <code>MediaStreamTrack</code> may have one or more <strong>channels</strong>. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like <em>left</em> or <em>right</em> in a stereo audio track.</p> + +<p><code>MediaStream</code> objects have a single <strong>input</strong> and a single <strong>output</strong>. A <code>MediaStream</code> object generated by {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} is called <em>local</em>, and has as its source input one of the user's cameras or microphones. A non-local <code>MediaStream</code> may be representing to a media element, like {{HTMLElement("video")}} or {{HTMLElement("audio")}}, a stream originating over the network, and obtained via the WebRTC {{domxref("RTCPeerConnection")}} API, or a stream created using the <a href="/en-US/docs/Web_Audio_API" title="/en-US/docs/Web_Audio_API">Web Audio API</a> {{domxref("MediaStreamAudioSourceNode")}}. The output of the <code>MediaStream</code> object is linked to a <strong>consumer</strong>. It can be a media elements, like {{HTMLElement("audio")}} or {{HTMLElement("video")}}, the WebRTC {{domxref("RTCPeerConnection")}} API or a <a href="/en-US/docs/Web_Audio_API" title="/en-US/docs/Web_Audio_API">Web Audio API</a> {{domxref("MediaStreamAudioDestinationNode")}}.</p> + +<h2 id="Referência">Referência</h2> + +<div class="index"> +<ul> + <li>{{event("addtrack")}} (event)</li> + <li>{{domxref("AudioStreamTrack")}}</li> + <li>{{domxref("BlobEvent")}}</li> + <li>{{event("ended")}} (event)</li> + <li>{{domxref("MediaStream")}}</li> + <li>{{domxref("MediaStreamTrack")}}</li> + <li>{{domxref("MediaStreamTrackEvent")}}</li> + <li>{{domxref("MediaTrackCapabilities")}}</li> + <li>{{domxref("MediaTrackConstraints")}}</li> + <li>{{domxref("MediaTrackSettings")}}</li> + <li>{{domxref("MediaTrackSupportedConstraints")}}</li> + <li>{{event("muted")}} (event)</li> + <li>{{domxref("NavigatorUserMedia")}}</li> + <li>{{domxref("NavigatorUserMediaError")}}</li> + <li>{{event("overconstrained")}} (event)</li> + <li>{{event("removetrack")}} (event)</li> + <li>{{event("started")}} (event)</li> + <li>{{event("unmuted")}} (event)</li> + <li>{{domxref("URL")}}</li> + <li>{{domxref("VideoStreamTrack")}}</li> +</ul> +</div> + +<h2 id="Guias_e_tutoriais">Guias e tutoriais</h2> + +<p>{{LandingPageListSubpages}}</p> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{ CompatibilityTable }} </p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera </th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Stream API </td> + <td>21{{ property_prefix("webkit") }} </td> + <td>Nightly 18{{ property_prefix("moz") }} </td> + <td>{{ CompatVersionUnknown }}</td> + <td>{{ CompatUnknown }} </td> + <td>12</td> + <td>{{ CompatUnknown }} </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>API de emissão</td> + <td>{{ CompatNo }} </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatUnknown }}</td> + <td>{{ CompatUnknown }} </td> + <td>{{ CompatNo }} </td> + <td>{{ CompatNo }} </td> + </tr> + </tbody> +</table> +</div> + +<p> </p> + +<p>Currently using WebRTC for accessing the camera is supported in Chrome, Opera and Firefox Nightly 18. Enabling WebRTC in Firefox Nightly requires you to set a flag in the configuration:</p> + +<ul> + <li>Type "about:config" in the address bar and say yes that you want to make changes</li> + <li>Find the "media.navigator.enabled" entry and set it to true</li> +</ul> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/API_WebRTC" title="/en-US/docs/WebRTC">WebRTC</a> - a página introdutória para a API</li> + <li>{{domxref("mediaDevices.getUserMedia()")}}</li> + <li><a href="/pt-PT/docs/Web/API/API_WebRTC/Tirar_fotografias">Tirar fotografias com a câmara da <em>Web</em></a>: tutorial sobre como utilizar <code>getUserMedia()</code>.</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/api_webrtc/index.html b/files/pt-pt/web/api/api_webrtc/index.html new file mode 100644 index 0000000000..8e1b31898b --- /dev/null +++ b/files/pt-pt/web/api/api_webrtc/index.html @@ -0,0 +1,287 @@ +--- +title: API de WebRTC +slug: Web/API/API_WebRTC +tags: + - API + - API de WebRTC + - API de WebRTCÁudio + - Multimedia + - Rede + - Video + - WebRTC + - emissão + - transmissão +translation_of: Web/API/WebRTC_API +--- +<div>{{APIRef("WebRTC")}}</div> + +<p><span class="seoSummary"><strong>WebRTC</strong> (Comunicações da <em>Web</em> em Tempo Real) é uma tecnologia que permite às aplicações e sites da <em>Web</em> capturar e opcionalmente transmitir multimédia de áudio e/ou vídeo, bem como trocar dados arbitrariamente entre navegadores sem a necessidade de um intermediário.</span> O conjunto de normas que compreende WebRTC torna possível a partilha de dados e realizar teleconferência <em>peer-to-peer</em>, sem precisar que o utilizador instale <em>plug-ins</em> ou qualquer outro software de terceiros.</p> + +<p>WebRTC consiste em diversos protocolos e APIs inter-relacionadas que trabalham em conjunto para obter isto. A documentação que irá encontrar aqui irá ajudá-lo a compreender o essencial de WebRTC, como configurar e utilizar ligações de dados e multimédia, e muito mais.</p> + +<h2 id="Conceitos_e_utilização_de_WebRTC">Conceitos e utilização de WebRTC</h2> + +<p>O WebRTC atende múltiplos propósitos e se destaca consideravelmente com <em>Media Capture</em> e <em>Streams API</em>. Juntos, eles fornecem recursos multimídia poderosos para a Web, incluindo suporte para conferências de áudio e vídeo, troca de arquivos, gerenciamento de identidade e interface com sistemas telefônicos legados, enviando sinais {{Glossary("DTMF")}} . As conexões entre pares podem ser feitas sem exigir drivers especiais ou plug-ins, e muitas vezes podem ser feitas sem nenhum servidor intermediário.</p> + +<p>As conexões entre dois pares são criadas usando - e representadas pela interface - {{domxref("RTCPeerConnection")}} . Uma vez que uma conexão foi estabelecida e aberta, os fluxos de mídia ({{domxref("MediaStream")}}s) e / ou canais de dados ({{domxref("RTCDataChannel")}}s) podem ser adicionados à conexão.</p> + +<p>Os fluxos de mídia podem ser constituídos de qualquer número de faixas de informações de mídia; As faixas, que são representadas por objetos com base na interface {{domxref("MediaStreamTrack")}} , podem conter um dos vários tipos de dados de mídia, incluindo áudio, vídeo e texto (como legendas ou nomes de capítulos) . A maioria dos fluxos consistem em pelo menos uma faixa de áudio e provavelmente também uma faixa de vídeo, e pode ser usados para enviar e receber mídia ao vivo ou informações de mídia armazenada (como um filme transmitido).</p> + +<p>Você também pode usar a conexão entre dois pares para trocar dados binários arbitrários usando a interface {{domxref("RTCDataChannel")}} . Isso pode ser usado para informações <em>back-channel</em>, troca de metadados, pacotes com status de jogos, transferências de arquivos ou mesmo como um canal primário para transferência de dados.</p> + +<p><em><strong>Mais detalhes e links para guias relevantes e tutoriais necessários</strong></em></p> + +<h2 id="Interfaces_de_WebRTC">Interfaces de WebRTC</h2> + +<p>Como a WebRTC fornece interfaces que trabalham juntas para realizar uma variedade de tarefas, dividimos as interfaces na lista abaixo por categoria. Veja a barra lateral para uma lista alfabética.</p> + +<h3 id="Gestão_e_configuração_de_ligação">Gestão e configuração de ligação</h3> + +<p>Essas interfaces são usadas para configurar, abrir e gerenciar conexões WebRTC.</p> + +<dl> + <dt>{{domxref("RTCPeerConnection")}}</dt> + <dd>Representa uma conexão WebRTC entre o computador local e um ponto remoto. Ele é usado para lidar com transmissão eficiente de dados entre os dois pares.</dd> + <dt>{{domxref("RTCDataChannel")}}</dt> + <dd>Representa um canal de dados bidirecional entre dois pares de uma conexão.</dd> + <dt>{{domxref("RTCDataChannelEvent")}}</dt> + <dd>Representa eventos que ocorrem ao anexar um {{domxref("RTCDataChannel")}} a um {{domxref("RTCPeerConnection")}} . O único evento enviado com esta interface é {{event("datachannel")}} .</dd> + <dt>{{domxref("RTCSessionDescription")}}</dt> + <dd>Representa os parâmetros de uma sessão. Cada RTCSessionDescription consiste em um tipo de descrição que indica qual parte do processo de negociação de oferta(offer) / resposta(answer) isso descreve e do SDP descritor da sessão.</dd> + <dt>{{domxref("RTCStatsReport")}}</dt> + <dd>Fornece informações detalhando estatísticas para uma conexão ou para uma faixa individual na conexão; O relatório pode ser obtido chamando {{domxref("RTCPeerConnection.getStats()")}} .</dd> + <dt>{{domxref("RTCIceCandidate")}}</dt> + <dd>Representa um servidor candidato que estabelece a conectividade de internet (ICE -internet connectivity establishment) para estabelecer um {{domxref("RTCPeerConnection")}} .</dd> + <dt>{{domxref("RTCIceTransport")}}</dt> + <dd>Representa informações sobre o transporte referentes ao estabelecimento de conectividade de internet (ICE - internet connectivity establishment).</dd> + <dt>{{domxref("RTCPeerConnectionIceEvent")}}</dt> + <dd>Representa eventos que ocorrem em relação aos candidatos ICE com o destino, geralmente um {{domxref("RTCPeerConnection")}} . Apenas um evento é deste tipo: {{event("icecandidate")}} .</dd> + <dt>{{domxref("RTCRtpSender")}}</dt> + <dd>Gerencia a codificação e a transmissão de dados para um {{domxref("MediaStreamTrack")}} em {{domxref("RTCPeerConnection")}}.</dd> + <dt>{{domxref("RTCRtpReceiver")}}</dt> + <dd>Gerencia a recepção e decodificação de dados para um {{domxref("MediaStreamTrack")}} em um {{domxref("RTCPeerConnection")}}.</dd> + <dt>{{domxref("RTCTrackEvent")}}</dt> + <dd>Indica que uma nova entrada {{domxref("MediaStreamTrack")}} foi criada e um objeto associado {{domxref("RTCRtpReceiver")}} foi adicionado ao objeto {{domxref("RTCPeerConnection")}} .</dd> +</dl> + +<h3 id="Identidade_e_segurança">Identidade e segurança</h3> + +<p>A API WebRTC inclui uma série de interfaces para gerenciar segurança e identidade.</p> + +<dl> + <dt>{{domxref("RTCIdentityProvider")}}</dt> + <dd>Permite que um agente do usuário possa solicitar que uma confirmação de identidade seja gerada ou validada.</dd> + <dt>{{domxref("RTCIdentityAssertion")}}</dt> + <dd>Representa a identidade de um ponto remoto da conexão atual. Caso nenhum par (peer) seja configurado e verificado, esta interface retorna <em>null</em>. Uma vez configurado, este não poderá ser alterado.</dd> + <dt>{{domxref("RTCIdentityProviderRegistrar")}}</dt> + <dd>Registra um provedor de identidade (idP).</dd> + <dt>{{domxref("RTCIdentityEvent")}}</dt> + <dd>Representa uma confirmação de identidade gerada por um provedor de identidade (idP). Isso geralmente é para um {{domxref("RTCPeerConnection")}}. O único evento enviado com este tipo é {{event("identityresult")}}.</dd> + <dt>{{domxref("RTCIdentityErrorEvent")}}</dt> + <dd>Representa um erro associado ao provedor de identidade (idP). Isso geralmente é para um {{domxref("RTCPeerConnection")}} . Dois eventos são enviados com este tipo: {{event("idpassertionerror")}} e {{event("idpvalidationerror")}} .</dd> + <dt>{{domxref("RTCCertificate")}}</dt> + <dd>Representa um certificado que um {{domxref("RTCPeerConnection")}} usa para autenticar.</dd> +</dl> + +<h3 id="Telefonia">Telefonia</h3> + +<p>Essas interfaces estão relacionadas à interatividade com redes telefônicas de comutação pública (PTSNs).</p> + +<dl> + <dt>{{domxref("RTCDTMFSender")}}</dt> + <dd>Gerencia a codificação e a transmissão da sinalização multi-frequência de dois tons (DTMF) para um {{domxref("RTCPeerConnection")}}.</dd> + <dt>{{domxref("RTCDTMFToneChangeEvent")}}</dt> + <dd>Indica uma ocorrência de uma multi-frequência de dois tons (DTMF). Este evento não faz bolha (bubble) (exceto quando indicado de outra forma) e não é cancelável (exceto quando indicado de outra forma).</dd> +</dl> + +<h3 id="Outros">Outros</h3> + +<dl> + <dt>{{domxref("RTCIceServer")}}</dt> + <dd>Define como ligar a um único servidor de ICE (tais como um servidor STUN ou TURN).</dd> +</dl> + +<p> </p> + +<h2 id="Guias">Guias</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Protocols">Introduction to WebRTC protocols</a></dt> + <dd>This article introduces the protocols on top of which the WebRTC API is built.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Connectivity">WebRTC connectivity</a></dt> + <dd>A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Session_lifetime">Lifetime of a WebRTC session</a></dt> + <dd>WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Signaling_and_video_calling">Signaling and two-way video calling</a></dt> + <dd>A tutorial and example which turbs a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Using_data_channels">Using WebRTC data channels</a></dt> + <dd>This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Using_DTMF">Using DTMF with WebRTC</a></dt> + <dd>WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the {{domxref("RTCDTMFSender")}} interface. This guide shows how to do so.</dd> +</dl> + +<h2 id="Tutoriais">Tutoriais</h2> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/adapter.js">Improving compatibility using WebRTC adapter.js</a></dt> + <dd>The WebRTC organization <a href="https://github.com/webrtc/adapter/">provides on GitHub the WebRTC adapter</a> to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Taking_still_photos">Taking still photos with WebRTC</a></dt> + <dd>This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.</dd> + <dt><a href="/en-US/docs/Web/API/WebRTC_API/Simple_RTCDataChannel_sample">A simple RTCDataChannel sample</a></dt> + <dd>The {{domxref("RTCDataChannel")}} interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the <a href="/en-US/docs/Web/API/WebSocket_API">WebSocket API</a>, so that the same programming model can be used for each.</dd> +</dl> + +<h2 id="Recursos">Recursos</h2> + +<h3 id="Protocolos">Protocolos</h3> + +<h4 id="WebRTC-proper_protocols">WebRTC-proper protocols</h4> + +<ul> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-alpn/"><cite>Application Layer Protocol Negotiation for Web Real-Time Communications</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-audio/"><cite>WebRTC Audio Codec and Processing Requirements</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-channel/"><cite>RTCWeb Data Channels</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-data-protocol/"><cite>RTCWeb Data Channel Protocol</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-rtp-usage/"><cite>Web Real-Time Communication (WebRTC): Media Transport and Use of RTP</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-security-arch/"><cite>WebRTC Security Architecture</cite></a></li> + <li><a href="http://datatracker.ietf.org/doc/draft-ietf-rtcweb-transports/"><cite>Transports for RTCWEB</cite></a></li> +</ul> + +<h4 id="Related_supporting_protocols">Related supporting protocols</h4> + +<ul> + <li><a href="https://tools.ietf.org/html/rfc5245">Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal for Offer/Answer Protocol</a></li> + <li><a href="https://tools.ietf.org/html/rfc5389"><cite>Session Traversal Utilities for NAT (STUN)</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc7064"><cite>URI Scheme for the Session Traversal Utilities for NAT (STUN) Protocol</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc7065"><cite>Traversal Using Relays around NAT (TURN) Uniform Resource Identifiers</cite></a></li> + <li><a href="https://tools.ietf.org/html/rfc3264"><cite>An Offer/Answer Model with Session Description Protocol (SDP)</cite></a></li> + <li><a href="https://datatracker.ietf.org/doc/draft-ietf-tram-turn-third-party-authz/"><cite>Session Traversal Utilities for NAT (STUN) Extension for Third Party Authorization</cite></a></li> +</ul> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebRTC 1.0')}}</td> + <td>{{Spec2('WebRTC 1.0')}}</td> + <td>A definição inicial da API do WebRTC.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>A definição inicial do objeto que transmite o fluxo de conteúdo de mídia.</td> + </tr> + <tr> + <td>{{SpecName('Media Capture DOM Elements')}}</td> + <td>{{Spec2('Media Capture DOM Elements')}}</td> + <td>A definição inicial sobre como obter fluxo de conteúdo de Elementos DOM</td> + </tr> + </tbody> +</table> + +<p>Em adição a estas especificações que definem a API necessária para usar o WebRTC, existem vários protocolos, listados em <a href="#Protocols">recursos</a>.</p> + +<h2 class="Related_Topics" id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{domxref("MediaDevices")}}</li> + <li>{{domxref("MediaStreamEvent")}}</li> + <li>{{domxref("MediaStreamConstraints")}}</li> + <li>{{domxref("MediaStreamTrack")}}</li> + <li>{{domxref("MessageEvent")}}</li> + <li>{{domxref("MediaStream")}}</li> + <li><a href="https://hacks.mozilla.org/2015/06/firefox-multistream-and-renegotiation-for-jitsi-videobridge/">Firefox multistream and renegotiation for Jitsi Videobridge</a></li> + <li><a href="https://hacks.mozilla.org/2015/04/peering-through-the-webrtc-fog-with-socketpeer/">Peering Through the WebRTC Fog with SocketPeer</a></li> + <li><a href="https://hacks.mozilla.org/2014/04/inside-the-party-bus-building-a-web-app-with-multiple-live-video-streams-interactive-graphics/">Inside the Party Bus: Building a Web App with Multiple Live Video Streams + Interactive Graphics</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html b/files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html new file mode 100644 index 0000000000..203ebfab5b --- /dev/null +++ b/files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html @@ -0,0 +1,222 @@ +--- +title: Tirar fotografias com a câmara da Web +slug: Web/API/API_WebRTC/Tirar_fotografias +tags: + - API + - Avançado + - Código amostra + - Exemplo + - Vídeo(2) + - WebRTC + - cãmara da Web +translation_of: Web/API/WebRTC_API/Taking_still_photos +--- +<p>{{WebRTCSidebar}}</p> + +<p><span class="seoSummary">This article shows how to use WebRTC to access the camera on a computer or mobile phone with WebRTC support and take a photo with it.</span> <a href="https://mdn-samples.mozilla.org/s/webrtc-capturestill">Try this sample</a> then read on to learn how it works.</p> + +<p>You can also jump straight to the <a class="external" href="https://github.com/mdn/samples-server/tree/master/s/webrtc-capturestill" rel="noopener">code on Github</a> if you like.</p> + +<h2 id="The_HTML_markup">The HTML markup</h2> + +<p><a class="external" href="https://github.com/mdn/samples-server/tree/master/s/webrtc-capturestill/index.html" rel="noopener">Our HTML interface</a> has two main operational sections: the stream and capture panel and the presentation panel. Each of these is presented side-by-side in its own {{HTMLElement("div")}} to facilitate styling and control.</p> + +<p>The first panel on the left contains two components: a {{HTMLElement("video")}} element, which will receive the stream from WebRTC, and a {{HTMLElement("button")}} the user clicks to capture a video frame.</p> + +<pre class="brush: html"> <div class="camera"> + <video id="video">Video stream not available.</video> + <button id="startbutton">Take photo</button> + </div></pre> + +<p>This is straightforward, and we'll see how it ties together when we get into the JavaScript code.</p> + +<p>Next, we have a {{HTMLElement("canvas")}} element into which the captured frames are stored, potentially manipulated in some way, and then converted into an output image file. This canvas is kept hidden by styling the canvas with {{cssxref("display")}}<code>:none</code>, to avoid cluttering up the screen — the user does not need to see this intermediate stage.</p> + +<p>We also have an {{HTMLElement("img")}} element into which we will draw the image — this is the final display shown to the user.</p> + +<pre class="brush: html"> <canvas id="canvas"> + </canvas> + <div class="output"> + <img id="photo" alt="The screen capture will appear in this box."> + </div></pre> + +<p>That's all of the relevant HTML. The rest is just some page layout fluff and a bit of text offering a link back to this page.</p> + +<h2 id="O_código_de_JavaScript"><span style="font-size: 30px;">O código de JavaScript</span></h2> + +<p>Now let's take a look at the <a class="external" href="https://github.com/mdn/samples-server/tree/master/s/webrtc-capturestill/capture.js" rel="noopener">JavaScript code</a>. We'll break it up into a few bite-sized pieces to make it easier to explain.</p> + +<h3 id="Initialização">Initialização</h3> + +<p>We start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using.</p> + +<pre class="brush: js">(function() { + var width = 320; // We will scale the photo width to this + var height = 0; // This will be computed based on the input stream + + var streaming = false; + + var video = null; + var canvas = null; + var photo = null; + var startbutton = null;</pre> + +<p>Those variables are:</p> + +<dl> + <dt><code>largura</code></dt> + <dd>Whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide.</dd> + <dt><code>altura</code></dt> + <dd>The output height of the image will be computed given the <code>width</code> and the aspect ratio of the stream.</dd> + <dt><code>transmissão</code></dt> + <dd>Indicates whether or not there is currently an active stream of video running.</dd> + <dt><code>vídeo</code></dt> + <dd>This will be a reference to the {{HTMLElement("video")}} element after the page is done loading.</dd> + <dt><code>canvas</code></dt> + <dd>This will be a reference to the {{HTMLElement("canvas")}} element after the page is done loading.</dd> + <dt><code>foto</code></dt> + <dd>This will be a reference to the {{HTMLElement("img")}} element after the page is done loading.</dd> + <dt><code>startbutton</code></dt> + <dd>This will be a reference to the {{HTMLElement("button")}} element that's used to trigger capture. We'll get that after the page is done loading.</dd> +</dl> + +<h3 id="The_startup()_function">The startup() function</h3> + +<p>The <code>startup()</code> function is run when the page has finished loading, courtesy of {{domxref("window.addEventListener()")}}. This function's job is to request access to the user's webcam, initialize the output {{HTMLElement("img")}} to a default state, and to establish the event listeners needed to receive each frame of video from the camera and react when the button is clicked to capture an image.</p> + +<h4 id="Getting_element_references">Getting element references</h4> + +<p>First, we grab references to the major elements we need to be able to access.</p> + +<pre class="brush: js"> function startup() { + video = document.getElementById('video'); + canvas = document.getElementById('canvas'); + photo = document.getElementById('photo'); + startbutton = document.getElementById('startbutton');</pre> + +<h4 id="Get_the_media_stream">Get the media stream</h4> + +<p>The next task is to get the media stream:</p> + +<pre class="brush: js"> navigator.mediaDevices.getUserMedia({ video: true, audio: false }) + .then(function(stream) { + video.srcObject = stream; + video.play(); + }) + .catch(function(err) { + console.log("An error occured! " + err); + }); +</pre> + +<p>Here, we're calling {{domxref("MediaDevices.getUserMedia()")}} and requesting a video stream (without audio). It returns a promise which we attach success and failure callbacks to.</p> + +<p>The success callback receives a <code>stream</code> object as input. It the {{HTMLElement("video")}} element's source to our new stream.</p> + +<p>Once the stream is linked to the <code><video></code> element, we start it playing by calling <code><a href="/en-US/docs/Web/API/HTMLMediaElement#play">HTMLMediaElement.play()</a></code>.</p> + +<p>The error callback is called if opening the stream doesn't work. This will happen for example if there's no compatible camera connected, or the user denied access.</p> + +<h4 id="Listen_for_the_video_to_start_playing">Listen for the video to start playing</h4> + +<p>After calling <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement#play">HTMLMediaElement.play()</a></code> on the {{HTMLElement("video")}}, there's a (hopefully brief) period of time that elapses before the stream of video begins to flow. To avoid blocking until that happens, we add an event listener to <code>video</code>, <code>canplay</code>, which is delivered when the video playback actually begins. At that point, all the properties in the <code>video</code> object have been configured based on the stream's format.</p> + +<pre class="brush: js"> video.addEventListener('canplay', function(ev){ + if (!streaming) { + height = video.videoHeight / (video.videoWidth/width); + + video.setAttribute('width', width); + video.setAttribute('height', height); + canvas.setAttribute('width', width); + canvas.setAttribute('height', height); + streaming = true; + } + }, false);</pre> + +<p>This callback does nothing unless it's the first time it's been called; this is tested by looking at the value of our <code>streaming</code> variable, which is <code>false</code> the first time this method is run.</p> + +<p>If this is indeed the first run, we set the video's height based on the size difference between the video's actual size, <code>video.videoWidth</code>, and the width at which we're going to render it, <code>width</code>.</p> + +<p>Finally, the <code>width</code> and <code>height</code> of both the video and the canvas are set to match each other by calling {{domxref("Element.setAttribute()")}} on each of the two properties on each element, and setting widths and heights as appropriate. Finally, we set the <code>streaming</code> variable to <code>true</code> to prevent us from inadvertently running this setup code again.</p> + +<h4 id="Handle_clicks_on_the_button">Handle clicks on the button</h4> + +<p>To capture a still photo each time the user clicks the <code>startbutton</code>, we need to add an event listener to the button, to be called when the <code>click</code> event is issued:</p> + +<pre class="brush: js"> startbutton.addEventListener('click', function(ev){ + takepicture(); + ev.preventDefault(); + }, false);</pre> + +<p>This method is simple enough: it just calls our <code>takepicture()</code> function, defined below in the section {{anch("Capturing a frame from the stream")}}, then calls {{domxref("Event.preventDefault()")}} on the received event to prevent the click from being handled more than once.</p> + +<h4 id="Wrapping_up_the_startup()_method">Wrapping up the startup() method</h4> + +<p>There are only two more lines of code in the <code>startup()</code> method:</p> + +<pre class="brush: js"> clearphoto(); + }</pre> + +<p>This is where we call the <code>clearphoto()</code> method we'll describe below in the section {{anch("Clearing the photo box")}}.</p> + +<h3 id="Clearing_the_photo_box">Clearing the photo box</h3> + +<p>Clearing the photo box involves creating an image, then converting it into a format usable by the {{HTMLElement("img")}} element that displays the most recently captured frame. That code looks like this:</p> + +<pre class="brush: js"> function clearphoto() { + var context = canvas.getContext('2d'); + context.fillStyle = "#AAA"; + context.fillRect(0, 0, canvas.width, canvas.height); + + var data = canvas.toDataURL('image/png'); + photo.setAttribute('src', data); + }</pre> + +<p>We start by getting a reference to the hidden {{HTMLElement("canvas")}} element that we use for offscreen rendering. Next we set the <code>fillStyle</code> to <code>#AAA</code> (a fairly light grey), and fill the entire canvas with that color by calling {{domxref("CanvasRenderingContext2D.fillRect()","fillRect()")}}.</p> + +<p>Last in this function, we convert the canvas into a PNG image and call <code>{{domxref("Element.setAttribute", "photo.setAttribute()")}}</code> to make our captured still box display the image.</p> + +<h3 id="Capturing_a_frame_from_the_stream">Capturing a frame from the stream</h3> + +<p>There's one last function to define, and it's the point to the entire exercise: the <code>takepicture()</code> function, whose job it is to capture the currently displayed video frame, convert it into a PNG file, and display it in the captured frame box. The code looks like this:</p> + +<pre class="brush: js"> function takepicture() { + var context = canvas.getContext('2d'); + if (width && height) { + canvas.width = width; + canvas.height = height; + context.drawImage(video, 0, 0, width, height); + + var data = canvas.toDataURL('image/png'); + photo.setAttribute('src', data); + } else { + clearphoto(); + } + }</pre> + +<p>As is the case any time we need to work with the contents of a canvas, we start by getting the {{domxref("CanvasRenderingContext2D","2D drawing context")}} for the hidden canvas.</p> + +<p>Then, if the width and height are both non-zero (meaning that there's at least potentially valid image data), we set the width and height of the canvas to match that of the captured frame, then call {{domxref("CanvasRenderingContext2D.drawImage()", "drawImage()")}} to draw the current frame of the video into the context, filling the entire canvas with the frame image.</p> + +<div class="note"> +<p><strong>Note:</strong> This takes advantage of the fact that the {{domxref("HTMLVideoElement")}} interface looks like a {{domxref("HTMLImageElement")}} to any API that accepts an <code>HTMLImageElement</code> as a parameter, with the video's current frame presented as the image's contents.</p> +</div> + +<p>Once the canvas contains the captured image, we convert it to PNG format by calling {{domxref("HTMLCanvasElement.toDataURL()")}} on it; finally, we call {{domxref("Element.setAttribute", "photo.setAttribute()")}} to make our captured still box display the image.</p> + +<p>If there isn't a valid image available (that is, the <code>width</code> and <code>height</code> are both 0), we clear the contents of the captured frame box by calling <code>clearphoto()</code>.</p> + +<h2 id="Fun_with_filters">Fun with filters</h2> + +<p>Since we're capturing images from the user's webcam by grabbing frames from a {{HTMLElement("video")}} element, we can very easily apply filters and fun effects to the video. As it turns out, any CSS filters you apply to the element using the {{cssxref("filter")}} property affect the captured photo. These filters can range from the simple (making the image black and white) to the extreme (gaussian blurs and hue rotation).</p> + +<p>You can play with this effect using, for example, the Firefox developer tools' <a href="/en-US/docs/Tools/Style_Editor">style editor</a>; see <a href="/en-US/docs/Tools/Page_Inspector/How_to/Edit_CSS_filters">Edit CSS filters</a> for details on how to do so.</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="https://mdn-samples.mozilla.org/s/webrtc-capturestill">Try this sample</a></li> + <li><a href="https://github.com/mdn/samples-server/tree/master/s/webrtc-capturestill">Sample code on Github</a></li> + <li>{{domxref("Navigator.getUserMedia()")}}</li> + <li>{{SectionOnPage("/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images", "Using frames from a video")}}</li> + <li>{{domxref("CanvasRenderingContext2D.drawImage()")}}</li> +</ul> diff --git a/files/pt-pt/web/api/audionode/index.html b/files/pt-pt/web/api/audionode/index.html new file mode 100644 index 0000000000..df63de86c6 --- /dev/null +++ b/files/pt-pt/web/api/audionode/index.html @@ -0,0 +1,207 @@ +--- +title: AudioNode +slug: Web/API/AudioNode +tags: + - API + - AudioNode + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Audio API +translation_of: Web/API/AudioNode +--- +<p>{{ APIRef("Web Audio API") }}</p> + +<p>The <strong><code>AudioNode</code></strong> interface is a generic interface for representing an audio processing module like an audio source (e.g. an HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} element, an {{domxref("OscillatorNode")}}, etc.), the audio destination, intermediate processing module (e.g. a filter like {{domxref("BiquadFilterNode")}} or {{domxref("ConvolverNode")}}), or volume control (like {{domxref("GainNode")}}).</p> + +<p>{{InheritanceDiagram}}</p> + +<p><img alt="AudioNodes participating in an AudioContext create a audio routing graph." src="https://mdn.mozillademos.org/files/9713/WebAudioBasics.png" style="display: block; height: 230px; margin: 0px auto; width: 677px;"></p> + +<p>An <code>AudioNode</code> has inputs and outputs, each with a given amount of <em>channels</em>.<em> </em>An <code>AudioNode</code> with zero inputs and one or multiple outputs is called a <em>source node</em>. The exact processing done varies from one <code>AudioNode</code> to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the {{domxref("AnalyserNode")}}, where the result of the processing is accessed separately).</p> + +<p>Different nodes can be linked together to build a <em>processing graph</em>. Such a graph is contained in an {{domxref("AudioContext")}}. Each <code>AudioNode</code> participates in exactly one such context. In general, processing nodes inherit the properties and methods of <code>AudioNode</code>, but also define their own functionality on top. See the individual node pages for more details, as listed on the <a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a> homepage.</p> + +<div class="note"> +<p><strong>Note</strong>: An <code>AudioNode</code> can be target of events, therefore it implements the {{domxref("EventTarget")}} interface.</p> +</div> + +<h2 id="Properties" style="">Properties</h2> + +<dl> + <dt>{{domxref("AudioNode.context")}} {{readonlyInline}}</dt> + <dd>Returns the associated {{domxref("AudioContext")}}, that is the object representing the processing graph the node is participating in.</dd> +</dl> + +<dl> + <dt>{{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}</dt> + <dd>Returns the number of inputs feeding the node. Source nodes are defined as nodes having a <code>numberOfInputs</code> property with a value of <code>0</code>.</dd> +</dl> + +<dl> + <dt>{{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}</dt> + <dd>Returns the number of outputs coming out of the node. Destination nodes — like {{ domxref("AudioDestinationNode") }} — have a value of <code>0</code> for this attribute.</dd> +</dl> + +<dl> + <dt>{{domxref("AudioNode.channelCount")}}</dt> + <dd>Represents an integer used to determine how many channels are used when <a href="/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#Up-mixing_and_down-mixing">up-mixing and down-mixing</a> connections to any inputs to the node. Its usage and precise definition depend on the value of {{domxref("AudioNode.channelCountMode")}}.</dd> +</dl> + +<dl> + <dt>{{domxref("AudioNode.channelCountMode")}}</dt> + <dd>Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.</dd> + <dt>{{domxref("AudioNode.channelInterpretation")}}</dt> + <dd>Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio <a href="/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#Up-mixing_and_down-mixing">up-mixing and down-mixing</a> will happen.<br> + The possible values are <code>"speakers"</code> or <code>"discrete"</code>.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Also implements methods from the interface </em>{{domxref("EventTarget")}}.</p> + +<dl> + <dt>{{domxref("AudioNode.connect()")}}</dt> + <dd>Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an {{domxref("AudioParam")}}.</dd> + <dt>{{domxref("AudioNode.disconnect()")}}</dt> + <dd>Allows us to disconnect the current node from another one it is already connected to.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<p>This simple snippet of code shows the creation of some audio nodes, and how the <code>AudioNode</code> properties and methods can be used. You can find examples of such usage on any of the examples linked to on the <a href="/en-US/docs/Web/API/Web_Audio_API">Web Audio API</a> landing page (for example <a href="https://github.com/mdn/violent-theremin">Violent Theremin</a>.)<span class="p"> </span></p> + +<pre class="brush: js;highlight[8,9,11,12,13,14]">var AudioContext = window.AudioContext || window.webkitAudioContext; + +var audioCtx = new AudioContext(); + +var oscillator = audioCtx.createOscillator(); +var gainNode = audioCtx.createGain(); + +oscillator.connect(gainNode); +gainNode.connect(audioCtx.destination); + +oscillator.context; +oscillator.numberOfInputs; +oscillator.numberOfOutputs; +oscillator.channelCount;</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Audio API', '#the-audionode-interface', 'AudioNode')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(10.0)}}{{property_prefix("webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(25.0)}}</td> + <td>{{CompatNo}}</td> + <td>15.0{{property_prefix("webkit")}}<br> + 22 (unprefixed)</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>channelCount</code> <code>channelCountMode</code></td> + <td>{{CompatVersionUnknown}} {{property_prefix("webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>connect</code><code>(AudioParam)</code></td> + <td>{{CompatVersionUnknown}} {{property_prefix("webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>25.0</td> + <td>1.2</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>channelCount</code><br> + <code>channelCountMode</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>connect</code><code>(AudioParam)</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> +</ul> diff --git a/files/pt-pt/web/api/blob/blob/index.html b/files/pt-pt/web/api/blob/blob/index.html new file mode 100644 index 0000000000..a00a527076 --- /dev/null +++ b/files/pt-pt/web/api/blob/blob/index.html @@ -0,0 +1,77 @@ +--- +title: Blob() +slug: Web/API/Blob/Blob +tags: + - API + - Blob + - Construtor + - File API + - Referencia +translation_of: Web/API/Blob/Blob +--- +<div>{{APIRef("File API")}}</div> + +<p><span class="seoSummary">O construtor <code>Blob()</code> devolve um novo objeto {{domxref("Blob")}}. O conteúdo do objeto <code>Blob</code> consiste na concatenação dos valores na matriz do primeiro parâmetro.</span></p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <var>novoBlob</var> = new Blob(<var>array</var>, <var>options</var>); +</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code><var>array</var></code></dt> + <dd>Uma {{jsxref("Array")}} de {{jsxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("USVString")}}, {{domxref("USVString")}}, ou uma mistura de quaisquer desses objetos, que serão colocados dentro do objeto {{domxref("Blob")}}. Os objetos <code>USVString</code> são codificados como UTF-8.</dd> + <dt><code><var>options</var></code> {{optional_inline}}</dt> + <dd> + <p>Um objeto opcional do tipo {{domxref("BlobPropertyBag")}} que pode especificar qualquer uma das seguintes propriedades:</p> + + <dl> + <dt><code>type</code> {{optional_inline}}</dt> + <dd>O {{Glossary("MIME type", "tipo MIME")}} dos dados que serão armazenados no <em>blob</em>. O valor predefinido é uma string vazia, (<code>""</code>).</dd> + <dt><code>endings</code> {{optional_inline}} {{non-standard_inline}}</dt> + <dd>Como interpretar os caracteres de nova linha (<code>\n</code>), se os dados são textos. O valor predefinido, <code>transparent</code>, copia os caracteres da nova linha para o <em>blob</em> sem os alterar. Para converter as novas linhas para a convenção nativa do sistema anfitrião, use o valor <code>native</code>.</dd> + </dl> + </dd> +</dl> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>Um novo objeto {{domxref("Blob")}} que contém os dados especificados.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js language-js notranslate">var dadosParaFicheiro = ['<a id="a"><b id="b">hey!</b></a>']; // uma matriz constituída por uma única DOMString +var oMeuBlob = new Blob(dadosParaFicheiro, {type : 'text/html'}); // o <em>blob</em></pre> + +<h2 id="Specification" name="Specification">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File API', '#constructorBlob', 'Blob()')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.Blob.Blob")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>A interface obsoleta {{domxref("BlobBuilder")}} que este construtor substitui.</li> +</ul> diff --git a/files/pt-pt/web/api/blob/index.html b/files/pt-pt/web/api/blob/index.html new file mode 100644 index 0000000000..878bc85e5e --- /dev/null +++ b/files/pt-pt/web/api/blob/index.html @@ -0,0 +1,157 @@ +--- +title: Blob +slug: Web/API/Blob +tags: + - API + - Blob + - File API + - Interface + - NeedsTranslation + - Raw + - Reference + - TopicStub + - data +translation_of: Web/API/Blob +--- +<div>{{APIRef("File API")}}</div> + +<p>The <strong><code>Blob</code></strong> object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a {{DOMxRef("ReadableStream")}} so its methods can be used for processing the data.</p> + +<p>Blobs can represent data that isn't necessarily in a JavaScript-native format. The {{DOMxRef("File")}} interface is based on <code>Blob</code>, inheriting blob functionality and expanding it to support files on the user's system.</p> + +<h2 id="Using_blobs">Using blobs</h2> + +<p>To construct a <code>Blob</code> from other non-blob objects and data, use the {{DOMxRef("Blob.Blob", "Blob()")}} constructor. To create a blob that contains a subset of another blob's data, use the {{DOMxRef("Blob.slice()", "slice()")}} method. To obtain a <code>Blob</code> object for a file on the user's file system, see the {{DOMxRef("File")}} documentation.</p> + +<p>The APIs accepting <code>Blob</code> objects are also listed in the {{DOMxRef("File")}} documentation.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{DOMxRef("Blob.Blob", "Blob()")}}</dt> + <dd>Returns a newly created <code>Blob</code> object which contains a concatenation of all of the data in the array passed into the constructor.</dd> +</dl> + +<h2 id="Instance_properties">Instance properties</h2> + +<dl> + <dt>{{DOMxRef("Blob.prototype.size")}} {{readonlyinline}}</dt> + <dd>The size, in bytes, of the data contained in the <code>Blob</code> object.</dd> + <dt>{{DOMxRef("Blob.prototype.type")}} {{readonlyinline}}</dt> + <dd>A string indicating the MIME type of the data contained in the <code>Blob</code>. If the type is unknown, this string is empty.</dd> +</dl> + +<h2 id="Instance_methods">Instance methods</h2> + +<dl> + <dt>{{DOMxRef("Blob.prototype.arrayBuffer()")}}</dt> + <dd>Returns a promise that resolves with an {{DOMxRef("ArrayBuffer")}} containing the entire contents of the <code>Blob</code> as binary data.</dd> + <dt>{{DOMxRef("Blob.prototype.slice()")}}</dt> + <dd>Returns a new <code>Blob</code> object containing the data in the specified range of bytes of the blob on which it's called.</dd> + <dt>{{DOMxRef("Blob.prototype.stream()")}}</dt> + <dd>Returns a {{DOMxRef("ReadableStream")}} that can be used to read the contents of the <code>Blob</code>.</dd> + <dt>{{DOMxRef("Blob.prototype.text()")}}</dt> + <dd>Returns a promise that resolves with a {{DOMxRef("USVString")}} containing the entire contents of the <code>Blob</code> interpreted as UTF-8 text.</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<h3 id="Creating_a_blob">Creating a blob</h3> + +<p>The {{DOMxRef("Blob.Blob", "Blob()")}} constructor can create blobs from other objects. For example, to construct a blob from a JSON string:</p> + +<pre class="brush: js notranslate">const obj = {hello: 'world'}; +const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});</pre> + +<h3 id="Creating_a_URL_representing_the_contents_of_a_typed_array">Creating a URL representing the contents of a typed array</h3> + +<p>The following code creates a JavaScript <a href="/en-US/docs/Web/JavaScript/Typed_arrays">typed array</a> and creates a new <code>Blob</code> containing the typed array's data. It then calls {{DOMxRef("URL.createObjectURL()")}} to convert the blob into a {{glossary("URL")}}.</p> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html notranslate"><p>This example creates a typed array containing the ASCII codes + for the space character through the letter Z, then converts it + to an object URL. A link to open that object URL is created. + Click the link to see the decoded object URL.</p></pre> + +<h4 id="JavaScript">JavaScript</h4> + +<p>The main piece of this code for example purposes is the <code>typedArrayToURL()</code> function, which creates a <code>Blob</code> from the given typed array and returns an object URL for it. Having converted the data into an object URL, it can be used in a number of ways, including as the value of the {{HTMLElement("img")}} element's {{htmlattrxref("src", "img")}} attribute (assuming the data contains an image, of course).</p> + +<pre class="brush: js notranslate">function typedArrayToURL(typedArray, mimeType) { + return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType})) +} + +const bytes = new Uint8Array(59); + +for(let i = 0; i < 59; i++) { + bytes[i] = 32 + i; +} + +const url = typedArrayToURL(bytes, 'text/plain'); + +const link = document.createElement('a'); +link.href = url; +link.innerText = 'Open the array URL'; + +document.body.appendChild(link);</pre> + +<h4 id="Result">Result</h4> + +<p>Click the link in the example to see the browser decode the object URL.</p> + +<p>{{EmbedLiveSample("Creating_a_URL_representing_the_contents_of_a_typed_array", 600, 200)}}</p> + +<h3 id="Extracting_data_from_a_blob">Extracting data from a blob</h3> + +<p>One way to read content from a <code>Blob</code> is to use a {{DOMxRef("FileReader")}}. The following code reads the content of a <code>Blob</code> as a typed array:</p> + +<pre class="brush: js notranslate">const reader = new FileReader(); +reader.addEventListener('loadend', () => { + // reader.result contains the contents of blob as a typed array +}); +reader.readAsArrayBuffer(blob);</pre> + +<p>Another way to read content from a <code>Blob</code> is to use a {{domxref("Response")}}. The following code reads the content of a <code>Blob</code> as text:</p> + +<pre class="brush: js notranslate">const text = await (new Response(blob)).text(); +</pre> + +<p>Or by using {{DOMxRef("Blob.prototype.text()")}}:</p> + +<pre class="brush: js notranslate">const text = await blob.text();</pre> + +<p>By using other methods of <code>FileReader</code>, it is possible to read the contents of a Blob as a string or a data URL.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('File API', '#blob-section', 'The <code>Blob</code> interface')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.Blob")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{DOMxRef("BlobBuilder")}}</li> + <li>{{DOMxRef("FileReader")}}</li> + <li>{{DOMxRef("File")}}</li> + <li>{{DOMxRef("URL.createObjectURL")}}</li> + <li><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Using files from web applications</a></li> +</ul> diff --git a/files/pt-pt/web/api/blob/size/index.html b/files/pt-pt/web/api/blob/size/index.html new file mode 100644 index 0000000000..fc6423a199 --- /dev/null +++ b/files/pt-pt/web/api/blob/size/index.html @@ -0,0 +1,73 @@ +--- +title: Blob.size +slug: Web/API/Blob/size +tags: + - API + - Blob + - Bytes + - Ficheiros + - File API + - Propriedade + - Referencia + - length + - size +translation_of: Web/API/Blob/size +--- +<div>{{APIRef("File API")}}</div> + +<p>A propriedade <strong><code>size</code></strong> da interface do {{domxref("Blob")}} retorna o tamanho do {{domxref("Blob")}} ou {{domxref("File")}} em <em>bytes</em>.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <em>sizeInBytes</em> = <em>blob</em>.size +</pre> + +<h3 id="Valor">Valor</h3> + +<p>O número de <em>bytes</em> de dados contidos dentro do <code>Blob</code> (ou do objeto baseado em <code>Blob</code>, como um {{domxref("File")}}).</p> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Este exemplo usa um {{HTMLElement("input")}} com os atributos <code>type="file"</code> e <code>multiple</code> para receber do utilizador um grupo de ficheiros, e depois um iterar sobre os ficheiros que emitem os seus nomes e comprimentos em <em>bytes</em>.</p> + +<pre class="brush:js notranslate">// fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput"> +var fileInput = document.getElementById("myfileinput"); + +// files is a FileList object (simliar to NodeList) +var files = fileInput.files; + +for (var i = 0; i < files.length; i++) { + console.log(files[i].name + " has a size of " + files[i].size + " Bytes"); +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('File API', '#dfn-size', 'Blob.size')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("api.Blob.size")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("Blob")}}</li> + <li><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Usar ficheiros de aplicações web</a></li> +</ul> diff --git a/files/pt-pt/web/api/blob/type/index.html b/files/pt-pt/web/api/blob/type/index.html new file mode 100644 index 0000000000..5744a80a5b --- /dev/null +++ b/files/pt-pt/web/api/blob/type/index.html @@ -0,0 +1,83 @@ +--- +title: Blob.type +slug: Web/API/Blob/type +tags: + - API + - Blob + - DOM + - File + - File API + - Formato + - MIME + - MIME Type + - Propriedade + - Referencia + - tipo +translation_of: Web/API/Blob/type +--- +<div>{{APIRef("File API")}}</div> + +<p><span class="seoSummary">A propriade <strong><code>type</code></strong> do objeto {{domxref("Blob")}} devolve o {{Glossary("MIME type")}} do ficheiro.</span></p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <em>mimetype</em> = <em>blob</em>.type</pre> + +<h3 id="Valor">Valor</h3> + +<p>Uma {{domxref("DOMString")}} que contem o MIME do ficheiro, ou uma <em>string</em> vazia se o tipo não consegue ser determinado.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Este exemplo pede ao utilizador que selecione uma série de ficheiros, depois verifica cada ficheiro para se certificar de que é um de um determinado conjunto de tipos de ficheiros de imagem.</p> + +<pre class="brush:js notranslate">var i, fileInput, files, allowedFileTypes; + +// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput"> +fileInput = document.getElementById("myfileinput"); + +// files é um objeto FileList (parecido ao NodeList) +files = fileInput.files; + +// a nossa aplicação só aceita imagens GIF, PNG, e JPEG +allowedFileTypes = ["image/png", "image/jpeg", "image/gif"]; + +for (i = 0; i < files.length; i++) { + // Testar se file.type é um dos MIME types permitidos. + if (allowedFileTypes.indexOf(<strong>files[i].type</strong>) > -1) { + // file.type é válido + } +}); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('File API', '#dfn-type', 'Blob.type')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("api.Blob.type")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("Blob")}}</li> + <li><em><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Using files from web applications</a></em></li> +</ul> diff --git a/files/pt-pt/web/api/client/index.html b/files/pt-pt/web/api/client/index.html new file mode 100644 index 0000000000..267c1fafc4 --- /dev/null +++ b/files/pt-pt/web/api/client/index.html @@ -0,0 +1,67 @@ +--- +title: Client +slug: Web/API/Client +tags: + - API + - Client + - Experimental + - Interface + - Referencia + - Service Workers + - Service worker API + - ServiceWorkerClient + - ServiceWorkers +translation_of: Web/API/Client +--- +<p>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</p> + +<p>A interface de <em>Client</em> representa um contexto executável, tal como um<span class="seoSummary"> {{domxref("Worker")}}, ou um {{domxref("SharedWorker")}}. Os {{domxref("Window")}} <em>clients</em> </span>são representados pelo mais específico <span class="seoSummary">{{domxref("WindowClient")}}. Pode obter os objetos <em><code>Client</code>/<code>WindowClient</code></em> a partir dos métodos, tais como {{domxref("Clients.matchAll","Clients.matchAll()")}} e {{domxref("Clients.get","Clients.get()")}}.</span></p> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("Client.postMessage()")}}</dt> + <dd>Sends a message to the client.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{domxref("Client.id")}} {{readonlyInline}}</dt> + <dd>The universally unique identifier of the client as a string.</dd> + <dt>{{domxref("Client.type")}} {{readonlyInline}}</dt> + <dd>The client's type as a string. It can be "<code>window"</code>, "<code>worker"</code>, or "<code>sharedworker"</code>.</dd> + <dt>{{domxref("Client.url")}} {{readonlyInline}}</dt> + <dd>The URL of the client as a string.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('Service Workers', '#client', 'Client')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Definitição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_Navegador">Compatibilidade de Navegador</h2> + + + +<p>{{Compat("api.Client")}}</p> + +<h2 id="Consulte_também">Consulte também:</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> +</ul> diff --git a/files/pt-pt/web/api/closeevent/closeevent/index.html b/files/pt-pt/web/api/closeevent/closeevent/index.html new file mode 100644 index 0000000000..b12c9d211e --- /dev/null +++ b/files/pt-pt/web/api/closeevent/closeevent/index.html @@ -0,0 +1,71 @@ +--- +title: CloseEvent() +slug: Web/API/CloseEvent/CloseEvent +tags: + - API + - CloseEvent + - Construtor + - Referencia +translation_of: Web/API/CloseEvent/CloseEvent +--- +<div>{{APIRef("Websockets API")}}</div> + +<p>O construtor <strong><code>CloseEvent()</code></strong> cria um novo {{domxref("CloseEvent")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <em>event</em> = new CloseEvent(<em>typeArg</em>, <em>closeEventInit</em>);</pre> + +<h3 id="Valores">Valores</h3> + +<dl> + <dt><code>typeArg</code></dt> + <dd>É uma {{domxref("DOMString")}} que representa o nome do evento.</dd> + <dt><code>closeEventInit</code> {{optional_inline}}</dt> +</dl> + +<dl> + <dd>É um dicionário <code>CloseEventInit</code>, com os seguintes<em> </em>campos: + + <ul> + <li><code>"wasClean"</code>, opcional e pré-definido como <code>false</code>, do tipo <code>long</code>, indica se a conexão foi terminada de forma limpa ou não.</li> + <li><code>"code"</code>, opcional e pré-definido como <code>0</code>, do tipo <code>unsigned short</code>, é o código de estado do encerrar da conexão enviada pelo servidor.</li> + <li><code>"reason"</code>, opcional e pré-definido como <code>''</code>, do tipo {{domxref("DOMString")}}, é a razão por qual o servidor terminou a conexão escrita para humanos.</li> + </ul> + + <div class="note"> + <p>O dicionário <code>CloseEventInit</code> também aceita campos do dicionário {{domxref("Event.Event", "EventInit")}}.</p> + </div> + </dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table" style="height: 49px; width: 1000px;"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG','comms.html#closeevent','CloseEvent()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.CloseEvent.CloseEvent")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("CloseEvent")}}, a interface dos objetos criados pelo construtor.</li> +</ul> diff --git a/files/pt-pt/web/api/closeevent/index.html b/files/pt-pt/web/api/closeevent/index.html new file mode 100644 index 0000000000..5cece5fd2b --- /dev/null +++ b/files/pt-pt/web/api/closeevent/index.html @@ -0,0 +1,195 @@ +--- +title: CloseEvent +slug: Web/API/CloseEvent +tags: + - API + - Interface + - Referencia + - Web + - WebSocket + - WebSockets +translation_of: Web/API/CloseEvent +--- +<div>{{APIRef("Websockets API")}}</div> + +<p>Um <code>CloseEvent</code> é enviado a clientes usando {{Glossary("WebSockets")}} quando a conexão é terminada. É enviado ao <em>listner</em> indicado pelo atributo <code>onclose</code> de objeto <code>WebSocket</code>.</p> + +<h2 id="Construtor">Construtor</h2> + +<dl> + <dt>{{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}</dt> + <dd>Cria um novo <code>CloseEvent</code>.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<p><em>Esta interface também herda propriedades do {{domxref("Event")}} de qual se deriva.</em></p> + +<dl> + <dt>{{domxref("CloseEvent.code")}} {{readOnlyInline}}</dt> + <dd>Devolve uma <code>unsigned short</code> que contem o código enviado pelo servidor. Os seguintes valores são os códigos de estado permitidos, as definições foram traduzidas a partir do <a href="https://www.iana.org/assignments/websocket/websocket.xml#close-code-number">site da IANA</a>. Note que os códigos 1xxx são só usados internamente pelo WebSocket e não para uso com os dados transportados (como quando o protocolo da aplicação é invalido). Os únicos códigos que podem ser especificados no Firefox são o código 1000 e a série de 3000 a 4999 inclusivo [<a href="https://searchfox.org/mozilla-central/rev/bf81d741ff5dd11bb364ef21306da599032fd479/dom/websocket/WebSocket.cpp#2533">Fonte</a>, <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1467107">Bug</a>].</dd> + <dd> + <table class="standard-table" id="Status_codes"> + <tbody> + <tr> + <td class="header">Código</td> + <td class="header">Nome</td> + <td class="header">Descrição</td> + </tr> + <tr> + <td><code>0</code>–<code>999</code></td> + <td></td> + <td><strong>Reservado e não utilizado.</strong></td> + </tr> + <tr> + <td><code>1000</code></td> + <td>Normal Closure</td> + <td> + <p>Encerramento normal; a conexão completou a tarefa para qual foi criada.</p> + </td> + </tr> + <tr> + <td><code>1001</code></td> + <td>Going Away</td> + <td> + <p>O terminal está a desaparecer, seja devido a uma falha do servidor ou porque o navegador está a navegar para longe da página que abriu a ligação.</p> + </td> + </tr> + <tr> + <td><code>1002</code></td> + <td>Protocol Error</td> + <td>O terminal está a terminar a conexão devido a um erro de protocolo.</td> + </tr> + <tr> + <td><code>1003</code></td> + <td>Unsupported Data</td> + <td>A conexão está a ser terminada porque o terminal recebeu dados num formato que não aceita (por exemplo um terminal de texto receber dados binarios).</td> + </tr> + <tr> + <td><code>1004</code></td> + <td></td> + <td><strong>Reservado.</strong> Uma definição pode ser atribuída no futuro.</td> + </tr> + <tr> + <td><code>1005</code></td> + <td>No Status Received</td> + <td><strong>Reservado.</strong> Indica que nenhum código de estado foi oferecido, apesar de ser esperado um código.</td> + </tr> + <tr> + <td><code>1006</code></td> + <td>Abnormal Closure</td> + <td><strong>Reservado.</strong> Usado para indicar que a conexão fechou anormalmente (isto é, sem uma <em>close frame</em> ser enviada) quando um código era esperado.</td> + </tr> + <tr> + <td><code>1007</code></td> + <td>Invalid frame payload data</td> + <td>O terminal está a terminar a conexão porque a mensagem continha dados inconsistentes (e.x. dados não codificados em UTF-8 numa mensagem de texto).</td> + </tr> + <tr> + <td><code>1008</code></td> + <td>Policy Violation</td> + <td>O terminal está a terminar a conexão porque recebeu uma mensagem que viola a sua política. Isto é um código genérico, usado quando os códigos 1003 e 1009 não são apropriados à situação.</td> + </tr> + <tr> + <td><code>1009</code></td> + <td>Message too big</td> + <td>O terminal está a terminar a conexão porque o <em>data frame</em> recebido é demasiado grande.</td> + </tr> + <tr> + <td><code>1010</code></td> + <td>Missing Extension</td> + <td>O cliente está a terminar a conexão porque esperava que o servidor negociasse uma ou mais extensões, mas não o fez.</td> + </tr> + <tr> + <td><code>1011</code></td> + <td>Internal Error</td> + <td>O servidor está a terminar a conexão porque encontrou uma condição inesperada que a impede de completar o pedido.</td> + </tr> + <tr> + <td><code>1012</code></td> + <td>Service Restart</td> + <td>O servidor está a terminar a conexão porque está a reiniciar. [<a href="https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html">Ref</a>]</td> + </tr> + <tr> + <td><code>1013</code></td> + <td>Try Again Later</td> + <td>O servidor está a terminar a conexão devido a uma condição temporária, por exemplo está sobrecarregado e está a reduzir o número de clientes. [<a href="https://www.ietf.org/mail-archive/web/hybi/current/msg09670.html">Ref</a>]</td> + </tr> + <tr> + <td><code>1014</code></td> + <td>Bad Gateway</td> + <td>O servidor está a agir como uma <em>gateway</em> ou <em>proxy</em> e recebeu uma resposta inválida dum servidor mais adiante na conexão. Isto é parecido com o código de estado HTTP 502.</td> + </tr> + <tr> + <td><code>1015</code></td> + <td>TLS Handshake</td> + <td><strong>Reservado.</strong> Indica que a conexão foi terminada devido a uma falha na execução de um aperto de mão TLS (por exemplo, o certificado do servidor não pode ser verificado).</td> + </tr> + <tr> + <td><code>1016</code>–<code>1999</code></td> + <td></td> + <td><strong>Reservado para o futuro uso de padrões WebSocket.</strong></td> + </tr> + <tr> + <td><code>2000</code>–<code>2999</code></td> + <td></td> + <td><strong>Reservado para uso de extensões de WebSocket.</strong></td> + </tr> + <tr> + <td><code>3000</code>–<code>3999</code></td> + <td></td> + <td>Disponivel para uso por bibliotecas e <em>frameworks</em>. <strong>Não</strong> é para ser utilizado por aplicações. Disponível para registo através da IANA de forma de primeiro a chegar primeiro servido.</td> + </tr> + <tr> + <td><code>4000</code>–<code>4999</code></td> + <td></td> + <td>Disponível para uso por aplicações.</td> + </tr> + </tbody> + </table> + </dd> + <dt>{{domxref("CloseEvent.reason")}} {{readOnlyInline}}</dt> + <dd>Devolve uma {{domxref("DOMString")}} a indicar a razão por qual o servidor terminou a conexão. Isto é específico ao servidor e sub-protocolo.</dd> + <dt>{{domxref("CloseEvent.wasClean")}} {{readOnlyInline}}</dt> + <dd>Devolve um {{jsxref("Boolean")}} que indica se a conexão não foi terminada de forma limpa.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interface também herda métodos de {{domxref("Event")}} de qual se deriva.</em></p> + +<dl> + <dt>{{domxref("CloseEvent.initCloseEvent()")}} {{Non-standard_inline}} {{Obsolete_inline}}</dt> + <dd>Inicializa o valor de um <code>CloseEvent</code>. Se o evento já foi enviado, o método não faz nada. Este método é obsoleto, use antes o construtor {{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('HTML WHATWG', 'web-sockets.html#the-closeevent-interface', 'CloseEvent') }}</td> + <td>{{ Spec2('HTML WHATWG') }}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.CloseEvent")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("WebSocket")}}</li> +</ul> diff --git a/files/pt-pt/web/api/document.dir/index.html b/files/pt-pt/web/api/document.dir/index.html new file mode 100644 index 0000000000..9d82a6b4ab --- /dev/null +++ b/files/pt-pt/web/api/document.dir/index.html @@ -0,0 +1,71 @@ +--- +title: Document.dir +slug: Web/API/Document.dir +tags: + - API + - DOM + - HTML + - dir + - ltr + - rtl +translation_of: Web/API/Document/dir +--- +<p>{{Apiref("Document")}}{{non-standard_header}}</p> +<p>A propriedade <code><strong>Document.dir</strong></code> é uma {{domxref("DOMString")}} que representa a direccionalidade do texto do documento, quer seja da esquerda para a direita (por omissão) ou da direita para a esquerda. Os valores possíveis são <code>'rtl'</code>, da direita para a esquerda e <code>'ltr'</code>, da esquerda para a direita.</p> +<h2 id="Síntaxe">Síntaxe</h2> +<pre class="syntaxbox"><em>dirStr</em> = <em>document.</em>dir; +<em>document.dir</em> = <em>dirStr;</em> +</pre> +<h2 id="Especificações">Especificações</h2> +<p>Este atributo, apesar de implementado por diversos browsers não faz parte de nenhuma especificação.</p> +<h2 id="Compatibilidade_por_browser">Compatibilidade por browser</h2> +<p>{{ CompatibilityTable() }}</p> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> + </table> +</div> +<div id="compat-mobile"> + <table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{ CompatUnknown() }}</td> + <td>{{CompatVersionUnknown}} [1]</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> + </table> +</div> +<p>[1] Antes do Firefox 23, a propriedade <code>document.dir</code> retornava "ltr" independentemente do valor atribuido a dir na raiz do elemento {{htmlelement("html")}}. Caso a direcção fosse definida no nó <code><html></code>, <code>document.dir</code> não teria qualquer efeito em alterá-la visivelmente (apesar disto, a obtenção da propriedade <code>document.dir</code> iria indicar que a direcção teria sido alterada). Contudo, se o atributo dir estiver definido no element<code>o <html></code> e for alterado, quer a direccionalidade do documento quer a propriedade <code>document.dir</code> irão reflectir a mudança.</p> +<h2 id="Ver_também">Ver também</h2> +<ul> + <li><a class="external" href="http://msdn.microsoft.com/en-us/library/ms533731.aspx" rel="freelink">http://msdn.microsoft.com/en-us/library/ms533731.aspx</a></li> +</ul> diff --git a/files/pt-pt/web/api/document/index.html b/files/pt-pt/web/api/document/index.html new file mode 100644 index 0000000000..6710b92f64 --- /dev/null +++ b/files/pt-pt/web/api/document/index.html @@ -0,0 +1,458 @@ +--- +title: Document +slug: Web/API/Document +tags: + - API + - DOM + - Documento + - Interface + - Referencia +translation_of: Web/API/Document +--- +<div>{{APIRef}}</div> + +<div> </div> + +<p><span class="seoSummary">A interface <strong><code>Document</code></strong> representa qualquer página da <em>Web </em>carregada no navegador e serve como um ponto de entrada para um conteúdo da página da <em>Web</em>, que é <a href="/pt-PT/docs/Using_the_W3C_DOM_Level_1_Core" title="Using_the_W3C_DOM_Level_1_Core">árvore DOM</a>.</span> A árvore DOM inclui elementos, tais como {{HTMLElement("body")}} e {{HTMLElement("table")}}, entre <a href="/pt-PT/docs/Web/HTML/Elemento">muitos outros</a>. Este fornece funcionalidade globalmente para o documento, tal como obter o URL da página e criar novos elementos no documento.</p> + +<p>{{inheritanceDiagram}}</p> + +<p>The <code>Document</code> interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. <a href="/en-US/docs/HTML" title="HTML">HTML</a>, <a href="/en-US/docs/XML" title="XML">XML</a>, SVG, …), a larger API is available: HTML documents, served with the <code>text/html</code> content type, also implement the {{domxref("HTMLDocument")}} interface, whereas XML and SVG documents implement the {{domxref("XMLDocument")}} interface.</p> + +<h2 id="Properties" name="Properties">Construtor</h2> + +<dl> + <dt>{{domxref("Document.Document","Document()")}}{{non-standard_inline}}</dt> + <dd>Cria um novo objeto <code>Document</code>.</dd> +</dl> + +<h2 id="Properties" name="Properties">Propriedades</h2> + +<p><em>This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.</em></p> + +<dl> + <dt>{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}</dt> + <dd>Provides access to all elements in the document. This is a legacy, non-standard interface and should not be used.</dd> + <dt>{{domxref("Document.async")}} {{Deprecated_inline}}</dt> + <dd>Used with {{domxref("Document.load")}} to indicate an asynchronous request.</dd> + <dt>{{domxref("Document.characterSet")}} {{readonlyinline}}</dt> + <dd>Returns the character set being used by the document.</dd> + <dt>{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}</dt> + <dd>Alias of {{domxref("Document.characterSet")}}. Use this property instead.</dd> + <dt>{{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Indicates whether the document is rendered in <em>quirks</em> or <em>strict</em> mode.</dd> + <dt>{{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Returns the Content-Type from the MIME Header of the current document.</dd> + <dt>{{domxref("Document.doctype")}} {{readonlyinline}}</dt> + <dd>Returns the Document Type Definition (DTD) of the current document.</dd> + <dt>{{domxref("Document.documentElement")}} {{readonlyinline}}</dt> + <dd>Returns the {{domxref("Element")}} that is a direct child of the document. For HTML documents, this is normally the {{HTMLElement("html")}} element.</dd> + <dt>{{domxref("Document.documentURI")}} {{readonlyinline}}</dt> + <dd>Returns the document location as a string.</dd> + <dt>{{domxref("Document.domConfig")}} {{Deprecated_inline}}</dt> + <dd>Should return a {{domxref("DOMConfiguration")}} object.</dd> + <dt>{{domxref("Document.fullscreen")}} {{obsolete_inline}}</dt> + <dd><code>true</code> when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.</dd> + <dt>{{domxref("Document.hidden")}} {{readonlyinline}}</dt> + <dd>…</dd> + <dt>{{domxref("Document.implementation")}} {{readonlyinline}}</dt> + <dd>Returns the DOM implementation associated with the current document.</dd> + <dt>{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}</dt> + <dd>Alias of {{domxref("Document.characterSet")}}. Use this property instead.</dd> + <dt>{{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}</dt> + <dd>Returns the name of the style sheet set that was last enabled. Has the value <code>null</code> until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.</dd> + <dt>{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}</dt> + <dd>Returns a {{jsxref("Boolean")}} that is <code>true</code> only if this document is synthetic, such as a standalone image, video, audio file, or the like.</dd> + <dt>{{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}</dt> + <dd>The element that's currently in full screen mode for this document.</dd> + <dt>{{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}</dt> + <dd><code>true</code> if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.</dd> + <dt>{{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>Returns the element set as the target for mouse events while the pointer is locked. <code>null</code> if lock is pending, pointer is unlocked, or if the target is in another document.</dd> + <dt>{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}</dt> + <dd>Returns the preferred style sheet set as specified by the page author.</dd> + <dt>{{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}</dt> + <dd>Returns a reference to the {{domxref("Element")}} that scrolls the document.</dd> + <dt>{{domxref("Document.selectedStyleSheetSet")}}</dt> + <dd>Returns which style sheet set is currently in use.</dd> + <dt>{{domxref("Document.styleSheets")}} {{readonlyinline}}</dt> + <dd>Returns a list of the style sheet objects on the current document.</dd> + <dt>{{domxref("Document.styleSheetSets")}} {{readonlyinline}}</dt> + <dd>Returns a list of the style sheet sets available on the document.</dd> + <dt>{{domxref("Document.timeline")}} {{readonlyinline}}</dt> + <dd>…</dd> + <dt>{{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}</dt> + <dd>…</dd> + <dt>{{domxref("Document.visibilityState")}} {{readonlyinline}}</dt> + <dd> + <p>Returns a <code>string</code> denoting the visibility state of the document. Possible values are <code>visible</code>, <code>hidden</code>, <code>prerender</code>, and <code>unloaded</code>.</p> + </dd> + <dt>{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}</dt> + <dd>Returns the encoding as determined by the XML declaration.</dd> + <dt>{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}</dt> + <dd>Returns <code>true</code> if the XML declaration specifies the document to be standalone (<em>e.g.,</em> An external part of the DTD affects the document's content), else <code>false</code>.</dd> + <dt>{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}</dt> + <dd>Returns the version number as specified in the XML declaration or <code>"1.0"</code> if the declaration is absent.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("ParentNode")}} interface:</p> + +<p>{{page("/en-US/docs/Web/API/ParentNode","Properties")}}</p> + +<h3 id="Extensão_para_o_documento_HTML">Extensão para o documento HTML</h3> + +<p><em>The <code>Document</code> interface for HTML documents inherits from the {{domxref("HTMLDocument")}} interface or, since HTML5, is extended for such documents.</em></p> + +<dl> + <dt>{{domxref("Document.activeElement")}} {{readonlyinline}}</dt> + <dd>Returns the currently focused element.</dd> + <dt>{{domxref("Document.alinkColor")}} {{Deprecated_inline}}</dt> + <dd>Returns or sets the color of active links in the document body.</dd> + <dt>{{domxref("Document.anchors")}}</dt> + <dd>Returns a list of all of the anchors in the document.</dd> + <dt>{{domxref("Document.applets")}} {{Deprecated_inline}}</dt> + <dd>Returns an ordered list of the applets within a document.</dd> + <dt>{{domxref("Document.bgColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the background color of the current document.</dd> + <dt>{{domxref("Document.body")}}</dt> + <dd>Returns the {{HTMLElement("body")}} element of the current document.</dd> + <dt>{{domxref("Document.cookie")}}</dt> + <dd>Returns a semicolon-separated list of the cookies for that document or sets a single cookie.</dd> + <dt>{{domxref("Document.defaultView")}} {{readonlyinline}}</dt> + <dd>Returns a reference to the window object.</dd> + <dt>{{domxref("Document.designMode")}}</dt> + <dd>Gets/sets the ability to edit the whole document.</dd> + <dt>{{domxref("Document.dir")}} {{readonlyinline}}</dt> + <dd>Gets/sets directionality (rtl/ltr) of the document.</dd> + <dt>{{domxref("Document.domain")}}</dt> + <dd>Gets/sets the domain of the current document.</dd> + <dt>{{domxref("Document.embeds")}} {{readonlyinline}}</dt> + <dd>Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.</dd> + <dt>{{domxref("document.fgColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the foreground color, or text color, of the current document.</dd> + <dt>{{domxref("Document.forms")}} {{readonlyinline}}</dt> + <dd>Returns a list of the {{HTMLElement("form")}} elements within the current document.</dd> + <dt>{{domxref("Document.head")}} {{readonlyinline}}</dt> + <dd>Returns the {{HTMLElement("head")}} element of the current document.</dd> + <dt>{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Gets/sets the height of the current document.</dd> + <dt>{{domxref("Document.images")}} {{readonlyinline}}</dt> + <dd>Returns a list of the images in the current document.</dd> + <dt>{{domxref("Document.lastModified")}} {{readonlyinline}}</dt> + <dd>Returns the date on which the document was last modified.</dd> + <dt>{{domxref("Document.linkColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the color of hyperlinks in the document.</dd> + <dt>{{domxref("Document.links")}} {{readonlyinline}}</dt> + <dd>Returns a list of all the hyperlinks in the document.</dd> + <dt>{{domxref("Document.location")}} {{readonlyinline}}</dt> + <dd>Returns the URI of the current document.</dd> + <dt>{{domxref("Document.plugins")}} {{readonlyinline}}</dt> + <dd>Returns a list of the available plugins.</dd> + <dt>{{domxref("Document.readyState")}} {{readonlyinline}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns loading status of the document.</dd> + <dt>{{domxref("Document.referrer")}} {{readonlyinline}}</dt> + <dd>Returns the URI of the page that linked to this page.</dd> + <dt>{{domxref("Document.scripts")}} {{readonlyinline}}</dt> + <dd>Returns all the {{HTMLElement("script")}} elements on the document.</dd> + <dt>{{domxref("Document.title")}}</dt> + <dd>Sets or gets the title of the current document.</dd> + <dt>{{domxref("Document.URL")}} {{readonlyInline}}</dt> + <dd>Returns<span style="line-height: 19.0909080505371px;"> the document location as a string.</span></dd> + <dt>{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}</dt> + <dd>Gets/sets the color of visited hyperlinks.</dd> + <dt>{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns the width of the current document.</dd> +</dl> + +<h3 id="Event_handlers" name="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("afterscriptexecute")}} event.</dd> + <dt>{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("beforescriptexecute")}} event.</dd> + <dt>{{domxref("Document.oncopy")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("copy")}} event.</dd> + <dt>{{domxref("Document.oncut")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("cut")}} event.</dd> + <dt>{{domxref("Document.onfullscreenchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.</dd> + <dt>{{domxref("Document.onfullscreenerror")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.</dd> + <dt>{{domxref("Document.onpaste")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("paste")}} event.</dd> + <dt>{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}</dt> + <dd>Represents the event handling code for the {{event("pointerlockchange")}} event.</dd> + <dt>{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}</dt> + <dd>Represetnts the event handling code for the {{event("pointerlockerror")}} event.</dd> + <dt>{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Represents the event handling code for the {{event("readystatechange")}} event.</dd> + <dt>{{domxref("Document.onselectionchange")}} {{experimental_inline}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.</dd> + <dt>{{domxref("Document.onvisibilitychange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.</dd> + <dt>{{domxref("Document.onwheel")}} {{non-standard_inline}}</dt> + <dd>Represents the event handling code for the {{event("wheel")}} event.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("GlobalEventHandlers")}} interface:</p> + +<p>{{Page("/en-US/docs/Web/API/GlobalEventHandlers", "Properties")}}</p> + +<h2 id="Methods" name="Methods">Methods</h2> + +<p><em>This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.</em></p> + +<dl> + <dt>{{domxref("Document.adoptNode()")}}</dt> + <dd>Adopt node from an external document.</dd> + <dt>{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}</dt> + <dd>See {{domxref("Window.captureEvents")}}.</dd> + <dt>{{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}</dt> + <dd>Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.</dd> + <dt>{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}</dt> + <dd>Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.</dd> + <dt>{{domxref("Document.createAttribute()")}}</dt> + <dd>Creates a new {{domxref("Attr")}} object and returns it.</dd> + <dt>{{domxref("Document.createAttributeNS()")}}</dt> + <dd>Creates a new attribute node in a given namespace and returns it.</dd> + <dt>{{domxref("Document.createCDATASection()")}}</dt> + <dd>Creates a new CDATA node and returns it.</dd> + <dt>{{domxref("Document.createComment()")}}</dt> + <dd>Creates a new comment node and returns it.</dd> + <dt>{{domxref("Document.createDocumentFragment()")}}</dt> + <dd>Creates a new document fragment.</dd> + <dt>{{domxref("Document.createElement()")}}</dt> + <dd>Creates a new element with the given tag name.</dd> + <dt>{{domxref("Document.createElementNS()")}}</dt> + <dd>Creates a new element with the given tag name and namespace URI.</dd> + <dt>{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}</dt> + <dd>Creates a new entity reference object and returns it.</dd> + <dt>{{domxref("Document.createEvent()")}}</dt> + <dd>Creates an event object.</dd> + <dt>{{domxref("Document.createNodeIterator()")}}</dt> + <dd>Creates a {{domxref("NodeIterator")}} object.</dd> + <dt>{{domxref("Document.createProcessingInstruction()")}}</dt> + <dd>Creates a new {{domxref("ProcessingInstruction")}} object.</dd> + <dt>{{domxref("Document.createRange()")}}</dt> + <dd>Creates a {{domxref("Range")}} object.</dd> + <dt>{{domxref("Document.createTextNode()")}}</dt> + <dd>Creates a text node.</dd> + <dt>{{domxref("Document.createTouch()")}} {{Deprecated_inline}}</dt> + <dd>Creates a {{domxref("Touch")}} object.</dd> + <dt>{{domxref("Document.createTouchList()")}}</dt> + <dd>Creates a {{domxref("TouchList")}} object.</dd> + <dt>{{domxref("Document.createTreeWalker()")}}</dt> + <dd>Creates a {{domxref("TreeWalker")}} object.</dd> + <dt>{{domxref("Document.elementFromPoint()")}}{{experimental_inline}}</dt> + <dd>Returns the topmost element at the specified coordinates. </dd> + <dt>{{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}</dt> + <dd>Returns an array of all elements at the specified coordinates.</dd> + <dt>{{domxref("Document.enableStyleSheetsForSet()")}}</dt> + <dd>Enables the style sheets for the specified style sheet set.</dd> + <dt>{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}</dt> + <dd>Release the pointer lock.</dd> + <dt>{{domxref("Document.getAnimations()")}} {{experimental_inline}}</dt> + <dd>Returns an array of all {{domxref("Animation")}} objects currently in effect, whose target elements are descendants of the <code>document</code>.</dd> + <dt>{{domxref("Document.getElementsByClassName()")}}</dt> + <dd>Returns a list of elements with the given class name.</dd> + <dt>{{domxref("Document.getElementsByTagName()")}}</dt> + <dd>Returns a list of elements with the given tag name.</dd> + <dt>{{domxref("Document.getElementsByTagNameNS()")}}</dt> + <dd>Returns a list of elements with the given tag name and namespace.</dd> + <dt>{{domxref("Document.importNode()")}}</dt> + <dd>Returns a clone of a node from an external document.</dd> + <dt>{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}</dt> + <dd>Replaces entities, normalizes text nodes, etc.</dd> + <dt>{{domxref("Document.registerElement()")}} {{experimental_inline}}</dt> + <dd>Registers a web component.</dd> + <dt>{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Releases the current mouse capture if it's on an element in this document.</dd> + <dt>{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>See {{domxref("Window.releaseEvents()")}}.</dd> + <dt>{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}</dt> + <dd>See {{domxref("Window.routeEvent()")}}.</dd> + <dt>{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Allows you to change the element being used as the background image for a specified element ID.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("ParentNode")}} interface:</p> + +<dl> + <dt>{{domxref("document.getElementById","document.getElementById(String id)")}}</dt> + <dd>Returns an object reference to the identified element.</dd> + <dt>{{domxref("document.querySelector","document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns the first Element node within the document, in document order, that matches the specified selectors.</dd> + <dt>{{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns a list of all the Element nodes within the document that match the specified selectors.</dd> +</dl> + +<p>The <code>Document</code> interface is extended with the {{domxref("XPathEvaluator")}} interface:</p> + +<dl> + <dt>{{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}</dt> + <dd>Compiles an <code><a href="/en-US/docs/XPathExpression" title="XPathExpression">XPathExpression</a></code> which can then be used for (repeated) evaluations.</dd> + <dt>{{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}</dt> + <dd>Creates an {{domxref("XPathNSResolver")}} object.</dd> + <dt>{{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}</dt> + <dd>Evaluates an XPath expression.</dd> +</dl> + +<h3 id="Extension_for_HTML_documents">Extension for HTML documents</h3> + +<p>The <code>Document</code> interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5, is extended for such documents:</p> + +<dl> + <dt>{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.</dd> + <dt>{{domxref("document.close()")}}</dt> + <dd>Closes a document stream for writing.</dd> + <dt>{{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}</dt> + <dd>On an editable document, executes a formating command.</dd> + <dt>{{domxref("document.getElementsByName","document.getElementsByName(String name)")}}</dt> + <dd>Returns a list of elements with the given name.</dd> + <dt>{{domxref("document.getSelection()")}}</dt> + <dd>Returns a {{domxref("Selection")}} object related to text selected in the document.</dd> + <dt>{{domxref("document.hasFocus()")}}</dt> + <dd>Returns <code>true</code> if the focus is currently located anywhere inside the specified document.</dd> + <dt>{{domxref("document.open()")}}</dt> + <dd>Opens a document stream for writing.</dd> + <dt>{{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}</dt> + <dd>Returns true if the formating command can be executed on the current range.</dd> + <dt>{{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}</dt> + <dd>Returns true if the formating command is in an indeterminate state on the current range.</dd> + <dt>{{domxref("document.queryCommandState","document.queryCommandState(String command)")}}</dt> + <dd>Returns true if the formating command has been executed on the current range.</dd> + <dt>{{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}</dt> + <dd>Returns true if the formating command is supported on the current range.</dd> + <dt>{{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}</dt> + <dd>Returns the current value of the current range for a formating command.</dd> + <dt>{{domxref("document.write","document.write(String text)")}}</dt> + <dd>Writes text in a document.</dd> + <dt>{{domxref("document.writeln","document.writeln(String text)")}}</dt> + <dd>Writes a line of text in a document.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('Page Visibility API', '#onvisiblitychange-event-handler', 'onvisibilitychange')}}</td> + <td>{{Spec2('Page Visibility API')}}</td> + <td>Adds <code>onvisibility</code><code>change</code>.</td> + </tr> + <tr> + <td>{{SpecName('Selection API', '', 'Extend Document and GlobalEventHandlers')}}</td> + <td>{{Spec2('Selection API')}}</td> + <td>Adds <code>onselectstart</code> and <code>onselectionchange</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM1','#i-Document','Document')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Initial definition for the interface</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core','#i-Document','Document')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>Supersede DOM 1</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core','#i-Document','Document')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Supersede DOM 2</td> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG','#interface-document','Document')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Intend to supersede DOM 3</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Turn the {{domxref("HTMLDocument")}} interface into a <code>Document</code> extension.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}</td> + <td>{{Spec2('DOM3 XPath')}}</td> + <td>Define the {{domxref("XPathEvaluator")}} interface which extend document.</td> + </tr> + <tr> + <td>{{SpecName('Page Visibility API', '#sec-document-interface', 'Document')}}</td> + <td>{{Spec2('Page Visibility API')}}</td> + <td>Extend the <code>Document</code> interface with the <code>visibilityState</code> and <code>hidden</code> attributes</td> + </tr> + <tr> + <td>{{SpecName('HTML Editing','#dom-document-getselection','Document')}}</td> + <td>{{Spec2('HTML Editing')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('CSSOM View')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('CSSOM')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + <tr> + <td>{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}</td> + <td>{{Spec2('Pointer Lock')}}</td> + <td>Extend the <code>Document</code> interface</td> + </tr> + </tbody> +</table> + +<h2 id="Notas_de_compatibilidade_do_navegador">Notas de compatibilidade do navegador</h2> + +<h3 id="Notas_do_Firefox">Notas do Firefox</h3> + +<p>Mozilla defines a set of non-standard properties made only for XUL content:</p> + +<dl> + <dt>{{domxref("document.currentScript")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the {{HTMLElement("script")}} element that is currently executing.</dd> + <dt>{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>(<strong>Mozilla add-ons only!</strong>) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).</dd> + <dt>{{domxref("document.popupNode")}}</dt> + <dd>Returns the node upon which a popup was invoked.</dd> + <dt>{{domxref("document.tooltipNode")}}</dt> + <dd>Returns the node which is the target of the current tooltip.</dd> +</dl> + +<p>Mozilla also define some non-standard methods:</p> + +<dl> + <dt>{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}</dt> + <dd>This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.</dd> + <dt>{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}</dt> + <dd>Use the {{domxref("Element.getBoundingClientRect()")}} method instead.</dd> + <dt>{{domxref("document.loadOverlay")}} {{Fx_minversion_inline("1.5")}}</dt> + <dd>Loads a <a href="/en-US/docs/XUL_Overlays" title="XUL_Overlays">XUL overlay</a> dynamically. This only works in XUL documents.</dd> + <dt>{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}</dt> + <dd>This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.</dd> +</dl> + +<h3 id="Notas_do_Internet_Explorer">Notas do Internet Explorer</h3> + +<p>Microsoft defines some non-standard properties:</p> + +<dl> + <dt>{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See <a href="http://msdn.microsoft.com/en-us/library/ms533752%28v=VS.85%29.aspx" title="http://msdn.microsoft.com/en-us/library/ms533752%28v=VS.85%29.aspx">MSDN</a>.</dd> + <dt><span style="font-weight: normal; line-height: 1.5;">Internet Explorer does not support all methods from the <code>Node</code> interface in the <code>Document</code> interface:</span></dt> +</dl> + +<dl> + <dt>{{domxref("document.contains")}}</dt> + <dd>As a work-around, <code>document.body.contains()</code> can be used.</dd> +</dl> + +<p> </p> diff --git a/files/pt-pt/web/api/document/queryselector/index.html b/files/pt-pt/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..e979e285d3 --- /dev/null +++ b/files/pt-pt/web/api/document/queryselector/index.html @@ -0,0 +1,134 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +tags: + - API + - DOM + - Document + - Elementos DOM + - Referencia + - Selector API + - Seletores CSS + - Seletors + - metodo + - querySelector +translation_of: Web/API/Document/querySelector +--- +<div>{{ApiRef("DOM")}}</div> + +<p>O método <code><strong>querySelector()</strong></code> de {{domxref("Document")}} retorna o primeiro {{domxref("Element")}} dentro do documento que corresponde ao seletor, ou grupo de seleteores especificados. Se não há elementos que correspondem, <code>null</code> é devolvido como resultado.</p> + +<div class="note"> +<p><strong>Nota</strong>: A correspondência é feita através de uma travessia <em>pre-order</em> em profundidade dos nódulos do documento, a começar com o primeiro elemento da marcação do documento e iterando através de nódulos sequenciais por ordem do número de nódulos filhos.</p> +</div> + +<h2 id="Syntaxe">Syntaxe</h2> + +<pre class="syntaxbox notranslate"><var>element</var> = document.querySelector(<var>selectors</var>); +</pre> + +<h3 id="Parameteros">Parameteros</h3> + +<dl> + <dt><var>selectors</var></dt> + <dd>Um {{domxref("DOMString")}} a conter um ou mais seletores para com que corresponder. Esta string tem de ser um seletor de CSS valido; se não é, uma <em>exception</em> <code>SYNTAX_ERR</code> é lançada. Veja <a href="/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors">Localizar elementos do DOM a usar seletores</a> para saber mais sobre seletor e como os gerir.</dd> +</dl> + +<div class="note"> +<p><strong>Nota:</strong> Os carateres que não fazem parte da sintaxe padrão do CSS devem ser evitados ao usar um caráter de barra invertida. Uma vez que o JavaScript também usa barra invertida para escapar, deve ter especial cuidado ao escrever <em>string literals</em> usando estes carateres. Veja {{anch("Escapar carateres especiais")}} para obter mais informação.</p> +</div> + +<h3 id="Resultado">Resultado</h3> + +<p>Um objeto {{domxref("HTMLElement")}} a representar o primeiro elemento no documento que corresponde aos <a href="/en-US/docs/Web/CSS/CSS_Selectors">seletores de CSS</a>, ou <code>null</code> se não há elementos correspondentes.</p> + +<p>Se precisar de uma lista de todos os elementos que correspondem ao seletores especificados, deve usar {{domxref("Document.querySelectorAll", "querySelectorAll()")}}.</p> + +<h3 id="Exeções">Exeções</h3> + +<dl> + <dt><code>SYNTAX_ERR</code></dt> + <dd>O syntaxe dos <em>selectors</em> especificados está incorrecto.</dd> +</dl> + +<h2 id="Notas_de_uso">Notas de uso</h2> + +<p>Se o seletor especificado corresponde a um ID que é incorretamente utilizado mais que uma vez num documento, o primeiro elemento com esse ID será devolvido.</p> + +<p><a href="/en-US/docs/Web/CSS/Pseudo-elements">Pseudoelementos de CSS</a> não devolvem elementos, como é especificado na <a href="http://www.w3.org/TR/selectors-api/#grammar">API de seletores</a>.</p> + +<h3 id="Escapar_carateres_especiais">Escapar carateres especiais</h3> + +<p>Para corresponder a um ID ou seletor que não segue a sintaxe de CSS padrão (ao usar o caráter de dois pontos ou espaço incorretamente), deve escapar o caráter com uma barra invertida ("<code>\</code>"). Como a barra invertida também é um caráter de escapar no JavaScript, se a escrever numa <em>string literal</em>, tem de a escapar duas vezes (primeiro para a <em>string</em> do JavaScript, e depois para o <code>querySelector()</code>):</p> + +<pre class="brush: html notranslate"><div id="foo\bar"></div> +<div id="foo:bar"></div> + +<script> + console.log('#foo\bar'); // "#fooar" (\b é o caráter de controlo para a barra invertida) + document.querySelector('#foo\bar'); // Corresponde a nada + + console.log('#foo\\bar'); // "#foo\bar" + console.log('#foo\\\\bar'); // "#foo\\bar" + document.querySelector('#foo\\\\bar'); // Corresponde ao primeiro div + + document.querySelector('#foo:bar'); // Corresponde a nada + document.querySelector('#foo\\:bar'); // Corresponde ao segundo div +</script></pre> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Encontrar_o_primeiro_elemento_que_corresponde_a_uma_classe">Encontrar o primeiro elemento que corresponde a uma classe</h3> + +<p>Neste exemplo, o primeiro elemento no documento com a classe <code>myclass</code> é devolvida:</p> + +<pre class="brush: js notranslate">var el = document.querySelector(".myclass"); +</pre> + +<h3 id="Um_seletor_mais_complexo">Um seletor mais complexo</h3> + +<p>Seletores são muito poderosos, como demonstrado no seguinte exemplo. O primeiro elemento {{HTMLElement("input")}} com o nome "login" (<code><input name="login"/></code>) encontrado dentro dum {{HTMLElement("div")}} cuja classe é "user-panel main" (<code><div class="user-panel main"></code>) no documento é devolvido:</p> + +<pre class="brush: js notranslate">var el = document.querySelector("div.user-panel.main input[name='login']"); +</pre> + +<h3 id="Negação">Negação</h3> + +<p>Todos os strings de seletores de CSS são válidos, assim também é possivel ter seletores de negação:</p> + +<pre class="brush: js notranslate">var el = document.querySelector("div.user-panel:not(.main) input[name='login']");</pre> + +<p>Isto seléciona um <code>input</code> que tem um <code>div</code> com classe <code>user-panel</code> como parente, mas sem a classe <code>main</code>.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("DOM WHATWG", "#dom-parentnode-queryselector", "document.querySelector()")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<div>{{Compat("api.Document.querySelector")}}</div> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors">Localizar elementos DOM a usar selectors</a></li> + <li>{{domxref("Element.querySelector()")}}</li> + <li>{{domxref("Document.querySelectorAll()")}}</li> + <li>{{domxref("Element.querySelectorAll()")}}</li> + <li><a href="/en-US/docs/Code_snippets/QuerySelector">Snippets de código para o querySelector</a></li> +</ul> diff --git a/files/pt-pt/web/api/document/visibilitychange_event/index.html b/files/pt-pt/web/api/document/visibilitychange_event/index.html new file mode 100644 index 0000000000..02df020b70 --- /dev/null +++ b/files/pt-pt/web/api/document/visibilitychange_event/index.html @@ -0,0 +1,148 @@ +--- +title: visibilitychange +slug: Web/API/Document/visibilitychange_event +translation_of: Web/API/Document/visibilitychange_event +--- +<p>O evento <code>visibilitychange</code> é ativado quando o conteúdo de um separador se torna visível ou foi ocultado.</p> + +<h2 id="Informação_geral">Informação geral</h2> + +<dl> + <dt style="float: left; text-align: right; width: 120px;">Especificação</dt> + <dd style="margin: 0 0 0 120px;">{{SpecName("Page Visibility API")}}</dd> + <dt style="float: left; text-align: right; width: 120px;">Interface</dt> + <dd style="margin: 0 0 0 120px;">{{domxref("event")}}</dd> + <dt style="float: left; text-align: right; width: 120px;">Bubbles</dt> + <dd style="margin: 0 0 0 120px;">Sim</dd> + <dt style="float: left; text-align: right; width: 120px;">Cancelável</dt> + <dd style="margin: 0 0 0 120px;">Não</dd> + <dt style="float: left; text-align: right; width: 120px;">Destino</dt> + <dd style="margin: 0 0 0 120px;">{{domxref("Document")}}</dd> + <dt style="float: left; text-align: right; width: 120px;">Ação Predefinida</dt> + <dd style="margin: 0 0 0 120px;"> </dd> + <dd style="margin: 0 0 0 120px;">None</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Propriedade</th> + <th scope="col">Tipo</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>target</code> {{readonlyInline}}</td> + <td>{{domxref("EventTarget")}}</td> + <td>The event target (the topmost target in the DOM tree).</td> + </tr> + <tr> + <td><code>type</code> {{readonlyInline}}</td> + <td>{{domxref("DOMString")}}</td> + <td>The type of event.</td> + </tr> + <tr> + <td><code>bubbles</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Whether the event normally bubbles or not.</td> + </tr> + <tr> + <td><code>cancelable</code> {{readonlyInline}}</td> + <td>{{jsxref("Boolean")}}</td> + <td>Whether the event is cancellable or not.</td> + </tr> + </tbody> +</table> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush:js;">document.addEventListener("visibilitychange", function() { + console.log( document.visibilityState ); +}); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Page Visibility API','#sec-visibilitychange-event','visibilitychange')}}</td> + <td>{{Spec2('Page Visibility API')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidade de navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>13 {{property_prefix("webkit")}}<br> + 33</td> + <td>{{CompatGeckoDesktop(10)}} {{property_prefix("moz")}}<br> + {{CompatGeckoDesktop(18)}}</td> + <td>10</td> + <td> + <p>12.10[1]</p> + </td> + <td>6.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>4.4 {{property_prefix("webkit")}}</td> + <td>{{CompatGeckoMobile(10)}} {{property_prefix("moz")}}<br> + {{CompatGeckoMobile(18)}}</td> + <td>{{CompatUnknown}}</td> + <td>12.10 [1]</td> + <td>7</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Doesn't fire the <code>visibilitychange</code> event when the browser window is minimized, nor set <code>hidden</code> to <code>true</code>.</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/Page_Visibility_API" title="DOM/Using_the_Page_Visibility_API">Utilização de Page Visibility API</a></li> + <li><a href="/pt-PT/docs/Web">Document.visibilityState</a></li> +</ul> diff --git a/files/pt-pt/web/api/domstring/index.html b/files/pt-pt/web/api/domstring/index.html new file mode 100644 index 0000000000..abd4b8962e --- /dev/null +++ b/files/pt-pt/web/api/domstring/index.html @@ -0,0 +1,43 @@ +--- +title: DOMString +slug: Web/API/DOMString +tags: + - API + - DOM + - Referencia + - String +translation_of: Web/API/DOMString +--- +<div>{{APIRef("DOM")}}</div> + +<p><strong><code>DOMString</code></strong> é uma <em>string</em> codificada em UTF-16. Como a JavaScript já usa <em>strings</em> deste tipo, <code>DOMString</code> é mapeado diretamente a uma {{jsxref("String")}}.</p> + +<p>Passar {{jsxref("null")}} a um método ou parametro que aceita uma <code>DOMString</code> tipicamente é convertido para uma <em>string</em> com o valor <code>"null"</code>.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}</td> + <td>{{Spec2('WebIDL')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>JavaScript {{jsxref("String")}}</li> + <li>{{domxref("USVString")}}</li> + <li>{{domxref("CSSOMString")}}</li> + <li><a href="/pt-PT/docs/Web/API/DOMString/Binary">Strings binários</a></li> +</ul> diff --git a/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html b/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html new file mode 100644 index 0000000000..32b15a8ea1 --- /dev/null +++ b/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html @@ -0,0 +1,70 @@ +--- +title: Eventos de Luz Ambiente +slug: Web/API/Eventos_de_Luz_Ambiente +tags: + - Luz Ambiente +translation_of: Web/API/Ambient_Light_Events +--- +<div>{{DefaultAPISidebar("Ambient Light Events")}}{{SeeCompatTable}}</div> + +<p>Os eventos de luz ambiente são uma maneira prática de tornar uma página da Web ou um aplicação ciente de qualquer alteração na intensidade da luz. Isto permite-lhes reagir a essa alteração, por exemplo, alterando o contraste da cor da interface do utilizador (IU) ou alterando a exposição necessária para tirar uma fotografia.</p> + +<h2 id="Eventos_de_Luz">Eventos de Luz</h2> + +<p>When the light sensor of a device detects a change in the light level, it notifies the browser of that change. When the browser gets such a notification, it fires a {{domxref("DeviceLightEvent")}} event that provides information about the exact light intensity.</p> + +<p>This event can be captured at the <code>window</code> object level by using the {{domxref("EventTarget.addEventListener","addEventListener")}} method (using the {{event("devicelight")}} event name) or by attaching an event handler to the {{domxref("window.ondevicelight")}} property.</p> + +<p>Once captured, the event object gives access to the light intensity expressed in <a href="http://en.wikipedia.org/wiki/Lux">lux</a> through the {{domxref("DeviceLightEvent.value")}} property.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js">if ('ondevicelight' in window) { + window.addEventListener('devicelight', function(event) { + var body = document.querySelector('body'); + if (event.value < 50) { + body.classList.add('darklight'); + body.classList.remove('brightlight'); + } else { + body.classList.add('brightlight'); + body.classList.remove('darklight'); + } + }); +} else { + console.log('devicelight event not supported'); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("AmbientLight", "", "Ambient Light Events")}}</td> + <td>{{Spec2("AmbientLight")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("api.DeviceLightEvent")}}</p> + +<p> </p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li>{{domxref("DeviceLightEvent")}}</li> + <li>{{event("devicelight")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/file/index.html b/files/pt-pt/web/api/file/file/index.html new file mode 100644 index 0000000000..a785c59a41 --- /dev/null +++ b/files/pt-pt/web/api/file/file/index.html @@ -0,0 +1,71 @@ +--- +title: File.File() +slug: Web/API/File/File +tags: + - API + - Construtor + - File API + - Referencia +translation_of: Web/API/File/File +--- +<div>{{APIRef("File")}}</div> + +<p>O construtor <code><strong>File()</strong></code> cria uma instância do objeto {{domxref("File")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">new File(bits, name[, options]);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>bits</code></dt> + <dd>Uma {{jsxref("Array")}} de objetos {{jsxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("USVString")}}, ou um misto de tais objetos, que será posto no {{domxref("File")}}. Objetos <code>USVString</code> são codificados em UTF-8.</dd> + <dt><code>name</code></dt> + <dd>Uma {{domxref("USVString")}} que representa o nome do ficheiro ou o caminho para o ficheiro.</dd> + <dt><code>options</code> {{optional_inline}}</dt> + <dd>Um objeto com atributos opcionais para o ficheiro. As opções disponíveis são: + <ul> + <li><code>type</code>: Uma {{domxref("DOMString")}} que representa o tipo MIME do conteúdo será posto no ficheiro. Tem um valor pré-definido de <code>""</code>.</li> + <li><code>lastModified</code>: Um número que representa o número de milissegundos entre o início da era Unix e a última data em que o ficheiro foi modificado. Tem um valor pré-definido de {{jsxref("Date.now()")}}.</li> + </ul> + </dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js notranslate">var file = new File(["foo"], "foo.txt", { + type: "text/plain", +});</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File API')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.File.File")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> + <li>{{domxref("Blob")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/filename/index.html b/files/pt-pt/web/api/file/filename/index.html new file mode 100644 index 0000000000..0e0ee197ae --- /dev/null +++ b/files/pt-pt/web/api/file/filename/index.html @@ -0,0 +1,37 @@ +--- +title: File.fileName +slug: Web/API/File/fileName +tags: + - API + - DOM + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Propriedade + - Referencia +translation_of: Web/API/File/fileName +--- +<div>{{APIRef("File API")}}{{non-standard_header}} {{obsolete_header(7.0)}}</div> + +<p>Retorna o nome do ficheiro. Por razões de segurança o caminho é excluído desta propriedade.</p> + +<div class="note">Esta propriedade está obsoleta. Use antes {{domxref("File.name")}}.</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <em>name</em> = <em>instanceOfFile</em>.fileName;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Uma <em>string</em></p> + +<h2 id="Specification" name="Specification">Especificação</h2> + +<p>Não faz parte duma especificação.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("File.name")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/filesize/index.html b/files/pt-pt/web/api/file/filesize/index.html new file mode 100644 index 0000000000..e17676ecee --- /dev/null +++ b/files/pt-pt/web/api/file/filesize/index.html @@ -0,0 +1,37 @@ +--- +title: File.fileSize +slug: Web/API/File/fileSize +tags: + - API + - DOM + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Propriedade + - Referencia +translation_of: Web/API/File/fileSize +--- +<p>{{APIRef("File API") }}{{non-standard_header}} {{deprecated_header(7.0)}}</p> + +<p>Retorna o tamanho do ficheiro em <em>bytes</em>.</p> + +<div class="note">Esta propriedade está obsoleta. Use antes {{domxref("Blob.size")}}.</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <em>size</em> = <em>instanceOfFile</em>.fileSize;</pre> + +<h3 id="Valor">Valor</h3> + +<p>Um número.</p> + +<h2 id="Especificação">Especificação</h2> + +<p>Não faz parte de nenhuma especificação.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("Blob.size")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/getasbinary/index.html b/files/pt-pt/web/api/file/getasbinary/index.html new file mode 100644 index 0000000000..8ec42cf1f2 --- /dev/null +++ b/files/pt-pt/web/api/file/getasbinary/index.html @@ -0,0 +1,77 @@ +--- +title: File.getAsBinary() +slug: Web/API/File/getAsBinary +tags: + - API + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Referencia + - metodo +translation_of: Web/API/File/getAsBinary +--- +<p>{{APIRef("File API")}}</p> + +<p>{{non-standard_header}}</p> + +<p>{{obsolete_header(7.0)}}</p> + +<h2 id="Sumário">Sumário</h2> + +<p>O método <code>getAsBinary</code> permite aceder aos dados de um ficheiro num formato <em>raw</em> binário.</p> + +<div class="note"> +<p><strong>Nota:</strong> Este método é obsoleto; use antes o método {{domxref("FileReader.readAsBinaryString()","readAsBinaryString()")}} ou {{domxref("FileReader.readAsArrayBuffer()","readAsArrayBuffer()")}} de {{domxref("FileReader")}}.</p> +</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="notranslate">var binary = <em>instanceOfFile</em>.getAsBinary();</pre> + +<h3 id="Retorna">Retorna</h3> + +<p>Uma <em>string</em>.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush:js; notranslate">// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple> +var fileInput = document.getElementById("myfileinput"); + +// files é um objeto de FileList (parecido ao NodeList) +var files = fileInput.files; + +// objeto com os tipos de media permitidos +var accept = { + binary : ["image/png", "image/jpeg"], + text : ["text/plain", "text/css", "application/xml", "text/html"] +}; + +var file; + +for (var i = 0; i < files.length; i++) { + file = files[i]; + + // se o ficheiro pode ser detetado + if (file !== null) { + if (accept.binary.indexOf(file.type) > -1) { + // file contem dados binarios, num formato permitido + var data = file.getAsBinary(); + } else if (accept.text.indexOf(file.type) > -1) { + // file contem texto, num formato permitido + var data = file.getAsText(); + // modificar dados com métodos de string + } + } +}</pre> + +<h2 id="Specification" name="Specification">Especificação</h2> + +<p>Não pertence a nenhuma especificação.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("File")}}</li> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/getasdataurl/index.html b/files/pt-pt/web/api/file/getasdataurl/index.html new file mode 100644 index 0000000000..e3e5bae4b3 --- /dev/null +++ b/files/pt-pt/web/api/file/getasdataurl/index.html @@ -0,0 +1,67 @@ +--- +title: File.getAsDataURL() +slug: Web/API/File/getAsDataURL +tags: + - API + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Referencia + - metodo +translation_of: Web/API/File/getAsDataURL +--- +<div>{{APIRef("File API") }}</div> + +<p>{{non-standard_header}}</p> + +<p>{{deprecated_header(7.0)}}</p> + +<h2 id="Sumário">Sumário</h2> + +<p><span class="seoSummary">O método <code>getAsDataURL</code> retorna um URL em estilo <a href="/en-US/docs/data_URIs"><code>data:</code></a> que codifica todo o conteúdo do ficheiro em questão.</span></p> + +<div class="note"> +<p><strong>Nota:</strong> Este método está obsoleto: use antes o método {{domxref("FileReader.readAsDataURL","readAsDataURL()")}} de {{domxref("FileReader")}}.</p> +</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="notranslate">var url = <var>instanceOfFile</var>.getAsDataURL();</pre> + +<h3 id="Retorna">Retorna</h3> + +<p>Uma string a representar um URL de estilo <a href="/en-US/docs/data_URIs"><code>data:</code></a></p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js notranslate">// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple> +var fileInput = document.getElementById("myfileinput"); + +// files é um objeto FileList (parecido ao NodeList) +var files = fileInput.files; + +// accept é um array com tipos de ficheiros aceites +var accept = ["image/png"]; + +// img é um HTMLImgElement: <img id="myimg"> +var img = document.getElementById("myimg"); + +// se aceitamos o primeiro tipo de ficheiro selecionado +if (accept.indexOf(files[0].mediaType) > -1) { + // apresentar a imagem + // igual a <img src="data:image/png,<imagedata>"> + img.src = files[0].getAsDataURL(); +} +</pre> + +<h2 id="Especificação">Especificação</h2> + +<p>Não pertence a nenhuma especificação.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("File")}}</li> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/getastext/index.html b/files/pt-pt/web/api/file/getastext/index.html new file mode 100644 index 0000000000..b20229737e --- /dev/null +++ b/files/pt-pt/web/api/file/getastext/index.html @@ -0,0 +1,83 @@ +--- +title: File.getAsText() +slug: Web/API/File/getAsText +tags: + - API + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Referencia + - metodo +translation_of: Web/API/File/getAsText +--- +<p>{{APIRef("File API") }}{{non-standard_header}}</p> + +<p>{{obsolete_header(7.0)}}</p> + +<h2 id="Sumário">Sumário</h2> + +<p>O método <code>getAsText</code> oferece os dados do ficheiro num formato de texto de acordo com uma codificação.</p> + +<div class="note"> +<p><strong>Note:</strong> Este método está obsoleto; use antes o método {{domxref("FileReader.readAsText()","readAsText()")}} de {{domxref("FileReader")}}.</p> +</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="notranslate">var <var>str</var> = <var>instanceOfFile</var>.getAsText(<var>encoding</var>);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><var>encoding</var></dt> + <dd>Uma <em>string</em> a indicar qual a codificação para usar nos dados devolvidos. Se o <em>string</em> estiver vazio, é utilizado UTF-8.</dd> +</dl> + +<h3 id="Retorna">Retorna</h3> + +<p>A string que contem os dados do ficheiro num formato de texto especificado pelo <code>encoding</code>.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js notranslate">// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple> +var fileInput = document.getElementById("myfileinput"); + +// files é um objeto de FileList (parecido ao NodeList) +var files = fileInput.files; + +// object com os formatos de media validos +var accept = { + binary : ["image/png", "image/jpeg"], + text : ["text/plain", "text/css", "application/xml", "text/html"] +}; + +var file; + +for (var i = 0; i < files.length; i++) { + file = files[i]; + + // se o formato do ficheiro foi detetado + if (file !== null) { + if (accept.text.indexOf(file.mediaType) > -1) { + // file contem texto, num formato permitido + // make sure it's encoded as utf-8 + var data = file.getAsText("utf-8"); + // modificar dados com métodos de string + + } else if (accept.binary.indexOf(file.mediaType) > -1) { + // binario + } + } +}</pre> + +<h2 id="Especificação">Especificação</h2> + +<p>Não pertence a nenhuma especificação.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("File")}}</li> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/index.html b/files/pt-pt/web/api/file/index.html new file mode 100644 index 0000000000..43e85438cb --- /dev/null +++ b/files/pt-pt/web/api/file/index.html @@ -0,0 +1,101 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - File API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/API/File +--- +<div>{{APIRef}}</div> + +<p>The <strong><code>File</code></strong> interface provides information about files and allows JavaScript in a web page to access their content.</p> + +<p><code>File</code> objects are generally retrieved from a {{DOMxRef("FileList")}} object returned as a result of a user selecting files using the {{HTMLElement("input")}} element, from a drag and drop operation's {{DOMxRef("DataTransfer")}} object, or from the <code>mozGetAsFile()</code> API on an {{DOMxRef("HTMLCanvasElement")}}.</p> + +<p>A <code>File</code> object is a specific kind of a {{DOMxRef("Blob")}}, and can be used in any context that a Blob can. In particular, {{DOMxRef("FileReader")}}, {{DOMxRef("URL.createObjectURL()")}}, {{DOMxRef("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, and {{DOMxRef("XMLHttpRequest", "", "send()")}} accept both <code>Blob</code>s and <code>File</code>s.</p> + +<p>See <a href="/en-US/docs/Using_files_from_web_applications">Using files from web applications</a> for more information and examples.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{DOMxRef("File.File", "File()")}}</dt> + <dd>Returns a newly constructed <code>File</code>.</dd> +</dl> + +<h2 id="Instance_properties">Instance properties</h2> + +<dl> + <dt>{{DOMxRef("File.prototype.lastModified")}} {{ReadOnlyInline}}</dt> + <dd>Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight).</dd> + <dt>{{DOMxRef("File.prototype.lastModifiedDate")}} {{Deprecated_Inline}} {{ReadOnlyInline}}</dt> + <dd>Returns the last modified {{JSxRef("Date")}} of the file referenced by the <code>File</code> object.</dd> + <dt>{{DOMxRef("File.prototype.name")}}{{ReadOnlyInline}}</dt> + <dd>Returns the name of the file referenced by the <code>File</code> object.</dd> + <dt>{{DOMxRef("File.prototype.webkitRelativePath")}} {{Non-standard_Inline}} {{ReadOnlyInline}}</dt> + <dd>Returns the path the URL of the {{DOMxRef("File")}} is relative to.</dd> +</dl> + +<p><code>File</code> implements {{DOMxRef("Blob")}}, so it also has the following properties available to it:</p> + +<dl> + <dt>{{DOMxRef("File.prototype.size")}} {{ReadOnlyInline}}</dt> + <dd>Returns the size of the file in bytes.</dd> + <dt>{{DOMxRef("File.prototype.type")}} {{ReadOnlyInline}}</dt> + <dd>Returns the <a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME </a>type of the file.</dd> +</dl> + +<h2 id="Instance_methods">Instance methods</h2> + +<p><em>The <code>File</code> interface doesn't define any methods, but inherits methods from the {{DOMxRef("Blob")}} interface:</em></p> + +<dl> + <dt>{{DOMxRef("Blob.prototype.slice()", "Blob.prototype.slice([start[, end[, contentType]]])")}}</dt> + <dd>Returns a new <code>Blob</code> object containing the data in the specified range of bytes of the source <code>Blob</code>.</dd> + <dt>{{DOMxRef("Blob.prototype.stream()")}}</dt> + <dd>Transforms the <code>File</code> into a {{DOMxRef("ReadableStream")}} that can be used to read the <code>File</code> contents.</dd> + <dt>{{DOMxRef("Blob.prototype.text()")}}</dt> + <dd>Transforms the <code>File</code> into a stream and reads it to completion. It returns a promise that resolves with a {{DOMxRef("USVString")}} (text).</dd> + <dt>{{DOMxRef("Blob.prototype.arrayBuffer()")}}</dt> + <dd>Transforms the <code>File</code> into a stream and reads it to completion. It returns a promise that resolves with an {{DOMxRef("ArrayBuffer")}}.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File API', "#file-section", "The <code>File</code> interface")}}</td> + <td>{{Spec2('File API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("api.File")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Using files from web applications</a></li> + <li>{{DOMxRef("FileReader")}}</li> + <li><a href="/en-US/docs/Extensions/Using_the_DOM_File_API_in_chrome_code">Using the DOM File API in chrome code</a> (for privileged code running in Gecko, such as Firefox add-ons)</li> +</ul> diff --git a/files/pt-pt/web/api/file/lastmodified/index.html b/files/pt-pt/web/api/file/lastmodified/index.html new file mode 100644 index 0000000000..9b05f6f3cf --- /dev/null +++ b/files/pt-pt/web/api/file/lastmodified/index.html @@ -0,0 +1,113 @@ +--- +title: File.lastModified +slug: Web/API/File/lastModified +tags: + - API + - Ficheiros + - File API + - Propriedade + - Referencia +translation_of: Web/API/File/lastModified +--- +<div>{{APIRef("File")}}</div> + +<p>A propriedade <em>read-only</em> <code><strong>File.lastModified</strong></code> indica a ultima data em que o ficheiro foi modificado, na forma do numero de milissegundos desde o início da era Unix (1 de janeiro de 1970 às 00:00:00). Os ficheiros cuja a data da última modificação não é conhecida devolvem a data actual.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">const <em>tempo</em> = <em>instanciaDeFicheiro</em>.lastModified; +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Um número que representa o número de milissegundos desde o início da época do Unix.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<h3 id="Leitura_a_partir_da_entrada_do_ficheiro">Leitura a partir da entrada do ficheiro</h3> + +<pre class="brush: html notranslate"><input type="file" multiple id="entradaDeFicheiro"> +</pre> + +<pre class="brush:js notranslate">const entradaDeFicheiro = document.querySelector('#entradaDeFicheiro'); +entradaDeFicheiro.addEventListener('change', (event) => { + // ficheiros é um objeto de FileList (semelhante a NodeList) + const ficheiros = event.target.files; + + for (let ficheiro of ficheiros) { + const data = new Date(ficheiro.lastModified); + console.log(`${ficheiro.name} tem uma última data modificada de ${data}`); + } +}); +</pre> + +<p>Veja os resultados abaixo:</p> + +<p>{{ EmbedLiveSample('Leitura_a_partir_da_entrada_do_ficheiro', 300, 50) }}</p> + +<h3 id="Ficheiros_criados_dinamicamente">Ficheiros criados dinamicamente</h3> + +<p>Se um objeto File for criado dinamicamente, a última data modificada pode ser fornecida na função construtor {{domxref("File.File()", "new File()")}}. Se estiver em falta, lastModified herda a hora actual de {{jsxref("Date.now()")}} no momento em que o objeto File é criado.</p> + +<pre class="brush:js notranslate">const ficheiroComData = new File([], 'file.bin', { + lastModified: new Date(2017, 1, 1), +}); +console.log(ficheiroComData.lastModified); //devolve 1485903600000 + +const ficheiroSemData = new File([], 'file.bin'); +console.log(ficheiroSemData.lastModified); //devolve data atual em milissegundos +</pre> + +<h2 id="Reduced_time_precision">Reduced time precision</h2> + +<p>To offer protection against timing attacks and fingerprinting, the precision of <code>someFile.lastModified</code> might get rounded depending on browser settings.<br> + In Firefox, the <code>privacy.reduceTimerPrecision</code> preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms.</p> + +<pre class="brush: js notranslate">// reduced time precision (2ms) in Firefox 60 +someFile.lastModified; +// 1519211809934 +// 1519211810362 +// 1519211811670 +// ... + + +// reduced time precision with `privacy.resistFingerprinting` enabled +someFile.lastModified; +// 1519129853500 +// 1519129858900 +// 1519129864400 +// ... +</pre> + +<p>In Firefox, you can also enabled <code>privacy.resistFingerprinting</code>, the precision will be 100ms or the value of <code>privacy.resistFingerprinting.reduceTimerPrecision.microseconds</code>, whichever is larger.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File API', '#file-attrs', 'lastModified')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.File.lastModified")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("File")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/lastmodifieddate/index.html b/files/pt-pt/web/api/file/lastmodifieddate/index.html new file mode 100644 index 0000000000..10d5d8c932 --- /dev/null +++ b/files/pt-pt/web/api/file/lastmodifieddate/index.html @@ -0,0 +1,80 @@ +--- +title: File.lastModifiedDate +slug: Web/API/File/lastModifiedDate +tags: + - API + - Ficheiros + - File + - File API + - Obsoleto + - Propriedade + - Read-only + - Referencia + - lastDateModified +translation_of: Web/API/File/lastModifiedDate +--- +<div>{{APIRef("File API") }} {{deprecated_header}}</div> + +<p>A propriedade <em>read-only</em> <code><strong>File.lastModifiedDate</strong></code><strong> </strong>devolve a ultima data em que o ficheiro foi modificado. Ficheiros onde a ultima data de modificação é desconhecida devolvem a data atual.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="notranslate">var time = <em>instanceOfFile</em>.lastModifiedDate</pre> + +<h3 id="Valor">Valor</h3> + +<p>Um objeto <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">Date</a></code> a indicar a data e hora da ultima modificação ao ficheiro.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush:js notranslate">// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput"> +var fileInput = document.getElementById("myfileinput"); + +// files é um objeto de FileList (parecido ao NodeList) +var files = fileInput.files; + +for (var i = 0; i < files.length; i++) { + alert(files[i].name + " has a last modified date of " + files[i].lastModifiedDate); +}</pre> + +<h2 id="Precisão_reduzida">Precisão reduzida</h2> + +<p>Para oferecer proteção contra <em>timing attacks</em> e <em>fingerprinting</em> a precisão de <code>someFile.lastModifiedDate.getTime()</code> pode ser arredondada dependente das preferências no navegador.</p> + +<p>No Firefox, a preferência <code>privacy.reduceTimerPrecision</code> está ligada por pré-definição com valores arredondados aos 20μs mais próximos no Firefox 59; e no Firefox 60 aos 2ms.</p> + +<pre class="brush: js notranslate">// precisão reduzida (2ms) no Firefox 60 +someFile.lastModifiedDate.getTime(); +// 1519211809934 +// 1519211810362 +// 1519211811670 +// ... + + +// precisão reduzida com a `privacy.resistFingerprinting` ligada +someFile.lastModifiedDate.getTime(); +// 1519129853500 +// 1519129858900 +// 1519129864400 +// ... +</pre> + +<p>No Firefox, também pode ligar a preferência <code>privacy.resistFingerprinting</code>, a precisão será arredondada aos 100ms mais próximos ou ao valor de <code>privacy.resistFingerprinting.reduceTimerPrecision.microseconds</code>, o que for maior.</p> + +<h2 id="Especificações">Especificações</h2> + +<p>Apesar de estar presente numa versão inicial do esboço do File API <em>spec</em>, esta propriedade foi removida e agora é <em>non-standard</em>. Use antes {{domxref("File.lastModified")}}.</p> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("api.File.lastModifiedDate")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("File")}}</li> +</ul> diff --git a/files/pt-pt/web/api/file/mozfullpath/index.html b/files/pt-pt/web/api/file/mozfullpath/index.html new file mode 100644 index 0000000000..24e126847f --- /dev/null +++ b/files/pt-pt/web/api/file/mozfullpath/index.html @@ -0,0 +1,17 @@ +--- +title: File.mozFullPath +slug: Web/API/File/mozFullPath +tags: + - API + - Ficheiros + - File + - File API + - Non-standard + - Propriedade + - Referencia + - mozFullPath +translation_of: Web/API/File/mozFullPath +--- +<div>{{APIRef("File API")}}{{draft}}{{Non-standard_header}}</div> + +<p><span class="seoSummary">Uma extensão privilegiada para a interface {{domxref("File")}}, a propriedade <code>mozFullPath</code> contém o caminho completo do ficheiro representado.</span> Esta propriedade só está disponível a partir do código do navegador ou de extensões Firefox ao estilo antigo com base no XPCOM. Não está disponível para o conteúdo da web.</p> diff --git a/files/pt-pt/web/api/file/name/index.html b/files/pt-pt/web/api/file/name/index.html new file mode 100644 index 0000000000..907a08a8e2 --- /dev/null +++ b/files/pt-pt/web/api/file/name/index.html @@ -0,0 +1,74 @@ +--- +title: File.name +slug: Web/API/File/name +tags: + - API + - File API + - Files + - Propriadade + - Referencia +translation_of: Web/API/File/name +--- +<div>{{APIRef("File API")}}</div> + +<div>Devolve o nome do ficheiro representado por um objeto {{domxref("File")}}. Por razões de segurança, o caminho é excluído desta propriedade.</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <var>name</var> = <var>file</var>.name;</pre> + +<h2 id="Valor">Valor</h2> + +<p>Uma string, que contem o nome do ficheiro sem o caminho, por exemplo "<code>O meu Resumo.rtf</code>".</p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: html notranslate"><input type="file" multiple onchange="processSelectedFiles(this)"> +</pre> + +<pre class="brush: js notranslate">function processSelectedFiles(fileInput) { + var files = fileInput.files; + + for (var i = 0; i < files.length; i++) { + alert("Filename " + files[i].name); + } +}</pre> + +<p>Veja os resultados abaixo:</p> + +<p>{{ EmbedLiveSample('Exemplo', 300, 50) }}</p> + + + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File API', '#file-attrs', 'name')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("api.File.name")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><em><a href="/en-US/docs/Using_files_from_web_applications">Using files from web applications</a></em></li> +</ul> diff --git a/files/pt-pt/web/api/file/type/index.html b/files/pt-pt/web/api/file/type/index.html new file mode 100644 index 0000000000..2b448d3086 --- /dev/null +++ b/files/pt-pt/web/api/file/type/index.html @@ -0,0 +1,75 @@ +--- +title: File.type +slug: Web/API/File/type +tags: + - API + - Ficheiros + - File API + - Propriedade + - Referencia + - Tipo de Ficheiro +translation_of: Web/API/File/type +--- +<div>{{APIRef("File API")}}</div> + +<p>Retorna a média (<a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME</a>) representado por um objeto {{domxref("File")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="brush: js notranslate">var name = <var>file</var>.type;</pre> + +<h2 id="Valor">Valor</h2> + +<p>Uma <em>string</em>, que contem o tipo de média (MIME) que indica o tipo do ficheiro, por exemplo "<code>image/png</code>" é devolvido para imagens PNG.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: html notranslate"><input type="file" multiple onchange="showType(this)"> +</pre> + +<pre class="brush: js notranslate">function showType(fileInput) { + var files = fileInput.files; + + for (var i = 0; i < files.length; i++) { + var name = files[i].name; + var type = files[i].type; + alert("Filename: " + name + " , Type: " + type); + } +}</pre> + +<div class="blockIndicator note"> +<p><br> + <strong>Nota:</strong> Baseado na atual implementação, navegadores não leem a <em>bytestream</em> dum ficheiro para determinar a sua média. É feito uma ilação baseada na extensão do ficheiro; uma imagem PNG com uma extensão ".txt" é atribuída o tipo "<code>text/plain</code>" e não "<code>image/png</code>". Além disso, <code>file.type</code> é geralmente fiável apenas para ficheiros comuns como imagens, documentos HTML, áudio e vídeo. Extensões de ficheiros pouco comuns devolveriam uma cadeia de caracteres vazia. A configuração do cliente (por exemplo, o Registo do Windows) pode resultar em valores inesperados mesmo para tipos comuns. <code>Os programadores são aconselhados a não confiar nesta propriedade como o único esquema de validação.</code></p> +</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File API', '#dfn-type', 'type')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.File.type")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/File/Using_files_from_web_applications">Usar ficheiros de aplicações web</a></li> + <li>Publicação de blogue (em inglês): <em><a href="https://textslashplain.com/2018/07/26/be-skeptical-of-client-reported-mime-content-types/">Be skeptical of client-reported MIME types</a></em></li> +</ul> diff --git a/files/pt-pt/web/api/file/webkitrelativepath/index.html b/files/pt-pt/web/api/file/webkitrelativepath/index.html new file mode 100644 index 0000000000..35f155c1c6 --- /dev/null +++ b/files/pt-pt/web/api/file/webkitrelativepath/index.html @@ -0,0 +1,80 @@ +--- +title: File.webkitRelativePath +slug: Web/API/File/webkitRelativePath +tags: + - Ficheiro +translation_of: Web/API/File/webkitRelativePath +--- +<p>{{APIRef("File API")}}</p> + +<p>O <strong><code>File.webkitRelativePath</code></strong> é uma propriedade só de leitura que contém um {{domxref("USVString")}} que especifica o caminho do ficheiro em relação ao diretório selecionado pelo utilizador num elemento {{HTMLElement("input")}} com o seu conjunto de atributos {{htmlattrxref("webkitdirectory", "input")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"> <code><em>relativePath = File</em></code>.webkitRelativePath</pre> + +<h3 id="Valor">Valor</h3> + +<p>Um {{domxref("USVString")}} que contem o caminho do ficheiro relativo ao diretório dos antepassados que o utilizador selecionou.</p> + +<h2 id="Example" name="Example">Exemplo</h2> + +<p>Neste exemplo, é apresentado um seletor de diretórios que permite ao utilizador escolher um ou mais diretórios. Quando o evento {{event("change")}} ocorre, é gerada e apresentada uma lista de todos os ficheiros contidos dentro das hierarquias de diretórios selecionados.</p> + +<h3 id="Conteúdo_HTML">Conteúdo HTML</h3> + +<pre class="brush: html notranslate"><input type="file" id="seletorDeFicheiros" name="listaDeFicheiros" webkitdirectory multiple /> +<ul id="listagem"></ul></pre> + +<h3 id="Conteúdo_JavaScript">Conteúdo JavaScript</h3> + +<pre class="brush: js notranslate">document.getElementById("seletorDeFicheiros").addEventListener("change", function(event) { + let output = document.getElementById("listagem"); + let ficheiros = event.target.files; + + for (let i = 0; i < ficheiros.length; i++) { + let item = document.createElement("li"); + item.innerHTML = ficheiros[i].webkitRelativePath; + output.appendChild(item); + }; +}, false); +</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{ EmbedLiveSample('Example') }}</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('File System API', '#dom-file-webkitrelativepath', 'webkitRelativePath') }}</td> + <td>{{ Spec2('File System API') }}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<p>Esta IPA não tem especificação oficial do W3C ou do WHATWG.</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidade</h2> + + + +<p>{{Compat("api.File.webkitRelativePath")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="pt-PT/docs/Web/API/File_and_Directory_Entries_API">API de entradas de ficheiros e diretórios</a></li> + <li>{{domxref("HTMLInputElement.webkitEntries")}}</li> + <li>{{domxref("HTMLInputElement.webkitdirectory")}}</li> +</ul> diff --git a/files/pt-pt/web/api/filereader/abort/index.html b/files/pt-pt/web/api/filereader/abort/index.html new file mode 100644 index 0000000000..3ffeae8ce9 --- /dev/null +++ b/files/pt-pt/web/api/filereader/abort/index.html @@ -0,0 +1,58 @@ +--- +title: FileReader.abort() +slug: Web/API/FileReader/abort +tags: + - API + - Ficheiros + - File API + - FileReader + - Referencia + - abort + - metodo +translation_of: Web/API/FileReader/abort +--- +<div>{{APIRef("File API")}}</div> + +<p>O método <strong><code>abort</code></strong> aborta a operação de leitura. Ao completar o abortamento, o {{domxref("FileReader.readyState","readyState")}} é <code>DONE</code>.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>instanceOfFileReader</var>.abort();</pre> + +<h3 id="Exceções">Exceções</h3> + +<dl> + <dt><code>DOM_FILE_ABORT_ERR</code></dt> + <dd>Lançado quando <code>abort</code> é chamado enquanto não há uma operação de leitura em progresso (ou seja, quando o <em>state</em> não é <code>LOADING</code>).</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("File API", "#abort", "abort()")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.FileReader.abort")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/filereader/error/index.html b/files/pt-pt/web/api/filereader/error/index.html new file mode 100644 index 0000000000..b308705d79 --- /dev/null +++ b/files/pt-pt/web/api/filereader/error/index.html @@ -0,0 +1,54 @@ +--- +title: FileReader.error +slug: Web/API/FileReader/error +tags: + - API + - Ficheiros + - File API + - Propriedade + - Referencia +translation_of: Web/API/FileReader/error +--- +<div>{{APIRef("File API")}}</div> + +<p>A propriedade <code><strong>error</strong></code> de {{domxref("FileReader")}} retorna o erro que ocorreu ao ler o ficheiro.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <var>error</var> = <var>instanceOfFileReader</var>.error +</pre> + +<h2 id="Valor">Valor</h2> + +<p>Um {{domxref("DOMError")}} com o erro. Em Chrome 48+/Firefox 58+ esta propriedade retorna uma {{domxref("DOMException")}} porque <code>DOMError</code> foi removido do <em>standard</em> do DOM.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("File API", "#dom-filereader-error", "FileReader: error")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.FileReader.error")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/filereader/index.html b/files/pt-pt/web/api/filereader/index.html new file mode 100644 index 0000000000..0df369c585 --- /dev/null +++ b/files/pt-pt/web/api/filereader/index.html @@ -0,0 +1,172 @@ +--- +title: FileReader +slug: Web/API/FileReader +tags: + - API + - DOM + - File API + - Files + - NeedsTranslation + - Reference + - TopicStub + - WebAPI +translation_of: Web/API/FileReader +--- +<p>{{ APIRef("File API") }}</p> + +<h2 id="Summary">Summary</h2> + +<p>The <code>FileReader</code> object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using {{ domxref("File") }} or {{ domxref("Blob") }} objects to specify the file or data to read.</p> + +<p>File objects may be obtained from a {{ domxref("FileList") }} object returned as a result of a user selecting files using the {{ HTMLElement("input") }} element, from a drag and drop operation's <a href="/En/DragDrop/DataTransfer" title="En/DragDrop/DataTransfer"><code>DataTransfer</code></a> object, or from the <code>mozGetAsFile()</code> API on an {{ domxref("HTMLCanvasElement") }}.</p> + +<h2 id="Constructor">Constructor</h2> + +<pre class="syntaxbox">FileReader FileReader();</pre> + +<p>See <a href="/en/Using_files_from_web_applications" title="en/Using files from web applications">Using files from web applications</a> for details and examples.</p> + +<h2 id="Properties" name="Properties">Properties</h2> + +<dl> + <dt>{{domxref("FileReader.error")}} {{readonlyinline}}</dt> + <dd>A {{domxref("DOMError")}} representing the error that occurred while reading the file.</dd> + <dt>{{domxref("FileReader.readyState")}} {{readonlyinline}}</dt> + <dd>A number indicating the state of the <code>FileReader</code>. This will be one of the {{ anch("State constants") }}.</dd> + <dt>{{domxref("FileReader.result")}} {{readonlyinline}}</dt> + <dd>The file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.</dd> +</dl> + +<h3 id="Event_handlers">Event handlers</h3> + +<dl> + <dt>{{domxref("FileReader.onabort")}}</dt> + <dd>A handler for the {{event("abort")}} event. This event is triggered each time the reading operation is aborted.</dd> + <dt>{{domxref("FileReader.onerror")}}</dt> + <dd>A handler for the {{event("error")}} event. This event is triggered each time the reading operation encounter an error.</dd> + <dt>{{domxref("FileReader.onload")}}</dt> + <dd>A handler for the {{event("load")}} event. This event is triggered each time the reading operation is successfully completed.</dd> + <dt>{{domxref("FileReader.onloadstart")}}</dt> + <dd>A handler for the {{event("loadstart")}} event. This event is triggered each time the reading is starting.</dd> + <dt>{{domxref("FileReader.onloadend")}}</dt> + <dd>A handler for the {{event("loadend")}} event. This event is triggered each time the reading operation is completed (either in success or failure).</dd> + <dt>{{domxref("FileReader.onprogress")}}</dt> + <dd>A handler for the {{event("progress")}} event. This event is triggered while reading a {{domxref("Blob")}} content.</dd> +</dl> + +<div class="note"> +<p>Note: As <code>FileReader</code> inherits from {{domxref("EventTarget")}}, all those events can also be listened for by using the {{domxref("EventTarget.addEventListener()","addEventListener")}} method.</p> +</div> + +<h3 id="State_constants" name="State_constants">State constants</h3> + +<ul> + <li><code>EMPTY </code> : <code>0</code> : No data has been loaded yet.</li> + <li><code>LOADING</code> : <code>1</code> : Data is currently being loaded.</li> + <li><code>DONE </code> : <code>2</code> : The entire read request has been completed.</li> +</ul> + +<h2 id="Methods" name="Methods">Methods</h2> + +<dl> + <dt>{{domxref("FileReader.abort()")}}</dt> + <dd>Aborts the read operation. Upon return, the <code>readyState</code> will be <code>DONE</code>.</dd> + <dt>{{domxref("FileReader.readAsArrayBuffer()")}} {{ gecko_minversion_inline("7.0") }}</dt> + <dd>Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the <code>result</code> attribute contains an {{domxref("ArrayBuffer")}} representing the file's data.</dd> + <dt>{{domxref("FileReader.readAsBinaryString()")}}</dt> + <dd>Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the <code>result</code> attribute contains the raw binary data from the file as a string.</dd> + <dt>{{domxref("FileReader.readAsDataURL()")}}</dt> + <dd>Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the <code>result</code> attribute contains a <code>data:</code> URL representing the file's data.</dd> + <dt>{{domxref("FileReader.readAsText()")}}</dt> + <dd>Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the <code>result</code> attribute contains the contents of the file as a text string.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('File API','#FileReader-interface','FileReader')}}</td> + <td>{{Spec2('File API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer*</th> + <th>Opera*</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatGeckoDesktop("1.9.2") }}</td> + <td>7</td> + <td>10</td> + <td>12.02</td> + <td>6.0.2</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>32</td> + <td>3</td> + <td>10</td> + <td>11.5</td> + <td>6.1</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Implementation_notes">Implementation notes</h3> + +<ul> + <li>IE9 has a <a href="http://html5labs.interoperabilitybridges.com/prototypes/fileapi/fileapi/info" title="http://html5labs.interoperabilitybridges.com/prototypes/fileapi/fileapi/info">File API Lab</a>.</li> + <li>Opera has <a href="http://www.opera.com/docs/specs/presto28/file/" title="http://my.opera.com/desktopteam/blog/2011/04/05/stability-gmail-socks">partial support</a> in 11.1.</li> +</ul> + +<h4 id="Gecko-specific_notes">Gecko-specific notes</h4> + +<ul> + <li>Prior to Gecko 2.0 beta 7 (Firefox 4.0 beta 7), all {{ domxref("Blob") }} parameters below were {{ domxref("File") }} parameters; this has since been updated to match the specification correctly.</li> + <li>Prior to Gecko 13.0 {{ geckoRelease("13.0") }} the <code>FileReader.error</code> property returned a {{ domxref("FileError") }} object. This interface has been removed and <code>FileReader.error</code> is now returning the {{ domxref("DOMError") }} object as defined in the latest FileAPI draft.</li> +</ul> + +<h2 id="See_also" name="See_also">See also</h2> + +<ul> + <li><a href="/en/Using_files_from_web_applications" title="en/Using files from web applications">Using files from web applications</a></li> + <li>{{ domxref("File") }}</li> + <li>{{ domxref("Blob") }}</li> + <li><a href="/en-US/docs/nsIDOMFileReader">nsIDOMFileReader</a> - For addons/privileged scope</li> +</ul> diff --git a/files/pt-pt/web/api/filereader/readasarraybuffer/index.html b/files/pt-pt/web/api/filereader/readasarraybuffer/index.html new file mode 100644 index 0000000000..d5122d8096 --- /dev/null +++ b/files/pt-pt/web/api/filereader/readasarraybuffer/index.html @@ -0,0 +1,64 @@ +--- +title: FileReader.readAsArrayBuffer() +slug: Web/API/FileReader/readAsArrayBuffer +tags: + - API + - DOM + - Ficheiros + - File API + - FileReader + - Referencia + - metodo + - readAsArrayBuffer +translation_of: Web/API/FileReader/readAsArrayBuffer +--- +<p>{{APIRef("File API")}}</p> + +<p>O método <code>readAsArrayBuffer()</code> da interface {{domxref("FileReader")}} é utilizado para começar a ler o conteúdo de um {{domxref("Blob")}} ou {{domxref("File")}} especificado. Quando a operação de leitura termina, o valor de {{domxref("FileReader.readyState","readyState")}} passa a ser <code>DONE</code>, e é acionado o evento {{domxref("FileReader/loadend_event", "loadend")}}. Nessa altura, o atributo {{domxref("FileReader.result","result")}} contém um {{domxref("ArrayBuffer")}} representando os dados do ficheiro.</p> + +<div class="blockIndicator note"> +<p><strong>API mais recente</strong><br> + O método {{domxref("Blob.arrayBuffer()")}} é uma API recente que serve para ler um ficheiro como um <em>array buffer</em>, usando <em>Promises</em>.</p> +</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>instanceOfFileReader</var>.readAsArrayBuffer(<var>blob</var>);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code><var>blob</var></code></dt> + <dd>O {{domxref("Blob")}} ou {{domxref("File")}} a partir do qual ler.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("File API", "#readAsArrayBuffer", "FileReader.readAsArrayBuffer")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.FileReader.readAsArrayBuffer")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/filereader/readasbinarystring/index.html b/files/pt-pt/web/api/filereader/readasbinarystring/index.html new file mode 100644 index 0000000000..44911105e6 --- /dev/null +++ b/files/pt-pt/web/api/filereader/readasbinarystring/index.html @@ -0,0 +1,85 @@ +--- +title: FileReader.readAsBinaryString() +slug: Web/API/FileReader/readAsBinaryString +tags: + - API + - Ficheiros + - File API + - Referencia + - metodo +translation_of: Web/API/FileReader/readAsBinaryString +--- +<p>{{APIRef("File API")}}</p> + +<p>O método <code>readAsBinaryString</code> é usado para iniciar a leitura dos conteúdos do {{domxref("Blob")}} ou {{domxref("File")}} indicado. Quando a operação da leitura é terminada, o {{domxref("FileReader.readyState","readyState")}} retorna <code>DONE</code>, e o {{event("loadend")}} é acionado. A propriedade {{domxref("FileReader.result","result")}} depois contem o binário bruto do ficheiro.</p> + +<p>Note que este método foi removido do File API, mas foi reintroduzido por motivos de compatibilidade com versões antigas.<br> + É recomendado usar {{domxref("FileReader.readAsArrayBuffer()")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="notranslate"><em>instanceOfFileReader</em>.readAsBinaryString(blob);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>blob</code></dt> + <dd>O {{domxref("Blob")}} ou {{domxref("File")}} a ser lido.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js notranslate">var canvas = document.createElement('canvas'); +var height = 200; +var width = 200; + +canvas.width = width; +canvas.height = height; + +var ctx = canvas.getContext('2d'); + +ctx.strokeStyle = '#090'; +ctx.beginPath(); +ctx.arc(width/2, height/2, width/2 - width/10, 0, Math.PI*2); +ctx.stroke(); + +canvas.toBlob(function (blob) { + var reader = new FileReader(); + + reader.onloadend = function () { + console.log(reader.result); + } + + reader.readAsBinaryString(blob); +});</pre> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Especificações</h2> + +<table class="spectable standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File API','#readAsBinaryString','readAsBinaryString')}}</td> + <td>{{Spec2('File API')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidade</h2> + + + +<p>{{Compat("api.FileReader.readAsBinaryString")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/filereader/readasdataurl/index.html b/files/pt-pt/web/api/filereader/readasdataurl/index.html new file mode 100644 index 0000000000..321d50d3ce --- /dev/null +++ b/files/pt-pt/web/api/filereader/readasdataurl/index.html @@ -0,0 +1,133 @@ +--- +title: FileReader.readAsDataURL() +slug: Web/API/FileReader/readAsDataURL +tags: + - API + - Base 64 + - Ficheiros + - File API + - FileReader + - Referencia + - metodo +translation_of: Web/API/FileReader/readAsDataURL +--- +<p>O método <code>readAsDataURL</code> é utilizado para ler os conteúdos dum {{domxref("Blob")}} ou {{domxref("File")}} especificado. Quando a operação de leitura é terminada, a propriedade {{domxref("FileReader.readyState","readyState")}} é atualizada para <code>DONE</code>, e o evento {{event("loadend")}} é lançado. Nessa altura, o atributo {{domxref("FileReader.result","result")}} contem os dados na forma <a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs">data: URL</a> que representa os dados do ficheiro em base 64 numa <em>string</em>.</p> + +<div class="note"> +<p><strong>Nota:</strong> O{{domxref("FileReader.result","result")}} da Blob não pode ser diretamente descodificado como Base64 sem remover a declaração Data-URL que precede os dados em Base64. Para ter só a <em>string</em> em Base64, primeiro tem de remover o <code>data:*/*;base64,</code> do resultado.</p> +</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><em>instanceOfFileReader</em>.readAsDataURL(blob);</pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>blob</code></dt> + <dd>O {{domxref("Blob")}} ou {{domxref("File")}} para ler.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html notranslate"><input type="file" onchange="previewFile()"><br> +<img src="" height="200" alt="Image preview..."></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js notranslate">function previewFile() { + const preview = document.querySelector('img'); + const file = document.querySelector('input[type=file]').files[0]; + const reader = new FileReader(); + + reader.addEventListener("load", function () { + // converter o file de imagem oara uma string de base 64 + preview.src = reader.result; + }, false); + + if (file) { + reader.readAsDataURL(file); + } +}</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{EmbedLiveSample("Exemplo", "100%", 240)}}</p> + +<h2 id="Exemplo_de_vários_files">Exemplo de vários files</h2> + +<h3 id="HTML_2">HTML</h3> + +<pre class="brush: html notranslate"><input id="browse" type="file" onchange="previewFiles()" multiple> +<div id="preview"></div></pre> + +<h3 id="JavaScript_2">JavaScript</h3> + +<pre class="brush: js notranslate">function previewFiles() { + + var preview = document.querySelector('#preview'); + var files = document.querySelector('input[type=file]').files; + + function readAndPreview(file) { + + // Make sure `file.name` matches our extensions criteria + if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { + var reader = new FileReader(); + + reader.addEventListener("load", function () { + var image = new Image(); + image.height = 100; + image.title = file.name; + image.src = this.result; + preview.appendChild( image ); + }, false); + + reader.readAsDataURL(file); + } + + } + + if (files) { + [].forEach.call(files, readAndPreview); + } + +} +</pre> + +<div class="note"><strong>Nota:</strong> O construtor <a href="/en-US/docs/Web/API/FileReader"><code>FileReader()</code></a> não é apoiado pela Internet Explorer anterior à versão 10. Para obter código totalmente compatível veja a nossa <a class="internal" href="https://mdn.mozillademos.org/files/3699/crossbrowser_image_preview.html" title="crossbrowser_image_preview.html">solução <em>crossbrowser</em> para pré-visualizar imagens</a>. Veja também <a href="https://mdn.mozillademos.org/files/3698/image_upload_preview.html">este exemplo mais complexo</a>.</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("File API", "#readAsDataURL", "readAsDataURL()")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.FileReader.readAsDataURL")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> + <li>{{domxref("URL.createObjectURL()")}}</li> +</ul> + +<div>{{APIRef("File API")}}</div> diff --git a/files/pt-pt/web/api/filereader/readastext/index.html b/files/pt-pt/web/api/filereader/readastext/index.html new file mode 100644 index 0000000000..d8f821e7ab --- /dev/null +++ b/files/pt-pt/web/api/filereader/readastext/index.html @@ -0,0 +1,63 @@ +--- +title: FileReader.readAsText() +slug: Web/API/FileReader/readAsText +tags: + - API + - Ficheiros + - File API + - Referencia + - metodo +translation_of: Web/API/FileReader/readAsText +--- +<div>{{APIRef("File API")}}</div> + +<p>O método <strong><code>readAsText()</code></strong> é utilizado para ler os conteúdos do {{domxref("Blob")}} ou {{domxref("File")}} indicado. Quando a operação de leitura é terminada, a propriedade {{domxref("FileReader.readyState","readyState")}} é modificada para <code>DONE</code>, o evento {{event("loadend")}} é lançado, e a propriedade {{domxref("FileReader.result","result")}} fica com os conteúdos do ficheiro em forma de <em>string</em>.</p> + +<div class="blockIndicator note"> +<p><strong>API mais recente disponível</strong><br> + {{domxref("Blob.text()")}} é um método mais recente, baseado na API de promessas, para ler um ficheiro como uma <em>string</em>.</p> +</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><em>instanceOfFileReader</em>.readAsText(blob[, encoding]);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>blob</code></dt> + <dd>O {{domxref("Blob")}} ou {{domxref("File")}} de qual ler.</dd> + <dt><code>encoding</code> {{optional_inline}}</dt> + <dd>Uma <em>string</em> a especificar qual codificação usar para os dados devolvidos. A UTF-8 é utilizada se não for definido.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("File API", "#readAsDataText", "readAsText()")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.FileReader.readAsText")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/filereader/readystate/index.html b/files/pt-pt/web/api/filereader/readystate/index.html new file mode 100644 index 0000000000..1147e43f29 --- /dev/null +++ b/files/pt-pt/web/api/filereader/readystate/index.html @@ -0,0 +1,96 @@ +--- +title: FileReader.readyState +slug: Web/API/FileReader/readyState +tags: + - API + - Ficheiros + - File API + - Propriedade + - Referencia +translation_of: Web/API/FileReader/readyState +--- +<div>{{APIRef("File API")}}</div> + +<p>A propriedade <strong><code>readyState</code></strong> de {{domxref("FileReader")}} fornece o estado actual da operação de leitura em que se encontra um <code>FileReader</code>. Um <code>FileReader</code> existe num dos seguintes estados:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Valor</th> + <th scope="col">Estado</th> + <th scope="col">Descrição</th> + </tr> + <tr> + <td><code>0</code></td> + <td><code>EMPTY</code></td> + <td>Foi criado um leitor. Nenhum dos métodos de leitura foi ainda chamado.</td> + </tr> + <tr> + <td><code>1</code></td> + <td><code>LOADING</code></td> + <td>Foi chamado um método de leitura.</td> + </tr> + <tr> + <td><code>2</code></td> + <td><code>DONE</code></td> + <td>A operação está concluída.</td> + </tr> + </thead> +</table> + +<dl> + <dt><code>EMPTY</code></dt> + <dd>O <code>FileReader</code> foi criado, mas ainda não foi chamado o método <code>readAs</code>.</dd> + <dt><code>LOADING</code></dt> + <dd>Foi invocado o método <code>readAs</code>. O {{domxref("File")}} ou {{domxref("Blob")}} está a ser lido, e ainda não ocorreu qualquer erro.</dd> + <dt><code>DONE</code></dt> + <dd>A operação lida está concluída. Isto pode significar que: todo o {{domxref("File")}} ou {{domxref("Blob")}} foi lido na memória, ocorreu um erro de leitura de ficheiro, ou {{domxref("FileReader.abort()", "abort()")}} foi chamado e a leitura foi cancelada.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js notranslate">var reader = new FileReader(); +console.log('EMPTY', reader.readyState); // readyState é 0 + +reader.readAsText(blob); +console.log('LOADING', reader.readyState); // readyState é 1 + +reader.onloadend = function () { + console.log('DONE', reader.readyState); // readyState é 2 +}; +</pre> + +<h2 id="Valor">Valor</h2> + +<p>Um número que é uma das três constantes de estado possíveis definidas para o {{domxref("FileReader")}} API.</p> + +<h2 id="Especificação">Especificação</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("File API", "#dom-filereader-readystate", "readyState")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.FileReader.readyState")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("Blob")}}</li> +</ul> diff --git a/files/pt-pt/web/api/filereader/result/index.html b/files/pt-pt/web/api/filereader/result/index.html new file mode 100644 index 0000000000..ea7ddd4bbd --- /dev/null +++ b/files/pt-pt/web/api/filereader/result/index.html @@ -0,0 +1,105 @@ +--- +title: FileReader.result +slug: Web/API/FileReader/result +tags: + - API + - Ficheiros + - File API + - FileReader + - Propriedade + - Referencia + - result +translation_of: Web/API/FileReader/result +--- +<div>{{APIRef("File API")}}</div> + +<p>A propriedade <code><strong>result</strong></code> de {{domxref("FileReader")}} devolve os conteúdo do ficheiro. Esta propriedade só é válida após a operação de leitura estar concluída, e o formato dos dados depende de qual método foi utilizado para iniciar a operação de leitura.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <var>file</var> = <var>instanceOfFileReader</var>.result +</pre> + +<h3 id="Valor">Valor</h3> + +<p>Uma <em>string</em> ou {{jsxref("ArrayBuffer")}} apropriado com base em qual dos métodos de leitura foi utilizado para iniciar a operação de leitura. O valor é <code>null</code> se a leitura ainda não estiver completa ou não foi bem sucedida.</p> + +<p>Os resultados são descritos abaixo.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Método</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{domxref("FileReader/readAsArrayBuffer", "readAsArrayBuffer()")}}</td> + <td>O <code>result</code> é um {{jsxref("Global_Objects/ArrayBuffer", "ArrayBuffer")}} de JavaScript que contem dados binários.</td> + </tr> + <tr> + <td>{{domxref("FileReader/readAsBinaryString", "readAsBinaryString()")}}</td> + <td>O <code>result</code> contém os dados binários brutos do ficheiro numa <em>string</em>.</td> + </tr> + <tr> + <td>{{domxref("FileReader/readAsDataURL", "readAsDataURL()")}}</td> + <td>O <code>result</code> é uma string com uma <code>data:</code> URL que representa os dados do ficheiro.</td> + </tr> + <tr> + <td>{{domxref("FileReader/readAsText", "readAsText()")}}</td> + <td>O <code>result</code> ié texto numa <em>string</em>.</td> + </tr> + </tbody> +</table> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Este exemplo apresenta uma função, <code>read()</code>, que lê um ficheiro a partir de uma <a href="/en-US/docs/Web/HTML/Element/input/file">entrada de ficheiro</a>. Funciona criando um objecto {{domxref("FileReader")}} e criando um ouvinte para eventos {{domxref("FileReader/load_event", "load")}}, de modo que quando o ficheiro é lido, o <code>result</code> é obtido e passado para a função callback fornecida para <code>read()</code>.</p> + +<p>O conteúdo é tratado como dados de texto brutos.</p> + +<pre class="brush: js notranslate">var fileInput = document.querySelector('input[type="file"]'); + +function read(callback) { + var file = fileInput.files.item(0); + var reader = new FileReader(); + + reader.onload = function() { + callback(reader.result); + } + + reader.readAsText(file); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("File API", "#dom-filereader-result", "result")}}</td> + <td>{{Spec2("File API")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.FileReader.result")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("FileReader")}}</li> +</ul> diff --git a/files/pt-pt/web/api/geolocation/index.html b/files/pt-pt/web/api/geolocation/index.html new file mode 100644 index 0000000000..39a22949bb --- /dev/null +++ b/files/pt-pt/web/api/geolocation/index.html @@ -0,0 +1,223 @@ +--- +title: Geolocalização +slug: Web/API/Geolocation +tags: + - API + - API de Geolocalização + - Avançada + - Contexto de segurança + - Interface + - Referencia +translation_of: Web/API/Geolocation +--- +<div>{{securecontext_header}}{{APIRef("Geolocation API")}}</div> + +<p>A interface de <code><strong>Geolocalização</strong></code> representa um objeto capaz de obter programaticamente a posição do dispositivo. Esta dá acesso ao conteúdo da Web para a localização do dispositivo. Isto permite que um site da Web ou aplicação ofereça resultados personalizados com base na localização do utilizador.</p> + +<p>Um objeto com esta interface é obtido utilizando a propriedade {{domxref("navigator.geolocation")}} implementada pelo objeto {{domxref("Navigator")}}.</p> + +<div class="note"> +<p><strong>Nota:</strong> por motivos de segurança, quando uma página da Web tenta aceder à informação da localização, o utilizador é notificado e é-lhe solicitado para dar permissão. Tenha em atenção que cada navegador tem as suas próprias políticas e métodos para solicitarem esta permissão.</p> +</div> + +<h2 id="Propriedades">Propriedades</h2> + +<p><em>A interface de <code>Geolocalização</code> não implementa, nem adquire qualquer propriedade.</em></p> + +<h2 id="Métodos">Métodos</h2> + +<p><em><em>A interface de <code>Geolocalização</code> não </em>adquire qualquer propriedade</em>.</p> + +<dl> + <dt>{{domxref("Geolocation.getCurrentPosition()")}} {{securecontext_inline}}</dt> + <dd>Determina a localização do dispositivo e devolve um objeto de {{domxref("Position")}} com os dados.</dd> + <dt>{{domxref("Geolocation.watchPosition()")}} {{securecontext_inline}}</dt> + <dd>Devolve um valor <code>longo</code> representando a nova função <em>estabelecida callback</em> para ser invocada sempre que a localização do dispositivo for alterada.</dd> + <dt>{{domxref("Geolocation.clearWatch()")}} {{securecontext_inline}}</dt> + <dd>Remove o manipulador particular instalado anteriormente, utilizando <code>watchPosition()</code>.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Geolocation')}}</td> + <td>{{Spec2('Geolocation')}}</td> + <td>Especificação inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>5</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>9</td> + <td>10.60<br> + Removed in 15.0<br> + Reintroduced in 16.0</td> + <td>5</td> + </tr> + <tr> + <td>Apenas contexto de segurança</td> + <td>47</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoDesktop("55")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("4")}}</td> + <td>{{CompatUnknown()}}</td> + <td>10.60</td> + <td>{{CompatUnknown()}}</td> + </tr> + <tr> + <td>Apenas contexto de segurança</td> + <td>{{CompatNo}}</td> + <td>47</td> + <td>{{CompatUnknown()}}</td> + <td>{{CompatGeckoDesktop("55")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/Geolocation/Utilizacao_da_geolocalizacao" title="/en-US/docs/WebAPI/Using_geolocation">API de geolocalização</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: 0% 0% repeat scroll rgba(0, 0, 0, 0); display: none; opacity: 1; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html b/files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html new file mode 100644 index 0000000000..40fb7ce571 --- /dev/null +++ b/files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html @@ -0,0 +1,242 @@ +--- +title: API de Geolocalização +slug: Web/API/Geolocation/Utilizacao_da_geolocalizacao +tags: + - API de Geolocalização + - Guía + - Intermediário +translation_of: Web/API/Geolocation_API +--- +<p>{{securecontext_header}}{{APIRef("Geolocation API")}}</p> + +<p>A <strong>API de geolocalização </strong>permite que o utilizador forneça a sua localização nas aplicações da Web, se assim o desejar. Por motivos de segurança, é solicitado ao utilizador para dar permissão para informar a informação da localização.</p> + +<h2 id="O_objeto_de_geolocalização">O objeto de geolocalização</h2> + +<p>A API de <a href="/pt-PT/docs/Web/API/Geolocation">Geolocation</a> é publicada através do objeto {{domxref("navigator.geolocation")}}.</p> + +<p>Se o objeto existir, os serviços de geolocalização estarão disponíveis. Pode testar a presença de geolocalização assim:</p> + +<pre class="brush: js">if ("geolocation" in navigator) { + /* geolocation is available */ +} else { + /* geolocation IS NOT available */ +} +</pre> + +<div class="note"> +<p><strong>Nota:</strong> On Firefox 24 and older versions, <code>"geolocation" in navigator</code> always returned <code>true</code> even if the API was disabled. This has been fixed with <a href="/en-US/docs/Mozilla/Firefox/Releases/25/Site_Compatibility">Firefox 25</a> to comply with the spec. ({{bug(884921)}}).</p> +</div> + +<h3 id="Obter_a_posição_atual">Obter a posição atual</h3> + +<p>To obtain the user's current location, you can call the {{domxref("geolocation.getCurrentPosition()","getCurrentPosition()")}} method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.</p> + +<div class="note"> +<p><strong>Nota:</strong> By default, {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or wifi) may be returned to {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.</p> +</div> + +<pre class="brush: js">navigator.geolocation.getCurrentPosition(function(position) { + do_something(position.coords.latitude, position.coords.longitude); +});</pre> + +<p>The above example will cause the <code>do_something()</code> function to execute when the location is obtained.</p> + +<h3 id="Vigiar_a_posição_atual">Vigiar a posição atual</h3> + +<p>If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the {{domxref("Geolocation.watchPosition()","watchPosition()")}} function, which has the same input parameters as {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}, can be called repeatedly.</p> + +<div class="note"> +<p><strong>Nota:</strong> pode utilizar {{domxref("Geolocation.watchPosition()","watchPosition()")}} sem uma chamada inicial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.</p> +</div> + +<pre class="brush: js">var watchID = navigator.geolocation.watchPosition(function(position) { + do_something(position.coords.latitude, position.coords.longitude); +});</pre> + +<p>The {{domxref("Geolocation.watchPosition()","watchPosition()")}} method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the {{domxref("Geolocation.clearWatch()","clearWatch()")}} method to stop watching the user's location.</p> + +<pre class="brush: js">navigator.geolocation.clearWatch(watchID); +</pre> + +<h3 id="Resposta_de_ajuste_preciso">Resposta de ajuste preciso</h3> + +<p>Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional <a href="/en-US/docs/Web/API/PositionOptions">PositionOptions</a> object.</p> + +<p>{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}</p> + +<p>A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:</p> + +<pre class="brush: js">function geo_success(position) { + do_something(position.coords.latitude, position.coords.longitude); +} + +function geo_error() { + alert("Sorry, no position available."); +} + +var geo_options = { + enableHighAccuracy: true, + maximumAge : 30000, + timeout : 27000 +}; + +var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);</pre> + +<h2 id="Descrever_uma_posição">Descrever uma posição</h2> + +<p>The user's location is described using a <code>Position</code> object referencing a <code>Coordinates</code> object.</p> + +<p>{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}</p> + +<p>{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}</p> + +<h2 id="Lidar_com_erros">Lidar com erros</h2> + +<p>The error callback function, if provided when calling <code>getCurrentPosition()</code> or <code>watchPosition()</code>, expects a <a href="/en-US/docs/Web/API/PositionError">PositionError</a> object as its first parameter.</p> + +<pre class="brush: js">function errorCallback(error) { + alert('ERROR(' + error.code + '): ' + error.message); +}; +</pre> + +<p>{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}</p> + +<h2 id="Exemplo_de_Geolocalização_Live">Exemplo de Geolocalização <em>Live</em></h2> + +<div class="hidden"> +<pre class="brush: css">body { + padding: 20px; + background-color:#ffffc9 +} + +p { margin : 0; } +</pre> +</div> + +<h3 id="Conteúdo_HTML">Conteúdo HTML</h3> + +<pre class="brush: html;"><p><button onclick="geoFindMe()">Show my location</button></p> +<div id="out"></div> +</pre> + +<h3 id="Conteúdo_JavaScript">Conteúdo JavaScript</h3> + +<pre class="brush: js;">function geoFindMe() { + var output = document.getElementById("out"); + + if (!navigator.geolocation){ + output.innerHTML = "<p>Geolocation is not supported by your browser</p>"; + return; + } + + function success(position) { + var latitude = position.coords.latitude; + var longitude = position.coords.longitude; + + output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>'; + + var img = new Image(); + img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false"; + + output.appendChild(img); + } + + function error() { + output.innerHTML = "Unable to retrieve your location"; + } + + output.innerHTML = "<p>Locating…</p>"; + + navigator.geolocation.getCurrentPosition(success, error); +} +</pre> + +<h3 id="Resultado_Live">Resultado <em>Live</em></h3> + +<p>{{EmbedLiveSample('Geolocation_Live_Example', 350, 410)}}</p> + +<h2 id="Aviso_para_permissão">Aviso para permissão</h2> + +<p>Any add-on hosted on <a href="https://addons.mozilla.org/">addons.mozilla.org</a> which makes use of geolocation data must explicitly request permission before doing so. The following function will request permission in a manner similar to the automatic prompt displayed for web pages. The user's response will be saved in the preference specified by the <code>pref</code> parameter, if applicable. The function provided in the <code>callback</code> parameter will be called with a boolean value indicating the user's response. If <code>true</code>, the add-on may access geolocation data.</p> + +<pre class="brush: js">function prompt(window, pref, message, callback) { + let branch = Components.classes["@mozilla.org/preferences-service;1"] + .getService(Components.interfaces.nsIPrefBranch); + + if (branch.getPrefType(pref) === branch.PREF_STRING) { + switch (branch.getCharPref(pref)) { + case "always": + return callback(true); + case "never": + return callback(false); + } + } + + let done = false; + + function remember(value, result) { + return function() { + done = true; + branch.setCharPref(pref, value); + callback(result); + } + } + + let self = window.PopupNotifications.show( + window.gBrowser.selectedBrowser, + "geolocation", + message, + "geo-notification-icon", + { + label: "Share Location", + accessKey: "S", + callback: function(notification) { + done = true; + callback(true); + } + }, [ + { + label: "Always Share", + accessKey: "A", + callback: remember("always", true) + }, + { + label: "Never Share", + accessKey: "N", + callback: remember("never", false) + } + ], { + eventCallback: function(event) { + if (event === "dismissed") { + if (!done) callback(false); + done = true; + window.PopupNotifications.remove(self); + } + }, + persistWhileVisible: true + }); +} + +prompt(window, + "extensions.foo-addon.allowGeolocation", + "Foo Add-on wants to know your location.", + function callback(allowed) { alert(allowed); }); +</pre> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{Compat("api.Geolocation")}}</p> + +<h3 id="Disponibilidade">Disponibilidade</h3> + +<p>Como a localização baseada em Wi-Fi é geralmente fornecida pelo Google, a API de Geolocalização "vanilla" pode estar indisponível na China. Pode utilizar os provedores locais de terceiros, tais como <a href="http://lbsyun.baidu.com/index.php?title=jspopular/guide/geolocation">Baidu</a>, <a href="https://lbs.amap.com/api/javascript-api/guide/services/geolocation#geolocation">Autonavi</a>, ou <a href="http://lbs.qq.com/tool/component-geolocation.html">Tencent</a>. Estes serviços utilziam o endereço de IP do utilizador e/ou uma aplicação local para fornecer o posicionamento melhorado.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{domxref("navigator.geolocation")}}</li> + <li><a href="https://developer.mozilla.org/pt-PT/docs/Web/Apps/Fundamentals/gather_and_modify_data/Plotting_yourself_on_the_map">Localizar-se no mapa</a></li> + <li><a href="https://www.w3.org/TR/geolocation-API/" rel="external">API de Geolocation em w3.org</a></li> + <li><a href="https://hacks.mozilla.org/2013/10/who-moved-my-geolocation/">Quem moveu a minha geolocalização?</a> (Blogue de <em>Hacks</em>)</li> +</ul> diff --git a/files/pt-pt/web/api/index.html b/files/pt-pt/web/api/index.html new file mode 100644 index 0000000000..196c30c28f --- /dev/null +++ b/files/pt-pt/web/api/index.html @@ -0,0 +1,14 @@ +--- +title: APIs da Web (Interfaces) +slug: Web/API +tags: + - API + - DOM + - JavaScript + - Referencia + - Web +translation_of: Web/API +--- +<p>Quando escrever código para a Web com Javascript, estão disponíveis muitas APIs excelentes. Em baixo, tem uma lista de interfaces (ou seja, tipos de objetos) que poderá utilizar durante o desenvolvimento da sua aplicaçao ou site da <em>Web</em>.</p> + +<p>{{APIListAlpha}}</p> diff --git a/files/pt-pt/web/api/mathmlelement/index.html b/files/pt-pt/web/api/mathmlelement/index.html new file mode 100644 index 0000000000..ee2504017a --- /dev/null +++ b/files/pt-pt/web/api/mathmlelement/index.html @@ -0,0 +1,72 @@ +--- +title: MathMLElement +slug: Web/API/MathMLElement +tags: + - API + - Interface + - MathML + - MathMLElement + - Referencia +translation_of: Web/API/MathMLElement +--- +<div>{{APIRef("MathML")}}</div> + +<p class="summary">A interface <strong><code>MathMLElement</code></strong> representa qualquer elemento <a href="/pt-PT/docs/Web/MathML">MathML</a>.</p> + +<h2 id="Propiedades">Propiedades</h2> + +<p><em>Esta interface não tem propriedades, mas herda propriedades de: {{DOMxRef("DocumentAndElementEventHandlers")}}, {{DOMxRef("Element")}}, {{DOMxRef("ElementCSSInlineStyle")}}, {{DOMxRef("GlobalEventHandlers")}}, {{DOMxRef("HTMLOrForeignElement")}}</em></p> + +<ul> +</ul> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interface não tem métodos, mas herda métodos de: {{DOMxRef("DocumentAndElementEventHandlers")}}, {{DOMxRef("Element")}}, {{DOMxRef("ElementCSSInlineStyle")}}, {{DOMxRef("GlobalEventHandlers")}}, {{DOMxRef("HTMLOrForeignElement")}}</em></p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="MathML">MathML</h3> + +<pre class="brush: html notranslate"><math xmlns="http://www.w3.org/1998/Math/MathML"> + <msqrt> + <mi>x</mi> + </msqrt> +</math></pre> + +<h3 id="JavaScript">JavaScript</h3> + +<pre class="brush: js notranslate">document.querySelector('msqrt').constructor.name; // MathMLElement</pre> + +<h2 id="Specification" name="Specification">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="https://mathml-refresh.github.io/mathml-core/#dom-mathmlelement">MathMLElement interface</a></td> + <td></td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.MathMLElement")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{DOMxRef("Element")}}</li> + <li>{{DOMxRef("HTMLElement")}}</li> + <li>{{DOMxRef("SVGElement")}}</li> +</ul> diff --git a/files/pt-pt/web/api/mediadevices/index.html b/files/pt-pt/web/api/mediadevices/index.html new file mode 100644 index 0000000000..68ea5de783 --- /dev/null +++ b/files/pt-pt/web/api/mediadevices/index.html @@ -0,0 +1,263 @@ +--- +title: MediaDevices +slug: Web/API/MediaDevices +tags: + - API + - Devices + - Interface + - Media + - Media Capture and Streams API + - Media Streams API + - MediaDevices + - NeedsTranslation + - Reference + - TopicStub + - WebRTC +translation_of: Web/API/MediaDevices +--- +<div>{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}</div> + +<p><span class="seoSummary">The <strong><code>MediaDevices</code></strong> interface provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data.</span></p> + +<h2 id="Properties">Properties</h2> + +<p><em>Inherits properties from its parent {{domxref("EventTarget")}}.</em></p> + +<h3 id="Handlers" name="Handlers">Event handlers</h3> + +<dl> + <dt>{{ domxref("MediaDevices.ondevicechange") }}</dt> + <dd>The event handler for the {{event("devicechange")}} event. This event is delivered to the <code>MediaDevices</code> object when a media input or output device is attached to or removed from the user's computer.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>Inherits methods from its parent {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{ domxref("EventTarget.addEventListener()") }}</dt> + <dd>Registers an event handler to a specific event type.</dd> + <dt>{{ domxref("MediaDevices.enumerateDevices()") }}</dt> + <dd>Obtains an array of information about the media input and output devices available on the system.</dd> + <dt>{{domxref("MediaDevices.getSupportedConstraints()")}}</dt> + <dd>Returns an object conforming to {{domxref("MediaTrackSupportedConstraints")}} indicating which constrainable properties are supported on the {{domxref("MediaStreamTrack")}} interface. See {{SectionOnPage("/en-US/docs/Web/API/Media_Streams_API", "Capabilities and constraints")}} to learn more about constraints and how to use them.</dd> + <dt>{{ domxref("MediaDevices.getUserMedia()") }}</dt> + <dd>With the user's permission through a prompt, turns on a camera or screensharing and/or a microphone on the system and provides a {{domxref("MediaStream")}} containing a video track and/or an audio track with the input.</dd> + <dt>{{ domxref("EventTarget.removeEventListener()") }}</dt> + <dd>Removes an event listener.</dd> +</dl> + +<h2 id="Example">Example</h2> + +<pre class="brush:js">'use strict'; + +// Put variables in global scope to make them available to the browser console. +var video = document.querySelector('video'); +var constraints = window.constraints = { + audio: false, + video: true +}; +var errorElement = document.querySelector('#errorMsg'); + +navigator.mediaDevices.getUserMedia(constraints) +.then(function(stream) { + var videoTracks = stream.getVideoTracks(); + console.log('Got stream with constraints:', constraints); + console.log('Using video device: ' + videoTracks[0].label); + stream.onremovetrack = function() { + console.log('Stream ended'); + }; + window.stream = stream; // make variable available to browser console + video.srcObject = stream; +}) +.catch(function(error) { + if (error.name === 'ConstraintNotSatisfiedError') { + errorMsg('The resolution ' + constraints.video.width.exact + 'x' + + constraints.video.width.exact + ' px is not supported by your device.'); + } else if (error.name === 'PermissionDeniedError') { + errorMsg('Permissions have not been granted to use your camera and ' + + 'microphone, you need to allow the page access to your devices in ' + + 'order for the demo to work.'); + } + errorMsg('getUserMedia error: ' + error.name, error); +}); + +function errorMsg(msg, error) { + errorElement.innerHTML += '<p>' + msg + '</p>'; + if (typeof error !== 'undefined') { + console.error(error); + } +}</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Media Capture', '#mediadevices', 'MediaDevices')}}</td> + <td>{{Spec2('Media Capture')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(47)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("36.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(30)}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>enumerateDevices()</code></td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(38)}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>getSupportedConstraints()</code></td> + <td>{{CompatChrome(53)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(44)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(40)}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>ondevicechange</code> and <code>devicechange</code> events</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(51)}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Stereo audio capture</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(55)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(47)}}</td> + <td>{{CompatChrome(47)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("36.0")}}</td> + <td>2.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatOperaMobile(30)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>enumerateDevices()</code></td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOperaMobile(38)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>getSupportedConstraints()</code></td> + <td>{{CompatChrome(53)}}</td> + <td>{{CompatChrome(52)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(50)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOperaMobile(40)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>ondevicechange</code> and <code>devicechange</code> events</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(51)}}<sup>[1]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Stereo audio capture</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> + +<p>[1] Support for the <code>devicechange</code> event and for {{domxref("MediaDevices.ondevicechange")}} landed in Firefox 51, but <em>only for Mac</em>, and disabled by default. It can be enabled by setting the preference <code>media.ondevicechange.enabled</code> to <code>true</code>. Support for this event was added for Linux and Windows—and it was enabled by default—starting in Firefox 52.</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Media_Streams_API">Media Capture and Streams API</a>: The API this interface is part of.</li> + <li><a href="/en-US/docs/Web/API/WebRTC_API">WebRTC API</a></li> + <li>{{domxref("Navigator.mediaDevices")}}: Returns a reference to a <code>MediaDevices</code> object that can be used to access devices.</li> + <li><a href="https://github.com/chrisjohndigital/CameraCaptureJS">CameraCaptureJS:</a> HTML5 video capture and playback using MediaDevices and the MediaStream Recording API (<a href="https://github.com/chrisjohndigital/CameraCaptureJS">source on GitHub</a>)</li> + <li><a href="https://github.com/chrisjohndigital/OpenLang">OpenLang</a>: HTML5 video language lab web application using MediaDevices and the MediaStream Recording API for video recording (<a href="https://github.com/chrisjohndigital/OpenLang">source on GitHub</a>)</li> +</ul> diff --git a/files/pt-pt/web/api/messageevent/index.html b/files/pt-pt/web/api/messageevent/index.html new file mode 100644 index 0000000000..f69342523b --- /dev/null +++ b/files/pt-pt/web/api/messageevent/index.html @@ -0,0 +1,139 @@ +--- +title: MessageEvent +slug: Web/API/MessageEvent +tags: + - API + - Canais + - Interface + - Mensagens + - Referencia + - WebSockets + - Window + - Workers +translation_of: Web/API/MessageEvent +--- +<div>{{APIRef("HTML DOM")}}</div> + +<p>A interface <code><strong>MessageEvent</strong></code> representa a mensagem recebida pelo objeto alvo.</p> + +<p>É usado para representar mensagens em:</p> + +<ul> + <li><a href="/en-US/docs/Web/API/Server-sent_events">Eventos enviados pelo servidor</a> (ver {{domxref("EventSource.onmessage")}}).</li> + <li><a href="/pt-PT/docs/Web/API/WebSockets_API">Web sockets</a> (ver a propriedade <code>onmessage</code> da interface <a href="/en-US/docs/Web/API/WebSocket">WebSocket</a>).</li> + <li>Envio de mensagens entre-documentos (ver {{domxref("Window.postMessage()")}} e {{domxref("Window.onmessage")}}).</li> + <li><a href="/en-US/docs/Web/API/Channel_Messaging_API">Mensagens em canal</a> (ver {{domxref("MessagePort.postMessage()")}} e {{domxref("MessagePort.onmessage")}}).</li> + <li>Envio de mensagens entre-documentos e entre-<em>workers</em> (ver as duas entradas acima, e tembém {{domxref("Worker.postMessage()")}}, {{domxref("Worker.onmessage")}}, {{domxref("ServiceWorkerGlobalScope.onmessage")}}, etc.)</li> + <li><a href="/en-US/docs/Web/API/Broadcast_Channel_API">Canais de transmissão</a> (ver {{domxref("Broadcastchannel.postMessage()")}}) e {{domxref("BroadcastChannel.onmessage")}}).</li> + <li>Canais de transmissão de WebRTC (ver {{domxref("RTCDataChannel.onmessage")}}).</li> +</ul> + +<p>A ação acionada por este evento é definida na função escolhida para ser o <em>event handler</em> do evento {{event("message")}} relevante (e.x. usar um <em>handler</em> <code>onmessage</code> como é menciondo antriormente).</p> + +<p>{{AvailableInWorkers}}<br> + {{InheritanceDiagram(600, 80)}}</p> + +<h2 id="Construtor">Construtor</h2> + +<dl> + <dt>{{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}</dt> + <dd>Cria um <code>MessageEvent</code>.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<p><em>Esta interface também herda propriedades da interface {{domxref("Event")}}, </em> <em>de qual se deriva</em><em>.</em></p> + +<dl> + <dt>{{domxref("MessageEvent.data")}} {{readonlyInline}}</dt> + <dd>Os dados enviados pelo emissor da mensagem.</dd> + <dt>{{domxref("MessageEvent.origin")}} {{readonlyInline}}</dt> + <dd>Uma {{domxref("USVString")}} que representa a origem do emissor da mensagem.</dd> + <dt>{{domxref("MessageEvent.lastEventId")}} {{readonlyInline}}</dt> + <dd>Uma {{domxref("DOMString")}} que representa um ID único para o evento.</dd> + <dt>{{domxref("MessageEvent.source")}} {{readonlyInline}}</dt> + <dd>Uma <code>MessageEventSource</code> (que pode ser um objeto {{domxref("WindowProxy")}}, {{domxref("MessagePort")}}, ou {{domxref("ServiceWorker")}}) que representa o emissor da mensagem.</dd> + <dt>{{domxref("MessageEvent.ports")}} {{readonlyInline}}</dt> + <dd>Uma matriz de objetos {{domxref("MessagePort")}} que representam as portas ao canal por qual as mensagens são enviadas (onde for apropriado, por exemplo em mensagens via canais ou ao enviar uma mensagem a um <em>worker</em> partilhado).</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interface também herda métodos de {{domxref("Event")}}, de qual se deriva.</em></p> + +<dl> + <dt>{{domxref("MessageEvent.initMessageEvent","initMessageEvent()")}} {{deprecated_inline}}</dt> + <dd>Inicializa um evento de mensagem. <strong>Não use</strong> — <strong>use antes o construtor {{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}.</strong></dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>No nosso<a class="external external-icon" href="https://github.com/mdn/simple-shared-worker">exemplo básico dum <em>worker</em> partilhado</a>, temos duas páginas de HTML, cada qual usa JavaScript para fazer um simples cálculo. Os <em>scripts</em> diferentes estão a utilizar o mesmo ficheiro de <em>worker</em> para fazer os cálculos — ambos podem-no aceder, mesmo se as páginas estiverem a correr em janelas diferentes.</p> + +<p>O seguinte <em>snippet</em> de código demonstra a criação dum objeto {{domxref("SharedWorker")}} usando o construtor {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}. Ambas <em>scripts</em> contêm isto:</p> + +<pre class="brush: js notranslate">var myWorker = new SharedWorker('worker.js'); +</pre> + +<p>Ambas <em>scripts</em> acedem ao <em>worker</em> através dum objeto {{domxref("MessagePort")}} criado usando a propriedade {{domxref("SharedWorker.port")}}. Se o evento <code>onmessage</code> foi adicionado usando <code>addEventListener</code>, a porta é manualmente criada usando o seu método <code>start()</code>:</p> + +<pre class="brush: js notranslate">myWorker.port.start();</pre> + +<p>Quando a porta é iniciada, ambos <em>scripts</em> enviam mensagens ao <em>worker</em> e processão mensagens vindas do <em>worker</em> usando <code>port.postMessage()</code> e <code>port.onmessage</code>, respetivamente:</p> + +<pre class="brush: js notranslate">first.onchange = function() { + myWorker.port.postMessage([first.value,second.value]); + console.log('Mensagem enviada ao worker'); +} + +second.onchange = function() { + myWorker.port.postMessage([first.value,second.value]); + console.log('Mensagem enviada ao worker'); +} + +myWorker.port.onmessage = function(e) { + result1.textContent = e.data; + console.log('Mensagem recebida do worker'); +}</pre> + +<p>Dentro do <em>worker</em> usamos o <em>handler</em> {{domxref("SharedWorkerGlobalScope.onconnect")}} para nos ligarmos à mesma porta a que referimos antes. As portas associadas a esse <em>worker</em> são acessíveis através da propriedade <code>ports</code> do evento {{event("connect")}} — nós depois usamos o método <code>start()</code> de {{domxref("MessagePort")}} para iniciar a porta, e o <em>handler</em> <code>onmessage</code> para lidar com as mensagens enviadas dos <em>threads</em> principais.</p> + +<pre class="brush: js notranslate">onconnect = function(e) { + var port = e.ports[0]; + + port.addEventListener('message', function(e) { + var workerResult = 'Result: ' + (e.data[0] * e.data[1]); + port.postMessage(workerResult); + }); + + port.start(); // Necessário quando se usa addEventListener. Senão é chamado implicitamente pelo setter onmessage. +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#messageevent", "MessageEvent")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.MessageEvent")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("ExtendableMessageEvent")}} — parecida a esta interface, mas usada como base de outras interfaces que necessitam dar mais flexibilidade aos seus utilizadores ou autores.</li> +</ul> diff --git a/files/pt-pt/web/api/metadados/index.html b/files/pt-pt/web/api/metadados/index.html new file mode 100644 index 0000000000..dd1c16c91d --- /dev/null +++ b/files/pt-pt/web/api/metadados/index.html @@ -0,0 +1,116 @@ +--- +title: Metadados +slug: Web/API/Metadados +tags: + - API + - API Entradas de Diretoria e Ficheiro + - API do Sistema de Ficheiros + - Ficheiros + - Interface + - Não Padrão + - Pff-line + - Referencia + - metadados +translation_of: Web/API/Metadata +--- +<p>{{ APIRef("File System API") }}{{SeeCompatTable}}{{Non-standard_header}}</p> + +<p>A interface de <strong><code>Metadados</code></strong> é utilizada por <u>API Entradas de Diretoria e Ficheiro</u> para conter a informação sobre a entrada do sistema de ficheiros. Estes metadados incluem o tamanho do ficheiro e a data e hora da modificação.</p> + +<div class="note"> +<p>Esta interface não está disponível através do escopo global; em vez disso, pode obter um objeto <code>Metadata</code> descrevendo uma {{domxref("FileSystemEntry")}} utilizando o método {{domxref("FileSystemEntry.getMetadata()")}}.</p> +</div> + +<h2 id="Propriedades" style="">Propriedades</h2> + +<dl> + <dt>{{domxref("Metadata.modificationTime", "modificationTime")}} {{ReadOnlyInline}}</dt> + <dd>A {{jsxref("Date")}} object indicating the date and time the entry was modified.</dd> +</dl> + +<dl> + <dt>{{domxref("Metadata.size", "size")}} {{ReadOnlyInline}}</dt> + <dd>A 64-bit unsigned integer indicating the size of the entry in bytes.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('File System API')}}</td> + <td>{{Spec2('File System API')}}</td> + <td>Draft of proposed API</td> + </tr> + </tbody> +</table> + +<p>Esta API não é uma especificação oficial de W3C ou WHATWG.</p> + +<h2 id="Browser_compatibility" name="Browser_compatibility">Compatibilidade de navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>13 {{property_prefix("webkit")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatNo}}</td> + <td>0.16 {{property_prefix("webkit")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/API_Entradas_de_Diretoria_e_Ficheiro">API Entradas de Diretoria e Ficheiro</a></li> + <li><a href="/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction">Introdução à API de Sistema de Ficheiros </a>(inglês)</li> + <li>{{domxref("FileSystemEntry")}}</li> + <li>{{domxref("FileSystemFileEntry")}} and {{domxref("FileSystemDirectoryEntry")}}</li> +</ul> diff --git a/files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html b/files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html new file mode 100644 index 0000000000..43aed9ed94 --- /dev/null +++ b/files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html @@ -0,0 +1,97 @@ +--- +title: Eventos online e offline +slug: Web/API/NavigatorOnLine/Eventos_online_e_offline +tags: + - AJAX + - DOM + - Desenvolvimento_Web + - Todas_as_Categorias +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +<p>O <a href="pt/Firefox_3_para_desenvolvedores">Firefox 3</a> implementou <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#offline">eventos Online/Offline</a> da <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/">especificação WHATWG Web Applications 1.0</a>.</p> + +<h3 id="Vis.C3.A3o_geral" name="Vis.C3.A3o_geral">Visão geral</h3> + +<p>Para construir uma boa aplicação web capaz de ser usada offline, você precisar saber quando sua aplicação está realmente offline. Casualmente, você pode também precisar saber quando a sua aplicação retornou ao estado 'online' novamente. Efetivamente, as exigências colapsam como tal:</p> + +<ol> + <li>Você precisa saber quando o usuário torna-se online, então você pode re-sincronizar com o servidor.</li> + <li>Você precisa saber quando o usuário está offline, então você pode estar seguro para fazer suas requisições do servidor e elas se enfileirarem para um tempo posterior.</li> +</ol> + +<p>Este é o processo em que eventos online/offline ajudam a banalizar.</p> + +<h3 id="API" name="API">API</h3> + +<h4 id="navigator.onLine" name="navigator.onLine"><code>navigator.onLine</code></h4> + +<p><code><a href="pt/DOM/window.navigator.onLine">navigator.onLine</a></code> é uma propriedade que mantém um valor <code>true</code>/<code>false</code> (<code>true</code> para online, <code>false</code> para offline). Esta propriedade é atualizada sempre que o usuário trocar do "Modo Offline" selecionando o item correspondente do menu (Arquivo -> Trabalhar Offline no Firefox).</p> + +<p>Adicionalmente, esta propriedade deve atualizar sempre que o navegador não for mais capaz de conectar a uma rede. De acordo com a especificação:</p> + +<blockquote cite="http://www.whatwg.org/specs/web-apps/current-work/#offline">O atributo <code>navigator.onLine</code> deve retornar falso se o agente de usuário não obtiver contato com a rede quando o usuário segue links ou quando<em>scripts</em> de uma página remota forem requisitados.</blockquote> + +<p>Firefox 2 atualiza esta propriedade quando trocando de/para o modo Offline do navegador, e quando perde/encontra conectividade com uma rede no Windows e Linux.</p> + +<p>Esta propriedade existe em antigas versões do Firefox e Internet Explorer (a especificação baseou-se fora destas implementações prévias), então você pode começar usando isto imediatamente. A detecção automática do estado da rede foi implementado no Firefox 2.</p> + +<h4 id="Eventos_.22online.22_e_.22offline.22" name="Eventos_.22online.22_e_.22offline.22">Eventos "<code>online</code>" e "<code>offline</code>"</h4> + +<p>O <a href="pt/Firefox_3_para_desenvolvedores">Firefox 3</a> introduz dois novos eventos: "<code>online</code>" e "<code>offline</code>". Estes dois eventos são colocados no <code><body></code> de cada página quando o navegador troca entre o modo online e offline. Adicionalmente, os eventos vão de <code>document.body</code>, para <code>document</code>, terminando em <code>window</code>. Ambos os eventos não são canceláveis (você não pode evitar o usuário de estar online, ou indo para offline).</p> + +<p>Você pode registrar ouvintes para estes eventos de algumas maneiras familiares:</p> + +<ul> + <li>usando <code><a href="pt/DOM/element.addEventListener">addEventListener</a></code> em <code>window</code>, <code>document</code>, ou <code>document.body</code></li> + <li>configurando as propriedades <code>.ononline</code> ou <code>.onoffline</code> em <code>document</code> ou <code>document.body</code> para um objeto <code>Function</code> JavaScript. (<strong>Nota:</strong> usando <code>window.ononline</code> ou <code>window.onoffline</code> você não trabalhará para razões de compatibilidade.)</li> + <li>especificando os atributos <code>ononline="..."</code> ou <code>onoffline="..."</code> na etiqueta <code><body></code> na marcação HTML.</li> +</ul> + +<h3 id="Exemplo" name="Exemplo">Exemplo</h3> + +<p>Há <a class="link-https" href="https://bugzilla.mozilla.org/attachment.cgi?id=220609">um caso de teste simples</a> que você pode rodar para verificar se os eventos estão trabalhando. <span class="comment">XXX Quando os "mochitestes" para isto forem criados, apontar para este e atualizar este exemplo -nickolay</span></p> + +<pre class="eval"> <!doctype html> + <html> + <head> + <script> + function updateOnlineStatus(msg) { + var status = document.getElementById("status"); + var condition = navigator.onLine ? "ONLINE" : "OFFLINE"; + status.setAttribute("class", condition); + var state = document.getElementById("state"); + state.innerHTML = condition; + var log = document.getElementById("log"); + log.appendChild(document.createTextNode("Event: " + msg + "; status=" + condition + "\n")); + } + function loaded() { + updateOnlineStatus("load"); + document.body.addEventListener("offline", function () { + updateOnlineStatus("offline") + }, false); + document.body.addEventListener("online", function () { + updateOnlineStatus("online") + }, false); + } + </script> + <style>...</style> + </head> + <body onload="loaded()"> + <div id="status"><p id="state"></p></div> + <div id="log"></div> + </body> + </html> +</pre> + +<h3 id="Refer.C3.AAncias" name="Refer.C3.AAncias">Referências</h3> + +<ul> + <li><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#offline">'Online/Offline events' section from the WHATWG Web Applications 1.0 Specification</a></li> + <li><a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=336359">The bug tracking online/offline events implementation in Firefox</a> e um <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=336682">follow-up</a></li> + <li><a class="link-https" href="https://bugzilla.mozilla.org/attachment.cgi?id=220609">A simple test case</a></li> + <li><a class="external" href="http://ejohn.org/blog/offline-events/">An explanation of Online/Offline events</a></li> +</ul> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> diff --git a/files/pt-pt/web/api/navigatoronline/index.html b/files/pt-pt/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..91197b69ef --- /dev/null +++ b/files/pt-pt/web/api/navigatoronline/index.html @@ -0,0 +1,134 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +tags: + - API + - HTML-DOM + - NeedsTranslation + - TopicStub +translation_of: Web/API/NavigatorOnLine +--- +<p>{{APIRef("HTML DOM")}}</p> + +<p>The <code><strong>NavigatorOnLine</strong></code> interface contains methods and properties related to the connectivity status of the browser.</p> + +<p>There is no object of type <code>NavigatorOnLine</code>, but other interfaces, like {{domxref("Navigator")}} or {{domxref("WorkerNavigator")}}, implement it.</p> + +<h2 id="Properties">Properties</h2> + +<p><em>The <code>NavigatorOnLine</code></em><em> interface doesn't inherit any property.</em></p> + +<dl> + <dt>{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}</dt> + <dd>Returns a {{domxref("Boolean")}} indicating whether the browser is working online.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>The </em><em><code>NavigatorOnLine</code></em><em> interface neither implements, nor inherit any method.</em></p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', '#navigatoronline', 'NavigatorOnLine')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from the latest snapshot, {{SpecName('HTML5 W3C')}}</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', '#navigatoronline', 'NavigatorOnLine')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName('HTML WHATWG')}} with its initial specification.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>on {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(29)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>on {{domxref("WorkerNavigator")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(29)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>The {{domxref("Navigator")}} interface that implements it.</li> + <li><a href="/en-US/docs/Web/API/NavigatorOnLine/Online_and_offline_events">Online and offline events</a></li> +</ul> diff --git a/files/pt-pt/web/api/node/index.html b/files/pt-pt/web/api/node/index.html new file mode 100644 index 0000000000..d1ea8d3557 --- /dev/null +++ b/files/pt-pt/web/api/node/index.html @@ -0,0 +1,407 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - Element + - Interface + - Node + - WebAPI +translation_of: Web/API/Node +--- +<div> + {{Apiref}}</div> +<p><code><strong>Node </strong></code>é uma interface da qual uma varidade de tipos do DOM herdam e permite que estes vários tipos seja tratados (ou testados) de forma similar.</p> +<p>As seguintes interfaces todas herdam de <code>Node</code> os seus métodos e propriedades:{{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (que {{domxref("Text")}}, {{domxref("Comment")}}, e {{domxref("CDATASection")}} herdam), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}</p> +<p>Estas interfaces podem retornar <code>null</code> em casos particulares, em que estes métodos e propriedades não são relevantes. Podem lançar uma excepção - por exempo, ao adicionar nós-filho a um tipo de nó para o qual não está prevista a existência de nós descendentes.</p> +<p> </p> +<h2 id="Propriedades">Propriedades</h2> +<p><em>Herda propriedades do seu pai {{domxref("EventTarget")}}</em>.<sup>[1]</sup></p> +<dl> + <dt> + {{domxref("Node.attributes")}} {{deprecated_inline}}</dt> + <dd> + ...</dd> + <dt> + {{domxref("Node.baseURI")}} {{readonlyInline}}</dt> + <dd> + Retorna uma {{domxref("DOMString")}} que represente o URL base. O conceito de URL base varia de língua para língua; em HTML corresponde: ao protocolo, nome do domínio e estrutura de directórios, ou seja, tudo até à última '<code>/</code>'.</dd> + <dt> + {{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}</dt> + <dd> + (Não disponível para conteúdo Web). O objecto {{ Interface("nsIURI") }} apenas de leitura representa o URI base para o elemento.</dd> + <dt> + {{domxref("Node.childNodes")}} {{readonlyInline}}</dt> + <dd> + Retorna uma {{domxref("NodeList")}} activa quem contém todos os descendentes desse nó. Sendo {{domxref("NodeList")}} uma lista activa, significa que os descendentes do <code>Node</code> mudam, o objecto {{domxref("NodeList")}} é automaticamente actualizado.</dd> + <dt> + {{domxref("Node.firstChild")}} {{readonlyInline}}</dt> + <dd> + Retorna um {{domxref("Node")}} que representa o primeiro descendente directo do nó ou <code>null</code> se o nó não tiver descendentes.</dd> + <dt> + {{domxref("Node.lastChild")}} {{readonlyInline}}</dt> + <dd> + Retorna um {{domxref("Node")}} que representa o último descendente directo do <code>Node, </code>ou <code>null</code> caso o <code>node</code> não tenha descendentes.</dd> + <dt> + {{domxref("Node.localName")}} {{readonlyInline}}{{obsolete_inline}}</dt> + <dd> + Retorna uma {{domxref("DOMString")}} que representa a parte local do nome qualificado do elemento. No Firefox 3.5 e anteriores, a propriedade exibe o nome local do elemento HTML em maiúsculas (mas não o faz para elementos XHTML). Em versões posteriores, isto não se verifica, portanto a propriedade é exibida em letras minúsculas para ambos HTML e XHTML. {{ gecko_minversion_inline("1.9.2") }}. Apesar da especificação requerer que <code>localName</code> seja definido no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.</dd> + <dt> + {{domxref("Node.namespaceURI")}} {{readonlyInline}}{{obsolete_inline}}</dt> + <dd> + O URI do namspace do <code>node</code> em causa, ou <code>null, </code>se não possuir<code> namespace</code>. No Firefox 3.5 e anteriores, elementos HTML não se encontravam em qualquer namespace. Em versões posteriores, elementos HTML estão no namespace <code><a class="linkification-ext external" href="http://www.w3.org/1999/xhtml" title="Linkification: http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a></code> quer na tree de HTML, quer na de XHTML {{ gecko_minversion_inline("1.9.2") }}</dd> + <dd> + Apesar da especificação requerer <code>namespaceURI</code> definido no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.</dd> + <dt> + {{domxref("Node.nextSibling")}} {{readonlyInline}}</dt> + <dd> + Retorna um {{domxref("Node")}} que representa o próximo <code>node</code> na tree, ou <code>null</code> caso esse <code>node</code> não exista.</dd> + <dt> + {{domxref("Node.nodeName")}} {{readonlyInline}}</dt> + <dd> + Retorna uma {{domxref("DOMString")}} que contém o nome do <code>Node</code>. A estrutura do nome difere do tipo do nome. Exemplo: um {{domxref("HTMLElement")}} irá conter o nome da tag correspondente, como <code>'audio'</code> para um {{domxref("HTMLAudioElement")}}, um {{domxref("Text")}} node irá ter a string <code>'#text'</code>, ou então um {{domxref("Document")}} node irá ter uma string <code>'#document'</code>.</dd> + <dt> + {{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}</dt> + <dd> + Um {{ Interface("nsIPrincipal") }} representa um node principal.</dd> + <dt> + {{domxref("Node.nodeType")}}{{readonlyInline}}</dt> + <dd> + Retorna um <code>unsigned short</code> que representa o tipo de node. Os valores possíveis são:<br> + <table class="standard-table"> + <tbody> + <tr> + <th scope="col">Nome</th> + <th scope="col">Valor</th> + </tr> + <tr> + <td><code>ELEMENT_NODE</code></td> + <td><code>1</code></td> + </tr> + <tr> + <td><code>ATTRIBUTE_NODE</code> {{deprecated_inline()}}</td> + <td><code>2</code></td> + </tr> + <tr> + <td><code>TEXT_NODE</code></td> + <td><code>3</code></td> + </tr> + <tr> + <td><code>CDATA_SECTION_NODE</code> {{deprecated_inline()}}</td> + <td><code>4</code></td> + </tr> + <tr> + <td><code>ENTITY_REFERENCE_NODE</code> {{deprecated_inline()}}</td> + <td><code>5</code></td> + </tr> + <tr> + <td><code>ENTITY_NODE</code> {{deprecated_inline()}}</td> + <td><code>6</code></td> + </tr> + <tr> + <td><code>PROCESSING_INSTRUCTION_NODE</code></td> + <td><code>7</code></td> + </tr> + <tr> + <td><code>COMMENT_NODE</code></td> + <td><code>8</code></td> + </tr> + <tr> + <td><code>DOCUMENT_NODE</code></td> + <td><code>9</code></td> + </tr> + <tr> + <td><code>DOCUMENT_TYPE_NODE</code></td> + <td><code>10</code></td> + </tr> + <tr> + <td><code>DOCUMENT_FRAGMENT_NODE</code></td> + <td><code>11</code></td> + </tr> + <tr> + <td><code>NOTATION_NODE</code> {{deprecated_inline()}}</td> + <td><code>12</code></td> + </tr> + </tbody> + </table> + </dd> + <dt> + {{domxref("Node.nodeValue")}}</dt> + <dd> + É a {{domxref("DOMString")}} que representa o valor de um objecto. Para a maioria dos tipos de <code>Node</code>, isto retorna <code>null</code> e qualquer operação é ignorada. Para nodes do tipo <code>TEXT_NODE</code> (objectos {{domxref("Text")}}), <code>COMMENT_NODE</code> ({{domxref("Comment")}} objects), e <code>PROCESSING_INSTRUCTION_NODE</code> ({{domxref("ProcessingInstruction")}} objects), o valor corresponde ao valor textual contido no objecto.</dd> + <dt> + {{domxref("Node.ownerDocument")}} {{readonlyInline}}</dt> + <dd> + Retorna o {{domxref("Document")}} a que este node pertence. Se nenhum documento está associado com este, retorna <code>null</code>.</dd> + <dt> + {{domxref("Node.parentNode")}} {{readonlyInline}}</dt> + <dd> + Retorna um {{domxref("Node")}} que é o ascendente deste node. Se não existir tal node, como por exemplo se este node se encontra no nível raiz da tree ou se não consta nesta, esta propriedade retorna <code>null</code>.</dd> + <dt> + {{domxref("Node.parentElement")}} {{readonlyInline}}</dt> + <dd> + Retorna um {{domxref("Element")}} que é o ascendente deste node. Caso este node não tenha ascendente ou se o seu ascendente não é um {{domxref("Element")}}, esta propriedade retorna <code>null</code>.</dd> + <dt> + {{domxref("Node.prefix")}} {{obsolete_inline}}</dt> + <dd> + É uma {{domxref("DOMString")}} que representa o prefixo do namespace do node, ou <code>null</code> caso nenhum prefixo seja especificado.</dd> + <dd> + Apesar da especificação requerer <code>localName</code> para ser definida no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.</dd> + <dt> + {{domxref("Node.previousSibling")}} {{readonlyInline}}</dt> + <dd> + Retorna um {{domxref("Node")}} que representa o node anterior na tree ou <code>null</code> caso o node não exista.</dd> + <dt> + {{domxref("Node.textContent")}}</dt> + <dd> + É uma {{domxref("DOMString")}} que representa o valor textual de um elemento e todos os seus descendentes.</dd> +</dl> +<h2 id="Métodos">Métodos</h2> +<p><em>Herda métodos dos seus pais {{domxref("EventTarget")}}</em>.<sup>[1]</sup></p> +<dl> + <dt> + {{domxref("Node.appendChild()")}}</dt> + <dd> + Insere um {{domxref("Node")}} como último descendente do elemento em causa.</dd> + <dt> + {{domxref("Node.cloneNode()")}}</dt> + <dd> + Clona um {{domxref("Node")}} e, opcionalmente, todo o seu conteúdo. Por omissão, clona o conteúdo do node.</dd> + <dt> + {{domxref("Node.compareDocumentPosition()")}}</dt> + <dd> + </dd> + <dt> + {{domxref("Node.contains()")}}</dt> + <dd> + </dd> + <dt> + {{domxref("Node.getFeature()")}} {{obsolete_inline}}</dt> + <dd> + ...</dd> + <dt> + {{domxref("Node.getUserData()")}} {{deprecated_inline}}</dt> + <dd> + Permite ao utilizador extrair alguma {{domxref("DOMUserData")}} do node.</dd> + <dt> + {{domxref("Node.hasAttributes()")}} {{obsolete_inline}}</dt> + <dd> + Retorna um {{domxref("Boolean")}} que indica se o elemento tem atributos ou não.</dd> + <dt> + {{domxref("Node.hasChildNodes()")}}</dt> + <dd> + Retorna um {{domxref("Boolean")}} que indica se o elemento tem descendentes ou não.</dd> + <dt> + {{domxref("Node.insertBefore")}}</dt> + <dd> + Insere o primeiro {{domxref("Node")}} dado num parâmetro imediatamente antes do segundo descendente deste {{domxref("Node")}}.</dd> + <dt> + {{domxref("Node.isDefaultNamespace")}}</dt> + <dd> + </dd> + <dt> + {{domxref("Node.isEqualNode")}}</dt> + <dd> + </dd> + <dt> + {{domxref("Node.isSameNode")}} {{obsolete_inline}}</dt> + <dd> + </dd> + <dt> + {{domxref("Node.isSupported")}} {{deprecated_inline}}</dt> + <dd> + Retorna uma flag <a href="https://developer.mozilla.org/en-US/docs/Web/API/Boolean" title="The Boolean object is an object wrapper for a boolean value."><code>Boolean</code></a> que contém o resultado de um teste à implementação do DOM para aferir o suporte deste ou do node a uma determinada propriedade.</dd> + <dt> + {{domxref("Node.lookupPrefix")}}</dt> + <dd> + </dd> + <dt> + {{domxref("Node.lookupNamespaceURI")}}</dt> + <dd> + </dd> + <dt> + {{domxref("Node.normalize")}}</dt> + <dd> + Limpa todos os nodes textuais abaixo deste (converge os adjacentes e remove os vazios)</dd> + <dt> + {{domxref("Node.removeChild")}}</dt> + <dd> + Remove um node descendenter do elemento actual. Este deve ser um descendente do node actual.</dd> + <dt> + {{domxref("Node.replaceChild")}}</dt> + <dd> + Substitui um {{domxref("Node")}} descendente do actual com o fornecido no segundo parâmetro.</dd> + <dt> + {{domxref("Node.setUserData")}} {{deprecated_inline}}</dt> + <dd> + Permite a um utilizador anexar, ou remover {{domxref("DOMUserData")}} do node.</dd> + <dd> + </dd> +</dl> +<h2 id="Exemplos">Exemplos</h2> +<h3 id="Percorrer_todos_os_nodes_descendentes">Percorrer todos os nodes descendentes</h3> +<p>A seguinte função itera sobre os nodes descendentes de um node recursivamente e executa uma função de callback sobre os mesmos (e sobre o próprio node-pai).</p> +<pre class="brush: js">function DOMComb (oParent, oCallback) { + if (oParent.hasChildNodes()) { + for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) { + DOMComb(oNode, oCallback); + } + } + oCallback.call(oParent); +}</pre> +<h4 id="Síntaxe">Síntaxe</h4> +<pre>DOMComb(parentNode, callbackFunction);</pre> +<h4 id="Descrição">Descrição</h4> +<p>Recursivamente iterar sobre os nodes descendentes de um <code>parentNode </code>e o próprio <code>parentNode</code>, executando uma <code>callbackFunction</code> sobre estes como objectos <a href="/en-US/docs/JavaScript/Reference/Operators/this" title="en-US/docs/JavaScript/Reference/Operators/this"><code>this</code></a>.</p> +<h4 id="Parâmetros">Parâmetros</h4> +<dl> + <dt> + <code>parentNode</code></dt> + <dd> + O node ascendente (<code><strong>Node</strong> <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object" title="en-US/docs/JavaScript/Reference/Global_Objects/Object">Object</a></code>).</dd> + <dt> + <code>callbackFunction</code></dt> + <dd> + A função de callback (<a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="en-US/docs/JavaScript/Reference/Global_Objects/Function"><code>Function</code></a>).</dd> +</dl> +<h4 id="Exemplo_de_utilização">Exemplo de utilização</h4> +<p>O exemplo seguinte envia para a <code>console.log </code>o conteúdo textual do body:</p> +<pre class="brush: js">function printContent () { + if (this.nodeValue) { console.log(this.nodeValue); } +} + +onload = function () { + DOMComb(document.body, printContent); +};</pre> +<h2 id="Especificações">Especificações</h2> +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Removidas as seguintes propriedades: <code>attributes</code>, <code>namespaceURI</code>, <code>prefix</code>, e <code>localName</code>.<br> + Removidos os seguintes métodos: <code>isSupported()</code>, <code>hasAttributes()</code>, <code>isSameNode()</code>, <code>getFeature()</code>, <code>setUserData()</code>, e <code>getUserData()</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM3 Core')}}</td> + <td>Os métodos <code>insertBefore()</code>, <code>replaceChild()</code>, <code>removeChild()</code>, e <code>appendChild()</code> retornam mais um tipo de erro (<code>NOT_SUPPORTED_ERR</code>) caso sejam chamados no {{domxref("Document")}}.<br> + O método <code>normalize()</code> foi modificado para que o node {{domxref("Text")}} possa também ser normalizado se a flag correcta de {{domxref("DOMConfiguration")}} estiver definida.<br> + Adicionados os seguintes métodos: <code>compareDocumentPosition()</code>, <code>isSameNode()</code>, <code>lookupPrefix()</code>, <code>isDefaultNamespace()</code>, <code>lookupNamespaceURI()</code>, <code>isEqualNode()</code>, <code>getFeature()</code>, <code>setUserData()</code>, e <code>getUserData().</code><br> + Adicionadas as seguintes propriedades: <code>baseURI</code> e <code>textContent</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM2 Core')}}</td> + <td>A propriedade <code>ownerDocument</code> foi ligeiramente alterada para que um {{domxref("DocumentFragment")}} possa também retornar <code>null</code>.<br> + Adicionadas as seguintes propriedades: <code>namespaceURI</code>, <code>prefix</code>, e <code>localName</code>.<br> + Adicionados os seguintes métodos: <code>normalize()</code>, <code>isSupported()</code> and <code>hasAttributes()</code>.</td> + </tr> + <tr> + <td>{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}</td> + <td>{{Spec2('DOM1')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> +<p> </p> +<h2 id="Compatibilidade_por_browser">Compatibilidade por browser</h2> +<p>{{CompatibilityTable}}</p> +<div id="compat-desktop"> + <table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>getFeature()</code>{{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("6.0")}}.<br> + Removida em: {{CompatGeckoDesktop("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>getUserData()</code>, <code>setUserData()</code> e <code>hasAttributes()</code> {{deprecated_inline}}</td> + <td>{{CompatNo}}</td> + <td>Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("21.0")}}.<br> + Removida em: {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>isSameNode()</code> {{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("9.0")}}.<br> + Removida em: {{CompatGeckoDesktop("10.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>isSupported()</code> {{obsolete_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("21.0")}}.<br> + Removida em: {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> + </table> +</div> +<div id="compat-mobile"> + <table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>getFeature()</code>{{obsolete_inline}}</td> + <td>{{CompatNo}}</td> + <td>Suportade desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("6.0")}}.<br> + Removida em: {{CompatGeckoDesktop("7.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> + </table> +</div> +<p>[1] Webkit e Blink incorrectamente não fazem com que <code>Node</code> herde de {{domxref("EventTarget")}}.</p> diff --git a/files/pt-pt/web/api/notification/index.html b/files/pt-pt/web/api/notification/index.html new file mode 100644 index 0000000000..d584cb349c --- /dev/null +++ b/files/pt-pt/web/api/notification/index.html @@ -0,0 +1,316 @@ +--- +title: Notificação +slug: Web/API/notification +translation_of: Web/API/Notification +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p>The <code>Notification</code> interface of the {{domxref('Notifications_API','Notifications API')}} is used to configure and display desktop notifications to the user.</p> + +<h2 id="Criador">Criador</h2> + +<dl> + <dt>{{domxref("Notification.Notification()")}}</dt> + <dd>Cria uma nova instância do objeto de {{domxref('Notificação')}}.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<h3 id="Propriedades_estáticas">Propriedades estáticas</h3> + +<p>These properties are available only on the <code>Notification</code> object itself.</p> + +<dl> + <dt>{{domxref("Notification.permission")}} {{readonlyinline}}</dt> + <dd>A string representing the current permission to display notifications. Possible value are: <code>denied</code> (the user refuses to have notifications displayed), <code>granted</code> (the user accepts having notifications displayed), or <code>default</code> (the user choice is unknown and therefore the browser will act as if the value were denied).</dd> +</dl> + +<h3 id="Propriedades_de_instância">Propriedades de instância</h3> + +<p>These properties are available only on instances of the <code>Notification</code> object.</p> + +<dl> + <dt>{{domxref("Notification.title")}} {{readonlyinline}}</dt> + <dd>The title of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.dir")}} {{readonlyinline}}</dt> + <dd>The text direction of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.lang")}} {{readonlyinline}}</dt> + <dd>The language code of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.body")}} {{readonlyinline}}</dt> + <dd>The body string of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.tag")}} {{readonlyinline}}</dt> + <dd>The ID of the notification (if any) as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.icon")}} {{readonlyinline}}</dt> + <dd>The URL of the image used as an icon of the notification as specified in the options parameter of the constructor.</dd> + <dt>{{domxref("Notification.data")}} {{readonlyinline}}</dt> + <dd>Returns a structured clone of the notification’s data.</dd> +</dl> + +<h4 id="Unsupported_properties">Unsupported properties</h4> + +<p>The following properties are listed in the most up-to-date spec, but are not supported in any browsers yet. It is advisable to keep checking back regularly to see if the status of these has updated, and let us know if you find any out of date information.</p> + +<dl> + <dt>{{domxref("Notification.noscreen")}} {{readonlyinline}}</dt> + <dd>Specifies whether the notification firing should enable the device's screen or not.</dd> + <dt>{{domxref("Notification.renotify")}} {{readonlyinline}}</dt> + <dd>Specifies whether the user should be notified after a new notification replaces an old one.</dd> + <dt>{{domxref("Notification.silent")}} {{readonlyinline}}</dt> + <dd>Specifies whether the notification should be silent, i.e. no sounds or vibrations should be issued, regardless of the device settings.</dd> + <dt>{{domxref("Notification.sound")}} {{readonlyinline}}</dt> + <dd>Specifies a sound resource to play when the notification fires, in place of the default system notification sound.</dd> + <dt>{{domxref("Notification.sticky")}} {{readonlyinline}}</dt> + <dd>Specifies whether the notification should be 'sticky', i.e. not easily clearable by the user.</dd> + <dt>{{domxref("Notification.vibrate")}} {{readonlyinline}}</dt> + <dd>Specifies a vibration pattern for devices with vibration hardware to emit.</dd> +</dl> + +<h4 id="Event_handlers">Event handlers</h4> + +<dl> + <dt>{{domxref("Notification.onclick")}}</dt> + <dd>A handler for the {{event("click")}} event. It is triggered each time the user clicks on the notification.</dd> + <dt>{{domxref("Notification.onerror")}}</dt> + <dd>A handler for the {{event("error")}} event. It is triggered each time the notification encounters an error.</dd> +</dl> + +<h4 id="Obsolete_handlers">Obsolete handlers</h4> + +<p>The following event handlers are still supported as listed in the {{anch("browser compatibility")}} section below, but are no longer listed in the current spec. I is safe therefore to assume they are obsolete, and may stop working in future browser versions.</p> + +<dl> + <dt>{{domxref("Notification.onclose")}}</dt> + <dd>A handler for the {{event("close")}} event. It is triggered when the user closes the notification.</dd> + <dt>{{domxref("Notification.onshow")}}</dt> + <dd>A handler for the {{event("show")}} event. It is triggered when the notification is displayed.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<h3 id="Métodos_estáticos">Métodos estáticos</h3> + +<p>These methods are available only on the <code>Notification</code> object itself.</p> + +<dl> + <dt>{{domxref("Notification.requestPermission()")}}</dt> + <dd>Requests permission from the user to display notifications.</dd> +</dl> + +<h3 id="Métodos_de_instância">Métodos de instância</h3> + +<p>These properties are available only on an instance of the <code>Notification</code> object or through its <a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain" title="/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain"><code>prototype</code></a>. The <code>Notification</code> object also inherits from the {{domxref("EventTarget")}} interface.</p> + +<dl> + <dt>{{domxref("Notification.close()")}}</dt> + <dd>Programmatically closes a notification.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Assume this basic HTML:</p> + +<pre class="brush: html"><button onclick="notifyMe()">Notify me!</button></pre> + +<p>It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.</p> + +<pre class="brush: js">function notifyMe() { + // Let's check if the browser supports notifications + if (!("Notification" in window)) { + alert("This browser does not support desktop notification"); + } + + // Let's check whether notification permissions have alredy been granted + else if (Notification.permission === "granted") { + // If it's okay let's create a notification + var notification = new Notification("Hi there!"); + } + + // Otherwise, we need to ask the user for permission + else if (Notification.permission !== 'denied') { + Notification.requestPermission(function (permission) { + // If the user accepts, let's create a notification + if (permission === "granted") { + var notification = new Notification("Hi there!"); + } + }); + } + + // At last, if the user has denied notifications, and you + // want to be respectful there is no need to bother them any more. +}</pre> + +<p>{{ EmbedLiveSample('Example', '100%', 30) }}</p> + +<p>In many cases, you don't need to be this verbose. For example, in our <a href="http://mdn.github.io/emogotchi/">Emogotchi demo</a> (<a href="https://github.com/mdn/emogotchi">see source code</a>), we simply run {{domxref("Notification.requestPermission")}} regardless to make sure we can get permission to send notifications:</p> + +<pre class="brush: js">Notification.requestPermission();</pre> + +<p>Then we run a simple <code>spawnNotification()</code> function when we want to fire a notification — this is passed arguments to specify the body, icon and title we want, then it creates the necessary <code>options</code> object and fires the notification using the {{domxref("Notification.Notification","Notification()")}} constructor.</p> + +<pre class="brush: js">function spawnNotification(theBody,theIcon,theTitle) { + var options = { + body: theBody, + icon: theIcon + } + var n = new Notification(theTitle,options); +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_do_navegador">Compatibilidade do navegador</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>5 {{ property_prefix("webkit") }} (see notes)<br> + 22</td> + <td>4.0 {{ property_prefix("moz") }} (see notes)<br> + 22</td> + <td>{{ CompatNo() }}</td> + <td>25</td> + <td>6 (see notes)</td> + </tr> + <tr> + <td><code>icon</code></td> + <td>5 {{ property_prefix("webkit") }} (see notes)<br> + 22</td> + <td>4.0 {{ property_prefix("moz") }} (see notes)<br> + 22</td> + <td>{{ CompatNo() }}</td> + <td>25</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>silent</code></td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>noscreen</code>, <code>renotify</code>, <code>sound</code>, <code>sticky</code></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatUnknown() }}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + <td>4.0 {{ property_prefix("moz") }} (see notes)<br> + 22</td> + <td>1.0.1 {{ property_prefix("moz") }} (see notes)<br> + 1.2</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + </tr> + <tr> + <td><code>icon</code></td> + <td>{{ CompatUnknown() }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>4.0 {{ property_prefix("moz") }} (see notes)<br> + 22</td> + <td>1.0.1 {{ property_prefix("moz") }} (see notes)<br> + 1.2</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>silent</code></td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(43.0)}}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(43.0)}}</td> + </tr> + <tr> + <td><code>noscreen</code>, <code>renotify</code>, <code>sound</code>, <code>sticky</code></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Notas_do_Firefox_OS">Notas do Firefox OS</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Firefox OS notes")}}</p> + +<h3 id="Notas_do_Chrome">Notas do Chrome</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Chrome notes")}}</p> + +<h3 id="Notas_do_Safari">Notas do Safari</h3> + +<p>{{Page("/en-US/docs/Web/API/Notifications_API", "Safari notes")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Utilizar API de Notificações</a></li> +</ul> diff --git a/files/pt-pt/web/api/notifications_api/index.html b/files/pt-pt/web/api/notifications_api/index.html new file mode 100644 index 0000000000..c41db167ce --- /dev/null +++ b/files/pt-pt/web/api/notifications_api/index.html @@ -0,0 +1,194 @@ +--- +title: Notifications API +slug: Web/API/Notifications_API +tags: + - Landing + - NeedsTranslation + - Notifications + - TopicStub + - permission + - system +translation_of: Web/API/Notifications_API +--- +<p>{{DefaultAPISidebar("Web Notifications")}}</p> + +<p class="summary">The Notifications API allows web pages to control the display of system notifications to the end user — these are outside the top-level browsing context viewport, so therefore can be displayed even the user has switched tabs or moved to a different app. The API is designed to be compatible with existing notification systems across different platforms.</p> + +<h2 id="Concepts_and_usage">Concepts and usage</h2> + +<p>On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the {{domxref("Notification.requestPermission()")}} method. This will spawn a request dialog, along the following lines:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/10819/notification-bubble.png" style="display: block; height: 205px; margin: 0 auto; width: 453px;"></p> + +<p>From here the user can choose to allow notifications from this origin, block notifications from this origin , or to not choose a this point. Once a choice has been made, the setting will generally persist for the current session. </p> + +<p>Next, a new notification is created using the {{domxref("Notification.Notification","Notification()")}} constructor. This has to be passed a title argument, and can optionally be passed an options object to specify options such as text direction, body text, icon to display, notification sound to play, and more.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>In addition, the Notifications API spec specifies a number of additions to the <a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a>, to allow service workers to fire notifications.</p> + +<div class="note"> +<p><strong>Note</strong>: To find out more about using notifications in your own app, read <a href="/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Using the Notifications API</a>.</p> +</div> + +<h2 id="Notifications_interfaces">Notifications interfaces</h2> + +<dl> + <dt>{{domxref("Notification")}}</dt> + <dd>Defines a notification object.</dd> +</dl> + +<h3 id="Service_worker_additions">Service worker additions</h3> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration")}}</dt> + <dd>Includes the {{domxref("ServiceWorkerRegistration.showNotification()")}} and {{domxref("ServiceWorkerRegistration.getNotifications()")}} method for controlling the display of notifications.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope")}}</dt> + <dd>Includes the {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} handler for firing custom functions when a notification is clicked.</dd> + <dt>{{domxref("NotificationEvent")}}</dt> + <dd>A specific type of event object, based on {{domxref("ExtendableEvent")}}, which represents a notification that has fired.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>5{{property_prefix("webkit")}}<sup>[1]</sup><br> + 22</td> + <td>{{CompatGeckoDesktop("2.0")}}{{property_prefix("moz")}}<sup>[2]</sup><br> + {{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>6<sup>[3]</sup></td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("41.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Service worker additions</td> + <td> + <p>{{CompatChrome(42.0)}}</p> + </td> + <td>{{CompatGeckoDesktop("42.0")}}<sup>[4]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + <td>{{CompatGeckoMobile(2.0)}}{{property_prefix("moz")}}<sup>[2]</sup><br> + {{CompatGeckoMobile(22.0)}}</td> + <td>1.0.1{{property_prefix("moz")}}<sup>[2]</sup><br> + 1.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td> + <p>{{CompatVersionUnknown}}</p> + </td> + </tr> + <tr> + <td>Available in workers</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(41.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Service worker additions</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(42.0)}}<sup>[4]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Before Chrome 22, the support for notification followed an <a href="http://www.chromium.org/developers/design-documents/desktop-notifications/api-specification">old prefixed version of the specification</a> and used the {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} object to instantiate a new notification. Before Chrome 32, {{domxref("Notification.permission")}} was not supported.</p> + +<p>[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification was done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its <code>createNotification()</code> method. In addition, the Notification was displayed when calling the <code>show()</code> method and supported only the <code>click</code> and <code>close</code> events (Nick Desaulniers wrote a <a href="https://github.com/nickdesaulniers/fxos-irc/blob/master/js/notification.js">Notification shim</a> to cover both newer and older implementations.)</p> + +<p>[3] Safari started to support notification with Safari 6, but only on Mac OSX 10.8+ (Mountain Lion).</p> + +<p>[4] Firefox 42 has shipped with web notifications from Service Workers disabled.</p> + +<h2 id="Firefox_OS_permissions">Firefox OS permissions</h2> + +<p>When using notifications in a Firefox OS app, be sure to add the <code>desktop-notification</code> permission in your manifest file. Notifications can be used at any permission level, hosted or above:</p> + +<pre class="brush: json">"permissions": { + "desktop-notification": {} +}</pre> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Using the Notifications API</a></li> +</ul> diff --git a/files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html b/files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html new file mode 100644 index 0000000000..ca76a8b6bd --- /dev/null +++ b/files/pt-pt/web/api/notifications_api/utilizar_api_notificações/index.html @@ -0,0 +1,289 @@ +--- +title: Utilizar a API de Notificações +slug: Web/API/Notifications_API/Utilizar_API_Notificações +translation_of: Web/API/Notifications_API/Using_the_Notifications_API +--- +<p>{{APIRef("Web Notifications")}}</p> + +<p class="summary">The <a href="/en-US/docs/Web/API/Notifications_API">Notifications API</a> lets a web page or app send notifications that are displayed outside the page at the system level; this lets web apps send information to a user even if the application is idle or in the background. This article looks at the basics of using this API in your own apps.</p> + +<p>{{AvailableInWorkers}}</p> + +<p>Typically, system notifications refer to the operating system's standard notification mechanism: think for example of how a typical desktop system or mobile device brodcasts notifications.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/10959/android-notification.png" style="display: block; height: 184px; margin: 0px auto; width: 300px;"><img alt="" src="https://mdn.mozillademos.org/files/10961/mac-notification.png" style="display: block; height: 97px; margin: 0px auto; width: 358px;"></p> + +<p>The system notification system will vary of course by platform and browser, but this is ok, and the Notifications API is written to be general enough for compatibility with most system notification systems.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<div class="column-container"> +<div class="column-half"> +<p>One of the most obvious use cases for web notifications is a web-based mail or IRC application that needs to notify the user when a new message is received, even if the user is doing something else with another application. Many real examples of this now exist, such as <a href="https://slack.com/">Slack</a>.</p> + +<p>We've written a couple of real world demos to give more of an idea of how web notifications can be used:</p> + +<ul> + <li><strong>To-do list</strong>: This is a simple to-do list app that stores data locally using <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> and notifies users when tasks are due using system notifications. <a href="https://github.com/mdn/to-do-notifications/tree/gh-pages">Download the To-do list code</a>, or <a href="http://mdn.github.io/to-do-notifications/">view the app running live</a>.</li> + <li><strong>Emogotchi</strong>: A rather silly parody of Tamagotchi, in which you have to keep your Emo miserable otherwise you lose the game. This uses system notifications to tell you how well you are doing, and to complain at you, ALL THE TIME. <a href="https://github.com/mdn/emogotchi">Download the Emogotchi code</a>, or <a href="http://mdn.github.io/emogotchi/">view it running live</a>.</li> +</ul> +</div> + +<div class="column-half"> +<p style="text-align: center;"><img alt="" src="https://mdn.mozillademos.org/files/10963/emogotchi.png" style="max-width: 300px; width: 70%;">.</p> +</div> +</div> + +<h2 id="Solicitar_permissão">Solicitar permissão</h2> + +<p>Before an app can send a notification, the user must grant the application the right to do so. This is a common requirement when an API tries to interact with something outside a web page — at least once, the user needs to specifically grant that application permission to present notifications, thereby letting the user control which apps/sites are allowed to display notifications.</p> + +<h3 id="Verificação_do_estado_da_permissão_atual">Verificação do estado da permissão atual</h3> + +<p>You can check to see if you already have permission by checking the value of the {{domxref("Notification.permission")}} read only property. It can have one of three possible values:</p> + +<dl> + <dt><code>default</code></dt> + <dd>The user hasn't been asked for permission yet, so notifications won't be displayed.</dd> + <dt><code>granted</code></dt> + <dd>The user has granted permission to display notifications, after having been asked previously.</dd> + <dt><code>denied</code></dt> + <dd>The user has explicitly declined permission to show notifications.</dd> +</dl> + +<h3 id="Obter_permissão">Obter permissão</h3> + +<p>If permission to display notifications hasn't been granted yet, the application needs to use the {{domxref("Notification.requestPermission()")}} method to request this form the user. In its simplest form, as used in the <a href="https://github.com/mdn/emogotchi/blob/gh-pages/main.js#L54">Emogotchi demo</a>, we just include the following:</p> + +<pre class="brush: js">Notification.requestPermission();</pre> + +<p>The method also optionally accepts a callback function that is called once the user has responded to the request to display permissions (as seen in the second <code>else ... if</code> block below.) Commonly, you'll ask for permission to display notifications when your app is first initialized, and before trying to instantiate any. If you wanted to be really thorough, you could use a construct like the following (see <a href="https://github.com/mdn/to-do-notifications/blob/gh-pages/scripts/todo.js#L305-L344">To-do List Notifications</a>):</p> + +<pre class="brush: js">function notifyMe() { + // Let's check if the browser supports notifications + if (!("Notification" in window)) { + alert("This browser does not support system notifications"); + } + + // Let's check whether notification permissions have already been granted + else if (Notification.permission === "granted") { + // If it's okay let's create a notification + var notification = new Notification("Hi there!"); + } + + // Otherwise, we need to ask the user for permission + else if (Notification.permission !== 'denied') { + Notification.requestPermission(function (permission) { + // If the user accepts, let's create a notification + if (permission === "granted") { + var notification = new Notification("Hi there!"); + } + }); + } + + // Finally, if the user has denied notifications and you + // want to be respectful there is no need to bother them any more. +}</pre> + +<div class="note"> +<p><strong>Note:</strong> Before version 37, Chrome doesn't let you call {{domxref("Notification.requestPermission()")}} in the <code>load</code> event handler (see <a href="https://code.google.com/p/chromium/issues/detail?id=274284" title="https://code.google.com/p/chromium/issues/detail?id=274284">issue 274284</a>).</p> +</div> + +<h3 id="Permissões_de_manifesto_do_Firefox_OS">Permissões de manifesto do Firefox OS</h3> + +<p>Please note that while the Notifications API is not {{Glossary("privileged")}} or {{Glossary("certified")}}, you should still include an entry in your <code>manifest.webapp</code> file when including it in an Firefox OS app:</p> + +<pre>"permissions": { + "desktop-notification": { + "description": "Needed for creating system notifications." + } +}, +"messages": [{"notification": "path/to/your/index.html"}] + +</pre> + +<div class="note"> +<p><strong>Note</strong>: When an application is installed, you shouldn't need to {{anch("Getting permission","explicitly request permission")}}, but you will still need the permissions and messages entries above for the notifications to be fired.</p> +</div> + +<h2 id="Criação_de_uma_notificação">Criação de uma notificação</h2> + +<p>Creating a notification is easy; just use the {{domxref("Notification")}} constructor. This constructor expects a title to display within the notification and some options to enhance the notification such as an {{domxref("Notification.icon","icon")}} or a text {{domxref("Notification.body","body")}}.</p> + +<p>For example, in the <a href="https://github.com/mdn/emogotchi/blob/gh-pages/main.js#L101-L117">Emogotchi example</a> we have two functions that can be called when a notification needs to be fired; which one is used depends on whether we want a set notification, or a notification that includes random body content:</p> + +<pre class="brush: js">function spawnNotification(theBody,theIcon,theTitle) { + var options = { + body: theBody, + icon: theIcon + } + var n = new Notification(theTitle,options); + setTimeout(n.close.bind(n), 5000); +} + +function randomNotification() { + var randomQuote = quoteChooser(); + var options = { + body: randomQuote, + icon: 'img/sad_head.png', + } + + var n = new Notification('Emogotchi says',options); + setTimeout(n.close.bind(n), 5000); +}</pre> + +<h2 id="Fechar_notificações">Fechar notificações</h2> + +<p>Firefox and Safari close notifications automatically after a few moments (around four seconds). This may also happen at the operating system level. Some browsers don't however, such as Chrome. To make sure that the notifications close in all browsers, at the end of the above functions, we call the {{domxref("Notification.close")}} func<code>tion</code> inside a {{domxref("WindowTimers.setTimeout","setTimeout()")}} function to close the notification after 4 seconds. Also note the use of <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bind()</a></code> to make sure the <code>close()</code> call is associated with the notification.</p> + +<pre class="brush: js">setTimeout(n.close.bind(n), 5000); +</pre> + +<div class="note"> +<p><strong>Note</strong>: When you receive a "close" event, there is no guarantee that it's the user who closed the notification. This is in line with the specification, which states: "When a notification is closed, either by the underlying notifications platform or by the user, the close steps for it must be run."</p> +</div> + +<h2 id="Eventos_de_notificação">Eventos de notificação</h2> + +<p>The notifications API spec lists two events that are triggered on the {{domxref("Notification")}} instance:</p> + +<dl> + <dt>{{event("click")}}</dt> + <dd>Triggered when the user clicks on the notification.</dd> + <dt>{{event("error")}}</dt> + <dd>Triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason.</dd> +</dl> + +<p>These events can be tracked using the {{domxref("Notification.onclick","onclick")}} and {{domxref("Notification.onerror","onerror")}} handlers. Because {{domxref("Notification")}} also inherits from {{domxref("EventTarget")}}, it's possible to use the {{domxref("EventTarget.addEventListener","addEventListener()")}} method on it.</p> + +<p>There are also two other events that used to be listed in the spec, but were recently removed. These may still work in browsers for a while, but they should be treated as obsolete and not used:</p> + +<dl> + <dt>{{event("close")}}</dt> + <dd>Triggered once the notification is closed.</dd> + <dt>{{event("show")}}</dt> + <dd>Triggered when the notification is displayed to the user.</dd> +</dl> + +<h2 id="Substituir_notificações_existentes">Substituir notificações existentes</h2> + +<p>It is usually undesirable for a user to receive a lot of notifications in a short space of time — for example, what if a messenger application notified a user for each incoming message, and they were being sent a lot? To avoid spamming the user with too many notifications, it's possible to modify the pending notifications queue, replacing single or multiple pending notifications with a new one.</p> + +<p>To do this, it's possible to add a tag to any new notification. If a notification already has the same tag and has not been displayed yet, the new notification replaces that previous notification. If the notification with the same tag has already <span style="line-height: 1.5;">been </span><span style="line-height: 1.5;">displayed, the previous notification is closed and the new one is displayed.</span></p> + +<h3 id="Exemplo_de_etiqueta">Exemplo de etiqueta</h3> + +<p>Assume the following basic HTML:</p> + +<pre class="brush: html"><button>Notify me!</button></pre> + +<p>It's possible to handle multiple notifications this way:</p> + +<pre class="brush: js">window.addEventListener('load', function () { + // At first, let's check if we have permission for notification + // If not, let's ask for it + if (window.Notification && Notification.permission !== "granted") { + Notification.requestPermission(function (status) { + if (Notification.permission !== status) { + Notification.permission = status; + } + }); + } + + var button = document.getElementsByTagName('button')[0]; + + button.addEventListener('click', function () { + // If the user agreed to get notified + // Let's try to send ten notifications + if (window.Notification && Notification.permission === "granted") { + var i = 0; + // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time. + var interval = window.setInterval(function () { + // Thanks to the tag, we should only see the "Hi! 9" notification + var n = new Notification("Hi! " + i, {tag: 'soManyNotification'}); + if (i++ == 9) { + window.clearInterval(interval); + } + }, 200); + } + + // If the user hasn't told if he wants to be notified or not + // Note: because of Chrome, we are not sure the permission property + // is set, therefore it's unsafe to check for the "default" value. + else if (window.Notification && Notification.permission !== "denied") { + Notification.requestPermission(function (status) { + if (Notification.permission !== status) { + Notification.permission = status; + } + + // If the user said okay + if (status === "granted") { + var i = 0; + // Using an interval cause some browsers (including Firefox) are blocking notifications if there are too much in a certain time. + var interval = window.setInterval(function () { + // Thanks to the tag, we should only see the "Hi! 9" notification + var n = new Notification("Hi! " + i, {tag: 'soManyNotification'}); + if (i++ == 9) { + window.clearInterval(interval); + } + }, 200); + } + + // Otherwise, we can fallback to a regular modal alert + else { + alert("Hi!"); + } + }); + } + + // If the user refuses to get notified + else { + // We can fallback to a regular modal alert + alert("Hi!"); + } + }); +});</pre> + +<p>See the live result below:</p> + +<p>{{ EmbedLiveSample('Tag_example', '100%', 30) }}</p> + +<h2 id="Receber_notificação_de_cliques_nas_notificações_da_aplicação">Receber notificação de cliques nas notificações da aplicação</h2> + +<p>When a user clicks on a notification generated by an app, you will be notified of this event in two different ways, depending on the circumstance:</p> + +<ol> + <li>A click event if your app has not closed or been put in the background between the time you create the notification and the time the user clicks on it.</li> + <li>A <a href="/en-US/docs/Web/API/Navigator/mozSetMessageHandler">system message</a> otherwise.</li> +</ol> + +<p>See <a href="https://github.com/mozilla/buddyup/commit/829cba7afa576052cf601c3e286b8d1981f93f45#diff-3">this code snippet</a> for an example of how to deal with this.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Notifications')}}</td> + <td>{{Spec2('Web Notifications')}}</td> + <td>Living standard</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_do_navegador">Compatibilidade do navegador</h2> + +<p>{{page("/en-US/Web/API/Notification","Browser compatibility")}}</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/en-US/Apps/Build/User_notifications">Referência das notificações do utilizador</a></li> + <li><a href="/en-US/Apps/Build/User_notifications/Notifying_users_via_the_Notification_and_Vibration">Notificação dos utilziadores via APIs de Notificação e Vibração</a></li> + <li>{{ domxref("Notificação") }}</li> +</ul> diff --git a/files/pt-pt/web/api/page_visibility_api/index.html b/files/pt-pt/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..de3ee0b3ab --- /dev/null +++ b/files/pt-pt/web/api/page_visibility_api/index.html @@ -0,0 +1,271 @@ +--- +title: Page Visibility API +slug: Web/API/Page_Visibility_API +tags: + - API + - DOM + - Intermediário + - Tutoriais +translation_of: Web/API/Page_Visibility_API +--- +<div>{{DefaultAPISidebar("Page Visibility API")}}</div> + +<p><span class="seoSummary">A <strong>Page Visibility API</strong> </span>permite-lhe saber quando uma página da <em>Web </em>está visível ou em foco. Com a navegação por separadores, existe uma chance razoável de que qualquer página da <em>Web </em>esteja em segundo plano e, portanto, não seja visível para o utilizador. Quando o utilizador minimiza a página da <em>Web </em>ou move-se para outro separador, a API envia um evento {{event('visibilitychange')}} sobre a visibilidade da página. Pode detetar o evento e executar algumas ações ou comportar-se de forma diferente. Por exemplo, se a sua aplicação da <em>Web </em>estiver a reproduzir um vídeo, esta pausará o momento em que o utilizador olha para outro navegador, e reproduz novamente quando o utilizador volta ao separador. O utilizador não perde o seu lugar no vídeo e pode continuar a assistir.</p> + +<p>Estados de visibilidade de uma {{HTMLElement("iframe")}} são iguais ao documento original. Ocultar a iframe com propriedades CSS não desencadeia eventos de visibilidade nem altera o estado do documento de conteúdo.</p> + +<h3 id="Benefícios">Benefícios</h3> + +<p>The API is particularly useful for saving resources by giving developers the opportunity to not perform unnecessary tasks when the webpage is not visible.</p> + +<ul> +</ul> + +<h3 id="Casos_de_utilização">Casos de utilização</h3> + +<p>Alguns exemplos:</p> + +<ul> + <li>A site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page.</li> + <li>An application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible.</li> + <li>A page wants to detect when it is being prerendered so it can keep accurate count of page views.</li> + <li>A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)</li> +</ul> + +<p>Developers have historically used imperfect proxies to detect this. For example, registering an onblur/onfocus handler on the window helps you know when your page is not the active page, but it does not tell you that your page is hidden to the user. The Page Visibility API addresses this. (When compared with registering onblur/onfocus handlers on the window, a key difference is that a page does <em>not</em> become hidden when another window is made active and the browser window loses focus. A page only becomes hidden when the user switches to a different tab or minimizes the browser window.)</p> + +<h3 id="Políticas_em_vigor_para_auxiliar_o_desempenho_da_página_de_fundo">Políticas em vigor para auxiliar o desempenho da página de fundo</h3> + +<p>Along with the Page Visibility API, there are a number of policies in place to mitigate negative performance effects associated with background tabs:</p> + +<ul> + <li>{{domxref("Window.requestAnimationFrame()")}} calls are paused in most browsers when running in background tabs or hidden {{ HTMLElement("iframe") }}s in order to improve performance and battery life.</li> + <li>Timers such as {{domxref("WindowOrWorkerGlobalScope.setTimeout")}} are throttled in background/inactive tabs to help improve performance. See <a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified">Reasons for delays longer than specified</a> for more details.</li> + <li>Budget-based background timeout throttling is now available in modern browsers (Firefox 58+, Chrome 57+), placing an additional limit on background timer CPU usage. This operates in a similar way across modern browsers, with the details being as follows: + <ul> + <li>In Firefox, windows in background tabs each have their own time budget in milliseconds — a max and a min value of +50 ms and -150 ms, respectively. Chrome is very similar except that the budget is specified in seconds.</li> + <li>Windows are subjected to throttling after 30 seconds, with the same throttling delay rules as specified for window timers (again, see <a href="/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified">Reasons for delays longer than specified</a>.) In Chrome, this value is 10 seconds.</li> + <li>Timer tasks are only permitted when the budget is non-negative.</li> + <li>When a timer has executed, the execution time is deducted from the budget of the window where the timeout gets called from.</li> + <li>The budget regenerates at a rate of 10 ms per second, in both Firefox and Chrome.</li> + </ul> + </li> + <li>Some processes are exempt from this throttling behaviour: + <ul> + <li>Applications playing audio are considered foreground and aren’t throttled.</li> + <li>Applications with real-time connections (<a href="/en-US/docs/Web/API/WebSockets_API">WebSockets</a> and <a href="/en-US/docs/Web/API/WebRTC_API">WebRTC</a>), to avoid closing these connections by timeout.</li> + <li><a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> processes.</li> + </ul> + </li> +</ul> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Ver <a href="http://daniemon.com/tech/webapps/page-visibility/">exemplo live </a>(vídeo com som).</p> + +<p>O exemplo, que pausa o vídeo quando muda para outro separador e reproduz novamente quando volta ao seu separador, foi criado com o seguinte código:</p> + +<pre class="brush: js">// Set the name of the hidden property and the change event for visibility +var hidden, visibilityChange; +if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support + hidden = "hidden"; + visibilityChange = "visibilitychange"; +} else if (typeof document.msHidden !== "undefined") { + hidden = "msHidden"; + visibilityChange = "msvisibilitychange"; +} else if (typeof document.webkitHidden !== "undefined") { + hidden = "webkitHidden"; + visibilityChange = "webkitvisibilitychange"; +} + +var videoElement = document.getElementById("videoElement"); + +// If the page is hidden, pause the video; +// if the page is shown, play the video +function handleVisibilityChange() { + if (document[hidden]) { + videoElement.pause(); + } else { + videoElement.play(); + } +} + +// Warn if the browser doesn't support addEventListener or the Page Visibility API +if (typeof document.addEventListener === "undefined" || typeof document.hidden === "undefined") { + console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API."); +} else { + // Handle page visibility change + document.addEventListener(visibilityChange, handleVisibilityChange, false); + + // When the video pauses, set the title. + // This shows the paused + videoElement.addEventListener("pause", function(){ + document.title = 'Paused'; + }, false); + + // When the video plays, set the title. + videoElement.addEventListener("play", function(){ + document.title = 'Playing'; + }, false); + +} +</pre> + +<h2 id="Resumo_das_propriedades">Resumo das propriedades</h2> + +<dl> + <dt> + <p id="document.hidden_Read_only">{{domxref("document.hidden")}} <span class="inlineIndicator readOnly readOnlyInline" title="This value may not be changed.">Read only </span></p> + </dt> + <dd> + <p>Returns <code>true</code> if the page is in a state considered to be hidden to the user, and <code>false</code> otherwise.</p> + </dd> + <dt> + <p id="document.visibilityState_Read_only">{{domxref("document.visibilityState")}} <span class="inlineIndicator readOnly readOnlyInline" title="This value may not be changed.">Read only </span></p> + </dt> + <dd> + <p>Is a <code>string</code> denoting the visibility state of the document. Possible values:</p> + + <ul> + <li><code>visible</code> : the page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window.</li> + <li><code>hidden</code> : the page content is not visible to the user. In practice this means that the document is either a background tab or part of a minimized window, or the OS screen lock is active.</li> + <li><code>prerender</code> : the page content is being prerendered and is not visible to the user (considered hidden for purposes of <code>document.hidden</code>). The document may start in this state, but will never transition to it from another value. Note: browser support is optional.</li> + <li><code>unloaded</code> : the page is being unloaded from memory. Note: browser support is optional.</li> + </ul> + + <pre class="brush: js">//startSimulation and pauseSimulation defined elsewhere +function handleVisibilityChange() { + if (document.hidden) { + pauseSimulation(); + } else { + startSimulation(); + } +} + +document.addEventListener("visibilitychange", handleVisibilityChange, false); +</pre> + </dd> + <dt> + <p>{{domxref("document.onvisibilitychange")}}</p> + </dt> + <dd> + <p>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.</p> + </dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Page Visibility API')}}</td> + <td>{{Spec2('Page Visibility API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>13 {{property_prefix("webkit")}}<br> + 33</td> + <td>{{CompatGeckoDesktop(18)}}<sup>[2]</sup></td> + <td>10</td> + <td>12.10<sup>[1]</sup></td> + <td>7</td> + </tr> + <tr> + <td><code>onvisibilitychange</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(56)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Budget-based background timeout throttling</td> + <td>57</td> + <td>{{CompatGeckoDesktop(58)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>5.0<sup>[3]</sup></td> + <td>{{CompatGeckoMobile(18)}}<sup>[2]</sup></td> + <td>10</td> + <td>12.10<sup>[1]</sup></td> + <td>7<sup>[4]</sup></td> + </tr> + <tr> + <td><code>onvisibilitychange</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(56)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Budget-based background timeout throttling</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(58)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Doesn't fire the {{event("visibilitychange")}} event when the browser window is minimized, nor set <code>hidden</code> to <code>true</code>.</p> + +<p>[2] From Firefox 10 to Firefox 51 included, this property could be used prefixed with <code>moz</code>.</p> + +<p>[3] Android 4.4 supports this feature if prefixed with <code>webkit</code>.</p> + +<p>[4] From iOS 11.0.2 onwards, the values are not correct in standalone mode (when you press "Add to Homescreen") and when the screen is locked (you pressed the power button). The value for <code>hidden</code> is <code>false</code> and <code>visibilityState</code> is <code>visible</code>.</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li>Descrição da <a href="http://blogs.msdn.com/b/ie/archive/2011/07/08/using-pc-hardware-more-efficiently-in-html5-new-web-performance-apis-part-2.aspx" title="Page Visibility on IEBlog">Page Visibility API</a> no IEBlog (inglês).</li> + <li>Descrição da <a href="http://code.google.com/chrome/whitepapers/pagevisibility.html" title="Page Visibility API by Google">Page Visibility API</a> pela Google (inglês).</li> +</ul> diff --git a/files/pt-pt/web/api/push_api/index.html b/files/pt-pt/web/api/push_api/index.html new file mode 100644 index 0000000000..9e94962adc --- /dev/null +++ b/files/pt-pt/web/api/push_api/index.html @@ -0,0 +1,175 @@ +--- +title: Push API +slug: Web/API/Push_API +tags: + - API + - Experimental + - Landing + - Notificações + - Push + - Referencia + - Service Workers +translation_of: Web/API/Push_API +--- +<div>{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}</div> + +<p class="summary"><strong>Push API</strong> permite que as aplicações da Web recebam as mensagens submetidas para as mesmas a partir de um servidor, se a aplicação da Web está em primeiro plano, ou mesmo atualmente carregada, num agente de utilizador. Isto permite que os programadores entreguem notificações e atualizações assíncronas aos utilizadores que optem, resultando num melhor compromisso com os novos conteúdos atualizados.</p> + +<h2 id="Conceitos_e_utilização_de_Push">Conceitos e utilização de <em>Push</em></h2> + +<p>For an app to receive push messages, it has to have an active <a href="/en-US/docs/Web/API/ServiceWorker_API">service worker</a>. When the service worker is active, it can subscribe to push notifications, using {{domxref("PushManager.subscribe()")}}.</p> + +<p>The resulting {{domxref("PushSubscription")}} includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data.</p> + +<p>The service worker will be started as necessary to handle incoming push messages, which are delivered to the {{domxref("ServiceWorkerGlobalScope.onpush")}} event handler. This allows apps to react to push messages being received, for example, by displaying a notification (using {{domxref("ServiceWorkerRegistration.showNotification()")}}.)</p> + +<p>Each subscription is unique to a service worker. The endpoint for the subscription is a unique <a href="http://www.w3.org/TR/capability-urls/">capability URL</a>: knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be able to send push messages to your application.</p> + +<p>Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different schemes for handling this, there is currently no standard mechanism. Firefox allows a limited number (quota) of push messages to be sent to an application, although Push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. In comparison, Chrome applies no limit, but requires that every push message causes a notification to be displayed.</p> + +<div class="note"> +<p><strong>Nota</strong>: As of Gecko 44, the allowed quota of push messages per application is not incremented when a new notification fires, when another is still visible, for a period of three seconds. This handles cases where a burst of notifications is received, and not all generate a visible notification.</p> +</div> + +<div class="note"> +<p><strong>Nota</strong>: Chrome versions earlier than 52 require you to set up a project on <a href="https://developers.google.com/cloud-messaging/">Google Cloud Messaging</a> to send push messages, and use the associated project number and API key when sending push notifications. It also requires an app manifest, with some special parameters to use this service.</p> +</div> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("PushEvent")}}</dt> + <dd>Represents a push action, sent to the <a href="/en-US/docs/Web/API/ServiceWorkerGlobalScope">global scope</a> of a {{domxref("ServiceWorker")}}. It contains information sent from an application to a {{domxref("PushSubscription")}}.</dd> + <dt>{{domxref("PushManager")}}</dt> + <dd>Provides a way to receive notifications from third-party servers, as well as request URLs for push notifications. This interface has replaced the functionality offered by the obsolete {{domxref("PushRegistrationManager")}} interface.</dd> + <dt>{{domxref("PushMessageData")}}</dt> + <dd>Provides access to push data sent by a server, and includes methods to manipulate the received data.</dd> + <dt>{{domxref("PushSubscription")}}</dt> + <dd>Provides a subcription's URL endpoint, and allows unsubscription from a push service.</dd> +</dl> + +<h2 id="Service_worker_additions">Service worker additions</h2> + +<p>The following additions to the <a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a> have been specified in the Push API spec to provide an entry point for using Push messages. They also monitor and respond to push and subscription change events.</p> + +<dl> + <dt>{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}</dt> + <dd>Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope.onpush")}}</dt> + <dd>An event handler fired whenever a {{Event("push")}} event occurs; that is, whenever a server push message is received.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}</dt> + <dd>An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Mozilla's <a href="https://serviceworke.rs/">ServiceWorker Cookbook</a> contains many useful Push examples.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName("Push API")}}</td> + <td>{{Spec2("Push API")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatChrome(42.0)}}</td> + <td>{{CompatGeckoDesktop(44.0)}}<sup>[1][3]</sup></td> + <td>{{CompatNo}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("PushEvent.data")}},<br> + {{domxref("PushMessageData")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(44.0)}}<sup>[3]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(48.0)}}<sup>[4]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}<sup>[2]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}</td> + </tr> + <tr> + <td>{{domxref("PushEvent.data")}},<br> + {{domxref("PushMessageData")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile(48.0)}}<sup>[4]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<ul> + <li>[1] Currently available only on desktop versions of Firefox; also, push messages are only delivered when Firefox is running.</li> + <li>[2] This is currently not implemented. See the <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/status/pushapi/">Microsoft Edge status information</a>.</li> + <li>[3] Push (and <a href="/en-US/docs/Web/API/Service_Worker_API">Service Workers</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 and 52 Extended Support Releases</a> (ESR.)</li> + <li>[4] Push has been enabled by default on Firefox for Android version 48.</li> +</ul> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="https://blog.mozilla.org/services/2016/08/23/sending-vapid-identified-webpush-notifications-via-mozillas-push-service/">Sending VAPID identified WebPush Notifications via Mozilla’s Push Service</a></li> + <li><a href="https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/">Web Push Notifications: Timely, Relevant, and Precise</a>, Joseph Medley</li> + <li><a href="/pt-PT/docs/Web/API/Service_Worker_API">Service Worker API</a></li> +</ul> diff --git a/files/pt-pt/web/api/service_worker_api/index.html b/files/pt-pt/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..343635d6c2 --- /dev/null +++ b/files/pt-pt/web/api/service_worker_api/index.html @@ -0,0 +1,335 @@ +--- +title: API de Service Worker +slug: Web/API/Service_Worker_API +tags: + - API + - Landing + - Off-line + - Referencia + - Resumo + - Service Workers + - Sinopse + - Workers +translation_of: Web/API/Service_Worker_API +--- +<div> +<p>{{ServiceWorkerSidebar}}</p> + +<p class="summary">Os <strong><em>service workers</em></strong> atuam essencialmente como servidores de <em>proxy </em>que ficam entre as aplicações da Web, e o navegador e a rede (quando disponível). Eles são destinados para (entre outras coisas) ativar a criação de experiências efetivas, intercetar pedidos de rede e tomando medidas adequadas com base na disponibilidade da rede e na atualização dos ativos no servidor. Eles também irão permitir o acesso para solicitar notificações e sincronizar as APIs em segundo plano.</p> +</div> + +<h2 id="Conceitos_e_utilização_do_service_worker">Conceitos e utilização do <em>service worker</em></h2> + +<p>A service worker is an event-driven <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">worker</a> registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)</p> + +<p>A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is not blocking. It is designed to be fully async; as a consequence, APIs such as synchronous <a href="/en-US/docs/Web/API/XMLHttpRequest">XHR</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage">localStorage</a> can't be used inside a service worker.</p> + +<p>Service workers only run over HTTPS, for security reasons. Having modified network requests wide open to man in the middle attacks would be really bad. In Firefox, Service Worker APIs are also hidden and cannot be used when the user is in <a href="https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history">private browsing mode</a>.</p> + +<div class="note"> +<p><strong>Nota</strong>: Service Workers win over previous attempts in this area such as <a href="http://alistapart.com/article/application-cache-is-a-douchebag">AppCache</a> because they don't make assumptions about what you are trying to do and then break when those assumptions are not exactly right; you have granular control over everything.</p> +</div> + +<div class="note"> +<p><strong>Nota</strong>: Service workers make heavy use of <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promises</a>, as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.</p> +</div> + +<h3 id="Registo">Registo</h3> + +<p>A service worker is first registered using the {{domxref("ServiceWorkerContainer.register()")}} method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.</p> + +<h3 id="Transferir_instalar_e_ativar">Transferir, instalar e ativar</h3> + +<p>Neste ponto, o seu <em>service worker </em>observará o seguinte ciclo vital:</p> + +<ol> + <li>Transferir</li> + <li>Instalar</li> + <li>Ativar</li> +</ol> + +<p>The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.</p> + +<p>After that it is downloaded every 24 hours or so. It <em>may</em> be downloaded more frequently, but it <strong>must</strong> be downloaded every 24h to prevent bad scripts from being annoying for too long.</p> + +<p>Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.</p> + +<p>If this is the first time a service worker has been made available, installation is attempted, then after a successful installation it is activated.</p> + +<p>If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the <em>worker in waiting</em>. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates (becoming the <em>active worker</em>). Activation can happen sooner using {{domxref("ServiceWorkerGlobalScope.skipWaiting()")}} and existing pages can be claimed by the active worker using {{domxref("Clients.claim()")}}.</p> + +<p>You can listen out for the {{domxref("InstallEvent")}}; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.</p> + +<p>There is also an <code>activate</code> event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.</p> + +<p>Your service worker can respond to requests using the {{domxref("FetchEvent")}} event. You can modify the response to these requests in any way you want, using the {{domxref("FetchEvent.respondWith")}} method.</p> + +<div class="note"> +<p><strong>Nota</strong>: Because <code>oninstall</code>/<code>onactivate</code> could take a while to complete, the service worker spec provides a <code>waitUntil</code> method that, when called <code>oninstall</code> or <code>onactivate</code>, passes a promise. Functional events are not dispatched to the service worker until the promise successfully resolves.</p> +</div> + +<p>Para um tutorial completo para mostrars como crair o seu primeiro exemplo básico, leia <a href="/pt-PT/docs/Web/API/Service_Worker_API/Using_Service_Workers">Utilização de <em>Service Workers</em></a>.</p> + +<h2 id="Outras_ideas_de_casos_de_utilização">Outras ideas de casos de utilização</h2> + +<p>Service workers are also intended to be used for such things as:</p> + +<ul> + <li>Background data synchronization</li> + <li>Responding to resource requests from other origins</li> + <li>Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data</li> + <li>Client-side compiling and dependency management of CoffeeScript, less, CJS/AMD modules, etc. for dev purposes</li> + <li>Hooks for background services</li> + <li>Custom templating based on certain URL patterns</li> + <li>Performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.</li> +</ul> + +<p>In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:</p> + +<ul> + <li><a href="https://github.com/slightlyoff/BackgroundSync">Background synchronization</a>: Start up a service worker even when no users are at the site, so caches can be updated, etc.</li> + <li><a href="/en-US/docs/Web/API/Push_API">Reacting to push messages</a>: Start up a service worker to send users a message to tell them new content is available.</li> + <li>Reacting to a particular time & date</li> + <li>Entering a geo-fence</li> +</ul> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt>{{domxref("Cache")}}</dt> + <dd>Represents the storage for {{domxref("Request")}} / {{domxref("Response")}} object pairs that are cached as part of the {{domxref("ServiceWorker")}} life cycle.</dd> + <dt>{{domxref("CacheStorage")}}</dt> + <dd>Represents the storage for {{domxref("Cache")}} objects. It provides a master directory of all the named caches that a {{domxref("ServiceWorker")}} can access and maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.</dd> + <dt>{{domxref("Client")}}</dt> + <dd>Represents the scope of a service worker client. A service worker client is either a document in a browser context or a {{domxref("SharedWorker")}}, which is controlled by an active worker.</dd> + <dt>{{domxref("Clients")}}</dt> + <dd>Represents a container for a list of {{domxref("Client")}} objects; the main way to access the active service worker clients at the current origin.</dd> + <dt>{{domxref("ExtendableEvent")}}</dt> + <dd>Extends the lifetime of the <code>install</code> and <code>activate</code> events dispatched on the {{domxref("ServiceWorkerGlobalScope")}} as part of the service worker lifecycle. This ensures that any functional events (like {{domxref("FetchEvent")}} ) are not dispatched to the {{domxref("ServiceWorker")}} until it upgrades database schemas, deletes outdated cache entries, etc.</dd> + <dt>{{domxref("ExtendableMessageEvent")}}</dt> + <dd>The event object of a {{event("message_(ServiceWorker)","message")}} event fired on a service worker (when a channel message is received on the {{domxref("ServiceWorkerGlobalScope")}} from another context) — extends the lifetime of such events.</dd> + <dt>{{domxref("FetchEvent")}}</dt> + <dd>The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onfetch")}} handler, <code>FetchEvent</code> represents a fetch action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. It contains information about the request and resulting response, and provides the {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}} method, which allows us to provide an arbitrary response back to the controlled page.</dd> + <dt>{{domxref("InstallEvent")}}</dt> + <dd>The parameter passed into the {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the <code>InstallEvent</code> interface represents an install action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. As a child of {{domxref("ExtendableEvent")}}, it ensures that functional events such as {{domxref("FetchEvent")}} are not dispatched during installation. </dd> + <dt>{{domxref("NavigationPreloadManager")}}</dt> + <dd>Provides methods for managing the preloading of resources with a service worker. </dd> + <dt>{{domxref("Navigator.serviceWorker")}}</dt> + <dd>Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the <a href="https://html.spec.whatwg.org/multipage/browsers.html#concept-document-window">associated document</a>.</dd> + <dt>{{domxref("NotificationEvent")}}</dt> + <dd>The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} handler, the <code>NotificationEvent</code> interface represents a notification click event that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.</dd> + <dt>{{domxref("ServiceWorker")}}</dt> + <dd>Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same <code>ServiceWorker</code> object.</dd> + <dt>{{domxref("ServiceWorkerContainer")}}</dt> + <dd>Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.</dd> + <dt>{{domxref("ServiceWorkerGlobalScope")}}</dt> + <dd>Represents the global execution context of a service worker.</dd> + <dt>{{domxref("ServiceWorkerMessageEvent")}} {{deprecated_inline}}</dt> + <dd>Represents a message sent to a {{domxref("ServiceWorkerGlobalScope")}}. <strong>Note that this interface is deprecated in modern browsers. Service worker messages will now use the {{domxref("MessageEvent")}} interface, for consistency with other web messaging features.</strong></dd> + <dt>{{domxref("ServiceWorkerRegistration")}}</dt> + <dd>Represents a service worker registration.</dd> + <dt>{{domxref("ServiceWorkerState")}} {{experimental_inline}}</dt> + <dd>Associated with its <a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker" title="The ServiceWorker interface of the ServiceWorker API provides a reference to a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same service worker, each through a unique ServiceWorker object."><code>ServiceWorker</code></a>'s state.</dd> + <dt>{{domxref("SyncEvent")}} {{non-standard_inline}}</dt> + <dd> + <p>The SyncEvent interface represents a sync action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a ServiceWorker. </p> + </dd> + <dt>{{domxref("SyncManager")}} {{non-standard_inline}}</dt> + <dd>Provides an interface for registering and listing sync registrations.</dd> + <dt>{{domxref("WindowClient")}}</dt> + <dd>Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of {{domxref("Client")}} object, with some additional methods and properties available.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Service Workers')}}</td> + <td>{{Spec2('Service Workers')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div>{{ CompatibilityTable() }}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(40)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>24</td> + <td>{{ CompatNo() }}<sup>[3]</sup></td> + </tr> + <tr> + <td>install/activate events</td> + <td>{{ CompatChrome(40) }}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>fetch event/request/<br> + <code>respondWith()</code></td> + <td>{{CompatChrome(40)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoDesktop("44.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>caches/cache</td> + <td> + <p class="p1">{{CompatChrome(42)}}</p> + </td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoDesktop("39.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>{{domxref("ServiceWorkerMessageEvent")}} deprecated in favour of {{domxref("MessageEvent")}}</td> + <td> + <p class="p1">{{CompatChrome(57)}}</p> + </td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatGeckoDesktop("55.0") }}<sup>[2]</sup></td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>NavigationPreloadManager</code></td> + <td>{{CompatChrome(59)}}</td> + <td>{{ CompatNo() }}</td> + <td></td> + <td>{{ CompatNo() }}</td> + <td>{{CompatOpera(46)}}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}<sup>[3]</sup></td> + </tr> + <tr> + <td> install/activate events</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>fetch event/request/<br> + <code>respondWith()</code></td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoMobile("44.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>caches/cache</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(40)}}</td> + <td>{{CompatNo}}<sup>[1]</sup></td> + <td>{{ CompatGeckoMobile("39.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td>{{domxref("ServiceWorkerMessageEvent")}} deprecated in favour of {{domxref("MessageEvent")}}</td> + <td>{{ CompatNo() }}</td> + <td> + <p class="p1">{{CompatChrome(57)}}</p> + </td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatGeckoMobile("55.0") }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + </tr> + <tr> + <td><code>NavigationPreloadManager</code></td> + <td>{{ CompatNo() }}</td> + <td>{{CompatChrome(59)}}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{ CompatNo() }}</td> + <td>{{CompatOperaMobile(46)}}</td> + <td>{{ CompatNo() }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] This feature is not supported yet, though it's <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/status/serviceworker/">already in development</a>.</p> + +<p>[2] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 & 52 Extended Support Releases</a> (ESR.)</p> + +<p>[3] This feature is not supported yet, though it's <a href="https://bugs.webkit.org/show_bug.cgi?id=174541">currently</a> <a href="https://webkit.org/status/#specification-service-workers">in development</a>.</p> + +<h2 id="Consulte_também">Consulte também:</h2> + +<ul> + <li><a href="https://serviceworke.rs">ServiceWorker Cookbook</a></li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li> + <li><a href="https://github.com/mdn/sw-test">Service workers basic code example</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> + <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> + <li><a href="https://www.fastly.com/blog/best-practices-for-using-the-vary-header">Best Practices for using the VARY header</a></li> +</ul> diff --git a/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html b/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..bce8c7d4f1 --- /dev/null +++ b/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,459 @@ +--- +title: Utilização de "Service Workers" +slug: Web/API/Service_Worker_API/Using_Service_Workers +tags: + - Guía + - ServiceWorker + - Serviço + - Workers + - básicos +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +<p>{{ServiceWorkerSidebar}}</p> + +<div class="summary"> +<p>This article provides information on getting started with service workers, including basic architecture, registering a service worker, the install and activation process for a new service worker, updating your service worker, cache control and custom responses, all in the context of a simple app with offline functionality. </p> +</div> + +<h2 id="The_premise_of_service_workers">The premise of service workers</h2> + +<p>One overriding problem that web users have suffered with for years is loss of connectivity. The best web app in the world will provide a terrible user experience if you can’t download it. There have been various attempts to create technologies to solve this problem, as our <a href="/en-US/Apps/Build/Offline">Offline</a> page shows, and some of the issues have been solved. But the overriding problem is that there still isn’t a good overall control mechanism for asset caching and custom network requests.<br> + <br> + The previous attempt — <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> — seemed to be a good idea because it allowed you to specify assets to cache really easily. However, it made many assumptions about what you were trying to do and then broke horribly when your app didn’t follow those assumptions exactly. Read Jake Archibald's (unfortunately-titled but well-written) <a href="http://alistapart.com/article/application-cache-is-a-douchebag">Application Cache is a Douchebag</a> for more details.</p> + +<div class="note"> +<p><strong>Nota</strong>: As of Firefox 44, when <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> is used to provide offline support for a page a warning message is now displayed in the console advising developers to use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> instead ({{bug("1204581")}}.)</p> +</div> + +<p>Service workers should finally fix these issues. Service worker syntax is more complex than that of AppCache, but the trade off is that you can use JavaScript to control your AppCache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more. Using a Service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as <a href="http://offlinefirst.org/">Offline First</a>). This is already available with native apps, which is one of the main reasons native apps are often chosen over web apps.</p> + +<h2 id="Setting_up_to_play_with_service_workers">Setting up to play with service workers</h2> + +<p>Many service workers features are now enabled by default in newer versions of supporting browsers. If however you find that demo code is not working in your installed versions, you might need to enable a pref:</p> + +<ul> + <li><strong>Firefox Nightly</strong>: Go to <code>about:config</code> and set <code>dom.serviceWorkers.enabled</code> to true; restart browser.</li> + <li><strong>Chrome Canary</strong>: Go to <code>chrome://flags</code> and turn on <code>experimental-web-platform-features</code>; restart browser (note that some features are now enabled by default in Chrome.)</li> + <li><strong>Opera</strong>: Go to <code>opera://flags</code> and enable <code>Support for ServiceWorker</code>; restart browser.</li> + <li><strong>Microsoft Edge</strong>: Go to <code>about:flags</code> and tick <code>Enable service workers</code>; restart browser.</li> +</ul> + +<p>You’ll also need to serve your code via HTTPS — Service workers are restricted to running across HTTPS for security reasons. GitHub is therefore a good place to host experiments, as it supports HTTPS. In order to facilitate local development, <code>localhost</code> is considered a secure origin by browsers as well.</p> + +<h2 id="Basic_architecture">Basic architecture</h2> + +<p>With service workers, the following steps are generally observed for basic set up:</p> + +<ol> + <li>The service worker URL is fetched and registered via {{domxref("serviceWorkerContainer.register()")}}.</li> + <li>If successful, the service worker is executed in a {{domxref("ServiceWorkerGlobalScope") }}; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access.</li> + <li>The service worker is now ready to process events.</li> + <li>Installation of the worker is attempted when service worker-controlled pages are accessed subsequently. An Install event is always the first one sent to a service worker (this can be used to start the process of populating an IndexedDB, and caching site assets). This is really the same kind of procedure as installing a native or Firefox OS app — making everything available for use offline.</li> + <li>When the <code>oninstall</code> handler completes, the service worker is considered installed.</li> + <li>Next is activation. When the service worker is installed, it then receives an activate event. The primary use of <code>onactivate</code> is for cleanup of resources used in previous versions of a Service worker script.</li> + <li>The Service worker will now control pages, but only those opened after the <code>register()</code> is successful. i.e. a document starts life with or without a Service worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled.</li> +</ol> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12636/sw-lifecycle.png" style="display: block; height: 867px; margin: 0px auto; width: 579px;"></p> + +<p>The below graphic shows a summary of the available service worker events:</p> + +<p><img alt="install, activate, message, fetch, sync, push" src="https://mdn.mozillademos.org/files/12632/sw-events.png" style="display: block; margin: 0px auto;"></p> + +<h3 id="Promises">Promises</h3> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a> are a great mechanism for running async operations, with success dependant on one another. This is central to the way service workers work.<br> + <br> + Promises can do a variety of things, but all you need to know for now is that if something returns a promise, you can attach <code>.then()</code> to the end and include callbacks inside it for success cases, or you can insert <code>.catch()</code> on the end if you want to include a failure callback.</p> + +<p>Let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent.</p> + +<h4 id="sync">sync</h4> + +<pre class="brush: js">try { + const value = myFunction(); + console.log(value); +} catch(err) { + console.log(err); +}</pre> + +<h4 id="async">async</h4> + +<pre class="brush: js">myFunction().then((value) => { + console.log(value); +}).catch((err) => { + console.log(err); +});</pre> + +<p>In the first example, we have to wait for <code>myFunction()</code> to run and return <code>value</code> before any more of the code can execute. In the second example, <code>myFunction()</code> returns a promise for <code>value</code>, then the rest of the code can carry on running. When the promise resolves, the code inside <code>then</code> will be run, asynchronously.<br> + <br> + Now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? This is a standard thing to want to do, but it can be a bit of a pain. We can use <code>.onload</code> to only display the image after it’s loaded, but what about events that start happening before we start listening to them? We could try to work around this using <code>.complete</code>, but it’s still not foolproof, and what about multiple images? And, ummm, it’s still synchronous, so blocks the main thread.<br> + <br> + Instead, we could build our own promise to handle this kind of case. (See our <a href="https://github.com/mdn/js-examples/tree/master/promises-test">Promises test</a> example for the source code, or <a href="https://mdn.github.io/js-examples/promises-test/">look at it running live</a>.)</p> + +<p>{{note("A real service worker implementation would use caching and onfetch rather than the deprecated XMLHttpRequest API. Those features are not used here so that you can focus on understanding Promises.")}}</p> + +<pre class="brush: js">const imgLoad = (url) => { + return new Promise((resolve, reject) => { + var request = new XMLHttpRequest(); + request.open('GET', url); + request.responseType = 'blob'; + + request.onload = () => { + if (request.status == 200) { + resolve(request.response); + } else { + reject(Error('Image didn\'t load successfully; error code:' + request.statusText)); + } + }; + + request.onerror = () => { + reject(Error('There was a network error.')); + }; + + request.send(); + }); +}</pre> + +<p>We return a new promise using the <code>Promise()</code> constructor, which takes as an argument a callback function with <code>resolve</code> and <code>reject</code> parameters. Somewhere in the function, we need to define what happens for the promise to resolve successfully or be rejected — in this case return a 200 OK status or not — and then call <code>resolve</code> on success, or <code>reject</code> on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won’t worry about that for now.</p> + +<p>When we come to call the <code>imgLoad()</code> function, we call it with the url to the image we want to load, as we might expect, but the rest of the code is a little different:</p> + +<pre class="brush: js">let body = document.querySelector('body'); +let myImage = new Image(); + +imgLoad('myLittleVader.jpg').then((response) => { + var imageURL = window.URL.createObjectURL(response); + myImage.src = imageURL; + body.appendChild(myImage); +}, (Error) => { + console.log(Error); +});</pre> + +<p>On to the end of the function call, we chain the promise <code>then()</code> method, which contains two functions — the first one is executed when the promise successfully resolves, and the second is called when the promise is rejected. In the resolved case, we display the image inside <code>myImage</code> and append it to the body (it’s argument is the <code>request.response</code> contained inside the promise’s <code>resolve</code> method); in the rejected case we return an error to the console.</p> + +<p>This all happens asynchronously.</p> + +<div class="note"> +<p><strong>Note</strong>: You can also chain promise calls together, for example:<br> + <code>myPromise().then(success, failure).then(success).catch(failure);</code></p> +</div> + +<div class="note"> +<p><strong>Note</strong>: You can find a lot more out about promises by reading Jake Archibald’s excellent <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises: there and back again</a>.</p> +</div> + +<h2 id="Service_workers_demo">Service workers demo</h2> + +<p>To demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called <a href="https://github.com/mdn/sw-test">sw-test</a>, which is a simple Star wars Lego image gallery. It uses a promise-powered function to read image data from a JSON object and load the images using Ajax, before displaying the images in a line down the page. We’ve kept things static and simple for now. It also registers, installs, and activates a service worker, and when more of the spec is supported by browsers it will cache all the files required so it will work offline!</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/8243/demo-screenshot.png" style="display: block; height: 410px; margin: 0px auto; width: 480px;"><br> + <br> + <br> + You can see the <a href="https://github.com/mdn/sw-test/">source code on GitHub</a>, and <a href="https://mdn.github.io/sw-test/">view the example live</a>. The one bit we’ll call out here is the promise (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L22-L47">app.js lines 22-47</a>), which is a modified version of what you read about above, in the <a href="https://mdn.github.io/js-examples/promises-test/">Promises test demo</a>. It is different in the following ways:</p> + +<ol> + <li>In the original, we only passed in a URL to an image we wanted to load. In this version, we pass in a JSON fragment containing all the data for a single image (see what they look like in <a href="https://github.com/mdn/sw-test/blob/gh-pages/image-list.js">image-list.js</a>). This is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. If you just passed in the url, and then tried to access the other items in the JSON separately when the <code>for()</code> loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.)</li> + <li>We actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L31-L34">app.js lines 31-34</a>). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.</li> + <li>To access the resolved promise values, we then access this function as you’d then expect (see <a href="https://github.com/mdn/sw-test/blob/gh-pages/app.js#L60-L64">app.js lines 60-64</a>). This may seem a bit odd at first, but this is the way promises work.</li> +</ol> + +<h2 id="Enter_service_workers">Enter service workers</h2> + +<p><strong>NOTE</strong> : We're using the <a href="http://es6-features.org/" rel="noopener">es6</a> <strong>arrow functions</strong> syntax in the Service Worker Implementation</p> + +<p>Now let’s get on to service workers!</p> + +<h3 id="Registering_your_worker">Registering your worker</h3> + +<p>The first block of code in our app’s JavaScript file — <code>app.js</code> — is as follows. This is our entry point into using service workers.</p> + +<pre class="brush: js">if ('serviceWorker' in navigator) { + navigator.serviceWorker.register('./sw-test/sw.js', {scope: './sw-test/'}) + .then((reg) => { + // registration worked + console.log('Registration succeeded. Scope is ' + reg.scope); + }).catch((error) => { + // registration failed + console.log('Registration failed with ' + error); + }); +}</pre> + +<ol> + <li>The outer block performs a feature detection test to make sure service workers are supported before trying to register one.</li> + <li>Next, we use the {{domxref("ServiceWorkerContainer.register()") }} function to register the service worker for this site, which is just a JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.)</li> + <li>The <code>scope</code> parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified '<code>/sw-test/'</code>, which means all content under the app's origin. If you leave it out, it will default to this value anyway, but we specified it here for illustration purposes.</li> + <li>The <code>.then()</code> promise function is used to chain a success case onto our promise structure. When the promise resolves successfully, the code inside it executes.</li> + <li>Finally, we chain a <code>.catch()</code> function onto the end that will run if the promise is rejected.</li> +</ol> + +<p>This registers a service worker, which runs in a worker context, and therefore has no DOM access. You then run code in the service worker outside of your normal pages to control their loading.<br> + <br> + A single service worker can control many pages. Each time a page within your scope is loaded, the service worker is installed against that page and operates on it. Bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn’t get its own unique worker.</p> + +<div class="note"> +<p><strong>Note</strong>: Your service worker functions like a proxy server, allowing you to modify requests and responses, replace them with items from its own cache, and more.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: One great thing about service workers is that if you use feature detection like we’ve shown above, browsers that don’t support service workers can just use your app online in the normal expected fashion. Furthermore, if you use AppCache and SW on a page, browsers that don’t support SW but do support AppCache will use that, and browsers that support both will ignore the AppCache and let SW take over.</p> +</div> + +<h4 id="Why_is_my_service_worker_failing_to_register">Why is my service worker failing to register?</h4> + +<p>This could be for the following reasons:</p> + +<ol> + <li>You are not running your application through HTTPS.</li> + <li>The path to your service worker file is not written correctly — it needs to be written relative to the origin, not your app’s root directory. In our example, the worker is at <code>https://mdn.github.io/sw-test/sw.js</code>, and the app’s root is <code>https://mdn.github.io/sw-test/</code>. But the path needs to be written as <code>/sw-test/sw.js</code>, not <code>/sw.js</code>.</li> + <li>The service worker being pointed to is on a different origin to that of your app. This is also not allowed.</li> +</ol> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12630/important-notes.png" style="display: block; height: 277px; margin: 0px auto; width: 574px;"></p> + +<p>Also note:</p> + +<ul> + <li>The service worker will only catch requests from clients under the service worker's scope.</li> + <li>The max scope for a service worker is the location of the worker.</li> + <li>If your service worker is active on a client being served with the <code>Service-Worker-Allowed</code> header, you can specify a list of max scopes for that worker.</li> + <li>In Firefox, Service Worker APIs are hidden and cannot be used when the user is in <a href="https://support.mozilla.org/en-US/kb/private-browsing-use-firefox-without-history">private browsing mode</a>.</li> +</ul> + +<h3 id="Install_and_activate_populating_your_cache">Install and activate: populating your cache</h3> + +<p>After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site.<br> + <br> + The install event is fired when an install is successfully completed. The install event is generally used to populate your browser’s offline caching capabilities with the assets you need to run your app offline. To do this, we use Service Worker’s brand new storage API — {{domxref("cache")}} — a global object on the service worker that allows us to store assets delivered by responses, and keyed by their requests. This API works in a similar way to the browser’s standard cache, but it is specific to your domain. It persists until you tell it not to — again, you have full control.</p> + +<div class="note"> +<p><strong>Note</strong>: The Cache API is not supported in every browser. (See the {{anch("Browser compatibility")}} section for more information.) If you want to use this now, you could consider using a polyfill like the one available in <a href="https://github.com/Polymer/topeka/blob/master/sw.js">Google's Topeka demo</a>, or perhaps store your assets in <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a>.</p> +</div> + +<p>Let’s start this section by looking at a code sample — this is the <a href="https://github.com/mdn/sw-test/blob/gh-pages/sw.js#L1-L18">first block you’ll find in our service worker</a>:</p> + +<pre class="brush: js">self.addEventListener('install', (event) => { + event.waitUntil( + caches.open('v1').then((cache) => { + return cache.addAll([ + './sw-test/', + './sw-test/index.html', + './sw-test/style.css', + './sw-test/app.js', + './sw-test/image-list.js', + './sw-test/star-wars-logo.jpg', + './sw-test/gallery/', + './sw-test/gallery/bountyHunters.jpg', + './sw-test/gallery/myLittleVader.jpg', + './sw-test/gallery/snowTroopers.jpg' + ]); + }) + ); +});</pre> + +<ol> + <li>Here we add an <code>install</code> event listener to the service worker (hence <code>self</code>), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the service worker will not install until the code inside <code>waitUntil()</code> has successfully occurred.</li> + <li>Inside <code>waitUntil()</code> we use the <a href="/en-US/docs/Web/API/CacheStorage/open"><code>caches.open()</code></a> method to create a new cache called <code>v1</code>, which will be version 1 of our site resources cache. This returns a promise for a created cache; once resolved, we then call a function that calls <code>addAll()</code> on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.</li> + <li>If the promise is rejected, the install fails, and the worker won’t do anything. This is ok, as you can fix your code and then try again the next time registration occurs.</li> + <li>After a successful installation, the service worker activates. This doesn’t have much of a distinct use the first time your service worker is installed/activated, but it means more when the service worker is updated (see the {{anch("Updating your service worker") }} section later on.)</li> +</ol> + +<div class="note"> +<p><strong>Note</strong>: <a href="/en-US/docs/Web/Guide/API/DOM/Storage">localStorage</a> works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> can be used inside a service worker for data storage if you require it.</p> +</div> + +<h3 id="Custom_responses_to_requests">Custom responses to requests</h3> + +<p>Now you’ve got your site assets cached, you need to tell service workers to do something with the cached content. This is easily done with the <code>fetch</code> event.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/12634/sw-fetch.png" style="display: block; margin: 0 auto;"></p> + +<p>A <code>fetch</code> event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if <code>index.html</code> makes a cross origin request to embed an image, that still goes through its service worker.)</p> + +<p>You can attach a <code>fetch</code> event listener to the service worker, then call the <code>respondWith()</code> method on the event to hijack our HTTP responses and update them with your own magic.</p> + +<pre class="brush: js">self.addEventListener('fetch', (event) => { + event.respondWith( + // magic goes here + ); +});</pre> + +<p>We could start by simply responding with the resource whose url matches that of the network request, in each case:</p> + +<pre class="brush: js">self.addEventListener('fetch', (event) => { + event.respondWith( + caches.match(event.request) + ); +});</pre> + +<p><code>caches.match(event.request)</code> allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests.</p> + +<p>Let’s look at a few other options we have when defining our magic (see our <a href="/en-US/docs/Web/API/Fetch_API">Fetch API documentation</a> for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)</p> + +<ol> + <li> + <p>The <code>{{domxref("Response.Response","Response()")}}</code> constructor allows you to create a custom response. In this case, we are just returning a simple text string:</p> + + <pre class="brush: js">new Response('Hello from your friendly neighbourhood service worker!');</pre> + </li> + <li> + <p>This more complex <code>Response</code> below shows that you can optionally pass a set of headers in with your response, emulating standard HTTP response headers. Here we are just telling the browser what the content type of our synthetic response is:</p> + + <pre class="brush: js">new Response('<p>Hello from your friendly neighbourhood service worker!</p>', { + headers: { 'Content-Type': 'text/html' } +});</pre> + </li> + <li> + <p>If a match wasn’t found in the cache, you could tell the browser to simply {{domxref("GlobalFetch.fetch","fetch")}} the default network request for that resource, to get the new resource from the network if it is available:</p> + + <pre class="brush: js">fetch(event.request);</pre> + </li> + <li> + <p>If a match wasn’t found in the cache, and the network isn’t available, you could just match the request with some kind of default fallback page as a response using {{domxref("CacheStorage.match","match()")}}, like this:</p> + + <pre class="brush: js">caches.match('./fallback.html');</pre> + </li> + <li> + <p>You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:</p> + + <pre class="brush: js">event.request.url +event.request.method +event.request.headers +event.request.body</pre> + </li> +</ol> + +<h2 id="Recovering_failed_requests">Recovering failed requests</h2> + +<p>So <code>caches.match(event.request)</code> is great when there is a match in the service worker cache, but what about cases when there isn’t a match? If we didn’t provide any kind of failure handling, our promise would resolve with <code>undefined</code> and we wouldn't get anything returned.</p> + +<p>Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:</p> + +<pre class="brush: js">self.addEventListener('fetch', (event) => { + event.respondWith( + caches.match(event.request).then((response) => { + return response || fetch(event.request); + }) + ); +});</pre> + +<p>If the resources aren't in the cache, they are requested from the network.</p> + +<p>If we were being really clever, we would not only request the resource from the network; we would also save it into the cache so that later requests for that resource could be retrieved offline too! This would mean that if extra images were added to the Star Wars gallery, our app could automatically grab them and cache them. The following would do the trick:</p> + +<pre class="brush: js">self.addEventListener('fetch', (event) => { + event.respondWith( + caches.match(event.request).then((resp) => { + return resp || fetch(event.request).then((response) => { + return caches.open('v1').then((cache) => { + cache.put(event.request, response.clone()); + return response; + }); + }); + }) + ); +});</pre> + +<p>Here we return the default network request with <code>return fetch(event.request)</code>, which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using <code>caches.open('v1')</code>; this also returns a promise. When that promise resolves, <code>cache.put()</code> is used to add the resource to the cache. The resource is grabbed from <code>event.request</code>, and the response is then cloned with <code>response.clone()</code> and added to the cache. The clone is put in the cache, and the original response is returned to the browser to be given to the page that called it.</p> + +<p>Cloning the response is necessary because request and response streams can only be read once. In order to return the response to the browser and put it in the cache we have to clone it. So the original gets returned to the browser and the clone gets sent to the cache. They are each read once.</p> + +<p>The only trouble we have now is that if the request doesn’t match anything in the cache, and the network is not available, our request will still fail. Let’s provide a default fallback so that whatever happens, the user will at least get something:</p> + +<pre class="brush: js">self.addEventListener('fetch', (event) => { + event.respondWith( + caches.match(event.request).then((resp) => { + return resp || fetch(event.request).then((response) => { + let responseClone = response.clone(); + caches.open('v1').then((cache) => { + cache.put(event.request, responseClone); + }); + + return response; + }); + }).catch(() => { + return caches.match('./sw-test/gallery/myLittleVader.jpg'); + }) + ); +});</pre> + +<p>We have opted for this fallback image because the only updates that are likely to fail are new images, as everything else is depended on for installation in the <code>install</code> event listener we saw earlier.</p> + +<h2 id="Updating_your_service_worker"><a id="Updating your service worker" name="Updating your service worker">Updating your service worker</a></h2> + +<p>If your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates.</p> + +<p>You’ll want to update your <code>install</code> event listener in the new service worker to something like this (notice the new version number):</p> + +<pre class="brush: js">self.addEventListener('install', (event) => { + event.waitUntil( + caches.open('v2').then((cache) => { + return cache.addAll([ + './sw-test/', + './sw-test/index.html', + './sw-test/style.css', + './sw-test/app.js', + './sw-test/image-list.js', + + … + + // include other new resources for the new version... + ]); + }) + ); +});</pre> + +<p>While this happens, the previous version is still responsible for fetches. The new version is installing in the background. We are calling the new cache <code>v2</code>, so the previous <code>v1</code> cache isn't disturbed.</p> + +<p>When no pages are using the current version, the new worker activates and becomes responsible for fetches.</p> + +<h3 id="Deleting_old_caches">Deleting old caches</h3> + +<p>You also get an <code>activate</code> event. This is a generally used to do stuff that would have broken the previous version while it was still running, for example getting rid of old caches. This is also useful for removing data that is no longer needed to avoid filling up too much disk space — each browser has a hard limit on the amount of cache storage that a given service worker can use. The browser does its best to manage disk space, but it may delete the Cache storage for an origin. The browser will generally delete all of the data for an origin or none of the data for an origin.</p> + +<p>Promises passed into <code>waitUntil()</code> will block other events until completion, so you can rest assured that your clean-up operation will have completed by the time you get your first <code>fetch</code> event on the new cache.</p> + +<pre class="brush: js">self.addEventListener('activate', (event) => { + var cacheKeeplist = ['v2']; + + event.waitUntil( + caches.keys().then((keyList) => { + return Promise.all(keyList.map((key) => { + if (cacheKeeplist.indexOf(key) === -1) { + return caches.delete(key); + } + })); + }) + ); +});</pre> + +<h2 id="Developer_tools">Developer tools</h2> + +<p>Chrome has <code>chrome://inspect/#service-workers</code>, which shows current service worker activity and storage on a device, and <code>chrome://serviceworker-internals</code>, which shows more detail and allows you to start/stop/debug the worker process. In the future they will have throttling/offline modes to simulate bad or non-existent connections, which will be a really good thing.</p> + +<p>Firefox has also started to implement some useful tools related to service workers:</p> + +<ul> + <li>You can navigate to <code><a href="/en-US/docs/Tools/about:debugging">about:debugging</a></code> to see what SWs are registered and update/remove them.</li> + <li>When testing you can get around the HTTPS restriction by checking the "Enable Service Workers over HTTP (when toolbox is open)" option in the <a href="/en-US/docs/Tools/Settings">Firefox Developer Tools settings</a>.</li> + <li>The "Forget" button, available in Firefox's customization options, can be used to clear service workers and their caches ({{bug(1252998)}}).</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: You may serve your app from <code>http://localhost</code> (e.g. using <code>me@localhost:/my/app$ <strong>python -m SimpleHTTPServer</strong></code>) for local development. See <a href="https://www.w3.org/TR/service-workers/#security-considerations">Security considerations</a></p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="http://blog.88mph.io/2017/07/28/understanding-service-workers/">Understanding Service Workers</a></li> + <li><a href="https://serviceworke.rs/">The Service Worker Cookbook</a></li> + <li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li> + <li>Download the <a href="https://mdn.mozillademos.org/files/12638/sw101.png">Service Workers 101 cheatsheet</a>.</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a></li> + <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li> +</ul> diff --git a/files/pt-pt/web/api/sharedworker/index.html b/files/pt-pt/web/api/sharedworker/index.html new file mode 100644 index 0000000000..5f7babaa6f --- /dev/null +++ b/files/pt-pt/web/api/sharedworker/index.html @@ -0,0 +1,200 @@ +--- +title: SharedWorker +slug: Web/API/SharedWorker +tags: + - API + - Interface + - Referencia + - SharedWorker + - Web Workers + - Workers +translation_of: Web/API/SharedWorker +--- +<div>{{APIRef("Web Workers API")}}</div> + +<p>A interface <code><strong>SharedWorker</strong></code> representa um tipo de <em>worker </em>específico que pode ser acedido <em>a partir de vários contextos de navegação</em>, tais como várias janelas, <em>iframes</em> ou até <em>workers</em>. Eles implementam uma interface diferente do que os <em>workers </em>dedicados e têm um âmbito global diferente, {{domxref("SharedWorkerGlobalScope")}}.</p> + +<div class="note"> +<p><strong>Nota:</strong> Se o SharedWorker puder ser acedido a partir de vários contextos de navegação, todos esses contextos de navegação devem partilhar exatamente a mesma origem (mesmo protocolo, anfitrião e porto).</p> +</div> + +<h2 id="Construtor">Construtor</h2> + +<dl> + <dt>{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}</dt> + <dd>Cria um <em>web worker</em> partilhado que executa uma <em>script</em> na URL indicada.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<p><em>Esta interface também herda propriedades de {{domxref("EventTarget")}} de qual se deriva, e implementa propriedades de {{domxref("AbstractWorker")}}.</em></p> + +<dl> + <dt>{{domxref("AbstractWorker.onerror")}}</dt> + <dd>É um {{domxref("EventListener")}} chamado quando um {{domxref("ErrorEvent")}} do tipo <code>error</code> sai do <em>worker</em>.</dd> + <dt>{{domxref("SharedWorker.port")}} {{readonlyInline}}</dt> + <dd>Devolve um objeto {{domxref("MessagePort")}} usado para controlar e comunicar com o <em>worker</em> partilhado.</dd> +</dl> + +<dl> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Esta interface também herda métodos de {{domxref("EventTarget")}} de qual se deriva, e implementa métodos de </em><em>{{domxref("AbstractWorker")}}.</em></p> + +<h2 id="Exemplo">Exemplo</h2> + +<p>No nosso <a class="external external-icon" href="https://github.com/mdn/simple-shared-worker">exemplo básico dum <em>worker</em> partilhado</a>, temos duas páginas de HTML, cada qual usa JavaScript para fazer um simples cálculo. Os <em>scripts</em> diferentes estão a utilizar o mesmo ficheiro de <em>worker</em> para fazer os cálculos — ambos podem-no aceder, mesmo se as páginas estiverem a correr em janelas diferentes.</p> + +<p>O seguinte <em>snippet</em> de código demonstra a criação dum objeto {{domxref("SharedWorker")}} usando o construtor {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}. Ambas <em>scripts</em> contêm isto:</p> + +<pre class="brush: js notranslate">var myWorker = new SharedWorker('worker.js'); +</pre> + +<p>Ambas <em>scripts</em> acedem ao <em>worker</em> através dum objeto {{domxref("MessagePort")}} criado usando a propriedade {{domxref("SharedWorker.port")}}. Se o evento <code>onmessage</code> foi adicionado usando <code>addEventListener</code>, a porta é manualmente criada usando o seu método <code>start()</code>:</p> + +<pre class="brush: js notranslate">myWorker.port.start();</pre> + +<p>Quando a porta é iniciada, ambos <em>scripts</em> enviam mensagens ao <em>worker</em> e processão mensagens vindas do <em>worker</em> usando <code>port.postMessage()</code> e <code>port.onmessage</code>, respetivamente:</p> + +<pre class="brush: js notranslate">first.onchange = function() { + myWorker.port.postMessage([first.value,second.value]); + console.log(' Mensagem enviada ao worker'); +} + +second.onchange = function() { + myWorker.port.postMessage([first.value,second.value]); + console.log(' Mensagem enviada ao worker'); +} + +myWorker.port.onmessage = function(e) { + result1.textContent = e.data; + console.log(' Mensagem recebida do worker'); +}</pre> + +<p>Dentro do <em>worker</em> usamos o <em>handler</em> {{domxref("SharedWorkerGlobalScope.onconnect")}} para nos ligarmos à mesma porta a que referimos antes. As portas associadas a esse <em>worker</em> são acessíveis através da propriedade <code>ports</code> do evento {{event("connect")}} — nós depois usamos o método <code>start()</code> de {{domxref("MessagePort")}} para iniciar a porta, e o <em>handler</em> <code>onmessage</code> para lidar com as mensagens enviadas dos <em>threads</em> principais.</p> + +<pre class="brush: js notranslate">onconnect = function(e) { + var port = e.ports[0]; + + port.addEventListener('message', function(e) { + var workerResult = 'Result: ' + (e.data[0] * e.data[1]); + port.postMessage(workerResult); + }); + + port.start(); // Necessário quando se usa addEventListener. Senão é chamado implicitamente pelo setter de onmessage. +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Sem diferenças em comparação a {{SpecName("Web Workers")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.SharedWorker")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{domxref("Worker")}}</li> + <li><a class="internal" href="/pt-PT/docs/Web/API/Web_Workers_API/Utilizacao_de_web_workers">Utilização de workers da Web</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style=""></div> + +<div id="SL_shadow_translation_result2" style="display: none;"></div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"></div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"></div> + +<div id="SL_alert_cont"></div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"></div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"></div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"></div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"></div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"></div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"></div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"></div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result"></div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"></div> + +<div id="SL_player2"></div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"></div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"></div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/sistema_de_ficheiros/index.html b/files/pt-pt/web/api/sistema_de_ficheiros/index.html new file mode 100644 index 0000000000..76c4db9d6c --- /dev/null +++ b/files/pt-pt/web/api/sistema_de_ficheiros/index.html @@ -0,0 +1,54 @@ +--- +title: Sistema de Ficheiros +slug: Web/API/Sistema_de_ficheiros +tags: + - API + - File API + - File System API + - File and Directory Entries API + - Interface + - Não Standard + - Offline + - filesystem +translation_of: Web/API/FileSystem +--- +<div> +<p>{{APIRef("File System API")}}{{SeeCompatTable}}</p> + +<p>A interface da "API de Entradas de Diretorias e Ficheiros" é usada para representar um sistema de ficheiros. Estes objetos podem ser obtidos a partir da propriedade {{domxref("FileSystemEntry.filesystem", "filesystem")}} em qualquer entrada do sistema de ficheiros. Alguns navegadores oferecem APIs adicionais para criar e gerir sistemas de ficheiros, por exemplo o método {{domxref("Window.requestFileSystem", "requestFileSystem()")}} encontrado no Chrome.</p> + +<p>Esta interface não dá acesso ao <em>filesystem</em> do utilizador. Em vez disso, terá uma "drive virtual" dentro da <em>sandbox</em> do navegador. Se quiser ter acesso ao sistema de ficheiros dos utilizadores, necessita de invocar o utilizador.</p> +</div> + +<h2 id="Conceitos_básicos">Conceitos básicos</h2> + +<p>Existem duas formas para aceder ao objeto <code>FileSystem</code>:</p> + +<ol> + <li>Pode pedir por um dentro duma <em>sandbox</em> para só a sua app ao chamar <code>window.requestFileSystem()</code>. Se a chamada tiver sucesso, é executada uma <em>callback handler</em>, que recebe como parâmetro um objeto <code>FileSystem</code> que descreve o sistema de ficheiros.</li> + <li>Pode o pedir através duma entrada no sistema de ficheiros, com a propriadade {{domxref("FileSystemEntry.filesystem", "filesystem")}}.</li> +</ol> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Atributos</h2> + +<dl> + <dt>{{domxref("FileSystem.name")}} {{ReadOnlyInline}}</dt> + <dd>Uma {{domxref("USVString")}} que representa o nome do sistema de ficheiros. Este nome é único na lista de sistemas de ficheiros exposta.</dd> + <dt>{{domxref("FileSystem.root")}} {{ReadOnlyInline}}</dt> + <dd>Um objeto de {{domxref("FileSystemDirectoryEntry")}} que representa a diretoria raiz do sistema de ficheiros. Através deste objeto, pode ganhar acesso a todos os ficheiros e diretorias no sistema.</dd> +</dl> + +<h2 id="Browser_Compatibility" name="Browser_Compatibility">Compatibilidade</h2> + + + +<p>{{Compat("api.FileSystem")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/API_Entradas_de_Diretoria_e_Ficheiro">API de Entradas de Diretorias e Ficheiros</a></li> + <li>Introdução à API de Entradas de Diretorias e Ficheiros</li> + <li>{{domxref("FileSystemEntry")}}, {{domxref("FileSystemFileEntry")}}, e {{domxref("FileSystemDirectoryEntry")}}</li> + <li>Artigo de MSDN: <em><a href="https://msdn.microsoft.com/library/mt732564">WebKitFileSystem object</a></em> (em inglês)</li> +</ul> diff --git a/files/pt-pt/web/api/urlsearchparams/index.html b/files/pt-pt/web/api/urlsearchparams/index.html new file mode 100644 index 0000000000..3cbed3eea5 --- /dev/null +++ b/files/pt-pt/web/api/urlsearchparams/index.html @@ -0,0 +1,207 @@ +--- +title: URLSearchParams +slug: Web/API/URLSearchParams +translation_of: Web/API/URLSearchParams +--- +<p>{{ApiRef("URL API")}}</p> + +<p>O interface <strong><code>URLSearchParams </code></strong>define métodos que permitem trabalhar com uma <em>query string</em> de um URL.</p> + +<p>Um objeto que implemente <code>URLSearchParams </code>pode ser utilizado diretamente numa estrutura {{jsxref("Statements/for...of", "for...of")}}, em vez de {{domxref('URLSearchParams.entries()', 'entries()')}}: <code>for (var p of mySearchParams) é equivalente a</code> <code>for (var p of mySearchParams.entries())</code>.</p> + +<h2 id="Construtor">Construtor</h2> + +<dl> + <dt>{{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}}</dt> + <dd>O construtor devolve um objeto <code>URLSearchParams</code>.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<p><em>Este interface não herda nehuma propriedade.</em></p> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Este interface não herda nehum método.</em></p> + +<dl> + <dt>{{domxref("URLSearchParams.append()")}}</dt> + <dd>Adiciona um par chave/valor como um novo parâmetro de pesquisa.</dd> + <dt>{{domxref("URLSearchParams.delete()")}}</dt> + <dd>Elimina o parâmetro de pesquisa e o seu valor, da lista de parâmetros de pesquisa.</dd> + <dt>{{domxref("URLSearchParams.entries()")}}</dt> + <dd>Devolve um {{jsxref("Iteration_protocols","iterator")}} que permite iterar pelos pares chave/valor neste objeto.</dd> + <dt>{{domxref("URLSearchParams.get()")}}</dt> + <dd>Devolve o primeiro valor relacionado com o parâmetro de pesquisa enviado.</dd> + <dt>{{domxref("URLSearchParams.getAll()")}}</dt> + <dd>Devolve todos os valores relacionados com um determinado parâmetro de pesquisa.</dd> + <dt>{{domxref("URLSearchParams.has()")}}</dt> + <dd>Devolve um {{jsxref("Boolean")}} , indicando de um determinado parâmetro de pesquisa existe.</dd> + <dt>{{domxref("URLSearchParams.keys()")}}</dt> + <dd>Devolve um {{jsxref("Iteration_protocols", "iterator")}} permitindo interar pelas <strong>chaves</strong> de todos os pares chave/valor existentes no objeto.</dd> + <dt>{{domxref("URLSearchParams.set()")}}</dt> + <dd>Define o valor associado a um parâmetro de pesquisa. Elimina outros valores se existirem.</dd> + <dt>{{domxref("URLSearchParams.toString()")}}</dt> + <dd>Devolve uma string com os parâmetros válidos para serem utilizados num URL.</dd> + <dt>{{domxref("URLSearchParams.values()")}}</dt> + <dd>Devolve um {{jsxref("Iteration_protocols", "iterator")}} que permite iterar por todos os <strong>valores</strong> dos pares chave/valor existentes neste objeto.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js">var paramsString = "q=URLUtils.searchParams&topic=api" +var searchParams = new URLSearchParams(paramsString); + +//Iterar pelos parâmetros de pesquisa. +for (let p of searchParams) { + console.log(p); +} + +searchParams.has("topic") === true; // true +searchParams.get("topic") === "api"; // true +searchParams.getAll("topic"); // ["api"] +searchParams.get("foo") === null; // true +searchParams.append("topic", "webdev"); +searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev" +searchParams.set("topic", "More webdev"); +searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev" +searchParams.delete("topic"); +searchParams.toString(); // "q=URLUtils.searchParams" +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}</td> + <td>{{Spec2('URL')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_Browsers">Compatibilidade Browsers</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoDesktop("29.0")}}</td> + <td>{{CompatNo}}</td> + <td>36</td> + <td>10.1</td> + </tr> + <tr> + <td><code>entries()</code>, <code>keys()</code>, <code>values()</code>, e suporte de <code>for...of</code></td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoDesktop("44.0")}}</td> + <td>{{CompatNo}}</td> + <td>36</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>USVString</code> for constructor <code>init</code> object</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("53.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Record for constructor <code>init</code> object</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("54.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome para Android</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoMobile("29.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(49)}}</td> + </tr> + <tr> + <td><code>entries()</code>, <code>keys()</code>, <code>values()</code>, e suport de <code>for...of</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoMobile("44.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(49)}}</td> + </tr> + <tr> + <td><code>USVString</code> for constructor <code>init</code> object</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("53.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Record for constructor <code>init</code> object</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("54.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>Outros interfaces relacionados com URL: {{domxref("URL")}}, {{domxref("URLUtils")}}.</li> + <li><a href="https://developers.google.com/web/updates/2016/01/urlsearchparams?hl=en">Google Developers: Manipulação simples de URL com URLSearchParams</a></li> +</ul> + +<dl> +</dl> diff --git a/files/pt-pt/web/api/web_audio_api/index.html b/files/pt-pt/web/api/web_audio_api/index.html new file mode 100644 index 0000000000..815ab1ad91 --- /dev/null +++ b/files/pt-pt/web/api/web_audio_api/index.html @@ -0,0 +1,512 @@ +--- +title: API de Áudio da Web +slug: Web/API/Web_Audio_API +tags: + - API + - API de Áudio da Web + - Exemplo + - Guía + - Landing + - Overview + - Resumo + - Web Audio API +translation_of: Web/API/Web_Audio_API +--- +<div> +<p>The Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning) and much more.</p> +</div> + +<h2 id="Conceitos_e_utilização_de_áudio_da_Web">Conceitos e utilização de áudio da <em>Web</em></h2> + +<p>The Web Audio API involves handling audio operations inside an <strong>audio context</strong>, and has been designed to allow <strong>modular routing</strong>. Basic audio operations are performed with <strong>audio nodes</strong>, which are linked together to form an <strong>audio routing graph</strong>. Several sources — with different types of channel layout — are supported even within a single context. This modular design provides the flexibility to create complex audio functions with dynamic effects.</p> + +<p>Audio nodes are linked into chains and simple webs by their inputs and outputs. They typically start with one or more sources. Sources provide arrays of sound intensities (samples) at very small timeslices, often tens of thousands of them per second. These could be either computed mathematically (such as {{domxref("OscillatorNode")}}), or they can be recordings from sound/video files (like {{domxref("AudioBufferSourceNode")}} and {{domxref("MediaElementAudioSourceNode")}}) and audio streams ({{domxref("MediaStreamAudioSourceNode")}}). In fact, sound files are just recordings of sound intensities themselves, which come in from microphones or electric instruments, and get mixed down into a single, complicated wave.</p> + +<p>Outputs of these nodes could be linked to inputs of others, which mix or modify these streams of sound samples into different streams. A common modification is multiplying the samples by a value to make them louder or quieter (as is the case with {{domxref("GainNode")}}). Once the sound has been sufficiently processed for the intended effect, it can be linked to the input of a destination ({{domxref("AudioContext.destination")}}), which sends the sound to the speakers or headphones. This last connection is only necessary if the user is supposed to hear the audio.</p> + +<p>A simple, typical workflow for web audio would look something like this:</p> + +<ol> + <li>Create audio context</li> + <li>Inside the context, create sources — such as <code><audio></code>, oscillator, stream</li> + <li>Create effects nodes, such as reverb, biquad filter, panner, compressor</li> + <li>Choose final destination of audio, for example your system speakers</li> + <li>Connect the sources up to the effects, and the effects to the destination.</li> +</ol> + +<p><img alt="A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrow between them pointing from left to right, indicating the flow of audio information." src="https://mdn.mozillademos.org/files/12241/webaudioAPI_en.svg" style="display: block; height: 143px; margin: 0px auto; width: 643px;"></p> + +<p>Timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. So applications such as drum machines and sequencers are well within reach.</p> + +<p>The Web Audio API also allows us to control how audio is <em>spatialized</em>. Using a system based on a <em>source-listener model</em>, it allows control of the <em>panning model</em> and deals with <em>distance-induced attenuation</em> or <em>doppler shift</em> induced by a moving source (or moving listener).</p> + +<div class="note"> +<p>You can read about the theory of the Web Audio API in a lot more detail in our article <a href="/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API">Basic concepts behind Web Audio API</a>.</p> +</div> + +<h2 id="Interfaces_de_API_de_Áudio_da_Web">Interfaces de API de Áudio da <em>Web</em></h2> + +<p>The Web Audio API has a number of interfaces and associated events, which we have split up into nine categories of functionality.</p> + +<h3 id="General_audio_graph_definition">General audio graph definition</h3> + +<p>General containers and definitions that shape audio graphs in Web Audio API usage.</p> + +<dl> + <dt>{{domxref("AudioContext")}}</dt> + <dd>The <strong><code>AudioContext</code></strong> interface represents an audio-processing graph built from audio modules linked together, each represented by an {{domxref("AudioNode")}}. An audio context controls the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an <code>AudioContext</code> before you do anything else, as everything happens inside a context.</dd> + <dt>{{domxref("AudioNode")}}</dt> + <dd>The <strong><code>AudioNode</code></strong><strong> </strong>interface represents an audio-processing module like an <em>audio source</em> (e.g. an HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} element), <em>audio destination</em>, <em>intermediate processing module</em> (e.g. a filter like {{domxref("BiquadFilterNode")}}, or <em>volume control</em> like {{domxref("GainNode")}}).</dd> + <dt>{{domxref("AudioParam")}}</dt> + <dd>The <strong><code>AudioParam</code></strong><strong> </strong>interface represents an audio-related parameter, like one of an {{domxref("AudioNode")}}. It can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.</dd> + <dt>The {{event("ended")}} event</dt> + <dd>The <code>ended</code> event is fired when playback has stopped because the end of the media was reached.</dd> +</dl> + +<h3 id="Defining_audio_sources">Defining audio sources</h3> + +<p>Interfaces that define audio sources for use in the Web Audio API.</p> + +<dl> + <dt>{{domxref("OscillatorNode")}}</dt> + <dd>The <strong><code style="font-size: 14px;">OscillatorNode</code></strong><strong> </strong>interface represents a periodic waveform, such as a sine or triangle wave. It is an {{domxref("AudioNode")}} audio-processing module that causes a given <em>frequency</em> of wave to be created.</dd> + <dt>{{domxref("AudioBuffer")}}</dt> + <dd>The <strong><code>AudioBuffer</code></strong> interface represents a short audio asset residing in memory, created from an audio file using the {{ domxref("AudioContext.decodeAudioData()") }} method, or created with raw data using {{ domxref("AudioContext.createBuffer()") }}. Once decoded into this form, the audio can then be put into an {{ domxref("AudioBufferSourceNode") }}.</dd> + <dt>{{domxref("AudioBufferSourceNode")}}</dt> + <dd>The <strong><code>AudioBufferSourceNode</code></strong> interface represents an audio source consisting of in-memory audio data, stored in an {{domxref("AudioBuffer")}}. It is an {{domxref("AudioNode")}} that acts as an audio source.</dd> + <dt>{{domxref("MediaElementAudioSourceNode")}}</dt> + <dd>The <code><strong>MediaElementAudio</strong></code><strong><code>SourceNode</code></strong> interface represents an audio source consisting of an HTML5 {{ htmlelement("audio") }} or {{ htmlelement("video") }} element. It is an {{domxref("AudioNode")}} that acts as an audio source.</dd> + <dt>{{domxref("MediaStreamAudioSourceNode")}}</dt> + <dd>The <code><strong>MediaStreamAudio</strong></code><strong><code>SourceNode</code></strong> interface represents an audio source consisting of a <a href="/en-US/docs/WebRTC" title="/en-US/docs/WebRTC">WebRTC</a> {{domxref("MediaStream")}} (such as a webcam, microphone, or a stream being sent from a remote computer). It is an {{domxref("AudioNode")}} that acts as an audio source.</dd> +</dl> + +<h3 id="Defining_audio_effects_filters">Defining audio effects filters</h3> + +<p>Interfaces for defining effects that you want to apply to your audio sources.</p> + +<dl> + <dt>{{domxref("BiquadFilterNode")}}</dt> + <dd>The <strong><code>BiquadFilterNode</code></strong><strong> </strong>interface represents a simple low-order filter. It is an {{domxref("AudioNode")}} that can represent different kinds of filters, tone control devices, or graphic equalizers. A <code>BiquadFilterNode</code> always has exactly one input and one output.</dd> + <dt>{{domxref("ConvolverNode")}}</dt> + <dd>The <code><strong>Convolver</strong></code><strong><code>Node</code></strong><strong> </strong>interface is an <span style="line-height: 1.5;">{{domxref("AudioNode")}} that</span><span style="line-height: 1.5;"> performs a Linear Convolution on a given {{domxref("AudioBuffer")}}, and is often used to achieve a reverb effect</span><span style="line-height: 1.5;">.</span></dd> + <dt>{{domxref("DelayNode")}}</dt> + <dd>The <strong><code>DelayNode</code></strong><strong> </strong>interface represents a <a href="http://en.wikipedia.org/wiki/Digital_delay_line" title="http://en.wikipedia.org/wiki/Digital_delay_line">delay-line</a>; an {{domxref("AudioNode")}} audio-processing module that causes a delay between the arrival of an input data and its propagation to the output.</dd> + <dt>{{domxref("DynamicsCompressorNode")}}</dt> + <dd>The <strong><code>DynamicsCompressorNode</code></strong> interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once.</dd> + <dt>{{domxref("GainNode")}}</dt> + <dd>The <strong><code>GainNode</code></strong><strong> </strong>interface represents a change in volume. It is an {{domxref("AudioNode")}} audio-processing module that causes a given <em>gain</em> to be applied to the input data before its propagation to the output.</dd> + <dt>{{domxref("StereoPannerNode")}}</dt> + <dd>The <code><strong>StereoPannerNode</strong></code> interface represents a simple stereo panner node that can be used to pan an audio stream left or right.</dd> + <dt>{{domxref("WaveShaperNode")}}</dt> + <dd>The <strong><code>WaveShaperNode</code></strong><strong> </strong>interface represents a non-linear distorter. It is an {{domxref("AudioNode")}} that use a curve to apply a waveshaping distortion to the signal. Beside obvious distortion effects, it is often used to add a warm feeling to the signal.</dd> + <dt>{{domxref("PeriodicWave")}}</dt> + <dd>Describes a periodic waveform that can be used to shape the output of an {{ domxref("OscillatorNode") }}.</dd> +</dl> + +<h3 id="Defining_audio_destinations">Defining audio destinations</h3> + +<p>Once you are done processing your audio, these interfaces define where to output it.</p> + +<dl> + <dt>{{domxref("AudioDestinationNode")}}</dt> + <dd>The <strong><code>AudioDestinationNode</code></strong> interface represents the end destination of an audio source in a given context — usually the speakers of your device.</dd> + <dt>{{domxref("MediaStreamAudioDestinationNode")}}</dt> + <dd>The <code><strong>MediaStreamAudio</strong></code><strong><code>DestinationNode</code></strong> interface represents an audio destination consisting of a <a href="/en-US/docs/WebRTC" title="/en-US/docs/WebRTC">WebRTC</a> {{domxref("MediaStream")}} with a single <code>AudioMediaStreamTrack</code>, which can be used in a similar way to a {{domxref("MediaStream")}} obtained from {{ domxref("MediaDevices.getUserMedia", "getUserMedia()") }}. It is an {{domxref("AudioNode")}} that acts as an audio destination.</dd> +</dl> + +<h3 id="Data_analysis_and_visualization">Data analysis and visualization</h3> + +<p>If you want to extract time, frequency, and other data from your audio, the <code>AnalyserNode</code> is what you need.</p> + +<dl> + <dt>{{domxref("AnalyserNode")}}</dt> + <dd>The <strong><code>AnalyserNode</code></strong> interface represents a node able to provide real-time frequency and time-domain analysis information, for the purposes of data analysis and visualization.</dd> +</dl> + +<h3 id="Splitting_and_merging_audio_channels">Splitting and merging audio channels</h3> + +<p>To split and merge audio channels, you'll use these interfaces.</p> + +<dl> + <dt>{{domxref("ChannelSplitterNode")}}</dt> + <dd>The <code><strong>ChannelSplitterNode</strong></code> interface separates the different channels of an audio source out into a set of <em>mono</em> outputs.</dd> + <dt>{{domxref("ChannelMergerNode")}}</dt> + <dd>The <code><strong>ChannelMergerNode</strong></code> interface reunites different mono inputs into a single output. Each input will be used to fill a channel of the output.</dd> +</dl> + +<h3 id="Audio_spatialization">Audio spatialization</h3> + +<p>These interfaces allow you to add audio spatialization panning effects to your audio sources.</p> + +<dl> + <dt>{{domxref("AudioListener")}}</dt> + <dd>The <strong><code>AudioListener</code></strong><strong> </strong>interface represents the position and orientation of the unique person listening to the audio scene used in audio spatialization.</dd> + <dt>{{domxref("PannerNode")}}</dt> + <dd>The <strong><code>PannerNode</code></strong><strong> </strong>interface represents the behavior of a signal in space. It is an {{domxref("AudioNode")}} audio-processing module describing its position with right-hand Cartesian coordinates, its movement using a velocity vector and its directionality using a directionality cone.</dd> +</dl> + +<h3 id="Audio_processing_in_JavaScript">Audio processing in JavaScript</h3> + +<p>You can write JavaScript code to process audio data. To do so, you use the interfaces and events listed below.</p> + +<div class="note"> +<p>As of the August 29, 2014 version of the Web Audio API spec. these features have been marked as deprecated, and are soon to be replaced by {{ anch("Audio_Workers") }}.</p> +</div> + +<dl> + <dt>{{domxref("ScriptProcessorNode")}}</dt> + <dd>The <strong><code>ScriptProcessorNode</code></strong><strong> </strong>interface allows the generation, processing, or analyzing of audio using JavaScript. It is an {{domxref("AudioNode")}} audio-processing module that is linked to two buffers, one containing the current input, one containing the output. An event, implementing the {{domxref("AudioProcessingEvent")}} interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data.</dd> + <dt>{{event("audioprocess")}} (event)</dt> + <dd>The <code>audioprocess</code> event is fired when an input buffer of a Web Audio API {{domxref("ScriptProcessorNode")}} is ready to be processed.</dd> + <dt>{{domxref("AudioProcessingEvent")}}</dt> + <dd>The <a href="/en-US/docs/Web_Audio_API" title="/en-US/docs/Web_Audio_API">Web Audio API</a> <code>AudioProcessingEvent</code> represents events that occur when a {{domxref("ScriptProcessorNode")}} input buffer is ready to be processed.</dd> +</dl> + +<h3 id="Offlinebackground_audio_processing">Offline/background audio processing</h3> + +<p>It is possible to process/render an audio graph very quickly in the background — rendering it to an {{domxref("AudioBuffer")}} rather than to the device's speakers — with the following.</p> + +<dl> + <dt>{{domxref("OfflineAudioContext")}}</dt> + <dd>The <strong><code>OfflineAudioContext</code></strong> interface is an {{domxref("AudioContext")}} interface representing an audio-processing graph built from linked together {{domxref("AudioNode")}}s. In contrast with a standard <code>AudioContext</code>, an <code>OfflineAudioContext</code> doesn't really render the audio but rather generates it, <em>as fast as it can</em>, in a buffer.</dd> + <dt>{{event("complete")}} (event)</dt> + <dd>The <code>complete</code> event is fired when the rendering of an {{domxref("OfflineAudioContext")}} is terminated.</dd> + <dt>{{domxref("OfflineAudioCompletionEvent")}}</dt> + <dd>The <code>OfflineAudioCompletionEvent</code> represents events that occur when the processing of an {{domxref("OfflineAudioContext")}} is terminated. The {{event("complete")}} event implements this interface.</dd> +</dl> + +<h3 id="Audio_Workers" name="Audio_Workers">Audio Workers</h3> + +<p>Audio workers provide the ability for direct scripted audio processing to be done inside a <a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">web worker</a> context, and are defined by a couple of interfaces (new as of 29th August 2014). These are not implemented in any browsers yet. When implemented, they will replace {{domxref("ScriptProcessorNode")}}, and the other features discussed in the <a href="#Audio_processing_via_JavaScript">Audio processing in JavaScript</a> section above.</p> + +<dl> + <dt>{{domxref("AudioWorkerNode")}}</dt> + <dd>The AudioWorkerNode interface represents an {{domxref("AudioNode")}} that interacts with a worker thread to generate, process, or analyse audio directly.</dd> + <dt>{{domxref("AudioWorkerGlobalScope")}}</dt> + <dd>The <code>AudioWorkerGlobalScope</code> interface is a <code>DedicatedWorkerGlobalScope</code>-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using JavaScript in a worker thread.</dd> + <dt>{{domxref("AudioProcessEvent")}}</dt> + <dd>This is an <code>Event</code> object that is dispatched to {{domxref("AudioWorkerGlobalScope")}} objects to perform processing.</dd> +</dl> + +<h2 id="Example" name="Example">Interfaces obsoletas</h2> + +<p>The following interfaces were defined in old versions of the Web Audio API spec, but are now obsolete and have been replaced by other interfaces.</p> + +<dl> + <dt>{{domxref("JavaScriptNode")}}</dt> + <dd>Used for direct audio processing via JavaScript. This interface is obsolete, and has been replaced by {{domxref("ScriptProcessorNode")}}.</dd> + <dt>{{domxref("WaveTableNode")}}</dt> + <dd>Used to define a periodic waveform. This interface is obsolete, and has been replaced by {{domxref("PeriodicWave")}}.</dd> +</dl> + +<h2 id="Example" name="Example">Exemplo</h2> + +<p>This example shows a wide variety of Web Audio API functions being used. You can see this code in action on the <a href="https://mdn.github.io/voice-change-o-matic/">Voice-change-o-matic</a> demo (also check out the <a href="https://github.com/mdn/voice-change-o-matic">full source code at Github</a>) — this is an experimental voice changer toy demo; keep your speakers turned down low when you use it, at least to start!</p> + +<p>The Web Audio API lines are highlighted; if you want to find out more about what the different methods, etc. do, have a search around the reference pages.</p> + +<pre class="brush: js; highlight:[1,2,9,10,11,12,36,37,38,39,40,41,62,63,72,114,115,121,123,124,125,147,151]">var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // define audio context +// Webkit/blink browsers need prefix, Safari won't work without window. + +var voiceSelect = document.getElementById("voice"); // select box for selecting voice effect options +var visualSelect = document.getElementById("visual"); // select box for selecting audio visualization options +var mute = document.querySelector('.mute'); // mute button +var drawVisual; // requestAnimationFrame + +var analyser = audioCtx.createAnalyser(); +var distortion = audioCtx.createWaveShaper(); +var gainNode = audioCtx.createGain(); +var biquadFilter = audioCtx.createBiquadFilter(); + +function makeDistortionCurve(amount) { // function to make curve shape for distortion/wave shaper node to use + var k = typeof amount === 'number' ? amount : 50, + n_samples = 44100, + curve = new Float32Array(n_samples), + deg = Math.PI / 180, + i = 0, + x; + for ( ; i < n_samples; ++i ) { + x = i * 2 / n_samples - 1; + curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) ); + } + return curve; +}; + +navigator.getUserMedia ( + // constraints - only audio needed for this app + { + audio: true + }, + + // Success callback + function(stream) { + source = audioCtx.createMediaStreamSource(stream); + source.connect(analyser); + analyser.connect(distortion); + distortion.connect(biquadFilter); + biquadFilter.connect(gainNode); + gainNode.connect(audioCtx.destination); // connecting the different audio graph nodes together + + visualize(stream); + voiceChange(); + + }, + + // Error callback + function(err) { + console.log('The following gUM error occured: ' + err); + } +); + +function visualize(stream) { + WIDTH = canvas.width; + HEIGHT = canvas.height; + + var visualSetting = visualSelect.value; + console.log(visualSetting); + + if(visualSetting == "sinewave") { + analyser.fftSize = 2048; + var bufferLength = analyser.frequencyBinCount; // half the FFT value + var dataArray = new Uint8Array(bufferLength); // create an array to store the data + + canvasCtx.clearRect(0, 0, WIDTH, HEIGHT); + + function draw() { + + drawVisual = requestAnimationFrame(draw); + + analyser.getByteTimeDomainData(dataArray); // get waveform data and put it into the array created above + + canvasCtx.fillStyle = 'rgb(200, 200, 200)'; // draw wave with canvas + canvasCtx.fillRect(0, 0, WIDTH, HEIGHT); + + canvasCtx.lineWidth = 2; + canvasCtx.strokeStyle = 'rgb(0, 0, 0)'; + + canvasCtx.beginPath(); + + var sliceWidth = WIDTH * 1.0 / bufferLength; + var x = 0; + + for(var i = 0; i < bufferLength; i++) { + + var v = dataArray[i] / 128.0; + var y = v * HEIGHT/2; + + if(i === 0) { + canvasCtx.moveTo(x, y); + } else { + canvasCtx.lineTo(x, y); + } + + x += sliceWidth; + } + + canvasCtx.lineTo(canvas.width, canvas.height/2); + canvasCtx.stroke(); + }; + + draw(); + + } else if(visualSetting == "off") { + canvasCtx.clearRect(0, 0, WIDTH, HEIGHT); + canvasCtx.fillStyle = "red"; + canvasCtx.fillRect(0, 0, WIDTH, HEIGHT); + } + +} + +function voiceChange() { + distortion.curve = new Float32Array; + biquadFilter.gain.value = 0; // reset the effects each time the voiceChange function is run + + var voiceSetting = voiceSelect.value; + console.log(voiceSetting); + + if(voiceSetting == "distortion") { + distortion.curve = makeDistortionCurve(400); // apply distortion to sound using waveshaper node + } else if(voiceSetting == "biquad") { + biquadFilter.type = "lowshelf"; + biquadFilter.frequency.value = 1000; + biquadFilter.gain.value = 25; // apply lowshelf filter to sounds using biquad + } else if(voiceSetting == "off") { + console.log("Voice settings turned off"); // do nothing, as off option was chosen + } + +} + +// event listeners to change visualize and voice settings + +visualSelect.onchange = function() { + window.cancelAnimationFrame(drawVisual); + visualize(stream); +} + +voiceSelect.onchange = function() { + voiceChange(); +} + +mute.onclick = voiceMute; + +function voiceMute() { // toggle to mute and unmute sound + if(mute.id == "") { + gainNode.gain.value = 0; // gain set to 0 to mute sound + mute.id = "activated"; + mute.innerHTML = "Unmute"; + } else { + gainNode.gain.value = 1; // gain set to 1 to unmute sound + mute.id = ""; + mute.innerHTML = "Mute"; + } +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Web Audio API')}}</td> + <td>{{Spec2('Web Audio API')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_do_navegador">Compatibilidade do navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>14 {{property_prefix("webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>23</td> + <td>{{CompatNo}}</td> + <td>15 {{property_prefix("webkit")}}<br> + 22 (unprefixed)</td> + <td>6 {{property_prefix("webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>28 {{property_prefix("webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>25</td> + <td>1.2</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>6 {{property_prefix("webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API">Visualizations with Web Audio API</a></li> + <li><a href="http://mdn.github.io/voice-change-o-matic/">Voice-change-O-matic example</a></li> + <li><a href="http://mdn.github.io/violent-theremin/">Violent Theremin example</a></li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialisation_basics">Web audio spatialisation basics</a></li> + <li><a href="http://www.html5rocks.com/tutorials/webaudio/positional_audio/" title="http://www.html5rocks.com/tutorials/webaudio/positional_audio/">Mixing Positional Audio and WebGL</a></li> + <li><a href="http://www.html5rocks.com/tutorials/webaudio/games/" title="http://www.html5rocks.com/tutorials/webaudio/games/">Developing Game Audio with the Web Audio API</a></li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext" title="/en-US/docs/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext">Porting webkitAudioContext code to standards based AudioContext</a></li> + <li><a href="https://github.com/bit101/tones">Tones</a>: a simple library for playing specific tones/notes using the Web Audio API.</li> + <li><a href="https://github.com/goldfire/howler.js/">howler.js</a>: a JS audio library that defaults to <a href="https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html">Web Audio API</a> and falls back to <a href="http://www.whatwg.org/specs/web-apps/current-work/#the-audio-element">HTML5 Audio</a>, as well as providing other useful features.</li> + <li><a href="https://github.com/mattlima/mooog">Mooog</a>: jQuery-style chaining of AudioNodes, mixer-style sends/returns, and more.</li> +</ul> + +<section id="Quick_Links"> +<h3 id="Hiperligações_Rápidas">Hiperligações Rápidas</h3> + +<ol> + <li data-default-state="open"><strong><a href="#">Guias</a></strong> + + <ol> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API">Basic concepts behind Web Audio API</a></li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API">Using the Web Audio API</a></li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API">Visualizations with Web Audio API</a></li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Web_audio_spatialization_basics">Web audio spatialization basics</a></li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext" title="/en-US/docs/Web_Audio_API/Porting_webkitAudioContext_code_to_standards_based_AudioContext">Porting webkitAudioContext code to standards based AudioContext</a></li> + </ol> + </li> + <li data-default-state="open"><strong><a href="#">Exemplos</a></strong> + <ol> + <li><a href="/en-US/docs/Web/API/Web_Audio_API/Simple_synth">Simple synth keyboard</a></li> + <li><a href="http://mdn.github.io/voice-change-o-matic/">Voice-change-O-matic</a></li> + <li><a href="http://mdn.github.io/violent-theremin/">Violent Theremin</a></li> + </ol> + </li> + <li data-default-state="open"><strong><a href="#">Interfaces</a></strong> + <ol> + <li>{{domxref("AnalyserNode")}}</li> + <li>{{domxref("AudioBuffer")}}</li> + <li>{{domxref("AudioBufferSourceNode")}}</li> + <li>{{domxref("AudioContext")}}</li> + <li>{{domxref("AudioDestinationNode")}}</li> + <li>{{domxref("AudioListener")}}</li> + <li>{{domxref("AudioNode")}}</li> + <li>{{domxref("AudioParam")}}</li> + <li>{{event("audioprocess")}} (event)</li> + <li>{{domxref("AudioProcessingEvent")}}</li> + <li>{{domxref("BiquadFilterNode")}}</li> + <li>{{domxref("ChannelMergerNode")}}</li> + <li>{{domxref("ChannelSplitterNode")}}</li> + <li>{{event("complete")}} (event)</li> + <li>{{domxref("ConvolverNode")}}</li> + <li>{{domxref("DelayNode")}}</li> + <li>{{domxref("DynamicsCompressorNode")}}</li> + <li>{{event("ended_(Web_Audio)", "ended")}} (event)</li> + <li>{{domxref("GainNode")}}</li> + <li>{{domxref("MediaElementAudioSourceNode")}}</li> + <li>{{domxref("MediaStreamAudioDestinationNode")}}</li> + <li>{{domxref("MediaStreamAudioSourceNode")}}</li> + <li>{{domxref("OfflineAudioCompletionEvent")}}</li> + <li>{{domxref("OfflineAudioContext")}}</li> + <li>{{domxref("OscillatorNode")}}</li> + <li>{{domxref("PannerNode")}}</li> + <li>{{domxref("PeriodicWave")}}</li> + <li>{{domxref("ScriptProcessorNode")}}</li> + <li>{{domxref("WaveShaperNode")}}</li> + </ol> + </li> +</ol> +</section> diff --git a/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html b/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html new file mode 100644 index 0000000000..d9a72f2694 --- /dev/null +++ b/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html @@ -0,0 +1,259 @@ +--- +title: Utilizar a API de Áudio da Web +slug: Web/API/Web_Audio_API/Utilizar_api_audio_web +tags: + - API + - API de Áudio da Web + - Guía + - Referencia + - Utilização + - básicos +translation_of: Web/API/Web_Audio_API/Using_Web_Audio_API +--- +<div>{{DefaultAPISidebar("Web Audio API")}}</div> + +<div class="summary"> +<p>Vamos ver como começar a utilizar a API de Áudio da Web. Nós iremos ver resumidamente alguns conceitos, e depois estudar um exemplo simples de caixa de som que nos permite carregar uma faixa de áudio, reproduzi-la e pausá-la, e alterar o seu volume e <em>panning</em> estéreo<span class="seoSummary">.</span></p> +</div> + +<div> +<p>The Web Audio API does not replace the <a href="/en-US/docs/Web/HTML/Element/audio"><audio></a> media element, but rather complements it, just like <a href="/en-US/docs/Web/HTML/Element/canvas"><canvas></a> coexists alongside the <a href="/en-US/docs/Web/HTML/Element/Img"><img></a> element. Your use case will determine what tools you use to implement audio. If you simply want to control playback of an audio track, the <audio> media element provides a better, quicker solution than the Web Audio API. If you want to carry out more complex audio processing, as well as playback, the Web Audio API provides much more power and control.</p> + +<p>A powerful feature of the Web Audio API is that it does not have a strict "sound call limitation". For example, there is no ceiling of 32 or 64 sound calls at one time. Some processors may be capable of playing more than 1,000 simultaneous sounds without stuttering.</p> +</div> + +<h2 id="Código_exemplo">Código exemplo</h2> + +<p>A nossa caixa de música parece-se com isto:</p> + +<p><img alt="A boombox with play, pan, and volume controls" src="https://mdn.mozillademos.org/files/16197/boombox.png" style="border-style: solid; border-width: 1px; height: 646px; width: 1200px;"></p> + +<p>Note the retro cassette deck with a play button, and vol and pan sliders to allow you to alter the volume and stereo panning. We could make this a lot more complex, but this is ideal for simple learning at this stage.</p> + +<p><a href="https://codepen.io/Rumyra/pen/qyMzqN/">Check out the final demo here on Codepen</a>, or see the <a href="https://github.com/mdn/webaudio-examples/tree/master/audio-basics">source code on GitHub</a>.</p> + +<h2 id="Suporte_para_navegador">Suporte para navegador</h2> + +<p>Modern browsers have good support for most features of the Web Audio API. There are a lot of features of the API, so for more exact information, you'll have to check the browser compatibility tables at the bottom of each reference page.</p> + +<h2 id="Gráficos_de_áudio">Gráficos de áudio</h2> + +<p>Everything within the Web Audio API is based around the concept of an audio graph, which is made up of nodes.</p> + +<p>The Web Audio API handles audio operations inside an <strong>audio context</strong>, and has been designed to allow <strong>modular routing</strong>. Basic audio operations are performed with <strong>audio nodes</strong>, which are linked together to form an <strong>audio routing graph</strong>. You have input nodes, which are the source of the sounds you are manipulating, modification nodes that change those sounds as desired, and output nodes (destinations), which allow you to save or hear those sounds.</p> + +<p>Several audio sources with different channel layouts are supported, even within a single context. Because of this modular design, you can create complex audio functions with dynamic effects.</p> + +<h2 id="Contxeto_de_Áudio">Contxeto de Áudio</h2> + +<p>To be able to do anything with the Web Audio API, we need to create an instance of the audio context. This then gives us access to all the features and functionality of the API.</p> + +<pre class="brush: js">// for legacy browsers +const AudioContext = window.AudioContext || window.webkitAudioContext; + +const audioCtx = new AudioContext(); +</pre> + +<p>So what's going on when we do this? A {{domxref("BaseAudioContext")}} is created for us automatically and extended to an online audio context. We'll want this because we're looking to play live sound.</p> + +<div class="note"> +<p><strong>Note</strong>: If you just want to process audio data, for instance, buffer and stream it but not play it, you might want to look into creating an {{domxref("OfflineAudioContext")}}.</p> +</div> + +<h2 id="Carregar_som">Carregar som</h2> + +<p>Now, the audio context we've created needs some sound to play through it. There are a few ways to do this with the API. Let's begin with a simple method — as we have a boombox, we most likely want to play a full song track. Also, for accessibility, it's nice to expose that track in the DOM. We'll expose the song on the page using an {{htmlelement("audio")}} element.</p> + +<pre class="brush: html"><audio src="myCoolTrack.mp3" type="audio/mpeg"></audio> +</pre> + +<div class="note"> +<p><strong>Nota</strong>: If the sound file you're loading is held on a different domain you will need to use the <code>crossorigin</code> attribute; see <a href="/en-US/docs/Web/HTTP/CORS">Cross Origin Resource Sharing (CORS)</a> for more information.</p> +</div> + +<p>To use all the nice things we get with the Web Audio API, we need to grab the source from this element and <em>pipe</em> it into the context we have created. Lucky for us there's a method that allows us to do just that — {{domxref("AudioContext.createMediaElementSource")}}:</p> + +<pre class="brush: js">// get the audio element +const audioElement = document.querySelector('audio'); + +// pass it into the audio context +const track = audioCtx.createMediaElementSource(audioElement); +</pre> + +<div class="note"> +<p><strong>Nota</strong>: The <code><audio></code> element above is represented in the DOM by an object of type {{domxref("HTMLMediaElement")}}, which comes with its own set of functionality. All of this has stayed intact; we are merely allowing the sound to be available to the Web Audio API.</p> +</div> + +<h2 id="Controlar_o_som">Controlar o som</h2> + +<p>When playing sound on the web, it's important to allow the user to control it. Depending on the use case, there's a myriad of options, but we'll provide functionality to play/pause the sound, alter the track's volume, and pan it from left to right.</p> + +<div class="note"> +<p><strong>Nota</strong>: We need to take into account the new autoplay policy that modern browsers have, which calls for a user gesture before media can play (see Chrome's <a href="https://developers.google.com/web/updates/2017/09/autoplay-policy-changes">Autoplay Policy Changes</a>, for example). This has been implemented because autoplaying media is really bad for many reasons — it is annoying and intrusive at the very least, and also causes accessibility problems. This is accounted for by our play/pause button.</p> +</div> + +<p>Let's take a look at our play and pause functionality to start with. We have a play button that changes to a pause button when the track is playing:</p> + +<pre class="brush: html"><button data-playing="false" role="switch" aria-checked="false"> + <span>Play/Pause</span> +</button> +</pre> + +<p>Before we can play our track we need to connect our audio graph from the audio source/input node to the destination.</p> + +<p>We've already created an input node by passing our audio element into the API. For the most part, you don't need to create an output node, you can just connect your other nodes to {{domxref("BaseAudioContext.destination")}}, which handles the situation for you:</p> + +<pre class="brush: js">track.connect(audioCtx.destination); +</pre> + +<p>A good way to visualise these nodes is by drawing an audio graph so you can visualize it. This is what our current audio graph looks like:</p> + +<p><img alt="an audio graph with an audio element source connected to the default destination" src="https://mdn.mozillademos.org/files/16195/graph1.jpg" style="border-style: solid; border-width: 1px; height: 486px; width: 1426px;"></p> + +<p>Now we can add the play and pause functionality.</p> + +<pre class="brush: js">// select our play button +const playButton = document.querySelector('button'); + +playButton.addEventListener('click', function() { + + // check if context is in suspended state (autoplay policy) + if (audioCtx.state === 'suspended') { + audioCtx.resume(); + } + + // play or pause track depending on state + if (this.dataset.playing === 'false') { + audioElement.play(); + this.dataset.playing = 'true'; + } else if (this.dataset.playing === 'true') { + audioElement.pause(); + this.dataset.playing = 'false'; + } + +}, false); +</pre> + +<p>We also need to take into account what to do when the track finishes playing. Our <code>HTMLMediaElement</code> fires an <code>ended</code> event once it's finished playing, so we can listen for that and run code accordingly:</p> + +<pre class="brush: js">audioElement.addEventListener('ended', () => { + playButton.dataset.playing = 'false'; +}, false); +</pre> + +<h2 id="Um_aparte_sobre_o_editor_de_Áudio_da_Web">Um aparte sobre o editor de Áudio da Web</h2> + +<p>Firefox has a tool available called the <a href="/en-US/docs/Tools/Web_Audio_Editor">Web Audio editor</a>. On any page that has an audio graph running on it, you can open the developer tools, and use the Web Audio tab to view the audio graph, see what properties each node has available, and change the values of those properties to see what effect that has.</p> + +<p><img alt="The Firefox web audio editor showing an audio graph with AudioBufferSource, IIRFilter, and AudioDestination" src="https://mdn.mozillademos.org/files/16198/web-audio-editor.png" style="border-style: solid; border-width: 1px; height: 365px; width: 1200px;"></p> + +<div class="note"> +<p><strong>Nota</strong>: The Web Audio editor is not enabled by default. To display it, you need to go into the Firefox developer tools settings and check the <em>Web Audio</em> checkbox in the <em>Default Developer Tools</em> section.</p> +</div> + +<h2 id="Modificar_o_som">Modificar o som</h2> + +<p>Let's delve into some basic modification nodes, to change the sound that we have. This is where the Web Audio API really starts to come in handy. First of all, let's change the volume. This can be done using a {{domxref("GainNode")}}, which represents how big our sound wave is.</p> + +<p>There are two ways you can create nodes with the Web Audio API. You can use the factory method on the context itself (e.g. <code>audioCtx.createGain()</code>) or via a constructor of the node (e.g. <code>new GainNode()</code>). We'll use the factory method in our code:</p> + +<pre class="brush: js">const gainNode = audioCtx.createGain(); +</pre> + +<p>Now we have to update our audio graph from before, so the input is connected to the gain, then the gain node is connected to the destination:</p> + +<pre class="brush: js">track.connect(gainNode).connect(audioCtx.destination); +</pre> + +<p>This will make our audio graph look like this:</p> + +<p><img alt="an audio graph with an audio element source, connected to a gain node that modifies the audio source, and then going to the default destination" src="https://mdn.mozillademos.org/files/16196/graph2.jpg" style="border-style: solid; border-width: 1px; height: 550px; width: 1774px;"></p> + +<p>The default value for gain is 1; this keeps the current volume the same. Gain can be set to a minimum of about -3.4 and a max of about 3.4. Here we'll allow the boombox to move the gain up to 2 (double the original volume) and down to 0 (this will effectively mute our sound).</p> + +<p>Let's give the user control to do this — we'll use a <a href="/en-US/docs/Web/HTML/Element/input/range">range input</a>:</p> + +<pre class="brush: html"><input type="range" id="volume" min="0" max="2" value="1" step="0.01" /> +</pre> + +<div class="note"> +<p><strong>Nota</strong>: Range inputs are a really handy input type for updating values on audio nodes. You can specify a range's values and use them directly with the audio node's parameters.</p> +</div> + +<p>So let's grab this input's value and update the gain value when the input node has its value changed by the user:</p> + +<pre class="brush: js">const volumeControl = document.querySelector('#volume'); + +volumeControl.addEventListener('input', function() { + gainNode.gain.value = this.value; +}, false); +</pre> + +<div class="note"> +<p><strong>Nota</strong>: The values of node objects (e.g. <code>GainNode.gain</code>) are not simple values; they are actually objects of type {{domxref("AudioParam")}} — these called parameters. This is why we have to set <code>GainNode.gain</code>'s <code>value</code> property, rather than just setting the value on <code>gain</code> directly. This enables them to be much more flexible, allowing for passing the parameter a specific set of values to change between over a set period of time, for example.</p> +</div> + +<p>Great, now the user can update the track's volume! The gain node is the perfect node to use if you want to add mute functionality.</p> + +<h2 id="Adicionar_panning_estéreo_à_sua_aplicação">Adicionar <em>panning</em> estéreo à sua aplicação</h2> + +<p>Let's add another modification node to practise what we've just learnt.</p> + +<p>There's a {{domxref("StereoPannerNode")}} node, which changes the balance of the sound between the left and right speakers, if the user has stereo capabilities.</p> + +<p>Note: The <code>StereoPannerNode</code> is for simple cases in which you just want stereo panning from left to right. There is also a {{domxref("PannerNode")}}, which allows for a great deal of control over 3D space, or sound <em>spatialisation</em>, for creating more complex effects. This is used in games and 3D apps to create birds flying overhead, or sound coming from behind the user for instance.</p> + +<p>To visualise it, we will be making our audio graph look like this:</p> + +<p><img alt="An image showing the audio graph showing an input node, two modification nodes (a gain node and a stereo panner node) and a destination node." src="https://mdn.mozillademos.org/files/16229/graphPan.jpg" style="border-style: solid; border-width: 1px; height: 532px; width: 2236px;"></p> + +<p>Let's use the constructor method of creating a node this time. When we do it this way, we have to pass in the context and any options that that particular node may take:</p> + +<pre class="brush: js">const pannerOptions = {pan: 0}; +const panner = new StereoPannerNode(audioCtx, pannerOptions); +</pre> + +<div class="note"> +<p><strong>Nota</strong>: The constructor method of creating nodes is not supported by all browsers at this time. The older factory methods are supported more widely.</p> +</div> + +<p>Here our values range from -1 (far left) and 1 (far right). Again let's use a range type input to vary this parameter:</p> + +<pre class="brush: html"><input type="range" id="panner" min="-1" max="1" value="0" step="0.01" /> +</pre> + +<p>We use the values from that input to adjust our panner values in the same way as we did before:</p> + +<pre class="brush: js">const pannerControl = document.querySelector('#panner'); + +pannerControl.addEventListener('input', function() { + panner.pan.value = this.value; +}, false); +</pre> + +<p>Let's adjust our audio graph again, to connect all the nodes together:</p> + +<pre class="brush: js">track.connect(gainNode).connect(panner).connect(audioCtx.destination); +</pre> + +<p>The only thing left to do is give the app a try: <a href="https://codepen.io/Rumyra/pen/qyMzqN/">Check out the final demo here on Codepen</a>.</p> + +<h2 id="Resumo">Resumo</h2> + +<p>Great! We have a boombox that plays our 'tape', and we can adjust the volume and stereo panning, giving us a fairly basic working audio graph.</p> + +<p>This makes up quite a few basics that you would need to start to add audio to your website or web app. There's a lot more functionality to the Web Audio API, but once you've grasped the concept of nodes and putting your audio graph together, we can move on to looking at more complex functionality.</p> + +<h2 id="Mais_exemplos">Mais exemplos</h2> + +<p>There are other examples available to learn more about the Web Audio API.</p> + +<p>The <a href="https://github.com/mdn/voice-change-o-matic">Voice-change-O-matic</a> is a fun voice manipulator and sound visualization web app that allows you to choose different effects and visualizations. The application is fairly rudimentary, but it demonstrates the simultaneous use of multiple Web Audio API features. (<a href="https://mdn.github.io/voice-change-o-matic/">run the Voice-change-O-matic live</a>).</p> + +<p><img alt="A UI with a sound wave being shown, and options for choosing voice effects and visualizations." src="https://mdn.mozillademos.org/files/7921/voice-change-o-matic.png" style="border-style: solid; border-width: 1px; display: block; height: 500px; margin: 0px auto; width: 640px;"></p> + +<p>Another application developed specifically to demonstrate the Web Audio API is the <a href="http://mdn.github.io/violent-theremin/">Violent Theremin</a>, a simple web application that allows you to change pitch and volume by moving your mouse pointer. It also provides a psychedelic lightshow (<a href="https://github.com/mdn/violent-theremin">see Violent Theremin source code</a>).</p> + +<p><img alt="A page full of rainbow colours, with two buttons labeled Clear screen and mute. " src="https://mdn.mozillademos.org/files/7919/violent-theremin.png" style="border-style: solid; border-width: 1px; display: block; height: 458px; margin: 0px auto; width: 640px;"></p> + +<p>Consulte também a nossa <a href="https://github.com/mdn/webaudio-examples">repositório de exemplos de áudio</a> para mais exemplos.</p> diff --git a/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html b/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html new file mode 100644 index 0000000000..ee969bfb75 --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html @@ -0,0 +1,443 @@ +--- +title: Funções e classes disponíveis para os Workers da Web +slug: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers +tags: + - Referencia + - Web +translation_of: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers +--- +<p>In addition to the standard <a href="/en-US/docs/Web/JavaScript">JavaScript</a> set of functions (such as {{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("Object")}}, {{jsxref("JSON")}}, etc), there are a variety of functions available from the DOM to workers. This article provides a list of those.</p> + +<p><strong>Workers run in another global context, {{domxref("DedicatedWorkerGlobalScope")}}, different from the current window</strong>. By default, methods and properties of {{domxref("Window")}} are not available to them, but {{domxref("DedicatedWorkerGlobalScope")}}, like <code>Window</code>, implements {{domxref("WindowTimers")}} and {{domxref("WindowBase64")}}.</p> + +<h2 id="Comparação_das_propriedades_e_métodos_de_diferentes_tipos_de_workers">Comparação das propriedades e métodos de diferentes tipos de <em>workers</em></h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Função</td> + <td class="header">Workers dedicados</td> + <td class="header">Shared workers</td> + <td class="header">Service workers</td> + <td class="header">Chrome workers {{Non-standard_inline}}</td> + <td class="header">Outside workers</td> + </tr> + <tr> + <td>{{domxref("WindowBase64.atob", "atob()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowBase64.btoa", "btoa()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowTimers.clearInterval", "clearInterval()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("Window.dump()", "dump()")}} {{non-standard_inline}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowTimers.setInterval", "setInterval()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WindowTimers.setTimeout", "setTimeout()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("Window")}}</td> + </tr> + <tr> + <td>{{domxref("WorkerGlobalScope.importScripts", "importScripts()")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>no</td> + </tr> + <tr> + <td>{{domxref("WorkerGlobalScope.close", "close()")}} {{non-standard_inline}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, on {{domxref("WorkerGlobalScope")}}</td> + <td>yes, but is a no-op.</td> + <td>Unknown</td> + <td>no</td> + </tr> + <tr> + <td>{{domxref("DedicatedWorkerGlobalScope.postMessage", "postMessage()")}}</td> + <td>yes, on {{domxref("DedicatedWorkerGlobalScope")}}</td> + <td>no</td> + <td>no</td> + <td>Unknown</td> + <td>no</td> + </tr> + </tbody> +</table> + +<h2 id="APIs_disponíveis_nos_workers">APIs disponíveis nos <em>workers</em></h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Função</td> + <td class="header">Funcionalidade</td> + <td class="header">Suporte no Gecko (Firefox)</td> + <td class="header">Support in IE</td> + <td class="header">Support in Blink (Chrome and Opera)</td> + <td class="header">Support in WebKit (Safari)</td> + </tr> + <tr> + <td>{{domxref("Broadcast_Channel_API","Broadcast Channel API")}}</td> + <td>Allows simple communication between {{glossary("browsing context", "browsing contexts")}} (that is <em>windows</em>, <em>tabs</em>, <em>frames</em>, or <em>iframes</em>) with the same {{glossary("origin")}} (usually pages from the same site).</td> + <td>{{ CompatGeckoDesktop(38)}}</td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatNo}}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatNo}}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatNo}}</span></td> + </tr> + <tr> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{domxref("Cache", "Cache")}}</span></td> + <td>Cache API<span style="background-color: rgba(212, 221, 228, 0.14902);"> provides the ability to programmatically</span> control cache storage associated with current origin.</td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatVersionUnknown}}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatNo}}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{ CompatChrome(43) }}</span></td> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{CompatUnknown}}</span></td> + </tr> + <tr> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{domxref("Channel_Messaging_API", "Channel Messaging API")}}</span></td> + <td>Allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a {{domxref("SharedWorker")}}, or two workers) to communicate directly via two ports.</td> + <td>{{ CompatGeckoDesktop(41)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{domxref("Console", "Console API")}}</span></td> + <td>Provides access to the browser's debugging console (e.g., the <a href="/en-US/docs/Tools/Web_Console">Web Console</a> in Firefox). The specifics of how it works vary from browser to browser, but there is a <em>de facto</em> set of features that are typically provided.</td> + <td>{{ CompatGeckoDesktop(38)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><span style="background-color: rgba(212, 221, 228, 0.14902);">{{domxref("CustomEvent")}}</span></td> + <td>The <strong><code>CustomEvent</code></strong> interface represents events initialized by an application for any purpose.</td> + <td>{{ CompatGeckoDesktop(48)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("Data_Store_API", "Data Store")}}</td> + <td>A powerful, flexible storage mechanism for multiple Firefox OS applications to use to store and share data between one another quickly, efficiently, and securely.</td> + <td>Only in Firefox OS internal (certified) applications, since v1.0.1.</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("DOMRequest")}} and {{domxref("DOMCursor")}}</td> + <td>Respectively, these objects represents an ongoing operation (with listeners for reacting to the operation completely successfully, or failing, for example), and an ongoing operation over a list of results.</td> + <td>{{ CompatGeckoDesktop(41)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("Fetch_API", "Fetch")}}</td> + <td>The Fetch spec provides an up-to-date definition of, and API for, fetching resources (e.g. across the network.)</td> + <td>Mostly in {{ CompatGeckoDesktop(34)}} behind pref, although a few features are later.</td> + <td>{{CompatNo}}</td> + <td>{{ CompatChrome(42) }}<br> + {{ CompatChrome(41) }} behind pref</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("FileReader")}}</td> + <td>This API allows asynchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects.</td> + <td>{{CompatGeckoDesktop(46)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("FileReaderSync")}}</td> + <td>This API allows synchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects. This is an API that works only in workers.</td> + <td>{{CompatGeckoDesktop(8)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("FormData")}}</td> + <td><code>FormData</code> objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest <a href="/en-US/docs/DOM/XMLHttpRequest#send()" title="XMLHttpRequest#send()"><code>send()</code></a> method.</td> + <td>{{CompatUnknown}} (should be in {{CompatGeckoDesktop(39)}})</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("ImageData")}}</td> + <td>The underlying pixel data of an area of a {{domxref("canvas")}} element. Manipulating such data can be a complex task better suited to be delegated to a Web Worker.</td> + <td>{{CompatGeckoDesktop(25)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("IndexedDB_API", "IndexedDB")}}</td> + <td>Database to store records holding simple values and hierarchical objects.</td> + <td>{{CompatGeckoDesktop(37)}}, {{CompatGeckoDesktop(42)}} for {{domxref("IDBCursorWithValue")}}.</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/Network_Information_API">Network Information API</a></td> + <td>provides information about the system's connection in terms of general connection type (e.g., 'wifi', 'cellular', etc.).</td> + <td>{{CompatGeckoMobile(53)}} only on mobile</td> + <td>{{CompatVersionUnknown}} only on mobile</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("Notifications_API", "Notifications")}}</td> + <td>Allows web pages to control the display of system notifications to the end user</td> + <td>{{CompatGeckoDesktop(41)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("Performance")}}</td> + <td>The <strong><code>Performance</code></strong> interface represents timing-related performance information for the given page.</td> + <td>{{ CompatGeckoDesktop("34.0") }}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatChrome("33.0") }}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{jsxref("Promise")}}</td> + <td>JavaScript objects that allow you to write asynchronous functions.</td> + <td>{{CompatGeckoDesktop(28)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/Server-sent_events">Server-sent events</a></td> + <td>Allows a server to push data to a web page at any point, after a connection has been opened to it.</td> + <td>{{CompatGeckoDesktop(53)}} (currently only available in dedicated and shared workers; not service workers.)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>{{domxref("ServiceWorkerRegistration")}}</td> + <td>You can register a service worker from inside a standard worker, and use associated functionality.</td> + <td>{{CompatGeckoDesktop(40)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("TextEncoder")}} and {{domxref("TextDecoder")}}</td> + <td>Create and return a new {{domxref("TextEncoder")}}, or respectively {{domxref("TextDecoder")}}, allowing to encode or decode strings into specific encodings.</td> + <td>{{CompatGeckoDesktop(20)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{ domxref("URL") }}</td> + <td>Workers can use the static methods <a href="/en-US/docs/DOM/window.URL.createObjectURL" title="/en-US/docs/DOM/window.URL.createObjectURL">URL.createObjectURL</a> and <a href="/en-US/docs/DOM/window.URL.revokeObjectURL" title="/en-US/docs/DOM/window.URL.revokeObjectURL">URL.revokeObjectURL</a> with {{domxref("Blob")}} objects accesible to the worker.<br> + Workers can also create a new URL using the {{domxref("URL.URL", "URL()")}} constructor and call any normal method on the returned object.</td> + <td>{{CompatGeckoDesktop(21)}} and {{CompatGeckoDesktop(26)}} for URL() constructor</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/API/WebGL_API">WebGL</a> with {{domxref("OffscreenCanvas")}}</td> + <td>WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins.</td> + <td>{{CompatGeckoDesktop(44)}} behind a feature preference setting. In <code>about:config</code>, set <code>gfx.offscreencanvas.enabled</code> to true.</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("WebSocket")}}</td> + <td>Creates and returns a new {{domxref("WebSocket")}} object; this mimics the behavior of the standard <code>WebSocket()</code> constructor.</td> + <td>{{CompatGeckoDesktop(37)}}</td> + <td>11.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("Worker")}}</td> + <td>Creates a new {{ domxref("Worker") }}. Yes, workers can spawn more workers.</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>10.0</td> + <td>{{CompatNo}} See <a class="external" href="https://code.google.com/p/chromium/issues/detail?id=31666" rel="external" title="http://code.google.com/p/chromium/issues/detail?id=31666">crbug.com/31666</a></td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>{{domxref("WorkerGlobalScope")}}</td> + <td>The global scope of workers. This objects defines <a href="#workerscope">worker-specific functions</a>.</td> + <td>{{CompatVersionUnknown}}</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("WorkerLocation")}}</td> + <td>The subset of the {{domxref("Location")}} interface available to workers.</td> + <td>{{CompatGeckoDesktop(1.9.2)}}</td> + <td>10.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("WorkerNavigator")}}</td> + <td>The subset of the {{domxref("Navigator")}} interface available to workers.</td> + <td>Basic implementation {{CompatVersionUnknown}}<br> + {{domxref("NavigatorID.appCodeName", "appCodeName")}}, {{domxref("NavigatorID.product", "product")}}, {{domxref("NavigatorID.taintEnabled", "taintEnabled()")}}: {{CompatGeckoDesktop(28)}}<br> + {{domxref("WorkerNavigator.onLine", "onLine")}}: {{CompatGeckoDesktop(29)}}<br> + {{domxref("NavigatorLanguage")}}: {{CompatVersionUnknown}}</td> + <td>{{domxref("NavigatorID.appName", "appName")}}, {{domxref("NavigatorID.appVersion", "appVersion")}}, {{domxref("WorkerNavigator.onLine", "onLine")}}, {{domxref("NavigatorID.platform", "platform")}}, {{domxref("NavigatorID.userAgent", "userAgent")}}: 10.0<br> + Other: {{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>{{domxref("XMLHttpRequest")}}</td> + <td>Creates and returns a new {{domxref("XMLHttpRequest")}} object; this mimics the behavior of the standard <code>XMLHttpRequest()</code> constructor. Note that the <code>responseXML</code> and <code>channel</code> attributes on <code>XMLHttpRequest</code> always return <code>null</code>.</td> + <td> + <p>Basic: {{CompatGeckoDesktop("1.9.1")}}</p> + + <p>{{domxref("XMLHttpRequest.response", "response")}} and {{domxref("XMLHttpRequest.responseType", "responseType")}} are available since {{CompatGeckoDesktop("10")}}</p> + + <p>{{domxref("XMLHttpRequest.timeout", "timeout")}} and {{domxref("XMLHttpRequest.ontimeout", "ontimeout")}} are available since {{CompatGeckoDesktop("13")}}</p> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/Web_Workers_API/Utilizacao_de_web_workers">Utilização de workers da Web</a></li> + <li>{{domxref("Worker")}}</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/web_workers_api/index.html b/files/pt-pt/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..9c1040b06f --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/index.html @@ -0,0 +1,234 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +tags: + - API + - NeedsTranslation + - Service Workers + - Shared Workers + - TopicStub + - Web Workers + - Workers +translation_of: Web/API/Web_Workers_API +--- +<p>{{DefaultAPISidebar("Web Workers API")}}</p> + +<p class="summary"><strong>Web Workers</strong> makes it possible to run a script operation in background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.</p> + +<h2 id="Web_Workers_concepts_and_usage">Web Workers concepts and usage</h2> + +<p>A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. This context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}).</p> + +<p>You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under <code>window</code>, including <a href="/en-US/docs/WebSockets">WebSockets</a>, and data storage mechanisms like <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> and the Firefox OS-only <a href="/en-US/docs/Web/API/Data_Store_API">Data Store API</a>. See <a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Functions and classes available to workers</a> for more details.</p> + +<p>Data is sent between workers and the main thread via a system of messages — both sides send their messages using the <code>postMessage()</code> method, and respond to messages via the <code>onmessage</code> event handler (the message is contained within the {{event("Message")}} event's <code>data</code> property). The data is copied rather than shared.</p> + +<p>Workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use <a class="internal" href="/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a> for network I/O, with the exception that the <code>responseXML</code> and <code>channel</code> attributes on <code>XMLHttpRequest</code> always return <code>null</code>.</p> + +<p>In addition to dedicated workers, there are other types of worker:</p> + +<ul> + <li>Shared workers are workers that can be utilized by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complex than dedicated workers — scripts must communicate via an active port. See {{domxref("SharedWorker")}} for more details.</li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorkers</a> essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.</li> + <li>Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to <a href="https://developer.mozilla.org/en/js-ctypes">js-ctypes</a> in your worker. See {{domxref("ChromeWorker")}} for more details. </li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API#Audio_Workers">Audio Workers</a> provide the ability for direct scripted audio processing to be done inside a web worker context.</li> +</ul> + +<div class="note"> +<p><strong>Note</strong>: As per the <a href="https://html.spec.whatwg.org/multipage/workers.html#runtime-script-errors-2">Web workers Spec</a>, worker error events should not bubble (see {{bug(1188141)}}. This has been implemented in Firefox 42.</p> +</div> + +<h2 id="Web_Worker_interfaces">Web Worker interfaces</h2> + +<dl> + <dt>{{domxref("AbstractWorker")}}</dt> + <dd>Abstracts properties and methods common to all kind of workers (i.e. {{domxref("Worker")}} or {{domxref("SharedWorker")}}).</dd> + <dt>{{domxref("Worker")}}</dt> + <dd>Represents a running worker thread, allowing you to pass messages to the running worker code.</dd> + <dt>{{domxref("WorkerLocation")}}</dt> + <dd>Defines the absolute location of the script executed by the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker" title="The Worker interface of the Web Workers API represents a background task that can be easily created and can send messages back to its creator. Creating a worker is as simple as calling the Worker() constructor and specifying a script to be run in the worker thread."><code>Worker</code></a>.</dd> +</dl> + +<dl> + <dt>{{domxref("SharedWorker")}}</dt> + <dd>Represents a specific kind of worker that can be <em>accessed</em> from several browsing contexts, being several windows, iframes or even workers.</dd> + <dt>{{domxref("WorkerGlobalScope")}}</dt> + <dd>Represents the generic scope of any worker (doing the same job as {{domxref("Window")}} does for normal web content). Different types of worker have scope objects that inherit from this interface and add more specific features.</dd> + <dt>{{domxref("DedicatedWorkerGlobalScope")}}</dt> + <dd>Represents the scope of a dedicated worker, inheriting from {{domxref("WorkerGlobalScope")}} and adding some dedicated features.</dd> + <dt>{{domxref("SharedWorkerGlobalScope")}}</dt> + <dd>Represents the scope of a shared worker, inheriting from {{domxref("WorkerGlobalScope")}} and adding some dedicated features.</dd> + <dt>{{domxref("WorkerNavigator")}}</dt> + <dd>Represents the identity and state of the user agent (the client):</dd> +</dl> + +<h2 id="Examples">Examples</h2> + +<p>We have created a couple of simple demos to show basic usage:</p> + +<ul> + <li><a href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a href="http://mdn.github.io/simple-web-worker/">run dedicated worker</a>).</li> + <li><a href="https://github.com/mdn/simple-shared-worker">Basic shared worker example</a> (<a href="http://mdn.github.io/simple-shared-worker/">run shared worker</a>).</li> +</ul> + +<p>You can find out more information on how these demos work in <a href="/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Using web workers</a>.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#workers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(1.9.1)}}</td> + <td>10.0</td> + <td>10.6</td> + <td>4</td> + </tr> + <tr> + <td>Shared workers</td> + <td>4</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(29)}}</td> + <td>{{CompatNo}}</td> + <td>10.6</td> + <td>4</td> + </tr> + <tr> + <td>Passing data using structured cloning</td> + <td>13</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(8)}}</td> + <td>10.0</td> + <td>11.5</td> + <td>6</td> + </tr> + <tr> + <td>Passing data using transferable objects</td> + <td>17 {{property_prefix("webkit")}}<br> + 21</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(18)}}</td> + <td>{{CompatNo}}</td> + <td>15</td> + <td>6</td> + </tr> + <tr> + <td>Global {{domxref("window.URL", "URL")}}</td> + <td>10<sup>[1]</sup><br> + 23</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(21)}}</td> + <td>11</td> + <td>15</td> + <td>6<sup>[1]</sup></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile(1.9.1)}}</td> + <td>1.0.1</td> + <td>10.0</td> + <td>11.5</td> + <td>5.1</td> + </tr> + <tr> + <td>Shared workers</td> + <td>{{CompatNo}}</td> + <td>4</td> + <td>{{CompatNo}}</td> + <td>29</td> + <td>1.4</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Passing data using structured cloning</td> + <td>{{CompatNo}}</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>8</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Passing data using transferable objects</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>18</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] As <code>webkitURL</code>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/basic_usage">Using Web Workers</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Worker Interface</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker">SharedWorker interface</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Functions and classes available to workers</a></li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/Advanced_concepts_and_examples">Advanced concepts and examples</a></li> + <li><a href="/en-US/docs/Web/API/ChromeWorker">ChromeWorker</a>: for using workers in privileged/chrome code</li> +</ul> diff --git a/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html b/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html new file mode 100644 index 0000000000..d9705559e7 --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html @@ -0,0 +1,1091 @@ +--- +title: Utilização de Web Workers +slug: Web/API/Web_Workers_API/Utilizacao_de_web_workers +tags: + - Avançado + - Firefox + - Guía + - JavaScript + - Operadores + - Workers +translation_of: Web/API/Web_Workers_API/Using_web_workers +--- +<div class="summary"> +<p><em>Web Workers</em> é um meio simples para o conteúdo da Web para executar <em>scripts</em> em segmentos em segundo plano. O segmento do <em>worker</em> pode realizar tarefas sem interferir com a interface do utilizador. Em adição, eles podem executar I/O, utilizando <code><a class="internal" href="/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIXMLHttpRequest">XMLHttpRequest</a></code> (embora<code> e responseXML</code> e os atributos de <code>channel</code> são sempre nulos). Uma vez criado, um <em>worker </em>pode enviar mensagens para o código JavaScript que o criou publicando mensagens para um manipulador de evento especificado por esse código (e vice-versa.) Este artigo fornece uma introdução detalhada para utilizar <em>workers </em>da Web.</p> +</div> + +<h2 id="API_de_Workers_da_Web">API de Workers da Web</h2> + +<p>A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. Thus, using the {{domxref("window")}} shortcut to get the current global scope (instead of {{domxref("window.self","self")}}) within a {{domxref("Worker")}} will return an error.</p> + +<p>The worker context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}). A dedicated worker is only accessible from the script that first spawned it, whereas shared workers can be accessed from multiple scripts.</p> + +<div class="note"> +<p><strong>Nota</strong>: See <a href="/en-US/docs/Web/API/Web_Workers_API">The Web Workers API landing page</a> for reference documentation on workers and additional guides.</p> +</div> + +<p>You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under <code>window</code>, including <a href="/en-US/docs/Web/API/WebSockets_API">WebSockets</a>, and data storage mechanisms like <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> and the Firefox OS-only <a href="/en-US/docs/Web/API/Data_Store_API">Data Store API</a>. See <a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Functions and classes available to workers</a> for more details.</p> + +<p>Data is sent between workers and the main thread via a system of messages — both sides send their messages using the <code>postMessage()</code> method, and respond to messages via the <code>onmessage</code> event handler (the message is contained within the {{event("Message")}} event's data attribute.) The data is copied rather than shared.</p> + +<p>Workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page. In addition, workers may use <a class="internal" href="/en-US/docs/Web/API/XMLHttpRequest"><code>XMLHttpRequest</code></a> for network I/O, with the exception that the <code>responseXML</code> and <code>channel</code> attributes on <code>XMLHttpRequest</code> always return <code>null</code>.</p> + +<h2 id="Workers_dedicados">Workers dedicados</h2> + +<p>As mentioned above, a dedicated worker is only accessible by the script that called it. In this section we'll discuss the JavaScript found in our <a class="external external-icon" href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a class="external external-icon" href="https://mdn.github.io/simple-web-worker/">run dedicated worker</a>): This allows you to enter two numbers to be multiplied together. The numbers are sent to a dedicated worker, multiplied together, and the result is returned to the page and displayed.</p> + +<p>This example is rather trivial, but we decided to keep it simple while introducing you to basic worker concepts. More advanced details are covered later on in the article.</p> + +<h3 id="Detecção_da_funcionalidade_worker">Detecção da funcionalidade worker</h3> + +<p>For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (<a href="https://github.com/mdn/simple-web-worker/blob/gh-pages/main.js">main.js</a>):</p> + +<pre class="brush: js">if (window.Worker) { + + ... + +}</pre> + +<h3 id="Geração_de_um_worker_dedicado">Geração de um <em>worker </em>dedicado</h3> + +<p>Creating a new worker is simple. All you need to do is call the {{domxref("Worker.Worker", "Worker()")}} constructor, specifying the URI of a script to execute in the worker thread (<a href="https://github.com/mdn/simple-web-worker/blob/gh-pages/main.js">main.js</a>):</p> + +<div style="overflow: hidden;"> +<pre class="brush: js">var myWorker = new Worker('worker.js'); +</pre> +</div> + +<h3 id="Enviar_mensagens_para_e_de_um_worker_dedicado">Enviar mensagens para /e de um <em>worker </em>dedicado</h3> + +<p>The magic of workers happens via the {{domxref("Worker.postMessage", "postMessage()")}} method and the {{domxref("Worker.onmessage", "onmessage")}} event handler. When you want to send a message to the worker, you post messages to it like this (<a href="https://github.com/mdn/simple-web-worker/blob/gh-pages/main.js">main.js</a>):</p> + +<pre class="brush: js">first.onchange = function() { + myWorker.postMessage([first.value,second.value]); + console.log('Message posted to worker'); +} + +second.onchange = function() { + myWorker.postMessage([first.value,second.value]); + console.log('Message posted to worker'); +}</pre> + +<p>So here we have two {{htmlelement("input")}} elements represented by the variables <code>first</code> and <code>second</code>; when the value of either is changed, <code>myWorker.postMessage([first.value,second.value])</code> is used to send the value inside both to the worker, as an array. You can send pretty much anything you like in the message.</p> + +<p>In the worker, we can respond when the message is received by writing an event handler block like this (<a href="https://github.com/mdn/simple-web-worker/blob/gh-pages/worker.js">worker.js</a>):</p> + +<pre class="brush: js">onmessage = function(e) { + console.log('Message received from main script'); + var workerResult = 'Result: ' + (e.data[0] * e.data[1]); + console.log('Posting message back to main script'); + postMessage(workerResult); +}</pre> + +<p>The <code>onmessage</code> handler allows us to run some code whenever a message is received, with the message itself being available in the <code>message</code> event's <code>data</code> attribute. Here we simply multiply together the two numbers then use <code>postMessage()</code> again, to post the result back to the main thread.</p> + +<p>Back in the main thread, we use <code>onmessage</code> again, to respond to the message sent back from the worker:</p> + +<pre class="brush: js">myWorker.onmessage = function(e) { + result.textContent = e.data; + console.log('Message received from worker'); +}</pre> + +<p>Here we grab the message event data and set it as the <code>textContent</code> of the result paragraph, so the user can see the result of the calculation.</p> + +<div class="note"> +<p><strong>Nota</strong>: The URI passed as a parameter to the <code>Worker</code> constructor must obey the <a href="/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a> .</p> + +<p>There is currently disagreement among browsers vendors on what URIs are of the same-origin; Gecko 10.0 {{geckoRelease("10.0")}} and later do allow data URIs and Internet Explorer 10 does not allow Blob URIs as a valid script for workers.</p> +</div> + +<div class="note"><strong>Nota</strong>: Notice that <code>onmessage</code> and <code>postMessage()</code> need to be hung off the <code>Worker</code> object when used in the main script thread, but not when used in the worker. This is because, inside the worker, the worker is effectively the global scope.</div> + +<div class="note"><strong>Nota</strong>: When a message is passed between the main thread and worker, it is copied or "transferred" (moved), not shared. Read {{anch("Transferring data to and from workers further details", "Transferring data to and from workers: further details")}} for a much more thorough explanation.</div> + +<h3 id="Terminar_um_worker">Terminar um <em>worker</em></h3> + +<p>If you need to immediately terminate a running worker from the main thread, you can do so by calling the worker's {{domxref("Worker", "terminate")}} method:</p> + +<pre class="brush: js">myWorker.terminate();</pre> + +<p>The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.</p> + +<p>In the worker thread, workers may close themselves by calling their own {{domxref("WorkerGlobalScope", "close")}} method:</p> + +<pre class="brush: js">close();</pre> + +<h3 id="Lidar_com_erros">Lidar com erros</h3> + +<p>When a runtime error occurs in the worker, its <code>onerror</code> event handler is called. It receives an event named <code>error</code> which implements the <code>ErrorEvent</code> interface.</p> + +<p>The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's <a class="internal" href="/en-US/docs/Web/API/Event/preventDefault"> <code>preventDefault()</code> </a> method.</p> + +<p>The error event has the following three fields that are of interest:</p> + +<dl> + <dt><code>message</code></dt> + <dd>A human-readable error message.</dd> + <dt><code>filename</code></dt> + <dd>The name of the script file in which the error occurred.</dd> + <dt><code>lineno</code></dt> + <dd>The line number of the script file on which the error occurred.</dd> +</dl> + +<h3 id="Gerar_subworkers">Gerar <em>subworkers</em></h3> + +<p>Workers may spawn more workers if they wish. So-called sub-workers must be hosted within the same origin as the parent page. Also, the URIs for subworkers are resolved relative to the parent worker's location rather than that of the owning page. This makes it easier for workers to keep track of where their dependencies are.</p> + +<h3 id="Importar_scripts_e_bibliotecas">Importar <em>scripts</em> e bibliotecas</h3> + +<p>Worker threads have access to a global function, <code>importScripts()</code>, which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:</p> + +<pre class="brush: js">importScripts(); /* imports nothing */ +importScripts('foo.js'); /* imports just "foo.js" */ +importScripts('foo.js', 'bar.js'); /* imports two scripts */ +importScripts('//example.com/hello.js'); /* You can import scripts from other origins */</pre> + +<p>The browser loads each listed script and executes it. Any global objects from each script may then be used by the worker. If the script can't be loaded, <code>NETWORK_ERROR</code> is thrown, and subsequent code will not be executed. Previously executed code (including code deferred using {{domxref("window.setTimeout()")}}) will still be functional though. Function declarations <strong>after</strong> the <code>importScripts()</code> method are also kept, since these are always evaluated before the rest of the code.</p> + +<div class="note"><strong>Note</strong>: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into <code>importScripts()</code> . This is done synchronously; <code>importScripts()</code> does not return until all the scripts have been loaded and executed.</div> + +<h2 id="Shared_workers_(Partilhados)"><em>Shared workers (Partilhados)</em></h2> + +<p>A shared worker is accessible by multiple scripts — even if they are being accessed by different windows, iframes or even workers. In this section we'll discuss the JavaScript found in our <a class="external external-icon" href="https://github.com/mdn/simple-shared-worker">Basic shared worker example</a> (<a class="external external-icon" href="https://mdn.github.io/simple-shared-worker/">run shared worker</a>): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: <em>multiplying two numbers</em>, or <em>squaring a number</em>. Both scripts use the same worker to do the actual calculation required.</p> + +<p>Here we'll concentrate on the differences between dedicated and shared workers. Note that in this example we have two HTML pages, each with JavaScript applied that uses the same single worker file.</p> + +<div class="note"> +<p><strong>Nota</strong>: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).</p> +</div> + +<div class="note"> +<p><strong>Nota</strong>: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ({{bug(1177621)}}).</p> +</div> + +<h3 id="Gerar_um_shared_worker">Gerar um <em>shared worker</em></h3> + +<p>Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/index.html">index.html</a> and <a href="https://mdn.github.io/simple-shared-worker/index2.html">index2.html</a>) — each one has to spin up the worker using code like the following:</p> + +<pre class="brush: js">var myWorker = new SharedWorker('worker.js');</pre> + +<p>One big difference is that with a shared worker you have to communicate via a <code>port</code> object — an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers).</p> + +<p>The port connection needs to be started either implicitly by use of the <code>onmessage </code>event handler or explicitly with the <code>start()</code> method before any messages can be posted. Although the <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/multiply.js">multiply.js</a> and <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/worker.js">worker.js</a> files in the demo currently call the <code>start()</code> method, those calls are not necessary since the <code>onmessage</code> event handler is being used. Calling <code>start()</code> is only needed if the <code>message</code> event is wired up via the <code>addEventListener()</code> method.</p> + +<p>When using the <code>start()</code> method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed.</p> + +<pre class="brush: js">myWorker.port.start(); // called in parent thread</pre> + +<pre class="brush: js">port.start(); // called in worker thread, assuming the <code>port</code> variable references a port</pre> + +<h3 id="Enviar_mensagens_parae_de_um_shared_worker">Enviar mensagens para/e de um <em>shared worker</em></h3> + +<p>Now messages can be sent to the worker as before, but the <code>postMessage()</code> method has to be invoked through the port object (again, you'll see similar constructs in both <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/multiply.js">multiply.js</a> and <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/square.js">square.js</a>):</p> + +<pre class="brush: js">squareNumber.onchange = function() { + myWorker.port.postMessage([squareNumber.value,squareNumber.value]); + console.log('Message posted to worker'); +}</pre> + +<p>Now, on to the worker. There is a bit more complexity here as well (<a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/worker.js">worker.js</a>):</p> + +<pre class="brush: js">onconnect = function(e) { + var port = e.ports[0]; + + port.onmessage = function(e) { + var workerResult = 'Result: ' + (e.data[0] * e.data[1]); + port.postMessage(workerResult); + } +}</pre> + +<p>First, we use an <code>onconnect</code> handler to fire code when a connection to the port happens (i.e. when the <code>onmessage</code> event handler in the parent thread is setup, or when the <code>start()</code> method is explicitly called in the parent thread).</p> + +<p>We use the <code>ports</code> attribute of this event object to grab the port and store it in a variable.</p> + +<p>Next, we add a <code>message</code> handler on the port to do the calculation and return the result to the main thread. Setting up this <code>message</code> handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to <code>port.start()</code> is not actually needed, as noted above.</p> + +<p>Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/multiply.js">multiply.js</a> and <a href="https://github.com/mdn/simple-shared-worker/blob/gh-pages/square.js">square.js</a>):</p> + +<pre class="brush: js">myWorker.port.onmessage = function(e) { + result2.textContent = e.data; + console.log('Message received from worker'); +}</pre> + +<p>When a message comes back through the port from the worker, we check what result type it is, then insert the calculation result inside the appropriate result paragraph.</p> + +<h2 id="Sobre_a_segurança_de_segmento">Sobre a segurança de segmento</h2> + +<p>The {{domxref("Worker")}} interface spawns real OS-level threads, and mindful programmers may be concerned that concurrency can cause “interesting” effects in your code if you aren't careful.</p> + +<p>However, since web workers have carefully controlled communication points with other threads, it's actually very hard to cause concurrency problems. There's no access to non-threadsafe components or the DOM. And you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.</p> + +<p>An example of a catastrophy would be like the following:</p> + +<h3 id="Conteúdo_HTML">Conteúdo HTML</h3> + +<pre class="brush: html"><html> +<head> +<title>Multithreading Catastrophy</title> +<style> +body { margin: 0px; } +canvas { position: absolute; top: 0; bottom: 0; left: 0; right:0; width: 100%; height: 100%; } +</style> +<script src="main.js" async></script> +</head> +<body> +<canvas id="canvas"></canvas> +</body> +</html></pre> + +<h3 id="Conteúdo_main.js">Conteúdo main.js</h3> + +<pre class="brush: js">// main.js +var myworker = new Worker("worker.js"), width=window.innerWidth, height=window.innerHeight, context=document.getElementById('canvas').getContext('2d'); +var imagedatatmp=context.createImageData(width,height); + +myworker.onmessage = function(data){ + imageData = imagedatatmp.from(data); +}; + +setTimeout(function draw_canvas() { + context.putImageData(imageData); + setTimeout(draw_canvas, 1000/60); +},10); + +window.onresize = window.reload; // Quick (to type) n' dirty way to resize;</pre> + +<h3 id="Conteúdo_worker.js">Conteúdo worker.js</h3> + +<pre class="brush: js">// worker.js +window.onmessage = function(width, height){ +var noise = function(x, y, z) { + var p = new Array(512), permutation = [151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180]; + for (var i = 0;i < 256;i++) p[256 + i] = p[i] = permutation[i]; + var X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255; x -= Math.floor(x), y -= Math.floor(y), z -= Math.floor(z); + var u = fade(x), v = fade(y), w = fade(z); + var A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z; + return scale(lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z)), lerp(u, grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z))), lerp(v, lerp(u, grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1)), lerp(u, grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1))))); +}; + function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); } + function lerp(t, a, b) { return a + t * (b - a); } + function grad(hash, x, y, z) { + var h = hash & 15; var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z; + return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); + } + function scale(n) { return (1 + n) / 2; } +var length = width*height; var canvasnoisedata=new UInt32Array(length); + +setTimeout(function make_noise() { +var i=length, z=Math.random()*1024; + while ( i-- ) { + canvasnoisedata[i] = noise(i%width+z,i/width+z,z); + } + setTimeout(make_noise, 1000/60); +},1000/60); + +setTimeout(function post_noise() { + postMessage( canvasnoisedata ); + setTimeout(post_noise, 1000/60); +},1000/60); +}; +</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{ EmbedLiveSample('ats.html') }}</p> + +<h2 id="Política_de_segurança_de_conteúdo">Política de segurança de conteúdo</h2> + +<p>Workers are considered to have their own execution context, distinct from the document that created them. For this reason they are, in general, not governed by the <a href="/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_Security_Policy">content security policy</a> of the document (or parent worker) that created them. So for example, suppose a document is served with the following header:</p> + +<pre>Content-Security-Policy: script-src 'self'</pre> + +<div>Among other things, this will prevent any scripts it includes from using <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval()</a></code>. However, if the script constructs a worker, code running in the worker's context <em>will</em> be allowed to use <code>eval()</code>.<br> +<br> +To specify a content security policy for the worker, set a <a href="/en-US/docs/Web/HTTP/Headers/Content-Security-Policy">Content-Security-Policy</a> response header for the request which delivered the worker script itself.<br> +<br> +The exception to this is if the worker script's origin is a globally unique identifier (for example, if its URL has a scheme of data or blob). In this case, the worker does inherit the CSP of the document or worker that created it.</div> + +<div> </div> + +<h2 id="Transferir_dados_parae_de_workers_detalhes_adicionais">Transferir dados para/e de <em>workers</em>: detalhes adicionais</h2> + +<p>Data passed between the main page and workers is <strong>copied</strong>, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker <strong>do not share the same instance</strong>, so the end result is that <strong>a duplicate</strong> is created on each end. Most browsers implement this feature as <a href="/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm">structured cloning</a>.</p> + +<p>To illustrate this, let's create for didactical purpose a function named <code>emulateMessage()</code>, which will simulate the behavior of a value that is <em>cloned and not shared</em> during the passage from a <code>worker</code> to the main page or vice versa:</p> + +<pre class="brush: js">function emulateMessage(vVal) { + return eval('(' + JSON.stringify(vVal) + ')'); +} + +// Tests + +// test #1 +var example1 = new Number(3); +console.log(typeof example1); // object +console.log(typeof emulateMessage(example1)); // number + +// test #2 +var example2 = true; +console.log(typeof example2); // boolean +console.log(typeof emulateMessage(example2)); // boolean + +// test #3 +var example3 = new String('Hello World'); +console.log(typeof example3); // object +console.log(typeof emulateMessage(example3)); // string + +// test #4 +var example4 = { + 'name': 'John Smith', + "age": 43 +}; +console.log(typeof example4); // object +console.log(typeof emulateMessage(example4)); // object + +// test #5 +function Animal(sType, nAge) { + this.type = sType; + this.age = nAge; +} +var example5 = new Animal('Cat', 3); +alert(example5.constructor); // Animal +alert(emulateMessage(example5).constructor); // Object</pre> + +<p>A value that is cloned and not shared is called <em>message</em>. As you will probably know by now, <em>messages</em> can be sent to and from the main thread by using <code>postMessage()</code>, and the <code>message</code> event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker.</p> + +<p><strong>example.html</strong>: (a página principal):</p> + +<pre class="brush: js">var myWorker = new Worker('my_task.js'); + +myWorker.onmessage = function(oEvent) { + console.log('Worker said : ' + oEvent.data); +}; + +myWorker.postMessage('ali');</pre> + +<p><strong>my_task.js</strong> (o <em>worker</em>):</p> + +<pre class="brush: js">postMessage("I\'m working before postMessage(\'ali\')."); + +onmessage = function(oEvent) { + postMessage('Hi ' + oEvent.data); +};</pre> + +<p>The <a href="/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm">structured cloning</a> algorithm can accept JSON and a few things that JSON can't — like circular references.</p> + +<h3 id="Passagem_de_exemplos_de_dados">Passagem de exemplos de dados</h3> + +<h4 id="Exemplo_1_Criar_um_genérico_assíncrono_eval()">Exemplo #1: Criar um genérico "assíncrono <code>eval()</code>"</h4> + +<p>The following example shows how to use a worker in order to <strong>asynchronously</strong> execute any JavaScript code allowed in a worker, through <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> within the worker:</p> + +<pre class="brush: js">// Syntax: asyncEval(code[, listener]) + +var asyncEval = (function () { + var aListeners = [], oParser = new Worker('data:text/javascript;charset=US-ASCII,onmessage%20%3D%20function%20%28oEvent%29%20%7B%0A%09postMessage%28%7B%0A%09%09%22id%22%3A%20oEvent.data.id%2C%0A%09%09%22evaluated%22%3A%20eval%28oEvent.data.code%29%0A%09%7D%29%3B%0A%7D'); + + oParser.onmessage = function(oEvent) { + if (aListeners[oEvent.data.id]) { aListeners[oEvent.data.id](oEvent.data.evaluated); } + delete aListeners[oEvent.data.id]; + }; + + return function(sCode, fListener) { + aListeners.push(fListener || null); + oParser.postMessage({ + 'id': aListeners.length - 1, + 'code': sCode + }); + }; +})();</pre> + +<p>The <a href="/en-US/docs/Web/HTTP/data_URIs">data URL</a> is equivalent to a network request, with the following response:</p> + +<pre class="brush: js">onmessage = function(oEvent) { + postMessage({ + 'id': oEvent.data.id, + 'evaluated': eval(oEvent.data.code) + }); +}</pre> + +<p>Amostra de utilização:</p> + +<pre class="brush: js">// asynchronous alert message... +asyncEval('3 + 2', function(sMessage) { + alert('3 + 2 = ' + sMessage); +}); + +// asynchronous print message... +asyncEval("\"Hello World!!!\"", function(sHTML) { + document.body.appendChild(document.createTextNode(sHTML)); +}); + +// asynchronous void... +asyncEval("(function () {\n\tvar oReq = new XMLHttpRequest();\n\toReq.open(\"get\", \"http://www.mozilla.org/\", false);\n\toReq.send(null);\n\treturn oReq.responseText;\n})()");</pre> + +<h4 id="Exemplo_2_Passagem_avançada_da_'Dados'_JSON_e_criar_um_sistema_de_troca">Exemplo #2: Passagem avançada da 'Dados' JSON e criar um sistema de troca</h4> + +<p>If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together.</p> + +<p>First, we create a QueryableWorker class that takes the <font face="Consolas, Liberation Mono, Courier, monospace">url</font> of the worker, a default listener, and an error handler, and this class is going to keep track of a list of listeners and help us communicate with the worker:</p> + +<pre class="brush: js">function QueryableWorker(url, defaultListener, onError) { + var instance = this, + worker = new Worker(url), + listeners = {}; + + this.defaultListener = defaultListener || function() {}; + + if (onError) {worker.onerror = onError;} + + this.postMessage = function(message) { + worker.postMessage(message); + } + + this.terminate = function() { + worker.terminate(); + } +}</pre> + +<p>Then we add the methods of adding/removing listeners:</p> + +<pre class="brush: js">this.addListeners = function(name, listener) { + listeners[name] = listener; +} + +this.removeListeners = function(name) { + delete listeners[name]; +}</pre> + +<p>Here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after three seconds. In order to achieve that we first implement a sendQuery method which queries if the worker actually has the corresponding methods to do what we want.</p> + +<pre class="brush: js">/* + This functions takes at least one argument, the method name we want to query. + Then we can pass in the arguments that the method needs. + */ +this.sendQuery = function() { + if (arguments.length < 1) { + throw new TypeError('QueryableWorker.sendQuery takes at least one argument'); + return; + } + worker.postMessage({ + 'queryMethod': arguments[0], + 'queryArguments': Array.prototype.slice.call(arguments, 1) + }); +}</pre> + +<p>We finish QueryableWorker with the <code>onmessage</code> method. If the worker has the corresponding methods we queried, it should return the name of the corresponding listener and the arguments it needs, we just need to find it in <code>listeners</code>.:</p> + +<pre class="brush: js">worker.onmessage = function(event) { + if (event.data instanceof Object && + event.data.hasOwnProperty('queryMethodListener') && + event.data.hasOwnProperty('queryMethodArguments')) { + listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments); + } else { + this.defaultListener.call(instance, event.data); + } +} +</pre> + +<p>Now onto the worker. First we need to have the methods to handle the two simple operations:</p> + +<pre class="brush: js">var queryableFunctions = { + getDifference: function(a, b) { + reply('printStuff', a - b); + }, + waitSomeTime: function() { + setTimeout(function() { + reply('doAlert', 3, 'seconds'); + }, 3000); + } +} + +function reply() { + if (arguments.length < 1) { + throw new TypeError('reply - takes at least one argument'); + return; + } + postMessage({ + queryMethodListener: arguments[0], + queryMethodArguments: Array.prototype.slice.call(arguments, 1) + }); +} + +/* This method is called when main page calls QueryWorker's postMessage method directly*/ +function defaultReply(message) { + // do something +} +</pre> + +<p>And the <code>onmessage</code> method is now trivial:</p> + +<pre class="brush: js">onmessage = function(event) { + if (event.data instanceof Object && + event.data.hasOwnProperty('queryMethod') && + event.data.hasOwnProperty('queryMethodArguments')) { + queryableFunctions[event.data.queryMethod] + .apply(self, event.data.queryMethodArguments); + } else { + defaultReply(event.data); + } +} +</pre> + +<p>Here are the full implementation:</p> + +<p><strong>example.html</strong> (the main page):</p> + +<pre class="brush: html"><!doctype html> + <html> + <head> + <meta charset="UTF-8" /> + <title>MDN Example - Queryable worker</title> + <script type="text/javascript"> + /* + QueryableWorker instances methods: + * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function + * postMessage(string or JSON Data): see Worker.prototype.postMessage() + * terminate(): terminates the Worker + * addListener(name, function): adds a listener + * removeListener(name): removes a listener + QueryableWorker instances properties: + * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly + */ + function QueryableWorker(url, defaultListener, onError) { + var instance = this, + worker = new Worker(url), + listeners = {}; + + this.defaultListener = defaultListener || function() {}; + + if (onError) {worker.onerror = onError;} + + this.postMessage = function(message) { + worker.postMessage(message); + } + + this.terminate = function() { + worker.terminate(); + } + + this.addListener = function(name, listener) { + listeners[name] = listener; + } + + this.removeListener = function(name) { + delete listeners[name]; + } + + /* + This functions takes at least one argument, the method name we want to query. + Then we can pass in the arguments that the method needs. + */ + this.sendQuery = function() { + if (arguments.length < 1) { + throw new TypeError('QueryableWorker.sendQuery takes at least one argument'); + return; + } + worker.postMessage({ + 'queryMethod': arguments[0], + 'queryMethodArguments': Array.prototype.slice.call(arguments, 1) + }); + } + + worker.onmessage = function(event) { + if (event.data instanceof Object && + event.data.hasOwnProperty('queryMethodListener') && + event.data.hasOwnProperty('queryMethodArguments')) { + listeners[event.data.queryMethodListener].apply(instance, event.data.queryMethodArguments); + } else { + this.defaultListener.call(instance, event.data); + } + } + } + + // your custom "queryable" worker + var myTask = new QueryableWorker('my_task.js'); + + // your custom "listeners" + myTask.addListener('printStuff', function (result) { + document.getElementById('firstLink').parentNode.appendChild(document.createTextNode('The difference is ' + result + '!')); + }); + + myTask.addListener('doAlert', function (time, unit) { + alert('Worker waited for ' + time + ' ' + unit + ' :-)'); + }); +</script> +</head> +<body> + <ul> + <li><a id="firstLink" href="javascript:myTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li> + <li><a href="javascript:myTask.sendQuery('waitSomeTime');">Wait 3 seconds</a></li> + <li><a href="javascript:myTask.terminate();">terminate() the Worker</a></li> + </ul> +</body> +</html></pre> + +<p><strong>my_task.js</strong> (o <em>worker</em>):</p> + +<pre class="brush: js">var queryableFunctions = { + // example #1: get the difference between two numbers: + getDifference: function(nMinuend, nSubtrahend) { + reply('printStuff', nMinuend - nSubtrahend); + }, + // example #2: wait three seconds + waitSomeTime: function() { + setTimeout(function() { reply('doAlert', 3, 'seconds'); }, 3000); + } +}; + +// system functions + +function defaultReply(message) { + // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly + // do something +} + +function reply() { + if (arguments.length < 1) { throw new TypeError('reply - not enough arguments'); return; } + postMessage({ 'queryMethodListener': arguments[0], 'queryMethodArguments': Array.prototype.slice.call(arguments, 1) }); +} + +onmessage = function(oEvent) { + if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty('queryMethod') && oEvent.data.hasOwnProperty('queryMethodArguments')) { + queryableFunctions[oEvent.data.queryMethod].apply(self, oEvent.data.queryMethodArguments); + } else { + defaultReply(oEvent.data); + } +};</pre> + +<p>It is possible to switch the content of each mainpage -> worker and worker -> mainpage message. And the property names "queryMethod", "queryMethodListeners", "queryMethodArguments" can be anything as long as they are consistent in <code>QueryableWorker</code> and the <code>worker</code>.</p> + +<h3 id="Passing_data_by_transferring_ownership_(transferable_objects)">Passing data by transferring ownership (transferable objects)</h3> + +<p>Google Chrome 17+ and Firefox 18+ contain an additional way to pass certain types of objects (transferable objects, that is objects implementing the {{domxref("Transferable")}} interface) to or from a worker with high performance. Transferable objects are transferred from one context to another with a zero-copy operation, which results in a vast performance improvement when sending large data sets. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred. Its ownership is transferred to the new context. For example, when transferring an {{domxref("ArrayBuffer")}} from your main app to a worker script, the original {{domxref("ArrayBuffer")}} is cleared and no longer usable. Its content is (quite literally) transferred to the worker context.</p> + +<pre class="brush: js">// Create a 32MB "file" and fill it. +var uInt8Array = new Uint8Array(1024 * 1024 * 32); // 32MB +for (var i = 0; i < uInt8Array.length; ++i) { + uInt8Array[i] = i; +} + +worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]); +</pre> + +<div class="note"> +<p><strong>Nota</strong>: For more information on transferable objects, performance, and feature-detection for this method, read <a href="http://updates.html5rocks.com/2011/12/Transferable-Objects-Lightning-Fast">Transferable Objects: Lightning Fast!</a> on HTML5 Rocks.</p> +</div> + +<h2 id="Workers_integrados">Workers integrados</h2> + +<p>There is not an "official" way to embed the code of a worker within a web page, like {{HTMLElement("script")}} elements do for normal scripts. But a {{HTMLElement("script")}} element that does not have a <code>src</code> attribute and has a <code>type</code> attribute that does not identify an executable MIME type can be considered a data block element that JavaScript could use. "Data blocks" is a more general feature of HTML5 that can carry almost any textual data. So, a worker could be embedded in this way:</p> + +<pre class="brush: html"><!DOCTYPE html> +<html> +<head> +<meta charset="UTF-8" /> +<title>MDN Example - Embedded worker</title> +<script type="text/js-worker"> + // This script WON'T be parsed by JS engines because its MIME type is text/js-worker. + var myVar = 'Hello World!'; + // Rest of your worker code goes here. +</script> +<script type="text/javascript"> + // This script WILL be parsed by JS engines because its MIME type is text/javascript. + function pageLog(sMsg) { + // Use a fragment: browser will only render/reflow once. + var oFragm = document.createDocumentFragment(); + oFragm.appendChild(document.createTextNode(sMsg)); + oFragm.appendChild(document.createElement('br')); + document.querySelector('#logDisplay').appendChild(oFragm); + } +</script> +<script type="text/js-worker"> + // This script WON'T be parsed by JS engines because its MIME type is text/js-worker. + onmessage = function(oEvent) { + postMessage(myVar); + }; + // Rest of your worker code goes here. +</script> +<script type="text/javascript"> + // This script WILL be parsed by JS engines because its MIME type is text/javascript. + + // In the past...: + // blob builder existed + // ...but now we use Blob...: + var blob = new Blob(Array.prototype.map.call(document.querySelectorAll('script[type=\'text\/js-worker\']'), function (oScript) { return oScript.textContent; }),{type: 'text/javascript'}); + + // Creating a new document.worker property containing all our "text/js-worker" scripts. + document.worker = new Worker(window.URL.createObjectURL(blob)); + + document.worker.onmessage = function(oEvent) { + pageLog('Received: ' + oEvent.data); + }; + + // Start the worker. + window.onload = function() { document.worker.postMessage(''); }; +</script> +</head> +<body><div id="logDisplay"></div></body> +</html></pre> + +<p>The embedded worker is now nested into a new custom <code>document.worker</code> property.</p> + +<p>It is also worth noting that you can also convert a function into a Blob, then generate an object URL from that blob. For example:</p> + +<pre class="brush: js">function fn2workerURL(fn) { + var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'}) + return URL.createObjectURL(blob) +}</pre> + +<h2 id="Exemplos_adicionais">Exemplos adicionais</h2> + +<p>This section provides further examples of how to use web workers.</p> + +<h3 id="Realizar_computações_em_segundo_plano">Realizar computações em segundo plano</h3> + +<p>Workers are mainly useful for allowing your code to perform processor-intensive calculations without blocking the user interface thread. In this example, a worker is used to calculate Fibonacci numbers.</p> + +<h4 id="O_código_de_JavaScript">O código de JavaScript</h4> + +<p>The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.</p> + +<pre class="brush: js">var results = []; + +function resultReceiver(event) { + results.push(parseInt(event.data)); + if (results.length == 2) { + postMessage(results[0] + results[1]); + } +} + +function errorReceiver(event) { + throw event.data; +} + +onmessage = function(event) { + var n = parseInt(event.data); + + if (n == 0 || n == 1) { + postMessage(n); + return; + } + + for (var i = 1; i <= 2; i++) { + var worker = new Worker('fibonacci.js'); + worker.onmessage = resultReceiver; + worker.onerror = errorReceiver; + worker.postMessage(n - i); + } + };</pre> + +<p>The worker sets the property <code>onmessage</code> to a function which will receive messages sent when the worker object's <code>postMessage()</code> is called (note that this differs from defining a global <em>variable</em> of that name, or defining a <em>function</em> with that name. <code>var onmessage</code> and <code>function onmessage</code> will define global properties with those names, but they will not register the function to receive messages sent by the web page that created the worker). This starts the recursion, spawning new copies of itself to handle each iteration of the calculation.</p> + +<h4 id="O_código_de_HTML">O código de HTML</h4> + +<pre class="brush: html"><!DOCTYPE html> +<html> + <head> + <meta charset="UTF-8" /> + <title>Test threads fibonacci</title> + </head> + <body> + + <div id="result"></div> + + <script language="javascript"> + + var worker = new Worker('fibonacci.js'); + + worker.onmessage = function(event) { + document.getElementById('result').textContent = event.data; + dump('Got: ' + event.data + '\n'); + }; + + worker.onerror = function(error) { + dump('Worker error: ' + error.message + '\n'); + throw error; + }; + + worker.postMessage('5'); + + </script> + </body> +</html> +</pre> + +<p>The web page creates a <code>div</code> element with the ID <code>result</code> , which gets used to display the result, then spawns the worker. After spawning the worker, the <code>onmessage</code> handler is configured to display the results by setting the contents of the <code>div</code> element, and the <code>onerror</code> handler is set to <a href="/en-US/docs/Debugging_JavaScript#dump.28.29">dump</a> the error message.</p> + +<p>Finally, a message is sent to the worker to start it.</p> + +<p><a class="external" href="/samples/workers/fibonacci">Try this example</a>.</p> + +<h3 id="Executar_IO_da_Web_em_segundo_plano">Executar I/O da Web em segundo plano</h3> + +<p>You can find an example of this in the article <a class="internal" href="/en-US/docs/Using_workers_in_extensions">Using workers in extensions</a> .</p> + +<h3 id="Dividir_tarefas_entre_mútiplos_workers">Dividir tarefas entre mútiplos <em>workers</em></h3> + +<p>As multi-core computers become increasingly common, it's often useful to divide computationally complex tasks among multiple workers, which may then perform those tasks on multiple-processor cores.</p> + +<h2 id="Outros_tipos_de_worker">Outros tipos de <em>worker</em></h2> + +<p>In addition to dedicated and shared web workers, there are other types of worker available:</p> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorkers</a> essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.</li> + <li>Chrome Workers are a Firefox-only type of worker that you can use if you are developing add-ons and want to use workers in extensions and have access to <a href="https://developer.mozilla.org/en/js-ctypes">js-ctypes</a> in your worker. See {{domxref("ChromeWorker")}} for more details.</li> + <li><a href="/en-US/docs/Web/API/Web_Audio_API#Audio_Workers">Audio Workers</a> provide the ability for direct scripted audio processing to be done in a web worker context.</li> +</ul> + +<h2 id="Funções_e_interfaces_disponíveis_nos_workers">Funções e interfaces disponíveis nos <em>workers</em></h2> + +<p>You can use most standard JavaScript features inside a web worker, including:</p> + +<ul> + <li>{{domxref("Navigator")}}</li> + <li>{{domxref("XMLHttpRequest")}}</li> + <li>{{jsxref("Global_Objects/Array", "Array")}}, {{jsxref("Global_Objects/Date", "Date")}}, {{jsxref("Global_Objects/Math", "Math")}}, and {{jsxref("Global_Objects/String", "String")}}</li> + <li>{{domxref("WindowTimers.setTimeout")}} and {{domxref("WindowTimers.setInterval")}}</li> +</ul> + +<p>The main thing you <em>can't</em> do in a Worker is directly affect the parent page. This includes manipulating the DOM and using that page's objects. You have to do it indirectly, by sending a message back to the main script via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}, then actioning the changes from there.</p> + +<div class="note"> +<p><strong>Note</strong>: For a complete list of functions available to workers, see <a href="/en-US/docs/Web/Reference/Functions_and_classes_available_to_workers">Functions and interfaces available to workers</a>.</p> +</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#workers', 'Web workers')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>4<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>10.0</td> + <td>10.6<sup>[1]</sup></td> + <td>4<sup>[2]</sup></td> + </tr> + <tr> + <td>Shared workers</td> + <td>4<sup>[1]</sup></td> + <td>{{CompatGeckoDesktop(29)}}</td> + <td>{{CompatNo}}</td> + <td>10.6</td> + <td>5<br> + {{CompatNo}} 6.1<sup>[4]</sup></td> + </tr> + <tr> + <td>Passing data using <a href="/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm">structured cloning</a></td> + <td>13</td> + <td>{{CompatGeckoDesktop(8)}}</td> + <td>10.0</td> + <td>11.5</td> + <td>6</td> + </tr> + <tr> + <td>Passing data using <a class="external" href="http://www.w3.org/html/wg/drafts/html/master/infrastructure.html#transferable-objects">transferable objects</a></td> + <td>17 {{property_prefix("webkit")}}<br> + 21</td> + <td>{{CompatGeckoDesktop(18)}}</td> + <td>{{CompatNo}}</td> + <td>15</td> + <td>6</td> + </tr> + <tr> + <td>Global {{domxref("window.URL", "URL")}}</td> + <td>10<sup>[3]</sup><br> + 23</td> + <td>{{CompatGeckoDesktop(21)}}</td> + <td>11</td> + <td>15</td> + <td>6<sup>[3]</sup></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>4<sup>[1]</sup></td> + <td>3.5</td> + <td>1.0.1</td> + <td>10.0</td> + <td>11.5<sup>[1]</sup></td> + <td>5.1<sup>[2]</sup></td> + </tr> + <tr> + <td>Shared workers</td> + <td>{{CompatNo}}</td> + <td>4<sup>[1]</sup></td> + <td>8</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Passing data using <a href="/en-US/docs/Web/Guide/API/DOM/The_structured_clone_algorithm">structured cloning</a></td> + <td>{{CompatNo}}</td> + <td>4</td> + <td>8</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Passing data using <a class="external" href="http://www.w3.org/html/wg/drafts/html/master/infrastructure.html#transferable-objects">transferable objects</a></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>18</td> + <td>1.0.1</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Chrome and Opera give an error "<code>Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'.</code>" when you try to run a worker locally. It needs to be on a proper domain.</p> + +<p>[2] As of Safari 7.1.2, you can call <code>console.log</code> from inside a worker, but it won't print anything to the console. Older versions of Safari don't allow you to call <code>console.log</code> from inside a worker.</p> + +<p>[3] This feature is implemented prefixed as <code>webkitURL</code>.</p> + +<p>[4] Safari <a href="https://bugs.webkit.org/show_bug.cgi?id=116359">removed SharedWorker support</a>.</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li>Interface de <em><code><a class="internal" href="/en-US/docs/Web/API/Worker">Worker</a></code></em></li> + <li>Interface de <em><code><a class="internal" href="/en-US/docs/Web/API/SharedWorker">SharedWorker</a></code></em></li> + <li><a href="/en-US/docs/Web/API/Worker/Functions_and_classes_available_to_workers">Funções disponíveis para os <em>workers</em></a></li> + <li><a href="/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">Conceitos avançados e exemplos</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none; font-size: 14px; line-height: 20px; margin-top: 22168px; margin-left: 26px; direction: ltr; text-align: left;">Further</div> + +<div id="SL_shadow_translator" style="display: none; top: 152px; left: 25px; box-shadow: rgb(186, 185, 181) 0px 0px 0px; width: 467px;"> +<div id="SL_planshet" style="background: rgb(239, 239, 239) none repeat scroll 0% 0%;"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: none; left: 49px;"> </div> + +<div id="SL_Bproviders" style=""> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_OFF" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_OFF" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; cursor: not-allowed;" title="Se o idioma de origem é definido como 'Detectar idioma', esta função não está disponível."> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: block;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy_hand" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch" style="display: none;"> </div> + + <div class="SL_font_on" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style="font-size: 14px; line-height: 20px; direction: ltr; text-align: left;">Further</div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: none;"> </div> + +<div id="SL_player2" style="display: none; height: 0px;"> </div> + +<div id="SL_alert100" style="display: none;">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(239, 239, 239) none repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: block; left: 49px;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/webgl_api/constantes/index.html b/files/pt-pt/web/api/webgl_api/constantes/index.html new file mode 100644 index 0000000000..8328c7976f --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/constantes/index.html @@ -0,0 +1,4023 @@ +--- +title: Contantes de WebGL +slug: Web/API/WebGL_API/Constantes +tags: + - API + - Referencia + - WebGL + - constantes +translation_of: Web/API/WebGL_API/Constants +--- +<div>{{WebGLSidebar}}</div> + +<p>The <a href="/en-US/docs/Web/API/WebGL_API">WebGL API</a> provides several constants that are passed into or returned by functions. All constants are of type {{domxref("GLenum")}}.</p> + +<p>Standard WebGL constants are installed on the {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} objects, so that you use them as <code>gl.CONSTANT_NAME</code>:</p> + +<pre class="brush: js">var canvas = document.getElementById('myCanvas'); +var gl = canvas.getContext('webgl'); + +gl.getParameter(gl.LINE_WIDTH); +</pre> + +<p>Some constants are also provided by <a href="/en-US/docs/Web/API/WebGL_API/Using_Extensions">WebGL extensions</a>. A <a href="#Constants_defined_in_WebGL_extensions">list</a> is provided below.</p> + +<pre class="brush: js">var debugInfo = gl.getExtension('WEBGL_debug_renderer_info'); +var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);</pre> + +<p>The <a href="/en-US/docs/Web/API/WebGL_API/Tutorial" title="WebGL tutorial">WebGL tutorial</a> has more information, examples, and resources on how to get started with WebGL.</p> + +<h2 id="Tabela_de_conteúdos">Tabela de conteúdos</h2> + +<ul> + <li><a href="#Standard_WebGL_1_constants">Standard WebGL 1 constants</a></li> + <li><a href="#Additional_constants_defined_WebGL_2">Standard WebGL 2 constants</a></li> + <li><a href="#Constants_defined_in_WebGL_extensions">WebGL extension constants</a></li> +</ul> + +<h2 id="Standard_WebGL_1_constants">Standard WebGL 1 constants</h2> + +<p>These constants are defined on the {{domxref("WebGLRenderingContext")}} interface.</p> + +<h3 id="Limpar_buffers">Limpar <em>buffers</em></h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.clear()")}} to clear buffer masks.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>DEPTH_BUFFER_BIT</code></td> + <td>0x00000100</td> + <td>Passed to <code>clear</code> to clear the current depth buffer.</td> + </tr> + <tr> + <td><code>STENCIL_BUFFER_BIT</code></td> + <td>0x00000400</td> + <td>Passed to <code>clear</code> to clear the current stencil buffer.</td> + </tr> + <tr> + <td><code>COLOR_BUFFER_BIT</code></td> + <td>0x00004000</td> + <td>Passed to <code>clear</code> to clear the current color buffer.</td> + </tr> + </tbody> +</table> + +<h3 id="Renderizar_primitivos">Renderizar primitivos</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.drawElements()")}} or {{domxref("WebGLRenderingContext.drawArrays()")}} to specify what kind of primitive to render.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>POINTS</code></td> + <td>0x0000</td> + <td>Passed to <code>drawElements</code> or <code>drawArrays</code> to draw single points.</td> + </tr> + <tr> + <td><code>LINES</code></td> + <td>0x0001</td> + <td>Passed to <code>drawElements</code> or <code>drawArrays</code> to draw lines. Each vertex connects to the one after it.</td> + </tr> + <tr> + <td><code>LINE_LOOP</code></td> + <td>0x0002</td> + <td>Passed to <code>drawElements</code> or <code>drawArrays</code> to draw lines. Each set of two vertices is treated as a separate line segment.</td> + </tr> + <tr> + <td><code>LINE_STRIP</code></td> + <td>0x0003</td> + <td>Passed to <code>drawElements</code> or <code>drawArrays</code> to draw a connected group of line segments from the first vertex to the last.</td> + </tr> + <tr> + <td><code>TRIANGLES</code></td> + <td>0x0004</td> + <td>Passed to <code>drawElements</code> or <code>drawArrays</code> to draw triangles. Each set of three vertices creates a separate triangle.</td> + </tr> + <tr> + <td><code>TRIANGLE_STRIP</code></td> + <td>0x0005</td> + <td>Passed to <code>drawElements</code> or <code>drawArrays</code> to draw a connected group of triangles.</td> + </tr> + <tr> + <td><code>TRIANGLE_FAN</code></td> + <td>0x0006</td> + <td>Passed to <code>drawElements</code> or <code>drawArrays</code> to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan.</td> + </tr> + </tbody> +</table> + +<h3 id="Modos_de_mistura">Modos de mistura</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.blendFunc()")}} or {{domxref("WebGLRenderingContext.blendFuncSeparate()")}} to specify the blending mode (for both, RBG and alpha, or separately).</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Nome da constante</th> + <th scope="col">Valor</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>ZERO</code></td> + <td>0</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to turn off a component.</td> + </tr> + <tr> + <td><code>ONE</code></td> + <td>1</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to turn on a component.</td> + </tr> + <tr> + <td><code>SRC_COLOR</code></td> + <td>0x0300</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by the source elements color.</td> + </tr> + <tr> + <td><code>ONE_MINUS_SRC_COLOR</code></td> + <td>0x0301</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by one minus the source elements color.</td> + </tr> + <tr> + <td><code>SRC_ALPHA</code></td> + <td>0x0302</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by the source's alpha.</td> + </tr> + <tr> + <td><code>ONE_MINUS_SRC_ALPHA</code></td> + <td>0x0303</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by one minus the source's alpha.</td> + </tr> + <tr> + <td><code>DST_ALPHA</code></td> + <td>0x0304</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by the destination's alpha.</td> + </tr> + <tr> + <td><code>ONE_MINUS_DST_ALPHA</code></td> + <td>0x0305</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by one minus the destination's alpha.</td> + </tr> + <tr> + <td><code>DST_COLOR</code></td> + <td>0x0306</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by the destination's color.</td> + </tr> + <tr> + <td><code>ONE_MINUS_DST_COLOR</code></td> + <td>0x0307</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by one minus the destination's color.</td> + </tr> + <tr> + <td><code>SRC_ALPHA_SATURATE</code></td> + <td>0x0308</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to multiply a component by the minimum of source's alpha or one minus the destination's alpha.</td> + </tr> + <tr> + <td><code>CONSTANT_COLOR</code></td> + <td>0x8001</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to specify a constant color blend function.</td> + </tr> + <tr> + <td><code>ONE_MINUS_CONSTANT_COLOR</code></td> + <td>0x8002</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to specify one minus a constant color blend function.</td> + </tr> + <tr> + <td><code>CONSTANT_ALPHA</code></td> + <td>0x8003</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to specify a constant alpha blend function.</td> + </tr> + <tr> + <td><code>ONE_MINUS_CONSTANT_ALPHA</code></td> + <td>0x8004</td> + <td>Passed to <code>blendFunc</code> or <code>blendFuncSeparate</code> to specify one minus a constant alpha blend function.</td> + </tr> + </tbody> +</table> + +<h3 id="Equações_de_mistura">Equações de mistura</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.blendEquation()")}} or {{domxref("WebGLRenderingContext.blendEquationSeparate()")}} to control how the blending is calculated (for both, RBG and alpha, or separately).</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Nome da constante</th> + <th scope="col">Valor</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>FUNC_ADD</code></td> + <td>0x8006</td> + <td>Passed to <code>blendEquation</code> or <code>blendEquationSeparate</code> to set an addition blend function.</td> + </tr> + <tr> + <td><code>FUNC_SUBSTRACT</code></td> + <td>0x800A</td> + <td>Passed to <code>blendEquation</code> or <code>blendEquationSeparate</code> to specify a subtraction blend function (source - destination).</td> + </tr> + <tr> + <td><code>FUNC_REVERSE_SUBTRACT</code></td> + <td>0x800B</td> + <td>Passed to <code>blendEquation</code> or <code>blendEquationSeparate</code> to specify a reverse subtraction blend function (destination - source).</td> + </tr> + </tbody> +</table> + +<h3 id="Obter_informação_do_parâmetro_GL">Obter informação do parâmetro GL</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Nome da constante</th> + <th scope="col">Valor</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>BLEND_EQUATION</code></td> + <td>0x8009</td> + <td>Passed to <code>getParameter</code> to get the current RGB blend function.</td> + </tr> + <tr> + <td><code>BLEND_EQUATION_RGB</code></td> + <td>0x8009</td> + <td>Passed to <code>getParameter</code> to get the current RGB blend function. Same as BLEND_EQUATION</td> + </tr> + <tr> + <td><code>BLEND_EQUATION_ALPHA</code></td> + <td>0x883D</td> + <td>Passed to <code>getParameter</code> to get the current alpha blend function. Same as BLEND_EQUATION</td> + </tr> + <tr> + <td><code>BLEND_DST_RGB</code></td> + <td>0x80C8</td> + <td>Passed to <code>getParameter</code> to get the current destination RGB blend function.</td> + </tr> + <tr> + <td><code>BLEND_SRC_RGB</code></td> + <td>0x80C9</td> + <td>Passed to <code>getParameter</code> to get the current destination RGB blend function.</td> + </tr> + <tr> + <td><code>BLEND_DST_ALPHA</code></td> + <td>0x80CA</td> + <td>Passed to <code>getParameter</code> to get the current destination alpha blend function.</td> + </tr> + <tr> + <td><code>BLEND_SRC_ALPHA</code></td> + <td>0x80CB</td> + <td>Passed to <code>getParameter</code> to get the current source alpha blend function.</td> + </tr> + <tr> + <td><code>BLEND_COLOR</code></td> + <td>0x8005</td> + <td>Passed to <code>getParameter</code> to return a the current blend color.</td> + </tr> + <tr> + <td><code>ARRAY_BUFFER_BINDING</code></td> + <td>0x8894</td> + <td>Passed to <code>getParameter</code> to get the array buffer binding.</td> + </tr> + <tr> + <td><code>ELEMENT_ARRAY_BUFFER_BINDING</code></td> + <td>0x8895</td> + <td>Passed to <code>getParameter</code> to get the current element array buffer.</td> + </tr> + <tr> + <td><code>LINE_WIDTH</code></td> + <td>0x0B21</td> + <td>Passed to <code>getParameter</code> to get the current <code>lineWidth</code> (set by the <code>lineWidth</code> method).</td> + </tr> + <tr> + <td><code>ALIASED_POINT_SIZE_RANGE</code></td> + <td>0x846D</td> + <td>Passed to <code>getParameter</code> to get the current size of a point drawn with <code>gl.POINTS</code></td> + </tr> + <tr> + <td><code>ALIASED_LINE_WIDTH_RANGE</code></td> + <td>0x846E</td> + <td>Passed to <code>getParameter</code> to get the range of available widths for a line. Returns a length-2 array with the lo value at 0, and hight at 1.</td> + </tr> + <tr> + <td><code>CULL_FACE_MODE</code></td> + <td>0x0B45</td> + <td>Passed to <code>getParameter</code> to get the current value of <code>cullFace</code>. Should return <code>FRONT</code>, <code>BACK</code>, or <code>FRONT_AND_BACK</code></td> + </tr> + <tr> + <td><code>FRONT_FACE</code></td> + <td>0x0B46</td> + <td>Passed to <code>getParameter</code> to determine the current value of <code>frontFace</code>. Should return <code>CW</code> or <code>CCW</code>.</td> + </tr> + <tr> + <td><code>DEPTH_RANGE</code></td> + <td>0x0B70</td> + <td>Passed to <code>getParameter</code> to return a length-2 array of floats giving the current depth range.</td> + </tr> + <tr> + <td><code>DEPTH_WRITEMASK</code></td> + <td>0x0B72</td> + <td>Passed to <code>getParameter</code> to determine if the depth write mask is enabled.</td> + </tr> + <tr> + <td><code>DEPTH_CLEAR_VALUE</code></td> + <td>0x0B73</td> + <td>Passed to <code>getParameter</code> to determine the current depth clear value.</td> + </tr> + <tr> + <td><code>DEPTH_FUNC</code></td> + <td>0x0B74</td> + <td>Passed to <code>getParameter</code> to get the current depth function. Returns <code>NEVER</code>, <code>ALWAYS</code>, <code>LESS</code>, <code>EQUAL</code>, <code>LEQUAL</code>, <code>GREATER</code>, <code>GEQUAL</code>, or <code>NOTEQUAL</code>.</td> + </tr> + <tr> + <td><code>STENCIL_CLEAR_VALUE</code></td> + <td>0x0B91</td> + <td>Passed to <code>getParameter</code> to get the value the stencil will be cleared to.</td> + </tr> + <tr> + <td><code>STENCIL_FUNC</code></td> + <td>0x0B92</td> + <td>Passed to <code>getParameter</code> to get the current stencil function. Returns <code>NEVER</code>, <code>ALWAYS</code>, <code>LESS</code>, <code>EQUAL</code>, <code>LEQUAL</code>, <code>GREATER</code>, <code>GEQUAL</code>, or <code>NOTEQUAL</code>.</td> + </tr> + <tr> + <td><code>STENCIL_FAIL</code></td> + <td>0x0B94</td> + <td>Passed to <code>getParameter</code> to get the current stencil fail function. Should return <code>KEEP</code>, <code>REPLACE</code>, <code>INCR</code>, <code>DECR</code>, <code>INVERT</code>, <code>INCR_WRAP</code>, or <code>DECR_WRAP</code>.</td> + </tr> + <tr> + <td><code>STENCIL_PASS_DEPTH_FAIL</code></td> + <td>0x0B95</td> + <td>Passed to <code>getParameter</code> to get the current stencil fail function should the depth buffer test fail. Should return <code>KEEP</code>, <code>REPLACE</code>, <code>INCR</code>, <code>DECR</code>, <code>INVERT</code>, <code>INCR_WRAP</code>, or <code>DECR_WRAP</code>.</td> + </tr> + <tr> + <td><code>STENCIL_PASS_DEPTH_PASS</code></td> + <td>0x0B96</td> + <td>Passed to <code>getParameter</code> to get the current stencil fail function should the depth buffer test pass. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.</td> + </tr> + <tr> + <td><code>STENCIL_REF</code></td> + <td>0x0B97</td> + <td>Passed to <code>getParameter</code> to get the reference value used for stencil tests.</td> + </tr> + <tr> + <td><code>STENCIL_VALUE_MASK</code></td> + <td>0x0B93</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_WRITEMASK</code></td> + <td>0x0B98</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_BACK_FUNC</code></td> + <td>0x8800</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_BACK_FAIL</code></td> + <td>0x8801</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_BACK_PASS_DEPTH_FAIL</code></td> + <td>0x8802</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_BACK_PASS_DEPTH_PASS</code></td> + <td>0x8803</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_BACK_REF</code></td> + <td>0x8CA3</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_BACK_VALUE_MASK</code></td> + <td>0x8CA4</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_BACK_WRITEMASK</code></td> + <td>0x8CA5</td> + <td> </td> + </tr> + <tr> + <td><code>VIEWPORT</code></td> + <td>0x0BA2</td> + <td>Returns an {{jsxref("Int32Array")}} with four elements for the current viewport dimensions.</td> + </tr> + <tr> + <td><code>SCISSOR_BOX</code></td> + <td>0x0C10</td> + <td>Returns an {{jsxref("Int32Array")}} with four elements for the current scissor box dimensions.</td> + </tr> + <tr> + <td><code>COLOR_CLEAR_VALUE</code></td> + <td>0x0C22</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_WRITEMASK</code></td> + <td>0x0C23</td> + <td> </td> + </tr> + <tr> + <td><code>UNPACK_ALIGNMENT</code></td> + <td>0x0CF5</td> + <td> </td> + </tr> + <tr> + <td><code>PACK_ALIGNMENT</code></td> + <td>0x0D05</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_TEXTURE_SIZE</code></td> + <td>0x0D33</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_VIEWPORT_DIMS</code></td> + <td>0x0D3A</td> + <td> </td> + </tr> + <tr> + <td><code>SUBPIXEL_BITS</code></td> + <td>0x0D50</td> + <td> </td> + </tr> + <tr> + <td><code>RED_BITS</code></td> + <td>0x0D52</td> + <td> </td> + </tr> + <tr> + <td><code>GREEN_BITS</code></td> + <td>0x0D53</td> + <td> </td> + </tr> + <tr> + <td><code>BLUE_BITS</code></td> + <td>0x0D54</td> + <td> </td> + </tr> + <tr> + <td><code>ALPHA_BITS</code></td> + <td>0x0D55</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_BITS</code></td> + <td>0x0D56</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_BITS</code></td> + <td>0x0D57</td> + <td> </td> + </tr> + <tr> + <td><code>POLYGON_OFFSET_UNITS</code></td> + <td>0x2A00</td> + <td> </td> + </tr> + <tr> + <td><code>POLYGON_OFFSET_FACTOR</code></td> + <td>0x8038</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_BINDING_2D</code></td> + <td>0x8069</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLE_BUFFERS</code></td> + <td>0x80A8</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLES</code></td> + <td>0x80A9</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLE_COVERAGE_VALUE</code></td> + <td>0x80AA</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLE_COVERAGE_INVERT</code></td> + <td>0x80AB</td> + <td> </td> + </tr> + <tr> + <td><code>COMPRESSED_TEXTURE_FORMATS</code></td> + <td>0x86A3</td> + <td> </td> + </tr> + <tr> + <td><code>VENDOR</code></td> + <td>0x1F00</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERER</code></td> + <td>0x1F01</td> + <td> </td> + </tr> + <tr> + <td><code>VERSION</code></td> + <td>0x1F02</td> + <td> </td> + </tr> + <tr> + <td><code>IMPLEMENTATION_COLOR_READ_TYPE</code></td> + <td>0x8B9A</td> + <td> </td> + </tr> + <tr> + <td><code>IMPLEMENTATION_COLOR_READ_FORMAT</code></td> + <td>0x8B9B</td> + <td> </td> + </tr> + <tr> + <td><code>BROWSER_DEFAULT_WEBGL</code></td> + <td>0x9244</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Buffers"><em>Buffers</em></h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.bufferData()")}}, {{domxref("WebGLRenderingContext.bufferSubData()")}}, {{domxref("WebGLRenderingContext.bindBuffer()")}}, or {{domxref("WebGLRenderingContext.getBufferParameter()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>STATIC_DRAW</code></td> + <td>0x88E4</td> + <td>Passed to <code>bufferData</code> as a hint about whether the contents of the buffer are likely to be used often and not change often.</td> + </tr> + <tr> + <td><code>STREAM_DRAW</code></td> + <td>0x88E0</td> + <td>Passed to <code>bufferData</code> as a hint about whether the contents of the buffer are likely to not be used often.</td> + </tr> + <tr> + <td><code>DYNAMIC_DRAW</code></td> + <td>0x88E8</td> + <td>Passed to <code>bufferData</code> as a hint about whether the contents of the buffer are likely to be used often and change often.</td> + </tr> + <tr> + <td><code>ARRAY_BUFFER</code></td> + <td>0x8892</td> + <td>Passed to <code>bindBuffer</code> or <code>bufferData</code> to specify the type of buffer being used.</td> + </tr> + <tr> + <td><code>ELEMENT_ARRAY_BUFFER</code></td> + <td>0x8893</td> + <td>Passed to <code>bindBuffer</code> or <code>bufferData</code> to specify the type of buffer being used.</td> + </tr> + <tr> + <td><code>BUFFER_SIZE</code></td> + <td>0x8764</td> + <td>Passed to <code>getBufferParameter</code> to get a buffer's size.</td> + </tr> + <tr> + <td><code>BUFFER_USAGE</code></td> + <td>0x8765</td> + <td>Passed to <code>getBufferParameter</code> to get the hint for the buffer passed in when it was created.</td> + </tr> + </tbody> +</table> + +<h3 id="Atributos_de_Vertex">Atributos de <em>Vertex</em></h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.getVertexAttrib()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Nome da constante</th> + <th scope="col">Valor</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>CURRENT_VERTEX_ATTRIB</code></td> + <td>0x8626</td> + <td>Passed to <code>getVertexAttrib</code> to read back the current vertex attribute.</td> + </tr> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_ENABLED</code></td> + <td>0x8622</td> + <td> </td> + </tr> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_SIZE</code></td> + <td>0x8623</td> + <td> </td> + </tr> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_STRIDE</code></td> + <td>0x8624</td> + <td> </td> + </tr> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_TYPE</code></td> + <td>0x8625</td> + <td> </td> + </tr> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_NORMALIZED</code></td> + <td>0x886A</td> + <td> </td> + </tr> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_POINTER</code></td> + <td>0x8645</td> + <td> </td> + </tr> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_BUFFER_BINDING</code></td> + <td>0x889F</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Culling">Culling</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.cullFace()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>CULL_FACE</code></td> + <td>0x0B44</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off culling. Can also be used with <code>getParameter</code> to find the current culling method.</td> + </tr> + <tr> + <td><code>FRONT</code></td> + <td>0x0404</td> + <td>Passed to <code>cullFace</code> to specify that only front faces should be drawn.</td> + </tr> + <tr> + <td><code>BACK</code></td> + <td>0x0405</td> + <td>Passed to <code>cullFace</code> to specify that only back faces should be drawn.</td> + </tr> + <tr> + <td><code>FRONT_AND_BACK</code></td> + <td>0x0408</td> + <td>Passed to <code>cullFace</code> to specify that front and back faces should be drawn.</td> + </tr> + </tbody> +</table> + +<h3 id="Enabling_and_disabling">Enabling and disabling</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.enable()")}} or {{domxref("WebGLRenderingContext.disable()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>BLEND</code></td> + <td>0x0BE2</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off blending. Can also be used with <code>getParameter</code> to find the current blending method.</td> + </tr> + <tr> + <td><code>DEPTH_TEST</code></td> + <td>0x0B71</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off the depth test. Can also be used with <code>getParameter</code> to query the depth test.</td> + </tr> + <tr> + <td><code>DITHER</code></td> + <td>0x0BD0</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off dithering. Can also be used with <code>getParameter</code> to find the current dithering method.</td> + </tr> + <tr> + <td><code>POLYGON_OFFSET_FILL</code></td> + <td>0x8037</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off the polygon offset. Useful for rendering hidden-line images, decals, and or solids with highlighted edges. Can also be used with <code>getParameter</code> to query the scissor test.</td> + </tr> + <tr> + <td><code>SAMPLE_ALPHA_TO_COVERAGE</code></td> + <td>0x809E</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off the alpha to coverage. Used in multi-sampling alpha channels.</td> + </tr> + <tr> + <td><code>SAMPLE_COVERAGE</code></td> + <td>0x80A0</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off the sample coverage. Used in multi-sampling.</td> + </tr> + <tr> + <td><code>SCISSOR_TEST</code></td> + <td>0x0C11</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off the scissor test. Can also be used with <code>getParameter</code> to query the scissor test.</td> + </tr> + <tr> + <td><code>STENCIL_TEST</code></td> + <td>0x0B90</td> + <td>Passed to <code>enable</code>/<code>disable</code> to turn on/off the stencil test. Can also be used with <code>getParameter</code> to query the stencil test.</td> + </tr> + <tr> + </tr> + </tbody> +</table> + +<h3 id="Errors">Errors</h3> + +<p>Constants returned from {{domxref("WebGLRenderingContext.getError()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>NO_ERROR</code></td> + <td>0</td> + <td>Returned from <code>getError</code>.</td> + </tr> + <tr> + <td><code>INVALID_ENUM</code></td> + <td>0x0500</td> + <td>Returned from <code>getError</code>.</td> + </tr> + <tr> + <td><code>INVALID_VALUE</code></td> + <td>0x0501</td> + <td>Returned from <code>getError</code>.</td> + </tr> + <tr> + <td><code>INVALID_OPERATION</code></td> + <td>0x0502</td> + <td>Returned from <code>getError</code>.</td> + </tr> + <tr> + <td><code>OUT_OF_MEMORY</code></td> + <td>0x0505</td> + <td>Returned from <code>getError</code>.</td> + </tr> + <tr> + <td><code>CONTEXT_LOST_WEBGL</code></td> + <td>0x9242</td> + <td>Returned from <code>getError</code>.</td> + </tr> + </tbody> +</table> + +<h3 id="Front_face_directions">Front face directions</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.frontFace()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>CW</code></td> + <td>0x0900</td> + <td>Passed to <code>frontFace</code> to specify the front face of a polygon is drawn in the clockwise direction</td> + </tr> + <tr> + <td><code>CCW</code></td> + <td>0x0901</td> + <td>Passed to <code>frontFace</code> to specify the front face of a polygon is drawn in the counter clockwise direction</td> + </tr> + </tbody> +</table> + +<h3 id="Hints">Hints</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.hint()")}}</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>DONT_CARE</code></td> + <td>0x1100</td> + <td>There is no preference for this behavior.</td> + </tr> + <tr> + <td><code>FASTEST</code></td> + <td>0x1101</td> + <td>The most efficient behavior should be used.</td> + </tr> + <tr> + <td><code>NICEST</code></td> + <td>0x1102</td> + <td>The most correct or the highest quality option should be used.</td> + </tr> + <tr> + <td><code>GENERATE_MIPMAP_HINT</code></td> + <td>0x8192</td> + <td>Hint for the quality of filtering when generating mipmap images with {{domxref("WebGLRenderingContext.generateMipmap()")}}.</td> + </tr> + </tbody> +</table> + +<h3 id="Data_types">Data types</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>BYTE</code></td> + <td>0x1400</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_BYTE</code></td> + <td>0x1401</td> + <td> </td> + </tr> + <tr> + <td><code>SHORT</code></td> + <td>0x1402</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_SHORT</code></td> + <td>0x1403</td> + <td> </td> + </tr> + <tr> + <td><code>INT</code></td> + <td>0x1404</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT</code></td> + <td>0x1405</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT</code></td> + <td>0x1406</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Pixel_formats">Pixel formats</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>DEPTH_COMPONENT</code></td> + <td>0x1902</td> + <td> </td> + </tr> + <tr> + <td><code>ALPHA</code></td> + <td>0x1906</td> + <td> </td> + </tr> + <tr> + <td><code>RGB</code></td> + <td>0x1907</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA</code></td> + <td>0x1908</td> + <td> </td> + </tr> + <tr> + <td><code>LUMINANCE</code></td> + <td>0x1909</td> + <td> </td> + </tr> + <tr> + <td><code>LUMINANCE_ALPHA</code></td> + <td>0x190A</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Pixel_types">Pixel types</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>UNSIGNED_BYTE</code></td> + <td>0x1401</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_SHORT_4_4_4_4</code></td> + <td>0x8033</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_SHORT_5_5_5_1</code></td> + <td>0x8034</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_SHORT_5_6_5</code></td> + <td>0x8363</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Shaders">Shaders</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.createShader()")}} or {{domxref("WebGLRenderingContext.getShaderParameter()")}}</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>FRAGMENT_SHADER</code></td> + <td>0x8B30</td> + <td>Passed to <code>createShader</code> to define a fragment shader.</td> + </tr> + <tr> + <td><code>VERTEX_SHADER</code></td> + <td>0x8B31</td> + <td>Passed to <code>createShader</code> to define a vertex shader</td> + </tr> + <tr> + <td><code>COMPILE_STATUS</code></td> + <td>0x8B81</td> + <td>Passed to <code>getShaderParamter</code> to get the status of the compilation. Returns false if the shader was not compiled. You can then query <code>getShaderInfoLog</code> to find the exact error</td> + </tr> + <tr> + <td><code>DELETE_STATUS</code></td> + <td>0x8B80</td> + <td>Passed to <code>getShaderParamter</code> to determine if a shader was deleted via <code>deleteShader</code>. Returns true if it was, false otherwise.</td> + </tr> + <tr> + <td><code>LINK_STATUS</code></td> + <td>0x8B82</td> + <td>Passed to <code>getProgramParameter</code> after calling <code>linkProgram</code> to determine if a program was linked correctly. Returns false if there were errors. Use <code>getProgramInfoLog</code> to find the exact error.</td> + </tr> + <tr> + <td><code>VALIDATE_STATUS</code></td> + <td>0x8B83</td> + <td>Passed to <code>getProgramParameter</code> after calling <code>validateProgram</code> to determine if it is valid. Returns false if errors were found.</td> + </tr> + <tr> + <td><code>ATTACHED_SHADERS</code></td> + <td>0x8B85</td> + <td>Passed to <code>getProgramParameter</code> after calling <code>attachShader</code> to determine if the shader was attached correctly. Returns false if errors occurred.</td> + </tr> + <tr> + <td><code>ACTIVE_ATTRIBUTES</code></td> + <td>0x8B89</td> + <td>Passed to <code>getProgramParameter</code> to get the number of attributes active in a program.</td> + </tr> + <tr> + <td><code>ACTIVE_UNIFORMS</code></td> + <td>0x8B86</td> + <td>Passed to <code>getProgramParamter</code> to get the number of uniforms active in a program.</td> + </tr> + <tr> + <td><code>MAX_VERTEX_ATTRIBS</code></td> + <td>0x8869</td> + <td>The maximum number of entries possible in the vertex attribute list.</td> + </tr> + <tr> + <td><code>MAX_VERTEX_UNIFORM_VECTORS</code></td> + <td>0x8DFB</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_VARYING_VECTORS</code></td> + <td>0x8DFC</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_COMBINED_TEXTURE_IMAGE_UNITS</code></td> + <td>0x8B4D</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_VERTEX_TEXTURE_IMAGE_UNITS</code></td> + <td>0x8B4C</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_TEXTURE_IMAGE_UNITS</code></td> + <td>0x8872</td> + <td>Implementation dependent number of maximum texture units. At least 8.</td> + </tr> + <tr> + <td><code>MAX_FRAGMENT_UNIFORM_VECTORS</code></td> + <td>0x8DFD</td> + <td> </td> + </tr> + <tr> + <td><code>SHADER_TYPE</code></td> + <td>0x8B4F</td> + <td> </td> + </tr> + <tr> + <td><code>SHADING_LANGUAGE_VERSION</code></td> + <td>0x8B8C</td> + <td> </td> + </tr> + <tr> + <td><code>CURRENT_PROGRAM</code></td> + <td>0x8B8D</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Depth_or_stencil_tests">Depth or stencil tests</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.depthFunc()")}} or {{domxref("WebGLRenderingContext.stencilFunc()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>NEVER</code></td> + <td>0x0200</td> + <td>Passed to <code>depthFunction</code> or <code>stencilFunction</code> to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.</td> + </tr> + <tr> + <td><code>ALWAYS</code></td> + <td>0x0207</td> + <td>Passed to <code>depthFunction</code> or <code>stencilFunction</code> to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.</td> + </tr> + <tr> + <td><code>LESS</code></td> + <td>0x0201</td> + <td>Passed to <code>depthFunction</code> or <code>stencilFunction</code> to specify depth or stencil tests will pass if the new depth value is less than the stored value.</td> + </tr> + <tr> + <td><code>EQUAL</code></td> + <td>0x0202</td> + <td>Passed to <code>depthFunction</code> or <code>stencilFunction</code> to specify depth or stencil tests will pass if the new depth value is equals to the stored value.</td> + </tr> + <tr> + <td><code>LEQUAL</code></td> + <td>0x0203</td> + <td>Passed to <code>depthFunction</code> or <code>stencilFunction</code> to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.</td> + </tr> + <tr> + <td><code>GREATER</code></td> + <td>0x0204</td> + <td>Passed to <code>depthFunction</code> or <code>stencilFunction</code> to specify depth or stencil tests will pass if the new depth value is greater than the stored value.</td> + </tr> + <tr> + <td><code>GEQUAL</code></td> + <td>0x0206</td> + <td>Passed to <code>depthFunction</code> or <code>stencilFunction</code> to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.</td> + </tr> + <tr> + <td><code>NOTEQUAL</code></td> + <td>0x0205</td> + <td>Passed to <code>depthFunction</code> or <code>stencilFunction</code> to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.</td> + </tr> + </tbody> +</table> + +<h3 id="Stencil_actions">Stencil actions</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.stencilOp()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>KEEP</code></td> + <td>0x1E00</td> + <td> </td> + </tr> + <tr> + <td><code>REPLACE</code></td> + <td>0x1E01</td> + <td> </td> + </tr> + <tr> + <td><code>INCR</code></td> + <td>0x1E02</td> + <td> </td> + </tr> + <tr> + <td><code>DECR</code></td> + <td>0x1E03</td> + <td> </td> + </tr> + <tr> + <td><code>INVERT</code></td> + <td>0x150A</td> + <td> </td> + </tr> + <tr> + <td><code>INCR_WRAP</code></td> + <td>0x8507</td> + <td> </td> + </tr> + <tr> + <td><code>DECR_WRAP</code></td> + <td>0x8508</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Textures">Textures</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>NEAREST</code></td> + <td>0x2600</td> + <td> </td> + </tr> + <tr> + <td><code>LINEAR</code></td> + <td>0x2601</td> + <td> </td> + </tr> + <tr> + <td><code>NEAREST_MIPMAP_NEAREST</code></td> + <td>0x2700</td> + <td> </td> + </tr> + <tr> + <td><code>LINEAR_MIPMAP_NEAREST</code></td> + <td>0x2701</td> + <td> </td> + </tr> + <tr> + <td><code>NEAREST_MIPMAP_LINEAR</code></td> + <td>0x2702</td> + <td> </td> + </tr> + <tr> + <td><code>LINEAR_MIPMAP_LINEAR</code></td> + <td>0x2703</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_MAG_FILTER</code></td> + <td>0x2800</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_MIN_FILTER</code></td> + <td>0x2801</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_WRAP_S</code></td> + <td>0x2802</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_WRAP_T</code></td> + <td>0x2803</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_2D</code></td> + <td>0x0DE1</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE</code></td> + <td>0x1702</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_CUBE_MAP</code></td> + <td>0x8513</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_BINDING_CUBE_MAP</code></td> + <td>0x8514</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_CUBE_MAP_POSITIVE_X</code></td> + <td>0x8515</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_CUBE_MAP_NEGATIVE_X</code></td> + <td>0x8516</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_CUBE_MAP_POSITIVE_Y</code></td> + <td>0x8517</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_CUBE_MAP_NEGATIVE_Y</code></td> + <td>0x8518</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_CUBE_MAP_POSITIVE_Z</code></td> + <td>0x8519</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_CUBE_MAP_NEGATIVE_Z</code></td> + <td>0x851A</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_CUBE_MAP_TEXTURE_SIZE</code></td> + <td>0x851C</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE0 - 31</code></td> + <td>0x84C0 - 0x84DF</td> + <td>A texture unit.</td> + </tr> + <tr> + <td><code>ACTIVE_TEXTURE</code></td> + <td>0x84E0</td> + <td>The current active texture unit.</td> + </tr> + <tr> + <td><code>REPEAT</code></td> + <td>0x2901</td> + <td> </td> + </tr> + <tr> + <td><code>CLAMP_TO_EDGE</code></td> + <td>0x812F</td> + <td> </td> + </tr> + <tr> + <td><code>MIRRORED_REPEAT</code></td> + <td>0x8370</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Uniform_types">Uniform types</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>FLOAT_VEC2</code></td> + <td>0x8B50</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_VEC3</code></td> + <td>0x8B51</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_VEC4</code></td> + <td>0x8B52</td> + <td> </td> + </tr> + <tr> + <td><code>INT_VEC2</code></td> + <td>0x8B53</td> + <td> </td> + </tr> + <tr> + <td><code>INT_VEC3</code></td> + <td>0x8B54</td> + <td> </td> + </tr> + <tr> + <td><code>INT_VEC4</code></td> + <td>0x8B55</td> + <td> </td> + </tr> + <tr> + <td><code>BOOL</code></td> + <td>0x8B56</td> + <td> </td> + </tr> + <tr> + <td><code>BOOL_VEC2</code></td> + <td>0x8B57</td> + <td> </td> + </tr> + <tr> + <td><code>BOOL_VEC3</code></td> + <td>0x8B58</td> + <td> </td> + </tr> + <tr> + <td><code>BOOL_VEC4</code></td> + <td>0x8B59</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_MAT2</code></td> + <td>0x8B5A</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_MAT3</code></td> + <td>0x8B5B</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_MAT4</code></td> + <td>0x8B5C</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLER_2D</code></td> + <td>0x8B5E</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLER_CUBE</code></td> + <td>0x8B60</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Shader_precision-specified_types">Shader precision-specified types</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>LOW_FLOAT</code></td> + <td>0x8DF0</td> + <td> </td> + </tr> + <tr> + <td><code>MEDIUM_FLOAT</code></td> + <td>0x8DF1</td> + <td> </td> + </tr> + <tr> + <td><code>HIGH_FLOAT</code></td> + <td>0x8DF2</td> + <td> </td> + </tr> + <tr> + <td><code>LOW_INT</code></td> + <td>0x8DF3</td> + <td> </td> + </tr> + <tr> + <td><code>MEDIUM_INT</code></td> + <td>0x8DF4</td> + <td> </td> + </tr> + <tr> + <td><code>HIGH_INT</code></td> + <td>0x8DF5</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Framebuffers_and_renderbuffers">Framebuffers and renderbuffers</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>FRAMEBUFFER</code></td> + <td>0x8D40</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER</code></td> + <td>0x8D41</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA4</code></td> + <td>0x8056</td> + <td> </td> + </tr> + <tr> + <td><code>RGB5_A1</code></td> + <td>0x8057</td> + <td> </td> + </tr> + <tr> + <td><code>RGB565</code></td> + <td>0x8D62</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_COMPONENT16</code></td> + <td>0x81A5</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_INDEX</code></td> + <td>0x1901</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_INDEX8</code></td> + <td>0x8D48</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_STENCIL</code></td> + <td>0x84F9</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_WIDTH</code></td> + <td>0x8D42</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_HEIGHT</code></td> + <td>0x8D43</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_INTERNAL_FORMAT</code></td> + <td>0x8D44</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_RED_SIZE</code></td> + <td>0x8D50</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_GREEN_SIZE</code></td> + <td>0x8D51</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_BLUE_SIZE</code></td> + <td>0x8D52</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_ALPHA_SIZE</code></td> + <td>0x8D53</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_DEPTH_SIZE</code></td> + <td>0x8D54</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_STENCIL_SIZE</code></td> + <td>0x8D55</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE</code></td> + <td>0x8CD0</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_OBJECT_NAME</code></td> + <td>0x8CD1</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL</code></td> + <td>0x8CD2</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE</code></td> + <td>0x8CD3</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT0</code></td> + <td>0x8CE0</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_ATTACHMENT</code></td> + <td>0x8D00</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL_ATTACHMENT</code></td> + <td>0x8D20</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_STENCIL_ATTACHMENT</code></td> + <td>0x821A</td> + <td> </td> + </tr> + <tr> + <td><code>NONE</code></td> + <td>0</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_COMPLETE</code></td> + <td>0x8CD5</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_INCOMPLETE_ATTACHMENT</code></td> + <td>0x8CD6</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT</code></td> + <td>0x8CD7</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_INCOMPLETE_DIMENSIONS</code></td> + <td>0x8CD9</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_UNSUPPORTED</code></td> + <td>0x8CDD</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_BINDING</code></td> + <td>0x8CA6</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_BINDING</code></td> + <td>0x8CA7</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_RENDERBUFFER_SIZE</code></td> + <td>0x84E8</td> + <td> </td> + </tr> + <tr> + <td><code>INVALID_FRAMEBUFFER_OPERATION</code></td> + <td>0x0506</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Pixel_storage_modes">Pixel storage modes</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.pixelStorei()")}}.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>UNPACK_FLIP_Y_WEBGL</code></td> + <td>0x9240</td> + <td> </td> + </tr> + <tr> + <td><code>UNPACK_PREMULTIPLY_ALPHA_WEBGL</code></td> + <td>0x9241</td> + <td> </td> + </tr> + <tr> + <td><code>UNPACK_COLORSPACE_CONVERSION_WEBGL</code></td> + <td>0x9243</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Constantes_adicionais_definidas_em_WebGL_2">Constantes adicionais definidas em WebGL 2</h2> + +<p>These constants are defined on the {{domxref("WebGL2RenderingContext")}} interface. All WebGL 1 constants are also available in a WebGL 2 context.</p> + +<h3 id="Obter_a_informação_do_parâmetro_GL">Obter a informação do parâmetro GL</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>READ_BUFFER</code></td> + <td>0x0C02</td> + <td> </td> + </tr> + <tr> + <td><code>UNPACK_ROW_LENGTH</code></td> + <td>0x0CF2</td> + <td> </td> + </tr> + <tr> + <td><code>UNPACK_SKIP_ROWS</code></td> + <td>0x0CF3</td> + <td> </td> + </tr> + <tr> + <td><code>UNPACK_SKIP_PIXELS</code></td> + <td>0x0CF4</td> + <td> </td> + </tr> + <tr> + <td><code>PACK_ROW_LENGTH</code></td> + <td>0x0D02</td> + <td> </td> + </tr> + <tr> + <td><code>PACK_SKIP_ROWS</code></td> + <td>0x0D03</td> + <td> </td> + </tr> + <tr> + <td><code>PACK_SKIP_PIXELS</code></td> + <td>0x0D04</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_BINDING_3D</code></td> + <td>0x806A</td> + <td> </td> + </tr> + <tr> + <td><code>UNPACK_SKIP_IMAGES</code></td> + <td>0x806D</td> + <td> </td> + </tr> + <tr> + <td><code>UNPACK_IMAGE_HEIGHT</code></td> + <td>0x806E</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_3D_TEXTURE_SIZE</code></td> + <td>0x8073</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_ELEMENTS_VERTICES</code></td> + <td>0x80E8</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_ELEMENTS_INDICES</code></td> + <td>0x80E9</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_TEXTURE_LOD_BIAS</code></td> + <td>0x84FD</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_FRAGMENT_UNIFORM_COMPONENTS</code></td> + <td>0x8B49</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_VERTEX_UNIFORM_COMPONENTS</code></td> + <td>0x8B4A</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_ARRAY_TEXTURE_LAYERS</code></td> + <td>0x88FF</td> + <td> </td> + </tr> + <tr> + <td><code>MIN_PROGRAM_TEXEL_OFFSET</code></td> + <td>0x8904</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_PROGRAM_TEXEL_OFFSET</code></td> + <td>0x8905</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_VARYING_COMPONENTS</code></td> + <td>0x8B4B</td> + <td> </td> + </tr> + <tr> + <td><code>FRAGMENT_SHADER_DERIVATIVE_HINT</code></td> + <td>0x8B8B</td> + <td> </td> + </tr> + <tr> + <td><code>RASTERIZER_DISCARD</code></td> + <td>0x8C89</td> + <td> </td> + </tr> + <tr> + <td><code>VERTEX_ARRAY_BINDING</code></td> + <td>0x85B5</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_VERTEX_OUTPUT_COMPONENTS</code></td> + <td>0x9122</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_FRAGMENT_INPUT_COMPONENTS</code></td> + <td>0x9125</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_SERVER_WAIT_TIMEOUT</code></td> + <td>0x9111</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_ELEMENT_INDEX</code></td> + <td>0x8D6B</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Texturas">Texturas</h3> + +<p>Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>RED</code></td> + <td>0x1903</td> + <td> </td> + </tr> + <tr> + <td><code>RGB8</code></td> + <td>0x8051</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA8</code></td> + <td>0x8058</td> + <td> </td> + </tr> + <tr> + <td><code>RGB10_A2</code></td> + <td>0x8059</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_3D</code></td> + <td>0x806F</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_WRAP_R</code></td> + <td>0x8072</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_MIN_LOD</code></td> + <td>0x813A</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_MAX_LOD</code></td> + <td>0x813B</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_BASE_LEVEL</code></td> + <td>0x813C</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_MAX_LEVEL</code></td> + <td>0x813D</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_COMPARE_MODE</code></td> + <td>0x884C</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_COMPARE_FUNC</code></td> + <td>0x884D</td> + <td> </td> + </tr> + <tr> + <td><code>SRGB</code></td> + <td>0x8C40</td> + <td> </td> + </tr> + <tr> + <td><code>SRGB8</code></td> + <td>0x8C41</td> + <td> </td> + </tr> + <tr> + <td><code>SRGB8_ALPHA8</code></td> + <td>0x8C43</td> + <td> </td> + </tr> + <tr> + <td><code>COMPARE_REF_TO_TEXTURE</code></td> + <td>0x884E</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA32F</code></td> + <td>0x8814</td> + <td> </td> + </tr> + <tr> + <td><code>RGB32F</code></td> + <td>0x8815</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA16F</code></td> + <td>0x881A</td> + <td> </td> + </tr> + <tr> + <td><code>RGB16F</code></td> + <td>0x881B</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_2D_ARRAY</code></td> + <td>0x8C1A</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_BINDING_2D_ARRAY</code></td> + <td>0x8C1D</td> + <td> </td> + </tr> + <tr> + <td><code>R11F_G11F_B10F</code></td> + <td>0x8C3A</td> + <td> </td> + </tr> + <tr> + <td><code>RGB9_E5</code></td> + <td>0x8C3D</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA32UI</code></td> + <td>0x8D70</td> + <td> </td> + </tr> + <tr> + <td><code>RGB32UI</code></td> + <td>0x8D71</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA16UI</code></td> + <td>0x8D76</td> + <td> </td> + </tr> + <tr> + <td><code>RGB16UI</code></td> + <td>0x8D77</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA8UI</code></td> + <td>0x8D7C</td> + <td> </td> + </tr> + <tr> + <td><code>RGB8UI</code></td> + <td>0x8D7D</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA32I</code></td> + <td>0x8D82</td> + <td> </td> + </tr> + <tr> + <td><code>RGB32I</code></td> + <td>0x8D83</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA16I</code></td> + <td>0x8D88</td> + <td> </td> + </tr> + <tr> + <td><code>RGB16I</code></td> + <td>0x8D89</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA8I</code></td> + <td>0x8D8E</td> + <td> </td> + </tr> + <tr> + <td><code>RGB8I</code></td> + <td>0x8D8F</td> + <td> </td> + </tr> + <tr> + <td><code>RED_INTEGER</code></td> + <td>0x8D94</td> + <td> </td> + </tr> + <tr> + <td><code>RGB_INTEGER</code></td> + <td>0x8D98</td> + <td> </td> + </tr> + <tr> + <td><code>RGBA_INTEGER</code></td> + <td>0x8D99</td> + <td> </td> + </tr> + <tr> + <td><code>R8</code></td> + <td>0x8229</td> + <td> </td> + </tr> + <tr> + <td><code>RG8</code></td> + <td>0x822B</td> + <td> </td> + </tr> + <tr> + <td>R16F</td> + <td>0x822D</td> + <td> </td> + </tr> + <tr> + <td>R32F</td> + <td>0x822E</td> + <td> </td> + </tr> + <tr> + <td>RG16F</td> + <td>0x822F</td> + <td> </td> + </tr> + <tr> + <td>RG32F</td> + <td>0x8230</td> + <td> </td> + </tr> + <tr> + <td>R8I</td> + <td>0x8231</td> + <td> </td> + </tr> + <tr> + <td>R8UI</td> + <td>0x8232</td> + <td> </td> + </tr> + <tr> + <td>R16I</td> + <td>0x8233</td> + <td> </td> + </tr> + <tr> + <td>R16UI</td> + <td>0x8234</td> + <td> </td> + </tr> + <tr> + <td>R32I</td> + <td>0x8235</td> + <td> </td> + </tr> + <tr> + <td>R32UI</td> + <td>0x8236</td> + <td> </td> + </tr> + <tr> + <td>RG8I</td> + <td>0x8237</td> + <td> </td> + </tr> + <tr> + <td>RG8UI</td> + <td>0x8238</td> + <td> </td> + </tr> + <tr> + <td>RG16I</td> + <td>0x8239</td> + <td> </td> + </tr> + <tr> + <td>RG16UI</td> + <td>0x823A</td> + <td> </td> + </tr> + <tr> + <td>RG32I</td> + <td>0x823B</td> + <td> </td> + </tr> + <tr> + <td>RG32UI</td> + <td>0x823C</td> + <td> </td> + </tr> + <tr> + <td>R8_SNORM</td> + <td>0x8F94</td> + <td> </td> + </tr> + <tr> + <td>RG8_SNORM</td> + <td>0x8F95</td> + <td> </td> + </tr> + <tr> + <td>RGB8_SNORM</td> + <td>0x8F96</td> + <td> </td> + </tr> + <tr> + <td>RGBA8_SNORM</td> + <td>0x8F97</td> + <td> </td> + </tr> + <tr> + <td><code>RGB10_A2UI</code></td> + <td>0x906F</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_IMMUTABLE_FORMAT </code></td> + <td>0x912F</td> + <td> </td> + </tr> + <tr> + <td><code>TEXTURE_IMMUTABLE_LEVELS</code></td> + <td>0x82DF</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Tipos_de_píxel">Tipos de píxel</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>UNSIGNED_INT_2_10_10_10_REV</code></td> + <td>0x8368</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_10F_11F_11F_REV</code></td> + <td>0x8C3B</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_5_9_9_9_REV</code></td> + <td>0x8C3E</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_32_UNSIGNED_INT_24_8_REV</code></td> + <td>0x8DAD</td> + <td> </td> + </tr> + <tr> + <td>UNSIGNED_INT_24_8</td> + <td>0x84FA</td> + <td> </td> + </tr> + <tr> + <td><code>HALF_FLOAT</code></td> + <td>0x140B</td> + <td> </td> + </tr> + <tr> + <td><code>RG</code></td> + <td>0x8227</td> + <td> </td> + </tr> + <tr> + <td><code>RG_INTEGER</code></td> + <td>0x8228</td> + <td> </td> + </tr> + <tr> + <td><code>INT_2_10_10_10_REV</code></td> + <td>0x8D9F</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Consultas">Consultas</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>CURRENT_QUERY</code></td> + <td>0x8865</td> + <td> </td> + </tr> + <tr> + <td><code>QUERY_RESULT </code></td> + <td>0x8866</td> + <td> </td> + </tr> + <tr> + <td><code>QUERY_RESULT_AVAILABLE</code></td> + <td>0x8867</td> + <td> </td> + </tr> + <tr> + <td><code>ANY_SAMPLES_PASSED</code></td> + <td>0x8C2F</td> + <td> </td> + </tr> + <tr> + <td><code>ANY_SAMPLES_PASSED_CONSERVATIVE</code></td> + <td>0x8D6A</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Draw_buffers">Draw buffers</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>MAX_DRAW_BUFFERS</code></td> + <td>0x8824</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER0</code></td> + <td>0x8825</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER1</code></td> + <td>0x8826</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER2</code></td> + <td>0x8827</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER3</code></td> + <td>0x8828</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER4</code></td> + <td>0x8829</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER5</code></td> + <td>0x882A</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER6</code></td> + <td>0x882B</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER7</code></td> + <td>0x882C</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER8</code></td> + <td>0x882D</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER9</code></td> + <td>0x882E</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER10</code></td> + <td>0x882F</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER11</code></td> + <td>0x8830</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER12</code></td> + <td>0x8831</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER13</code></td> + <td>0x8832</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER14</code></td> + <td>0x8833</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_BUFFER15</code></td> + <td>0x8834</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_COLOR_ATTACHMENTS</code></td> + <td>0x8CDF</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT1</code></td> + <td>0x8CE1</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT2</code></td> + <td>0x8CE2</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT3</code></td> + <td>0x8CE3</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT4</code></td> + <td>0x8CE4</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT5</code></td> + <td>0x8CE5</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT6</code></td> + <td>0x8CE6</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT7</code></td> + <td>0x8CE7</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT8</code></td> + <td>0x8CE8</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT9</code></td> + <td>0x8CE9</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT10</code></td> + <td>0x8CEA</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT11</code></td> + <td>0x8CEB</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT12</code></td> + <td>0x8CEC</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT13</code></td> + <td>0x8CED</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT14</code></td> + <td>0x8CEE</td> + <td> </td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT15</code></td> + <td>0x8CEF</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Samplers"><em>Samplers</em></h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>SAMPLER_3D</code></td> + <td>0x8B5F</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLER_2D_SHADOW</code></td> + <td>0x8B62</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLER_2D_ARRAY</code></td> + <td>0x8DC1</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLER_2D_ARRAY_SHADOW</code></td> + <td>0x8DC4</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLER_CUBE_SHADOW</code></td> + <td>0x8DC5</td> + <td> </td> + </tr> + <tr> + <td><code>INT_SAMPLER_2D</code></td> + <td>0x8DCA</td> + <td> </td> + </tr> + <tr> + <td><code>INT_SAMPLER_3D</code></td> + <td>0x8DCB</td> + <td> </td> + </tr> + <tr> + <td><code>INT_SAMPLER_CUBE</code></td> + <td>0x8DCC</td> + <td> </td> + </tr> + <tr> + <td><code>INT_SAMPLER_2D_ARRAY</code></td> + <td>0x8DCF</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_SAMPLER_2D</code></td> + <td>0x8DD2</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_SAMPLER_3D</code></td> + <td>0x8DD3</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_SAMPLER_CUBE</code></td> + <td>0x8DD4</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_SAMPLER_2D_ARRAY</code></td> + <td>0x8DD7</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_SAMPLES</code></td> + <td>0x8D57</td> + <td> </td> + </tr> + <tr> + <td><code>SAMPLER_BINDING</code></td> + <td>0x8919</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Buffers_2"><em>Buffers</em></h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>PIXEL_PACK_BUFFER</code></td> + <td>0x88EB</td> + <td> </td> + </tr> + <tr> + <td><code>PIXEL_UNPACK_BUFFER</code></td> + <td>0x88EC</td> + <td> </td> + </tr> + <tr> + <td><code>PIXEL_PACK_BUFFER_BINDING</code></td> + <td>0x88ED</td> + <td> </td> + </tr> + <tr> + <td><code>PIXEL_UNPACK_BUFFER_BINDING </code></td> + <td>0x88EF</td> + <td> </td> + </tr> + <tr> + <td><code>COPY_READ_BUFFER</code></td> + <td>0x8F36</td> + <td> </td> + </tr> + <tr> + <td><code>COPY_WRITE_BUFFER</code></td> + <td>0x8F37</td> + <td> </td> + </tr> + <tr> + <td><code>COPY_READ_BUFFER_BINDING</code></td> + <td>0x8F36</td> + <td> </td> + </tr> + <tr> + <td><code>COPY_WRITE_BUFFER_BINDING</code></td> + <td>0x8F37</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Tipos_de_dados">Tipos de dados</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>FLOAT_MAT2x3</code></td> + <td>0x8B65</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_MAT2x4</code></td> + <td>0x8B66</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_MAT3x2</code></td> + <td>0x8B67</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_MAT3x4 </code></td> + <td>0x8B68</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_MAT4x2</code></td> + <td>0x8B69</td> + <td> </td> + </tr> + <tr> + <td><code>FLOAT_MAT4x3</code></td> + <td>0x8B6A</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_VEC2</code></td> + <td>0x8DC6</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_VEC3</code></td> + <td>0x8DC7</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_INT_VEC4</code></td> + <td>0x8DC8</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_NORMALIZED</code></td> + <td>0x8C17</td> + <td> </td> + </tr> + <tr> + <td><code>SIGNED_NORMALIZED</code></td> + <td>0x8F9C</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Atributos_de_Vertex_2">Atributos de <em>Vertex</em></h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_INTEGER </code></td> + <td>0x88FD</td> + <td> </td> + </tr> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_DIVISOR</code></td> + <td>0x88FE</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Transform_feedback">Transform feedback</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>TRANSFORM_FEEDBACK_BUFFER_MODE</code></td> + <td>0x8C7F</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS</code></td> + <td>0x8C80</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_VARYINGS</code></td> + <td>0x8C83</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_BUFFER_START</code></td> + <td>0x8C84</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_BUFFER_SIZE</code></td> + <td>0x8C85</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN</code></td> + <td>0x8C88</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS</code></td> + <td>0x8C8A</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS</code></td> + <td>0x8C8B</td> + <td> </td> + </tr> + <tr> + <td><code>INTERLEAVED_ATTRIBS</code></td> + <td>0x8C8C</td> + <td> </td> + </tr> + <tr> + <td><code>SEPARATE_ATTRIBS</code></td> + <td>0x8C8D</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_BUFFER</code></td> + <td>0x8C8E</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_BUFFER_BINDING</code></td> + <td>0x8C8F</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK</code></td> + <td>0x8E22</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_PAUSED</code></td> + <td>0x8E23</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_ACTIVE</code></td> + <td>0x8E24</td> + <td> </td> + </tr> + <tr> + <td><code>TRANSFORM_FEEDBACK_BINDING</code></td> + <td>0x8E25</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Framebuffers_e_renderbuffers"><em>Framebuffers </em>e <em>renderbuffers</em></h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING</code></td> + <td>0x8210</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE</code></td> + <td>0x8211</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_RED_SIZE</code></td> + <td>0x8212</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_GREEN_SIZE</code></td> + <td>0x8213</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_BLUE_SIZE</code></td> + <td>0x8214</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE</code></td> + <td>0x8215</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE</code></td> + <td>0x8216</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE</code></td> + <td>0x8217</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_DEFAULT</code></td> + <td>0x8218</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_STENCIL_ATTACHMENT</code></td> + <td>0x821A</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_STENCIL</code></td> + <td>0x84F9</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH24_STENCIL8</code></td> + <td>0x88F0</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_FRAMEBUFFER_BINDING</code></td> + <td>0x8CA6</td> + <td> </td> + </tr> + <tr> + <td><code>READ_FRAMEBUFFER</code></td> + <td>0x8CA8</td> + <td> </td> + </tr> + <tr> + <td><code>DRAW_FRAMEBUFFER</code></td> + <td>0x8CA9</td> + <td> </td> + </tr> + <tr> + <td><code>READ_FRAMEBUFFER_BINDING</code></td> + <td>0x8CAA</td> + <td> </td> + </tr> + <tr> + <td><code>RENDERBUFFER_SAMPLES</code></td> + <td>0x8CAB</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER</code></td> + <td>0x8CD4</td> + <td> </td> + </tr> + <tr> + <td><code>FRAMEBUFFER_INCOMPLETE_MULTISAMPLE</code></td> + <td>0x8D56</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Uniforms">Uniforms</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>UNIFORM_BUFFER</code></td> + <td>0x8A11</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BUFFER_BINDING</code></td> + <td>0x8A28</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BUFFER_START</code></td> + <td>0x8A29</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BUFFER_SIZE</code></td> + <td>0x8A2A</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_VERTEX_UNIFORM_BLOCKS</code></td> + <td>0x8A2B</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_FRAGMENT_UNIFORM_BLOCKS</code></td> + <td>0x8A2D</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_COMBINED_UNIFORM_BLOCKS</code></td> + <td>0x8A2E</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_UNIFORM_BUFFER_BINDINGS</code></td> + <td>0x8A2F</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_UNIFORM_BLOCK_SIZE</code></td> + <td>0x8A30</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS</code></td> + <td>0x8A31</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS</code></td> + <td>0x8A33</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BUFFER_OFFSET_ALIGNMENT</code></td> + <td>0x8A34</td> + <td> </td> + </tr> + <tr> + <td><code>ACTIVE_UNIFORM_BLOCKS</code></td> + <td>0x8A36</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_TYPE </code></td> + <td>0x8A37</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_SIZE</code></td> + <td>0x8A38</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BLOCK_INDEX</code></td> + <td>0x8A3A</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_OFFSET</code></td> + <td>0x8A3B</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_ARRAY_STRIDE</code></td> + <td>0x8A3C</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_MATRIX_STRIDE</code></td> + <td>0x8A3D</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_IS_ROW_MAJOR</code></td> + <td>0x8A3E</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BLOCK_BINDING</code></td> + <td>0x8A3F</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BLOCK_DATA_SIZE</code></td> + <td>0x8A40</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BLOCK_ACTIVE_UNIFORMS</code></td> + <td>0x8A42</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES</code></td> + <td>0x8A43</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER</code></td> + <td>0x8A44</td> + <td> </td> + </tr> + <tr> + <td><code>UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER</code></td> + <td>0x8A46</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Objetos_de_sincronização">Objetos de sincronização</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>OBJECT_TYPE</code></td> + <td>0x9112</td> + <td> </td> + </tr> + <tr> + <td><code>SYNC_CONDITION</code></td> + <td>0x9113</td> + <td> </td> + </tr> + <tr> + <td><code>SYNC_STATUS</code></td> + <td>0x9114</td> + <td> </td> + </tr> + <tr> + <td><code>SYNC_FLAGS</code></td> + <td>0x9115</td> + <td> </td> + </tr> + <tr> + <td><code>SYNC_FENCE</code></td> + <td>0x9116</td> + <td> </td> + </tr> + <tr> + <td><code>SYNC_GPU_COMMANDS_COMPLETE</code></td> + <td>0x9117</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNALED</code></td> + <td>0x9118</td> + <td> </td> + </tr> + <tr> + <td><code>SIGNALED</code></td> + <td>0x9119</td> + <td> </td> + </tr> + <tr> + <td><code>ALREADY_SIGNALED</code></td> + <td>0x911A</td> + <td> </td> + </tr> + <tr> + <td><code>TIMEOUT_EXPIRED</code></td> + <td>0x911B</td> + <td> </td> + </tr> + <tr> + <td><code>CONDITION_SATISFIED</code></td> + <td>0x911C</td> + <td> </td> + </tr> + <tr> + <td><code>WAIT_FAILED</code></td> + <td>0x911D</td> + <td> </td> + </tr> + <tr> + <td><code>SYNC_FLUSH_COMMANDS_BIT</code></td> + <td>0x00000001</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="Constantes_diversas">Constantes diversas</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>COLOR</code></td> + <td>0x1800</td> + <td> </td> + </tr> + <tr> + <td>DEPTH</td> + <td>0x1801</td> + <td> </td> + </tr> + <tr> + <td><code>STENCIL</code></td> + <td>0x1802</td> + <td> </td> + </tr> + <tr> + <td><code>MIN</code></td> + <td>0x8007</td> + <td> </td> + </tr> + <tr> + <td>MAX</td> + <td>0x8008</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_COMPONENT24</code></td> + <td>0x81A6</td> + <td> </td> + </tr> + <tr> + <td><code>STREAM_READ</code></td> + <td>0x88E1</td> + <td> </td> + </tr> + <tr> + <td><code>STREAM_COPY</code></td> + <td>0x88E2</td> + <td> </td> + </tr> + <tr> + <td><code>STATIC_READ</code></td> + <td>0x88E5</td> + <td> </td> + </tr> + <tr> + <td><code>STATIC_COPY</code></td> + <td>0x88E6</td> + <td> </td> + </tr> + <tr> + <td><code>DYNAMIC_READ</code></td> + <td>0x88E9</td> + <td> </td> + </tr> + <tr> + <td><code>DYNAMIC_COPY</code></td> + <td>0x88EA</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH_COMPONENT32F</code></td> + <td>0x8CAC</td> + <td> </td> + </tr> + <tr> + <td><code>DEPTH32F_STENCIL8</code></td> + <td>0x8CAD</td> + <td> </td> + </tr> + <tr> + <td><code>INVALID_INDEX</code></td> + <td>0xFFFFFFFF</td> + <td> </td> + </tr> + <tr> + <td><code>TIMEOUT_IGNORED</code></td> + <td>-1</td> + <td> </td> + </tr> + <tr> + <td><code>MAX_CLIENT_WAIT_TIMEOUT_WEBGL</code></td> + <td>0x9247</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Constantes_definidas_nas_extensões_de_WebGL">Constantes definidas nas extensões de WebGL</h2> + +<h3 id="domxref(ANGLE_instanced_arrays)">{{domxref("ANGLE_instanced_arrays")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE</code></td> + <td>0x88FE</td> + <td>Describes the frequency divisor used for instanced rendering.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_debug_renderer_info)">{{domxref("WEBGL_debug_renderer_info")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>UNMASKED_VENDOR_WEBGL</code></td> + <td>0x9245</td> + <td>Passed to <code>getParameter</code> to get the vendor string of the graphics driver.</td> + </tr> + <tr> + <td><code>UNMASKED_RENDERER_WEBGL</code></td> + <td>0x9246</td> + <td>Passed to <code>getParameter</code> to get the renderer string of the graphics driver.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(EXT_texture_filter_anisotropic)">{{domxref("EXT_texture_filter_anisotropic")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>MAX_TEXTURE_MAX_ANISOTROPY_EXT</code></td> + <td>0x84FF</td> + <td>Returns the maximum available anisotropy.</td> + </tr> + <tr> + <td><code>TEXTURE_MAX_ANISOTROPY_EXT</code></td> + <td>0x84FE</td> + <td>Passed to <code>texParameter</code> to set the desired maximum anisotropy for a texture.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_compressed_texture_s3tc)">{{domxref("WEBGL_compressed_texture_s3tc")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>COMPRESSED_RGB_S3TC_DXT1_EXT</code></td> + <td>0x83F0</td> + <td>A DXT1-compressed image in an RGB image format.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGBA_S3TC_DXT1_EXT</code></td> + <td>0x83F1</td> + <td>A DXT1-compressed image in an RGB image format with a simple on/off alpha value.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGBA_S3TC_DXT3_EXT</code></td> + <td>0x83F2</td> + <td>A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGBA_S3TC_DXT5_EXT</code></td> + <td>0x83F3</td> + <td>A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_compressed_texture_etc)">{{domxref("WEBGL_compressed_texture_etc")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>COMPRESSED_R11_EAC</code></td> + <td>0x9270</td> + <td>One-channel (red) unsigned format compression.</td> + </tr> + <tr> + <td><code>COMPRESSED_SIGNED_R11_EAC</code></td> + <td>0x9271</td> + <td>One-channel (red) signed format compression.</td> + </tr> + <tr> + <td><code>COMPRESSED_RG11_EAC</code></td> + <td>0x9272</td> + <td>Two-channel (red and green) unsigned format compression.</td> + </tr> + <tr> + <td><code>COMPRESSED_SIGNED_RG11_EAC</code></td> + <td>0x9273</td> + <td>Two-channel (red and green) signed format compression.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGB8_ETC2</code></td> + <td>0x9274</td> + <td>Compresses RBG8 data with no alpha channel.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGBA8_ETC2_EAC</code></td> + <td>0x9275</td> + <td>Compresses RGBA8 data. The RGB part is encoded the same as <code>RGB_ETC2</code>, but the alpha part is encoded separately.</td> + </tr> + <tr> + <td><code>COMPRESSED_SRGB8_ETC2</code></td> + <td>0x9276</td> + <td>Compresses sRBG8 data with no alpha channel.</td> + </tr> + <tr> + <td><code>COMPRESSED_SRGB8_ALPHA8_ETC2_EAC</code></td> + <td>0x9277</td> + <td>Compresses sRGBA8 data. The sRGB part is encoded the same as <code>SRGB_ETC2</code>, but the alpha part is encoded separately.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2</code></td> + <td>0x9278</td> + <td>Similar to <code>RGB8_ETC</code>, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.</td> + </tr> + <tr> + <td><code>COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2</code></td> + <td>0x9279</td> + <td>Similar to <code>SRGB8_ETC</code>, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_compressed_texture_pvrtc)">{{domxref("WEBGL_compressed_texture_pvrtc")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>COMPRESSED_RGB_PVRTC_4BPPV1_IMG</code></td> + <td>0x8C00</td> + <td>RGB compression in 4-bit mode. One block for each 4×4 pixels.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGBA_PVRTC_4BPPV1_IMG</code></td> + <td>0x8C02</td> + <td>RGBA compression in 4-bit mode. One block for each 4×4 pixels.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGB_PVRTC_2BPPV1_IMG</code></td> + <td>0x8C01</td> + <td>RGB compression in 2-bit mode. One block for each 8×4 pixels.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGBA_PVRTC_2BPPV1_IMG</code></td> + <td>0x8C03</td> + <td>RGBA compression in 2-bit mode. One block for each 8×4 pixe</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_compressed_texture_etc1)">{{domxref("WEBGL_compressed_texture_etc1")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>COMPRESSED_RGB_ETC1_WEBGL</code></td> + <td>0x8D64</td> + <td>Compresses 24-bit RGB data with no alpha channel.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_compressed_texture_atc)">{{domxref("WEBGL_compressed_texture_atc")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>COMPRESSED_RGB_ATC_WEBGL</code></td> + <td>0x8C92</td> + <td>Compresses RGB textures with no alpha channel.</td> + </tr> + <tr> + <td><code>COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL</code></td> + <td>0x8C92</td> + <td>Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp).</td> + </tr> + <tr> + <td><code>COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL</code></td> + <td>0x87EE</td> + <td>Compresses RGBA textures using interpolated alpha encoding (useful when alpha transitions are gradient).</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_depth_texture)">{{domxref("WEBGL_depth_texture")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>UNSIGNED_INT_24_8_WEBGL</code></td> + <td>0x84FA</td> + <td>Unsigned integer type for 24-bit depth texture data.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(OES_texture_half_float)">{{domxref("OES_texture_half_float")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>HALF_FLOAT_OES</code></td> + <td>0x8D61</td> + <td>Half floating-point type (16-bit).</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_color_buffer_float)">{{domxref("WEBGL_color_buffer_float")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>RGBA32F_EXT</code></td> + <td>0x8814</td> + <td>RGBA 32-bit floating-point color-renderable format.</td> + </tr> + <tr> + <td><code>RGB32F_EXT</code></td> + <td>0x8815</td> + <td>RGB 32-bit floating-point color-renderable format.</td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT</code></td> + <td>0x8211</td> + <td> </td> + </tr> + <tr> + <td><code>UNSIGNED_NORMALIZED_EXT</code></td> + <td>0x8C17</td> + <td> </td> + </tr> + </tbody> +</table> + +<h3 id="domxref(EXT_blend_minmax)">{{domxref("EXT_blend_minmax")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>MIN_EXT</code></td> + <td>0x8007</td> + <td>Produces the minimum color components of the source and destination colors.</td> + </tr> + <tr> + <td><code>MAX_EXT</code></td> + <td>0x8008</td> + <td>Produces the maximum color components of the source and destination colors.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(EXT_sRGB)">{{domxref("EXT_sRGB")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>SRGB_EXT</code></td> + <td>0x8C40</td> + <td>Unsized sRGB format that leaves the precision up to the driver.</td> + </tr> + <tr> + <td><code>SRGB_ALPHA_EXT</code></td> + <td>0x8C42</td> + <td>Unsized sRGB format with unsized alpha component.</td> + </tr> + <tr> + <td><code>SRGB8_ALPHA8_EXT</code></td> + <td>0x8C43</td> + <td>Sized (8-bit) sRGB and alpha formats.</td> + </tr> + <tr> + <td><code>FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT</code></td> + <td>0x8210</td> + <td>Returns the framebuffer color encoding.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(OES_standard_derivatives)">{{domxref("OES_standard_derivatives")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>FRAGMENT_SHADER_DERIVATIVE_HINT_OES</code></td> + <td>0x8B8B</td> + <td>Indicates the accuracy of the derivative calculation for the GLSL built-in functions: <code>dFdx</code>, <code>dFdy</code>, and <code>fwidth</code>.</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(WEBGL_draw_buffers)">{{domxref("WEBGL_draw_buffers")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>COLOR_ATTACHMENT0_WEBGL</code></td> + <td>0x8CE0</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT1_WEBGL</code></td> + <td>0x8CE1</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT2_WEBGL</code></td> + <td>0x8CE2</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT3_WEBGL</code></td> + <td>0x8CE3</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT4_WEBGL</code></td> + <td>0x8CE4</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT5_WEBGL</code></td> + <td>0x8CE5</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT6_WEBGL</code></td> + <td>0x8CE6</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT7_WEBGL</code></td> + <td>0x8CE7</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT8_WEBGL</code></td> + <td>0x8CE8</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT9_WEBGL</code></td> + <td>0x8CE9</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT10_WEBGL</code></td> + <td>0x8CEA</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT11_WEBGL</code></td> + <td>0x8CEB</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT12_WEBGL</code></td> + <td>0x8CEC</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT13_WEBGL</code></td> + <td>0x8CED</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT14_WEBGL</code></td> + <td>0x8CEE</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>COLOR_ATTACHMENT15_WEBGL</code></td> + <td>0x8CEF</td> + <td>Framebuffer color attachment point</td> + </tr> + <tr> + <td><code>DRAW_BUFFER0_WEBGL</code></td> + <td>0x8825</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER1_WEBGL</code></td> + <td>0x8826</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER2_WEBGL</code></td> + <td>0x8827</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER3_WEBGL</code></td> + <td>0x8828</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER4_WEBGL</code></td> + <td>0x8829</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER5_WEBGL</code></td> + <td>0x882A</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER6_WEBGL</code></td> + <td>0x882B</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER7_WEBGL</code></td> + <td>0x882C</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER8_WEBGL</code></td> + <td>0x882D</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER9_WEBGL</code></td> + <td>0x882E</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER10_WEBGL</code></td> + <td>0x882F</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER11_WEBGL</code></td> + <td>0x8830</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER12_WEBGL</code></td> + <td>0x8831</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER13_WEBGL</code></td> + <td>0x8832</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER14_WEBGL</code></td> + <td>0x8833</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>DRAW_BUFFER15_WEBGL</code></td> + <td>0x8834</td> + <td>Draw buffer</td> + </tr> + <tr> + <td><code>MAX_COLOR_ATTACHMENTS_WEBGL</code></td> + <td>0x8CDF</td> + <td>Maximum number of framebuffer color attachment points</td> + </tr> + <tr> + <td><code>MAX_DRAW_BUFFERS_WEBGL</code></td> + <td>0x8824</td> + <td>Maximum number of draw buffers</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(OES_vertex_array_object)">{{domxref("OES_vertex_array_object")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Constant name</th> + <th scope="col">Value</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>VERTEX_ARRAY_BINDING_OES</code></td> + <td>0x85B5</td> + <td>The bound vertex array object (VAO).</td> + </tr> + </tbody> +</table> + +<h3 id="domxref(EXT_disjoint_timer_query)">{{domxref("EXT_disjoint_timer_query")}}</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Nome da constante</th> + <th scope="col">Valor</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>QUERY_COUNTER_BITS_EXT</code></td> + <td>0x8864</td> + <td>The number of bits used to hold the query result for the given target.</td> + </tr> + <tr> + <td><code>CURRENT_QUERY_EXT</code></td> + <td>0x8865</td> + <td>The currently active query.</td> + </tr> + <tr> + <td><code>QUERY_RESULT_EXT</code></td> + <td>0x8866</td> + <td>The query result.</td> + </tr> + <tr> + <td><code>QUERY_RESULT_AVAILABLE_EXT</code></td> + <td>0x8867</td> + <td>A Boolean indicating whether or not a query result is available.</td> + </tr> + <tr> + <td><code>TIME_ELAPSED_EXT</code></td> + <td>0x88BF</td> + <td>Elapsed time (in nanoseconds).</td> + </tr> + <tr> + <td><code>TIMESTAMP_EXT</code></td> + <td>0x8E28</td> + <td>The current time.</td> + </tr> + <tr> + <td><code>GPU_DISJOINT_EXT</code></td> + <td>0x8FBB</td> + <td>A Boolean indicating whether or not the GPU performed any disjoint operation.</td> + </tr> + </tbody> +</table> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}</td> + <td>{{Spec2('WebGL')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('WebGL2', "#3.7", "WebGL2RenderingContext")}}</td> + <td>{{Spec2('WebGL2')}}</td> + <td>Defines additional constants.</td> + </tr> + </tbody> +</table> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{domxref("WebGLRenderingContext")}}</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/webgl_api/dados/index.html b/files/pt-pt/web/api/webgl_api/dados/index.html new file mode 100644 index 0000000000..8257367513 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/dados/index.html @@ -0,0 +1,133 @@ +--- +title: Dados em WebGL +slug: Web/API/WebGL_API/Dados +tags: + - 3D + - API de WebGL + - Atributos + - Desenho + - Gráficos 3D + - Guía + - Intermediário + - Uniforms + - Varyings + - WebGL + - graficos +translation_of: Web/API/WebGL_API/Data +--- +<div>{{WebGLSidebar}}{{draft}}</div> + +<p>Shader programs have access to three kinds of data storage, each of which has a specific use case. Each kind of variable is accessible by one or both types of shader program (depending on the data store type) and possibly by the site's JavaScript code, depending on the specific type of variable.</p> + +<h2 id="Tipos_de_dados_GLSL">Tipos de dados GLSL</h2> + +<p><<document the basic types, vectors, etc; see <a href="https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)">Data Type (GLSL)</a> on the Khronos WebGL wiki>></p> + +<h2 id="Variáveis_de_GLSL">Variáveis de GLSL</h2> + +<p>There are three kinds of "variable" or data storage available in GLSL, each of which with its own purpose and use cases: <strong>{{anch("Attributes", "attributes")}}</strong>, <strong>{{anch("Varyings", "varyings")}}</strong>, and <strong>{{anch("Uniforms", "uniforms")}}</strong>.</p> + +<h3 id="Atributos">Atributos</h3> + +<p><strong>Attributes</strong> are GLSL variables which are only available to the vertex shader (as variables) and the JavaScript code. Attributes are typically used to store color information, texture coordinates, and any other data calculated or retrieved that needs to be shared between the JavaScript code and the vertex shader.</p> + +<p><<add how to use them>></p> + +<h3 id="Varyings"><em>Varyings</em></h3> + +<p><strong>Varyings</strong> are variables that are declared by the vertex shader and used to pass data from the vertex shader to the fragment shader. This is commonly used to share a vertex's {{interwiki("wikipedia", "Normal_(geometry)", "normal vector")}} after it has been computed by the vertex shader.</p> + +<p><<how to use>></p> + +<h3 id="Uniforms"><em>Uniforms</em></h3> + +<p><strong>Uniforms</strong> are set by the JavaScript code and are available to both the vertex and fragment shaders. They're used to provide values that will be the same for everything drawn in the frame, such as lighting positions and magnitudes, global transformation and perspective details, and so forth.</p> + +<p><<add details>></p> + +<h2 id="Buffers"><em>Buffers</em></h2> + +<p><<add information>></p> + +<h2 id="Texturas">Texturas</h2> + +<p><<add information>></p> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: none; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/webgl_api/index.html b/files/pt-pt/web/api/webgl_api/index.html new file mode 100644 index 0000000000..69f79c67f6 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/index.html @@ -0,0 +1,255 @@ +--- +title: 'API de WebGL: Gráficos 2D e 3D para a Web' +slug: Web/API/WebGL_API +tags: + - 3D + - API de WebGL + - Avançado + - Gráficos 3D + - Multimedia + - Referencia + - Resumo + - Sinopse + - WebGL + - graficos +translation_of: Web/API/WebGL_API +--- +<div>{{WebGLSidebar}}</div> + +<div class="summary"> +<p>WebGL (Biblioteca de Gráficos da Web) é uma API de JavaScript para a renderização de gráficos 2D e 3D interativos dentro de qualquer navegador da Web compatível sem a utilização de plug-ins. WebGL fazi isso, ao introduzir uma API que está em conformidade com o OpenGL ES 2.0 que pode ser utilizado em elementos {{HTMLElement("canvas")}} de HTML5.</p> +</div> + +<p>O suporte para WebGL está presente no <a href="/pt-PT/docs/Mozilla/Firefox" title="Firefox 4 for developers">Firefox</a> 4+, <a href="http://www.google.com/chrome/" title="http://www.google.com/chrome/">Google Chrome</a> 9+, <a href="http://www.opera.com/" title="http://www.opera.com/">Opera</a> 12+, <a href="http://www.apple.com/safari/" title="http://www.apple.com/fr/safari/">Safari </a>5.1+ and <a href="http://windows.microsoft.com/en-us/internet-explorer/browser-ie" title="http://windows.microsoft.com/en-us/internet-explorer/download-ie">Internet Explorer</a> 11+, e <a href="https://www.microsoft.com/pt-pt/windows/microsoft-edge">Microsoft Edge</a> build 10240+; contudo, o dispositivo do utilizador também deve ter hardware que suporte estas funcionalidades.</p> + +<p>O elemento {{HTMLElement("canvas")}} também é utilizado por <a href="/pt-PT/docs/Web/API/API_de_canvas">Canvas 2D</a> para gráficos 2D nas páginas da Web.</p> + +<h2 id="Referência">Referência</h2> + +<h3 id="Interfaces_padrão">Interfaces padrão</h3> + +<div class="index"> +<ul> + <li>{{domxref("WebGLRenderingContext")}}</li> + <li>{{domxref("WebGL2RenderingContext")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLActiveInfo")}}</li> + <li>{{domxref("WebGLBuffer")}}</li> + <li>{{domxref("WebGLContextEvent")}}</li> + <li>{{domxref("WebGLFramebuffer")}}</li> + <li>{{domxref("WebGLProgram")}}</li> + <li>{{domxref("WebGLQuery")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLRenderbuffer")}}</li> + <li>{{domxref("WebGLSampler")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLShader")}}</li> + <li>{{domxref("WebGLShaderPrecisionFormat")}}</li> + <li>{{domxref("WebGLSync")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLTexture")}}</li> + <li>{{domxref("WebGLTransformFeedback")}} {{experimental_inline}}</li> + <li>{{domxref("WebGLUniformLocation")}}</li> + <li>{{domxref("WebGLVertexArrayObject")}} {{experimental_inline}}</li> +</ul> +</div> + +<h3 id="Extensões">Extensões</h3> + +<div class="index"> +<ul> + <li>{{domxref("ANGLE_instanced_arrays")}}</li> + <li>{{domxref("EXT_blend_minmax")}}</li> + <li>{{domxref("EXT_color_buffer_float")}}</li> + <li>{{domxref("EXT_color_buffer_half_float")}}</li> + <li>{{domxref("EXT_disjoint_timer_query")}}</li> + <li>{{domxref("EXT_frag_depth")}}</li> + <li>{{domxref("EXT_sRGB")}}</li> + <li>{{domxref("EXT_shader_texture_lod")}}</li> + <li>{{domxref("EXT_texture_filter_anisotropic")}}</li> + <li>{{domxref("OES_element_index_uint")}}</li> + <li>{{domxref("OES_standard_derivatives")}}</li> + <li>{{domxref("OES_texture_float")}}</li> + <li>{{domxref("OES_texture_float_linear")}}</li> + <li>{{domxref("OES_texture_half_float")}}</li> + <li>{{domxref("OES_texture_half_float_linear")}}</li> + <li>{{domxref("OES_vertex_array_object")}}</li> + <li>{{domxref("WEBGL_color_buffer_float")}}</li> + <li>{{domxref("WEBGL_compressed_texture_astc")}}</li> + <li>{{domxref("WEBGL_compressed_texture_atc")}}</li> + <li>{{domxref("WEBGL_compressed_texture_etc")}}</li> + <li>{{domxref("WEBGL_compressed_texture_etc1")}}</li> + <li>{{domxref("WEBGL_compressed_texture_pvrtc")}}</li> + <li>{{domxref("WEBGL_compressed_texture_s3tc")}}</li> + <li>{{domxref("WEBGL_compressed_texture_s3tc_srgb")}}</li> + <li>{{domxref("WEBGL_debug_renderer_info")}}</li> + <li>{{domxref("WEBGL_debug_shaders")}}</li> + <li>{{domxref("WEBGL_depth_texture")}}</li> + <li>{{domxref("WEBGL_draw_buffers")}}</li> + <li>{{domxref("WEBGL_lose_context")}}</li> +</ul> +</div> + +<h3 id="Eventos">Eventos</h3> + +<ul> + <li>{{Event("webglcontextlost")}}</li> + <li>{{Event("webglcontextrestored")}}</li> + <li>{{Event("webglcontextcreationerror")}}</li> +</ul> + +<h3 id="Constantes_e_tipos">Constantes e tipos</h3> + +<ul> + <li><a href="/pt-PT/docs/Web/API/WebGL_API/Constantes">Constantes de WebGL</a></li> + <li><a href="/pt-PT/docs/Web/API/WebGL_API/Tipos">Tipos de WebGL</a></li> +</ul> + +<h3 id="WebGL_2">WebGL 2</h3> + +<p>WebGL 2 é uma atualização muito importante para WebGL que é fornecida através da inteface de {{domxref("WebGL2RenderingContext")}}. Esta tem como base o OpenGL ES 3.0 e novas funcionalidades includas:</p> + +<ul> + <li><a href="/en-US/docs/Web/API/WebGL2RenderingContext/texImage3D">3D textures</a>,</li> + <li><a href="/en-US/docs/Web/API/WebGLSampler">Sampler objects</a>,</li> + <li><a href="/en-US/docs/Web/API/WebGL2RenderingContext#Uniform_buffer_objects">Uniform Buffer objects</a>,</li> + <li><a href="/en-US/docs/Web/API/WebGLSync">Sync objects</a>,</li> + <li><a href="/en-US/docs/Web/API/WebGLQuery">Query objects</a>,</li> + <li><a href="/en-US/docs/Web/API/WebGLTransformFeedback">Transform Feedback objects</a>,</li> + <li>Promoted extensions that are now core to WebGL 2: <a href="/en-US/docs/Web/API/WebGLVertexArrayObject">Vertex Array objects</a>, <a href="/en-US/docs/Web/API/WebGL2RenderingContext/drawArraysInstanced">instancing</a>, <a href="/en-US/docs/Web/API/WebGL2RenderingContext/drawBuffers">multiple render targets</a>, <a href="/en-US/docs/Web/API/EXT_frag_depth">fragment depth</a>.</li> +</ul> + +<p>See also the blog post <a href="https://hacks.mozilla.org/2017/01/webgl-2-lands-in-firefox/">"WebGL 2 lands in Firefox"</a> and <a href="http://webglsamples.org/WebGL2Samples/">webglsamples.org/WebGL2Samples</a> for a few demos.</p> + +<h2 id="Guias_e_tutoriais">Guias e tutoriais</h2> + +<p>Below, you'll find an assortment of guides to help you learn WebGL concepts and tutorials that offer step-by-step lessons and examples.</p> + +<h3 id="Guias">Guias</h3> + +<dl> + <dt><a href="/pt-PT/docs/Web/API/WebGL_API/Dados">Dados em WebGL</a></dt> + <dd>A guide to variables, buffers, and other types of data used when writing WebGL code.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/WebGL_best_practices">WebGL best practices</a></dt> + <dd>Tips and suggestions to help you improve the quality, performance, and reliability of your WebGL content.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Using_Extensions">Using extensions</a></dt> + <dd>A guide to using WebGL extensions.</dd> +</dl> + +<h3 id="Tutoriais">Tutoriais</h3> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Tutorial">WebGL tutorial</a></dt> + <dd>A beginner's guide to WebGL core concepts. A good place to start if you don't have previous WebGL experience.</dd> +</dl> + +<h3 id="Exemplos">Exemplos</h3> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Basic_2D_animation_example">A basic 2D WebGL animation example</a></dt> + <dd>This example demonstrates the simple animation of a one-color shape. Topics examined are adapting to aspect ratio differences, a function to build shader programs from sets of multiple shaders, and the basics of drawing in WebGL.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/By_example">WebGL by example</a></dt> + <dd>A series of live samples with short explanations that showcase WebGL concepts and capabilities. The examples are sorted according to topic and level of difficulty, covering the WebGL rendering context, shader programming, textures, geometry, user interaction, and more.</dd> +</dl> + +<h3 id="Tutoriais_avançados">Tutoriais avançados</h3> + +<dl> + <dt><a href="/en-US/docs/Web/API/WebGL_API/WebGL_model_view_projection">WebGL model view projection</a></dt> + <dd>A detailed explanation of the three core matrices that are typically used to represent a 3D object view: the model, view and projection matrices.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API/Matrix_math_for_the_web">Matrix math for the web</a></dt> + <dd>A useful guide to how 3D transform matrices work, and can be used on the web — both for WebGL calculations and in CSS3 transforms.</dd> +</dl> + +<h2 id="Recursos">Recursos</h2> + +<ul> + <li><a href="https://www.youtube.com/embed/H4c8t6myAWU/?feature=player_detailpage">Raw WebGL: An introduction to WebGL</a> A talk by Nick Desaulniers that introduces the basics of WebGL. This is a great place to start if you've never done low-level graphics programming.</li> + <li><a href="http://www.khronos.org/webgl/" title="http://www.khronos.org/webgl/">Khronos WebGL site</a> The main web site for WebGL at the Khronos Group.</li> + <li><a href="http://learningwebgl.com/blog/?page_id=1217" title="http://learningwebgl.com/blog/">Learning WebGL</a> A site with tutorials on how to use WebGL.</li> + <li><a href="http://www.html5rocks.com/en/tutorials/webgl/webgl_fundamentals/" title="http://www.html5rocks.com/en/tutorials/webgl/webgl_fundamentals/">WebGL Fundamentals</a> A basic tutorial with fundamentals of WebGL.</li> + <li><a href="http://webglplayground.net" title="http://webglplayground.net">WebGL playground</a> An online tool for creating and sharing WebGL projects. Good for quick prototyping and experimenting.</li> + <li><a href="http://www.webglacademy.com" title="http://www.webglacademy.com">WebGL Academy</a> An HTML/JavaScript editor with tutorials to learn basics of webgl programming.</li> + <li><a href="http://webglstats.com/">WebGL Stats</a> A site with statistics about WebGL capabilities in browsers on different platforms.</li> +</ul> + +<h3 id="Bibliotecas">Bibliotecas</h3> + +<ul> + <li><a class="link-https" href="https://github.com/toji/gl-matrix" title="https://github.com/toji/gl-matrix">glMatrix</a> is a JavaScript matrix and vector library for high-performance WebGL apps.</li> + <li><a href="http://senchalabs.github.com/philogl/">PhiloGL</a> is a WebGL framework for data visualization, creative coding, and game development.</li> + <li><a href="http://www.pixijs.com/">Pixi.js</a> is a fast, open-source 2D WebGL renderer.</li> + <li><a href="https://playcanvas.com/">PlayCanvas</a> is an open-source game engine.</li> + <li><a href="http://sylvester.jcoglan.com/" title="http://sylvester.jcoglan.com/">Sylvester</a> is an open-source library for manipulating vectors and matrices. Not optimized for WebGL but extremely robust.</li> + <li><a href="https://threejs.org/">three.js</a> is an open-source, fully featured 3D WebGL library.</li> +</ul> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('WebGL')}}</td> + <td>{{Spec2('WebGL')}}</td> + <td>Initial definition. Based on OpenGL ES 2.0</td> + </tr> + <tr> + <td>{{SpecName('WebGL2')}}</td> + <td>{{Spec2('WebGL2')}}</td> + <td>Builds on top of WebGL 1. Based on OpenGL ES 3.0.</td> + </tr> + <tr> + <td>{{SpecName('OpenGL ES 2.0')}}</td> + <td>{{Spec2('OpenGL ES 2.0')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('OpenGL ES 3.0')}}</td> + <td>{{Spec2('OpenGL ES 3.0')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<h3 id="WebGL_1">WebGL 1</h3> + +<div> + + +<p>{{Compat("api.WebGLRenderingContext", 0)}}</p> + +<h3 id="WebGL_2_2">WebGL 2</h3> + +<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("api.WebGL2RenderingContext", 0)}}</p> +</div> + +<h3 id="Notas_de_compatibilidade">Notas de compatibilidade</h3> + +<p>In addition to the browser, the GPU itself also needs to support the feature. So, for example, S3 Texture Compression (S3TC) is only available on Tegra-based tablets. Most browsers make the WebGL context available through the <code>webgl</code> context name, but older ones need <code>experimental-webgl</code> as well. In addition, the upcoming <a href="/en-US/docs/Web/API/WebGL2RenderingContext">WebGL 2</a> is fully backwards-compatible and will have the context name <code>webgl2</code>.</p> + +<h3 id="Notas_do_Gecko">Notas do Gecko</h3> + +<h4 id="Depuração_e_teste_de_WebGL">Depuração e teste de WebGL</h4> + +<p>Starting with Gecko 10.0 {{geckoRelease("10.0")}}, there are two preferences available which let you control the capabilities of WebGL for testing purposes:</p> + +<dl> + <dt><code>webgl.min_capability_mode</code></dt> + <dd>A Boolean property that, when <code>true</code>, enables a minimum capability mode. When in this mode, WebGL is configured to only support the bare minimum feature set and capabilities required by the WebGL specification. This lets you ensure that your WebGL code will work on any device or browser, regardless of their capabilities. This is <code>false</code> by default.</dd> + <dt><code>webgl.disable_extensions</code></dt> + <dd>A Boolean property that, when <code>true</code>, disables all WebGL extensions. This is <code>false</code> by default.</dd> +</dl> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/API_de_canvas">API de Canvas</a></li> + <li><a href="https://developer.mozilla.org/pt-PT/docs/Web/API/WebGLRenderingContext/getSupportedExtensions">informação de compatibilidade sobre as extensões WebGL</a></li> +</ul> diff --git a/files/pt-pt/web/api/webgl_api/tipos/index.html b/files/pt-pt/web/api/webgl_api/tipos/index.html new file mode 100644 index 0000000000..a1762958ae --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/tipos/index.html @@ -0,0 +1,242 @@ +--- +title: Tipos de WebGL +slug: Web/API/WebGL_API/Tipos +translation_of: Web/API/WebGL_API/Types +--- +<div>{{WebGLSidebar}}</div> + +<p>Os seguintes tipos são utilizados nas interfaces de <a href="/pt-PT/docs/Web/API/WebGL_API">WebGL</a>.</p> + +<h2 id="WebGL_1">WebGL 1</h2> + +<p>These types are used within a {{domxref("WebGLRenderingContext")}}.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Tipo</td> + <td class="header">Tipo de IDL Web</td> + <td class="header">Descrição</td> + </tr> + <tr> + <td><code>GLenum</code></td> + <td><code>unsigned long</code></td> + <td>Used for enums. See also the list of <a href="/en-US/docs/Web/API/WebGL_API/Constants">constants</a>.</td> + </tr> + <tr> + <td><code>GLboolean</code></td> + <td><code>boolean</code></td> + <td>A {{jsxref("Boolean")}}.</td> + </tr> + <tr> + <td><code>GLbitfield</code></td> + <td><code>unsigned long</code></td> + <td>A bit field that stores multiple, logical bits. Used for example in {{domxref("WebGLRenderingContext.clear()")}}.</td> + </tr> + <tr> + <td><code>GLbyte</code></td> + <td><code>byte</code></td> + <td>8-bit twos complement signed integer.</td> + </tr> + <tr> + <td><code>GLshort</code></td> + <td><code>short</code></td> + <td>16-bit twos complement signed integer.</td> + </tr> + <tr> + <td><code>GLint</code></td> + <td><code>long</code></td> + <td>32-bit twos complement signed integer.</td> + </tr> + <tr> + <td><code>GLsizei</code></td> + <td><code>long</code></td> + <td>Used for sizes (e.g. width and height of the drawing buffer).</td> + </tr> + <tr> + <td><code>GLintptr</code></td> + <td><code>long long</code></td> + <td>Special type for pointer arithmetic.</td> + </tr> + <tr> + <td><code>GLsizeiptr</code></td> + <td><code>long long</code></td> + <td>Special type for pointer arithmetic.</td> + </tr> + <tr> + <td><code>GLubyte</code></td> + <td><code>octet</code></td> + <td>8-bit twos complement unsigned integer.</td> + </tr> + <tr> + <td><code>GLushort</code></td> + <td><code>unsigned short</code></td> + <td>16-bit twos complement unsigned integer.</td> + </tr> + <tr> + <td><code>GLuint</code></td> + <td><code>unsigned long</code></td> + <td>32-bit twos complement unsigned integer.</td> + </tr> + <tr> + <td><code>GLfloat</code></td> + <td><code>unrestricted float</code></td> + <td>32-bit IEEE floating point number.</td> + </tr> + <tr> + <td><code>GLclampf</code></td> + <td><code>unrestricted float</code></td> + <td>Clamped 32-bit IEEE floating point number.</td> + </tr> + </tbody> +</table> + +<h2 id="WebGL_2">WebGL 2</h2> + +<p>These types are used within a {{domxref("WebGL2RenderingContext")}}. All WebGL 1 types are used as well.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Tipo</td> + <td class="header">Tipo IDL Web</td> + <td class="header">Descrição</td> + </tr> + <tr> + <td><code>GLint64</code></td> + <td><code>long long</code></td> + <td>Signed 64-bit integer number.</td> + </tr> + </tbody> +</table> + +<h2 id="WebGL_extensions">WebGL extensions</h2> + +<p>Estes tipos são utilziados dentro das <a href="/pt-PT/docs/Web/API/WebGL_API/Utilizar_Extensões">extensões de WebGL</a>.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Tipo</td> + <td class="header">Tipo de IDL Web</td> + <td class="header">Descrição</td> + </tr> + <tr> + <td><code>GLuint64EXT</code></td> + <td><code>long long</code></td> + <td>Unsigned 64-bit integer number.</td> + </tr> + </tbody> +</table> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('WebGL', "#5.1", "Types")}}</td> + <td>{{Spec2('WebGL')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('WebGL2', "#3.1", "Types")}}</td> + <td>{{Spec2('WebGL2')}}</td> + <td>Defines additional types.</td> + </tr> + <tr> + <td>{{SpecName('EXT_disjoint_timer_query', "", "GLuint64EXT")}}</td> + <td>{{Spec2('EXT_disjoint_timer_query')}}</td> + <td>Adds <code>GLuint64EXT</code></td> + </tr> + </tbody> +</table> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{domxref("WebGLRenderingContext")}}</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/webgl_api/utilizar_extensões/index.html b/files/pt-pt/web/api/webgl_api/utilizar_extensões/index.html new file mode 100644 index 0000000000..a8bbe535d2 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/utilizar_extensões/index.html @@ -0,0 +1,718 @@ +--- +title: Utilizar extensões de WebGL +slug: Web/API/WebGL_API/Utilizar_Extensões +tags: + - Avançado + - WebGL +translation_of: Web/API/WebGL_API/Using_Extensions +--- +<div>{{WebGLSidebar}}</div> + +<p>WebGL, like its sister APIs (OpenGL and OpenGL ES), supports extensions. A complete list of extensions is available in the <a class="external" href="http://www.khronos.org/registry/webgl/extensions/">khronos webgl extension registry</a>.</p> + +<div class="note"><strong>Nota:</strong> In WebGL, unlike in other GL APIs, extensions are only available if explicitly requested.</div> + +<h2 id="Nomes_de_extensão_canónica_prefixos_e_preferências_da_empresa">Nomes de extensão canónica, prefixos e preferências da empresa</h2> + +<p>Extensions may be supported by browser vendors before being officially ratified (but only when they are in draft stage). In that case, their name can be prefixed by the vendor prefix (<code>MOZ_</code>, <code>WEBKIT_</code>, etc.) or the extension is only available once a browser preference has been toggled.</p> + +<p>If you wish to work with the bleeding edge of extensions, and want to keep working on upon ratification (assuming, of course, that the extension doesn't change in incompatible ways), that you query the canonical extension name as well as the vendor extension name. For instance:</p> + +<pre class="brush:js">var ext = ( + gl.getExtension('OES_vertex_array_object') || + gl.getExtension('MOZ_OES_vertex_array_object') || + gl.getExtension('WEBKIT_OES_vertex_array_object') +); +</pre> + +<p>Note that, vendor prefix have been discouraged more and more and thus most browser implement experimental extensions behind a feature flag rather than vendor prefix.</p> + +<p>The feature flags are:</p> + +<ul> + <li><code>webgl.enable-draft-extensions</code> in Firefox</li> + <li><code>chrome://flags/#enable-webgl-draft-extensions</code> in Chromium based browsers (Chrome, Opera).</li> +</ul> + +<h2 id="Convenções_de_nomeação">Convenções de nomeação</h2> + +<p>WebGL extensions are prefixed with "ANGLE", "OES", "EXT" or "WEBGL". These prefixes reflect origin and intent:</p> + +<ul> + <li>ANGLE_: Extensions that are written by the <a href="https://en.wikipedia.org/wiki/ANGLE_%28software%29">ANGLE library</a> authors.</li> + <li>OES_: Extensions that mirror functionality from OpenGL ES or OpenGL API extensions approved by the respective architecture review boards.</li> + <li>EXT_: Extensions that mirror other OpenGL ES or OpenGL API extensions.</li> + <li>WEBGL_: Extensions that are WebGL-specific and intended to be compatible with multiple web browsers. It should also be used for extensions which originated with the OpenGL ES or OpenGL APIs, but whose behavior has been significantly altered.</li> +</ul> + +<h2 id="Extensões_de_consulta_disponíveis">Extensões de consulta disponíveis</h2> + +<p>O contexto de WebGL suporta a consulta de quais as extensões que estão disponíveis.</p> + +<pre class="brush:js">var available_extensions = gl.getSupportedExtensions();</pre> + +<p>The {{domxref("WebGLRenderingContext.getSupportedExtensions()")}} method returns an array of strings, one for each supported extension.</p> + +<h2 id="Lista_de_extensões">Lista de extensões</h2> + +<p>As extensões atuais são:</p> + +<p>{{page("pt-PT/docs/Web/API/WebGL_API", "Extensões")}}</p> + +<h2 id="Ativar_uma_extensão">Ativar uma extensão</h2> + +<p>Before an extension can be used it has to be enabled using {{domxref("WebGLRenderingContext.getExtension()")}}. For example:</p> + +<pre class="brush:js">var float_texture_ext = gl.getExtension('OES_texture_float');</pre> + +<p>The return value is <code>null</code> if the extension is not supported, or an extension object otherwise.</p> + +<h2 id="Objetos_de_extensão">Objetos de extensão</h2> + +<p>If an extension defines specific symbols or functions that are not available in the core specification of WebGL, they will be available on the extension object returned by the call to <code>gl.getExtension()</code>.</p> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>9</td> + <td>{{CompatGeckoDesktop("2.0")}}</td> + <td>11</td> + <td>12</td> + <td>5.1</td> + </tr> + <tr> + <td><code>ANGLE_instanced_arrays</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("33.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_blend_minmax</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("33.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_color_buffer_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("49.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_color_buffer_half_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("30.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_disjoint_timer_query</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("41.0")}} [1]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_frag_depth</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("30.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_sRGB</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("28.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_shader_texture_lod</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("50.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_texture_filter_anisotropic</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("17.0")}} [2]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_element_index_uint</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("24.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_standard_derivatives</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("10.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_texture_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("6.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_texture_float_linear</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("24.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_texture_half_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("29.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_texture_half_float_linear</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("30.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_vertex_array_object</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("25.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_color_buffer_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("30.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_astc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("53.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_atc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("18.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_etc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("51.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_etc1</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("30.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_pvrtc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("18.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_s3tc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("22.0")}} [2]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_s3tc_srgb</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("55.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_debug_renderer_info</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("19.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_debug_shaders</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("30.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_depth_texture</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("22.0")}} [2]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_draw_buffers</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("28.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_lose_context</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("22.0")}} [2]</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidades</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>25</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>12</td> + <td>8.0</td> + </tr> + <tr> + <td><code>ANGLE_instanced_arrays</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_blend_minmax</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_color_buffer_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_color_buffer_half_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_disjoint_timer_query</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_frag_depth</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_sRGB</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_shader_texture_lod</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>EXT_texture_filter_anisotropic</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_element_index_uint</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_standard_derivatives</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_texture_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_texture_float_linear</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_texture_half_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_texture_half_float_linear</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>OES_vertex_array_object</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_color_buffer_float</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_astc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_atc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_etc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_etc1</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_s3tc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_pvrtc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_s3tc</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_compressed_texture_s3tc_srgb</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_debug_renderer_info</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_debug_shaders</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_depth_texture</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_draw_buffers</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>WEBGL_lose_context</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Toggling the <code>webgl.enable-draft-extensions</code> preference in about:config is required.</p> + +<p>[2] This extension was prefixed with <code>MOZ_</code> in prior versions.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{domxref("WebGLRenderingContext.getSupportedExtensions()")}}</li> + <li>{{domxref("WebGLRenderingContext.getExtension()")}}</li> + <li><a href="webglreport.com">Relatório de WebGL</a></li> + <li><a href="http://webglstats.comhttp://webglstats.com">Estatísticas de WebGL</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/webglrenderingcontext/index.html b/files/pt-pt/web/api/webglrenderingcontext/index.html new file mode 100644 index 0000000000..7d9b4ef24e --- /dev/null +++ b/files/pt-pt/web/api/webglrenderingcontext/index.html @@ -0,0 +1,444 @@ +--- +title: WebGLRenderingContext +slug: Web/API/WebGLRenderingContext +tags: + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext +--- +<div>{{APIRef("WebGL")}}</div> + +<p>A interface de <code><strong>WebGLRenderingContext</strong></code> fornece o contexto de renderização de OpenGL ES 2.0 para a superfície de desenho de um elemento {{HTMLElement("canvas")}} de HTML.</p> + +<p>Para obter um objeto desta interface, <em>call</em> {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} num elemento de <code><canvas></code>, fornecendo "webgl" como um argumento:</p> + +<pre class="brush: js">var canvas = document.getElementById('myCanvas'); +var gl = canvas.getContext('webgl'); +</pre> + +<p>Once you have the WebGL rendering context for a canvas, you can render within it.</p> + +<p>The <a href="/en-US/docs/Web/API/WebGL_API/Tutorial" title="WebGL tutorial">WebGL tutorial</a> has more information, examples, and resources on how to get started with WebGL.</p> + +<h2 id="Constantes">Constantes</h2> + +<p>See the <a href="/en-US/docs/Web/API/WebGL_API/Constants">WebGL constants</a> page.</p> + +<h2 id="O_contexto_de_WebGL">O contexto de WebGL</h2> + +<p>The following properties and methods provide general information and functionality to deal with the WebGL context:</p> + +<dl> + <dt>{{domxref("WebGLRenderingContext.canvas")}}</dt> + <dd>A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.</dd> + <dt>{{domxref("WebGLRenderingContext.commit()")}} {{experimental_inline}}</dt> + <dd> + <p>Pushes frames back to the original {{domxref("HTMLCanvasElement")}}, if the context is not directly fixed to a specific canvas.</p> + </dd> + <dt>{{domxref("WebGLRenderingContext.drawingBufferWidth")}}</dt> + <dd>The read-only width of the current drawing buffer. Should match the width of the canvas element associated with this context.</dd> + <dt>{{domxref("WebGLRenderingContext.drawingBufferHeight")}}</dt> + <dd>The read-only height of the current drawing buffer. Should match the height of the canvas element associated with this context.</dd> + <dt>{{domxref("WebGLRenderingContext.getContextAttributes()")}}</dt> + <dd>Returns a <code>WebGLContextAttributes</code> object that contains the actual context parameters. Might return {{jsxref("null")}}, if the context is lost.</dd> + <dt>{{domxref("WebGLRenderingContext.isContextLost()")}}</dt> + <dd>Returns <code>true</code> if the context is lost, otherwise returns <code>false</code>.</dd> +</dl> + +<h2 id="Visualização_e_recorte">Visualização e recorte</h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.scissor()")}}</dt> + <dd>Defines the scissor box.</dd> + <dt>{{domxref("WebGLRenderingContext.viewport()")}}</dt> + <dd>Sets the viewport.</dd> +</dl> + +<h2 id="Informação_de_estado">Informação de estado</h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.activeTexture()")}}</dt> + <dd>Selects the active texture unit.</dd> + <dt>{{domxref("WebGLRenderingContext.blendColor()")}}</dt> + <dd>Sets the source and destination blending factors.</dd> + <dt>{{domxref("WebGLRenderingContext.blendEquation()")}}</dt> + <dd>Sets both the RGB blend equation and alpha blend equation to a single equation.</dd> + <dt>{{domxref("WebGLRenderingContext.blendEquationSeparate()")}}</dt> + <dd>Sets the RGB blend equation and alpha blend equation separately.</dd> + <dt>{{domxref("WebGLRenderingContext.blendFunc()")}}</dt> + <dd>Defines which function is used for blending pixel arithmetic.</dd> + <dt>{{domxref("WebGLRenderingContext.blendFuncSeparate()")}}</dt> + <dd>Defines which function is used for blending pixel arithmetic for RGB and alpha components separately.</dd> + <dt>{{domxref("WebGLRenderingContext.clearColor()")}}</dt> + <dd>Specifies the color values used when clearing color buffers.</dd> + <dt>{{domxref("WebGLRenderingContext.clearDepth()")}}</dt> + <dd>Specifies the depth value used when clearing the depth buffer.</dd> + <dt>{{domxref("WebGLRenderingContext.clearStencil()")}}</dt> + <dd>Specifies the stencil value used when clearing the stencil buffer.</dd> + <dt>{{domxref("WebGLRenderingContext.colorMask()")}}</dt> + <dd>Sets which color components to enable or to disable when drawing or rendering to a {{domxref("WebGLFramebuffer")}}.</dd> + <dt>{{domxref("WebGLRenderingContext.cullFace()")}}</dt> + <dd>Specifies whether or not front- and/or back-facing polygons can be culled.</dd> + <dt>{{domxref("WebGLRenderingContext.depthFunc()")}}</dt> + <dd>Specifies a function that compares incoming pixel depth to the current depth buffer value.</dd> + <dt>{{domxref("WebGLRenderingContext.depthMask()")}}</dt> + <dd>Sets whether writing into the depth buffer is enabled or disabled.</dd> + <dt>{{domxref("WebGLRenderingContext.depthRange()")}}</dt> + <dd>Specifies the depth range mapping from normalized device coordinates to window or viewport coordinates.</dd> + <dt>{{domxref("WebGLRenderingContext.disable()")}}</dt> + <dd>Disables specific WebGL capabilities for this context.</dd> + <dt>{{domxref("WebGLRenderingContext.enable()")}}</dt> + <dd>Enables specific WebGL capabilities for this context.</dd> + <dt>{{domxref("WebGLRenderingContext.frontFace()")}}</dt> + <dd>Specifies whether polygons are front- or back-facing by setting a winding orientation.</dd> + <dt>{{domxref("WebGLRenderingContext.getParameter()")}}</dt> + <dd>Returns a value for the passed parameter name.</dd> + <dt>{{domxref("WebGLRenderingContext.getError()")}}</dt> + <dd>Returns error information.</dd> + <dt>{{domxref("WebGLRenderingContext.hint()")}}</dt> + <dd>Specifies hints for certain behaviors. The interpretation of these hints depend on the implementation.</dd> + <dt>{{domxref("WebGLRenderingContext.isEnabled()")}}</dt> + <dd>Tests whether a specific WebGL capability is enabled or not for this context.</dd> + <dt>{{domxref("WebGLRenderingContext.lineWidth()")}}</dt> + <dd>Sets the line width of rasterized lines.</dd> + <dt>{{domxref("WebGLRenderingContext.pixelStorei()")}}</dt> + <dd>Specifies the pixel storage modes</dd> + <dt>{{domxref("WebGLRenderingContext.polygonOffset()")}}</dt> + <dd>Specifies the scale factors and units to calculate depth values.</dd> + <dt>{{domxref("WebGLRenderingContext.sampleCoverage()")}}</dt> + <dd>Specifies multi-sample coverage parameters for anti-aliasing effects.</dd> + <dt>{{domxref("WebGLRenderingContext.stencilFunc()")}}</dt> + <dd>Sets the both front and back function and reference value for stencil testing.</dd> + <dt>{{domxref("WebGLRenderingContext.stencilFuncSeparate()")}}</dt> + <dd>Sets the front and/or back function and reference value for stencil testing.</dd> + <dt>{{domxref("WebGLRenderingContext.stencilMask()")}}</dt> + <dd>Controls enabling and disabling of both the front and back writing of individual bits in the stencil planes.</dd> + <dt>{{domxref("WebGLRenderingContext.stencilMaskSeparate()")}}</dt> + <dd>Controls enabling and disabling of front and/or back writing of individual bits in the stencil planes.</dd> + <dt>{{domxref("WebGLRenderingContext.stencilOp()")}}</dt> + <dd>Sets both the front and back-facing stencil test actions.</dd> + <dt>{{domxref("WebGLRenderingContext.stencilOpSeparate()")}}</dt> + <dd>Sets the front and/or back-facing stencil test actions.</dd> +</dl> + +<h2 id="Buffers"><em>Buffers</em></h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.bindBuffer()")}}</dt> + <dd>Binds a <code>WebGLBuffer</code> object to a given target.</dd> + <dt>{{domxref("WebGLRenderingContext.bufferData()")}}</dt> + <dd>Updates buffer data.</dd> + <dt>{{domxref("WebGLRenderingContext.bufferSubData()")}}</dt> + <dd>Updates buffer data starting at a passed offset.</dd> + <dt>{{domxref("WebGLRenderingContext.createBuffer()")}}</dt> + <dd>Creates a <code>WebGLBuffer</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.deleteBuffer()")}}</dt> + <dd>Deletes a <code>WebGLBuffer</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.getBufferParameter()")}}</dt> + <dd>Returns information about the buffer.</dd> + <dt>{{domxref("WebGLRenderingContext.isBuffer()")}}</dt> + <dd>Returns a Boolean indicating if the passed buffer is valid.</dd> +</dl> + +<h2 id="Framebuffers"><em>Framebuffers</em></h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.bindFramebuffer()")}}</dt> + <dd>Binds a <code>WebGLFrameBuffer</code> object to a given target.</dd> + <dt>{{domxref("WebGLRenderingContext.checkFramebufferStatus()")}}</dt> + <dd>Returns the status of the framebuffer.</dd> + <dt>{{domxref("WebGLRenderingContext.createFramebuffer()")}}</dt> + <dd>Creates a <code>WebGLFrameBuffer</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.deleteFramebuffer()")}}</dt> + <dd>Deletes a <code>WebGLFrameBuffer</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.framebufferRenderbuffer()")}}</dt> + <dd>Attaches a <code>WebGLRenderingBuffer</code> object to a <code>WebGLFrameBuffer</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.framebufferTexture2D()")}}</dt> + <dd>Attaches a textures image to a <code>WebGLFrameBuffer</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()")}}</dt> + <dd>Returns information about the framebuffer.</dd> + <dt>{{domxref("WebGLRenderingContext.isFramebuffer()")}}</dt> + <dd>Returns a Boolean indicating if the passed <code>WebGLFrameBuffer</code> object is valid.</dd> + <dt>{{domxref("WebGLRenderingContext.readPixels()")}}</dt> + <dd>Reads a block of pixels from the <code>WebGLFrameBuffer</code>.</dd> +</dl> + +<h2 id="Renderbuffers"><em>Renderbuffers</em></h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.bindRenderbuffer()")}}</dt> + <dd>Binds a <code>WebGLRenderBuffer</code> object to a given target.</dd> + <dt>{{domxref("WebGLRenderingContext.createRenderbuffer()")}}</dt> + <dd>Creates a <code>WebGLRenderBuffer</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.deleteRenderbuffer()")}}</dt> + <dd>Deletes a <code>WebGLRenderBuffer</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.getRenderbufferParameter()")}}</dt> + <dd>Returns information about the renderbuffer.</dd> + <dt>{{domxref("WebGLRenderingContext.isRenderbuffer()")}}</dt> + <dd>Returns a Boolean indicating if the passed <code>WebGLRenderingBuffer</code> is valid.</dd> + <dt>{{domxref("WebGLRenderingContext.renderbufferStorage()")}}</dt> + <dd>Creates a renderbuffer data store.</dd> +</dl> + +<h2 id="Texturas">Texturas</h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.bindTexture()")}}</dt> + <dd>Binds a <code>WebGLTexture</code> object to a given target.</dd> + <dt>{{domxref("WebGLRenderingContext.compressedTexImage2D()")}}</dt> + <dd>Specifies a 2D texture image in a compressed format.</dd> + <dt>{{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}}</dt> + <dd>Specifies a 2D texture sub-image in a compressed format.</dd> + <dt>{{domxref("WebGLRenderingContext.copyTexImage2D()")}}</dt> + <dd>Copies a 2D texture image.</dd> + <dt>{{domxref("WebGLRenderingContext.copyTexSubImage2D()")}}</dt> + <dd>Copies a 2D texture sub-image.</dd> + <dt>{{domxref("WebGLRenderingContext.createTexture()")}}</dt> + <dd>Creates a <code>WebGLTexture</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.deleteTexture()")}}</dt> + <dd>Deletes a <code>WebGLTexture</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.generateMipmap()")}}</dt> + <dd>Generates a set of mipmaps for a <code>WebGLTexture</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.getTexParameter()")}}</dt> + <dd>Returns information about the texture.</dd> + <dt>{{domxref("WebGLRenderingContext.isTexture()")}}</dt> + <dd>Returns a Boolean indicating if the passed <code>WebGLTexture</code> is valid.</dd> + <dt>{{domxref("WebGLRenderingContext.texImage2D()")}}</dt> + <dd>Specifies a 2D texture image.</dd> + <dt>{{domxref("WebGLRenderingContext.texSubImage2D()")}}</dt> + <dd>Updates a sub-rectangle of the current <code>WebGLTexture</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.texParameter", "WebGLRenderingContext.texParameterf()")}}</dt> + <dd>Sets texture parameters.</dd> + <dt>{{domxref("WebGLRenderingContext.texParameter", "WebGLRenderingContext.texParameteri()")}}</dt> + <dd>Sets texture parameters.</dd> +</dl> + +<h2 id="Programas_e_shaders">Programas e <em>shaders</em></h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.attachShader()")}}</dt> + <dd>Attaches a <code>WebGLShader</code> to a <code>WebGLProgram</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.bindAttribLocation()")}}</dt> + <dd>Binds a generic vertex index to a named attribute variable.</dd> + <dt>{{domxref("WebGLRenderingContext.compileShader()")}}</dt> + <dd>Compiles a <code>WebGLShader</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.createProgram()")}}</dt> + <dd>Creates a <code>WebGLProgram</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.createShader()")}}</dt> + <dd>Creates a <code>WebGLShader</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.deleteProgram()")}}</dt> + <dd>Deletes a <code>WebGLProgram</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.deleteShader()")}}</dt> + <dd>Deletes a <code>WebGLShader</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.detachShader()")}}</dt> + <dd>Detaches a <code>WebGLShader</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.getAttachedShaders()")}}</dt> + <dd>Returns a list of <code>WebGLShader</code> objects attached to a <code>WebGLProgram</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.getProgramParameter()")}}</dt> + <dd>Returns information about the program.</dd> + <dt>{{domxref("WebGLRenderingContext.getProgramInfoLog()")}}</dt> + <dd>Returns the information log for a <code>WebGLProgram</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.getShaderParameter()")}}</dt> + <dd>Returns information about the shader.</dd> + <dt>{{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}}</dt> + <dd>Returns a <code>WebGLShaderPrecisionFormat</code> object describing the precision for the numeric format of the shader.</dd> + <dt>{{domxref("WebGLRenderingContext.getShaderInfoLog()")}}</dt> + <dd>Returns the information log for a <code>WebGLShader</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.getShaderSource()")}}</dt> + <dd>Returns the source code of a <code>WebGLShader</code> as a string.</dd> + <dt>{{domxref("WebGLRenderingContext.isProgram()")}}</dt> + <dd>Returns a Boolean indicating if the passed <code>WebGLProgram</code> is valid.</dd> + <dt>{{domxref("WebGLRenderingContext.isShader()")}}</dt> + <dd>Returns a Boolean indicating if the passed <code>WebGLShader</code> is valid.</dd> + <dt>{{domxref("WebGLRenderingContext.linkProgram()")}}</dt> + <dd>Links the passed <code>WebGLProgram</code> object.</dd> + <dt>{{domxref("WebGLRenderingContext.shaderSource()")}}</dt> + <dd>Sets the source code in a <code>WebGLShader</code>.</dd> + <dt>{{domxref("WebGLRenderingContext.useProgram()")}}</dt> + <dd>Uses the specified <code>WebGLProgram</code> as part the current rendering state.</dd> + <dt>{{domxref("WebGLRenderingContext.validateProgram()")}}</dt> + <dd>Validates a <code>WebGLProgram</code>.</dd> +</dl> + +<h2 id="Uniforms_e_atributos"><em>Uniforms </em>e atributos</h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.disableVertexAttribArray()")}}</dt> + <dd>Disables a vertex attribute array at a given position.</dd> + <dt>{{domxref("WebGLRenderingContext.enableVertexAttribArray()")}}</dt> + <dd>Enables a vertex attribute array at a given position.</dd> + <dt>{{domxref("WebGLRenderingContext.getActiveAttrib()")}}</dt> + <dd>Returns information about an active attribute variable.</dd> + <dt>{{domxref("WebGLRenderingContext.getActiveUniform()")}}</dt> + <dd>Returns information about an active uniform variable.</dd> + <dt>{{domxref("WebGLRenderingContext.getAttribLocation()")}}</dt> + <dd>Returns the location of an attribute variable.</dd> + <dt>{{domxref("WebGLRenderingContext.getUniform()")}}</dt> + <dd>Returns the value of a uniform variable at a given location.</dd> + <dt>{{domxref("WebGLRenderingContext.getUniformLocation()")}}</dt> + <dd>Returns the location of a uniform variable.</dd> + <dt>{{domxref("WebGLRenderingContext.getVertexAttrib()")}}</dt> + <dd>Returns information about a vertex attribute at a given position.</dd> + <dt>{{domxref("WebGLRenderingContext.getVertexAttribOffset()")}}</dt> + <dd>Returns the address of a given vertex attribute.</dd> + <dt>{{domxref("WebGLRenderingContext.uniform()", "WebGLRenderingContext.uniform[1234][fi][v]()")}}</dt> + <dd>Specifies a value for a uniform variable.</dd> + <dt>{{domxref("WebGLRenderingContext.uniformMatrix()", "WebGLRenderingContext.uniformMatrix[234]fv()")}}</dt> + <dd>Specifies a matrix value for a uniform variable.</dd> + <dt>{{domxref("WebGLRenderingContext.vertexAttrib()", "WebGLRenderingContext.vertexAttrib[1234]f[v]()")}}</dt> + <dd>Specifies a value for a generic vertex attribute.</dd> + <dt>{{domxref("WebGLRenderingContext.vertexAttribPointer()")}}</dt> + <dd>Specifies the data formats and locations of vertex attributes in a vertex attributes array.</dd> +</dl> + +<h2 id="Drawing_buffers">Drawing buffers</h2> + +<dl> + <dt>{{domxref("WebGLRenderingContext.clear()")}}</dt> + <dd>Clears specified buffers to preset values.</dd> + <dt>{{domxref("WebGLRenderingContext.drawArrays()")}}</dt> + <dd>Renders primitives from array data.</dd> + <dt>{{domxref("WebGLRenderingContext.drawElements()")}}</dt> + <dd>Renders primitives from element array data.</dd> + <dt>{{domxref("WebGLRenderingContext.finish()")}}</dt> + <dd>Blocks execution until all previously called commands are finished.</dd> + <dt>{{domxref("WebGLRenderingContext.flush()")}}</dt> + <dd>Empties different buffer commands, causing all commands to be executed as quickly as possible.</dd> +</dl> + +<h2 id="Trabalhar_com_extensões">Trabalhar com extensões</h2> + +<p>These methods manage WebGL extensions:</p> + +<dl> + <dt>{{domxref("WebGLRenderingContext.getSupportedExtensions()")}}</dt> + <dd>Returns an {{jsxref("Array")}} of {{domxref("DOMString")}} elements with all the supported WebGL extensions.</dd> + <dt>{{domxref("WebGLRenderingContext.getExtension()")}}</dt> + <dd>Returns an extension object.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="WebGL_context_feature_detection">WebGL context feature detection</h3> + +<p>{{page("/en-US/Learn/WebGL/By_example/Detect_WebGL", "summary")}}</p> + +<p>{{page("/en-US/Learn/WebGL/By_example/Detect_WebGL", "detect-webgl-source")}}</p> + +<p>{{EmbedLiveSample("detect-webgl-source", 660,150 ,"" , "Learn/WebGL/By_example/Detect_WebGL")}}</p> + +<h3 id="Effect_of_canvas_size_on_rendering_with_WebGL">Effect of canvas size on rendering with WebGL</h3> + +<p>{{page("/en-US/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-intro")}}</p> + +<p>{{page("/en-US/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-source")}}</p> + +<p>{{EmbedLiveSample("canvas-size-and-webgl-source", 660,180 ,"" , "Learn/WebGL/By_example/Canvas_size_and_WebGL")}}</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}</td> + <td>{{Spec2('WebGL')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("api.WebGLRenderingContext")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{domxref("HTMLCanvasElement")}}</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/websocket/index.html b/files/pt-pt/web/api/websocket/index.html new file mode 100644 index 0000000000..9820afc0b5 --- /dev/null +++ b/files/pt-pt/web/api/websocket/index.html @@ -0,0 +1,148 @@ +--- +title: WebSocket +slug: Web/API/WebSocket +tags: + - API + - Interface + - WebSocket + - WebSockets +translation_of: Web/API/WebSocket +--- +<div>{{APIRef("Web Sockets API")}}</div> + +<p>O objeto <code>WebSocket</code> fornece a API para criar e gerir uma ligação <a href="/pt-PT/docs/Web/API/WebSockets_API">WebSocket</a> a um servidor, bem como para enviar e receber dados sobre a ligação.</p> + +<p>Para criar uma <code>WebSocket</code>, use o construtor <code><a href="/pt-PT/docs/Web/API/WebSocket/WebSocket">WebSocket()</a></code>.</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("WebSocket.WebSocket", "WebSocket(url[, protocols])")}}</dt> + <dd>Devolve um objeto <code>WebSocket</code> acabado de criar.</dd> +</dl> + +<h2 id="Constantes">Constantes</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Constante</td> + <td class="header">Valor</td> + </tr> + <tr> + <td><code>WebSocket.CONNECTING</code></td> + <td><code>0</code></td> + </tr> + <tr> + <td><code>WebSocket.OPEN</code></td> + <td><code>1</code></td> + </tr> + <tr> + <td><code>WebSocket.CLOSING</code></td> + <td><code>2</code></td> + </tr> + <tr> + <td><code>WebSocket.CLOSED</code></td> + <td><code>3</code></td> + </tr> + </tbody> +</table> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{domxref("WebSocket.binaryType")}}</dt> + <dd>O tipo de dados binarios usado pela conexão.</dd> + <dt>{{domxref("WebSocket.bufferedAmount")}} {{readonlyinline}}</dt> + <dd>O numero de bytes de dados em fila.</dd> + <dt>{{domxref("WebSocket.extensions")}} {{readonlyinline}}</dt> + <dd>As extensões selecionadas pelo servidor.</dd> + <dt>{{domxref("WebSocket.onclose")}}</dt> + <dd>Um <em>event listener</em> para ser chamado quando a ligação terminar.</dd> + <dt>{{domxref("WebSocket.onerror")}}</dt> + <dd>Um <em>event listener</em> para ser chamado quando um erro ocorre.</dd> + <dt>{{domxref("WebSocket.onmessage")}}</dt> + <dd>Um <em>event listener</em> para ser chamado quando uma mensagem é recebida do servidor.</dd> + <dt>{{domxref("WebSocket.onopen")}}</dt> + <dd>Um <em>event listener</em> para ser chamado quando a ligação é iniciada.</dd> + <dt>{{domxref("WebSocket.protocol")}} {{readonlyinline}}</dt> + <dd>O sub-protocolo selecionado pelo servidor.</dd> + <dt>{{domxref("WebSocket.readyState")}} {{readonlyinline}}</dt> + <dd>O estado atual da conexão.</dd> + <dt>{{domxref("WebSocket.url")}} {{readonlyinline}}</dt> + <dd>O URL absoluto da WebSocket.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("WebSocket.close", "WebSocket.close([code[, reason]])")}}</dt> + <dd>Termina a conexão.</dd> + <dt>{{domxref("WebSocket.send", "WebSocket.send(data)")}}</dt> + <dd>Adiciona dados à fila para ser transmitida.</dd> +</dl> + +<h2 id="Eventos">Eventos</h2> + +<p>Observe estes eventos usando <code>addEventListener()</code> ou atribuindo um agente de escuta de eventos à propriedade <code>oneventname</code> desta interface.</p> + +<dl> + <dt>{{domxref("WebSocket/close_event", "close")}}</dt> + <dd>Lançado quando uma ligação com um <code>WebSocket</code> é fechada.<br> + Também disponível através da propriedade {{domxref("WebSocket/onclose", "onclose")}}.</dd> + <dt>{{domxref("WebSocket/error_event", "error")}}</dt> + <dd>Lançado quando uma ligação com um <code>WebSocket</code> foi fechada devido a um erro, como quando alguns dados não puderam ser enviados.<br> + Também disponível através da propriedade {{domxref("WebSocket/onerror", "onerror")}}.</dd> + <dt>{{domxref("WebSocket/message_event", "message")}}</dt> + <dd>Lançado quando os dados são recebidos através de um <code>WebSocket</code>.<br> + Também disponível através da propriedade {{domxref("WebSocket/onmessage", "onmessage")}}.</dd> + <dt>{{domxref("WebSocket/open_event", "open")}}</dt> + <dd>Lançado quando uma ligação com um <code>WebSocket</code> é aberta.<br> + Também disponível através da propriedade {{domxref("WebSocket/onopen", "onopen")}}.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js notranslate">// Criar ligação WebSocket. +const socket = new WebSocket('ws://localhost:8080'); + +// Ligação conectada +socket.addEventListener('open', function (event) { + socket.send('Hello Server!'); +}); + +// Ficar a ouvir por mensagens +socket.addEventListener('message', function (event) { + console.log('Message from server ', event.data); +});</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th>Especificação</th> + <th>Estado</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("HTML WHATWG", "#network", "WebSocket")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("api.WebSocket")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_aplica%C3%A7%C3%A3o_cliente_de_WebSocket">Escrever aplicação cliente de WebSocket</a></li> +</ul> diff --git a/files/pt-pt/web/api/websocket/websocket/index.html b/files/pt-pt/web/api/websocket/websocket/index.html new file mode 100644 index 0000000000..6c7a39f7ac --- /dev/null +++ b/files/pt-pt/web/api/websocket/websocket/index.html @@ -0,0 +1,59 @@ +--- +title: WebSocket() +slug: Web/API/WebSocket/WebSocket +tags: + - API + - Construtor + - Referencia + - Web API + - WebSocket +translation_of: Web/API/WebSocket/WebSocket +--- +<p>{{APIRef("Web Sockets API")}}</p> + +<p>O construtor <code><strong>WebSocket()</strong></code> devolve um novo objeto de {{domxref("WebSocket")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">var <em>aWebSocket</em> = new WebSocket(<em>url</em> [, protocols]);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>url</code></dt> + <dd>O URL a qual se conectar; este deve ser o URL a qual o servidor WebSocket responderá.</dd> + <dt><code>protocols</code> {{optional_inline}}</dt> + <dd>Uma <em>string</em> ou uma matriz de <em>strings</em> que representam protocolos. Estas <em>strings</em> representam sub-protocolos, para que um servidor possa implementar vários sub-protocolos WebSocket (por exemplo, pode querer que um servidor seja capaz de lidar com diferentes tipos de interações dependendo do <code>protocol</code> indicado). Se não é dado um valor ao parâmetro, fica pré-definido como uma <em>string</em> vazia.</dd> +</dl> + +<h3 id="Exceções_lançadas">Exceções lançadas</h3> + +<dl> + <dt><code>SECURITY_ERR</code></dt> + <dd>A porta a qual a que se está a tentar ligar está bloqueada.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></dt> + <dd>O URL é invalido.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', '#dom-websocket', 'the WebSocket constructor')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.WebSocket.WebSocket")}}</p> diff --git a/files/pt-pt/web/api/websockets_api/escrever_aplicação_cliente_de_websocket/index.html b/files/pt-pt/web/api/websockets_api/escrever_aplicação_cliente_de_websocket/index.html new file mode 100644 index 0000000000..c66e10ceaf --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/escrever_aplicação_cliente_de_websocket/index.html @@ -0,0 +1,180 @@ +--- +title: Escrever aplicação cliente de WebSocket +slug: Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket +tags: + - Client + - Exemplo + - Guía + - Networking + - Web Sockets API + - WebSocket + - WebSocket API + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications +--- +<div>{{APIRef("Websockets API")}}</div> + +<p>WebSocket client applications use the <a href="/en-US/docs/Web/API/Websockets_API">WebSocket API</a> to communicate with <a href="/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers">WebSocket servers</a> using the WebSocket protocol.</p> + +<p>{{AvailableInWorkers}}</p> + +<div class="note"> +<p><strong>Note:</strong> The example snippets in this article are taken from our WebSocket chat client/server sample. <a href="https://github.com/mdn/samples-server/tree/master/s/websocket-chat">See the code</a>, then <a href="https://mdn-samples.mozilla.org/s/websocket-chat">try out the example for yourself</a>.</p> +</div> + +<h2 id="Creating_a_WebSocket_object">Creating a WebSocket object</h2> + +<p>In order to communicate using the WebSocket protocol, you need to create a {{domxref("WebSocket")}} object; this will automatically attempt to open the connection to the server.</p> + +<p>The WebSocket constructor accepts one required and one optional parameter:</p> + +<pre class="syntaxbox notranslate"><em>webSocket</em> = new WebSocket(<em>url</em>, <em>protocols</em>); +</pre> + +<dl> + <dt><code>url</code></dt> + <dd>The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme <code>wss://</code>, although some software may allow you to use the insecure <code>ws://</code> for local connections.</dd> + <dt><code>protocols</code> {{ optional_inline() }}</dt> + <dd>Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified <code>protocol</code>). If you don't specify a protocol string, an empty string is assumed.</dd> +</dl> + +<p>The constructor will throw a <code>SecurityError</code> if the destination doesn't allow access. This may happen if you attempt to use an insecure connection (most {{Glossary("user agent", "user agents")}} now require a secure link for all WebSocket connections unless they're on the same device or possibly on the same network).</p> + +<h3 id="Connection_errors">Connection errors</h3> + +<p>If an error occurs while attempting to connect, first a simple event with the name <code>error</code> is sent to the {{domxref("WebSocket")}} object (thereby invoking its {{domxref("WebSocket.onerror", "onerror")}} handler), and then the {{domxref("CloseEvent")}} is sent to the <code>WebSocket</code> object (thereby invoking its {{domxref("WebSocket.onclose", "onclose")}} handler) to indicate the reason for the connection's closing.</p> + +<p>The browser may also output to its console a more descriptive error message as well as a closing code as defined in <a class="external" href="http://tools.ietf.org/html/rfc6455#section-7.4" title="RFC 6455 Section 7.4">RFC 6455, Section 7.4</a> through the {{domxref("CloseEvent")}}.</p> + +<h3 id="Examples">Examples</h3> + +<p>This simple example creates a new WebSocket, connecting to the server at <code><span class="nowiki">wss://www.example.com/socketserver</span></code>. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.</p> + +<pre class="brush: js notranslate">var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne"); +</pre> + +<p>On return, {{domxref("WebSocket.readyState", "exampleSocket.readyState")}} is <code>CONNECTING</code>. The <code>readyState</code> will become <code>OPEN</code> once the connection is ready to transfer data.</p> + +<p>If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:</p> + +<pre class="brush: js notranslate">var exampleSocket = new WebSocket("wss://www.example.com/socketserver", ["protocolOne", "protocolTwo"]); +</pre> + +<p>Once the connection is established (that is, <code>readyState</code> is <code>OPEN</code>), {{domxref("WebSocket.protocol", "exampleSocket.protocol")}} will tell you which protocol the server selected.</p> + +<p>Establishing a WebSocket relies on the <a href="/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism">HTTP Upgrade mechanism</a>, so the request for the protocol upgrade is implicit when we address the web server as <code><span class="nowiki">ws://www.example.com</span></code> or <code><span class="nowiki">wss://www.example.com</span></code>.</p> + +<h2 id="Sending_data_to_the_server">Sending data to the server</h2> + +<p>Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the <code>WebSocket</code> object's {{domxref("WebSocket.send", "send()")}} method for each message you want to send:</p> + +<pre class="brush: js notranslate">exampleSocket.send("Here's some text that the server is urgently awaiting!"); +</pre> + +<p>You can send data as a string, {{ domxref("Blob") }}, or {{jsxref("ArrayBuffer")}}.</p> + +<p>As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the <code>send()</code> method immediately after creating a WebSocket object will be successful. We can at least be sure that attempting to send data only takes place once a connection is established by defining an {{domxref("WebSocket.onopen", "onopen")}} event handler to do the work:</p> + +<pre class="brush: js notranslate">exampleSocket.onopen = function (event) { + exampleSocket.send("Here's some text that the server is urgently awaiting!"); +}; +</pre> + +<h3 id="Using_JSON_to_transmit_objects">Using JSON to transmit objects</h3> + +<p>One handy thing you can do is use {{glossary("JSON")}} to send reasonably complex data to the server. For example, a chat program can interact with a server using a protocol implemented using packets of JSON-encapsulated data:</p> + +<pre class="brush: js notranslate">// Send text to all users through the server +function sendText() { + // Construct a msg object containing the data the server needs to process the message from the chat client. + var msg = { + type: "message", + text: document.getElementById("text").value, + id: clientID, + date: Date.now() + }; + + // Send the msg object as a JSON-formatted string. + exampleSocket.send(JSON.stringify(msg)); + + // Blank the text input element, ready to receive the next line of text from the user. + document.getElementById("text").value = ""; +} +</pre> + +<h2 id="Receiving_messages_from_the_server">Receiving messages from the server</h2> + +<p>WebSockets is an event-driven API; when messages are received, a <code>message</code> event is sent to the <code>WebSocket</code> object. To handle it, add an event listener for the <code>message</code> event, or use the {{domxref("WebSocket.onmessage", "onmessage")}} event handler. To begin listening for incoming data, you can do something like this:</p> + +<pre class="brush: js notranslate">exampleSocket.onmessage = function (event) { + console.log(event.data); +} +</pre> + +<h3 id="Receiving_and_interpreting_JSON_objects">Receiving and interpreting JSON objects</h3> + +<p>Let's consider the chat client application first alluded to in {{ anch("Using JSON to transmit objects") }}. There are assorted types of data packets the client might receive, such as:</p> + +<ul> + <li>Login handshake</li> + <li>Message text</li> + <li>User list updates</li> +</ul> + +<p>The code that interprets these incoming messages might look like this:</p> + +<pre class="brush: js notranslate">exampleSocket.onmessage = function(event) { + var f = document.getElementById("chatbox").contentDocument; + var text = ""; + var msg = JSON.parse(event.data); + var time = new Date(msg.date); + var timeStr = time.toLocaleTimeString(); + + switch(msg.type) { + case "id": + clientID = msg.id; + setUsername(); + break; + case "username": + text = "<b>User <em>" + msg.name + "</em> signed in at " + timeStr + "</b><br>"; + break; + case "message": + text = "(" + timeStr + ") <b>" + msg.name + "</b>: " + msg.text + "<br>"; + break; + case "rejectusername": + text = "<b>Your username has been set to <em>" + msg.name + "</em> because the name you chose is in use.</b><br>" + break; + case "userlist": + var ul = ""; + for (i=0; i < msg.users.length; i++) { + ul += msg.users[i] + "<br>"; + } + document.getElementById("userlistbox").innerHTML = ul; + break; + } + + if (text.length) { + f.write(text); + document.getElementById("chatbox").contentWindow.scrollByPages(1); + } +}; +</pre> + +<p>Here we use {{jsxref("JSON.parse()")}} to convert the JSON object back into the original object, then examine and act upon its contents.</p> + +<h3 id="Text_data_format">Text data format</h3> + +<p>Text received over a WebSocket connection is in UTF-8 format.</p> + +<h2 id="Closing_the_connection">Closing the connection</h2> + +<p>When you've finished using the WebSocket connection, call the WebSocket method {{domxref("WebSocket.close", "close()")}}:</p> + +<pre class="brush: js notranslate">exampleSocket.close(); +</pre> + +<p>It may be helpful to examine the socket's {{domxref("WebSocket.bufferedAmount", "bufferedAmount")}} attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. If this value isn't 0, there's pending data still, so you may wish to wait before closing the connection.</p> + +<h2 id="Security_considerations">Security considerations</h2> + +<p>WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure WebSocket connection from a page loaded using HTTPS or vice-versa. Most browsers now only allow secure WebSocket connections, and no longer support using them in insecure contexts.</p> diff --git a/files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html b/files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html new file mode 100644 index 0000000000..7f3b996573 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html @@ -0,0 +1,257 @@ +--- +title: Escrever servidores de WebSocket +slug: Web/API/WebSockets_API/Escrever_servidores_de_WebSocket +tags: + - Guía + - HTML5 + - Tutorial + - WebSocket + - WebSocket API + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_servers +--- +<div>{{APIRef("Websockets API")}}</div> + +<p>Um servidor WebSocket não é nada mais que uma aplicação que escuta qualquer porta de um servidor TCP que possui um protocolo específico. A tarefa de criar um servidor personalizado é uma tarefa complexa para a maioria; no entanto, é simples implementar um servidor simples de WebSocket numa plataforma á sua escolha.</p> + +<p>Um servidor WebSocket pode ser escrito em qualquer linguagem de servidor que suporte <a href="https://en.wikipedia.org/wiki/Berkeley_sockets">Berkeley sockets</a>, como C(++), Python, PHP, ou <a href="/en-US/docs/Web/JavaScript/Server-Side_JavaScript">server-side JavaScript</a>. Este tutorial não se foca em nenhuma linguagem em específico, mas serve como guia para facilitar o desenvolver do seu próprio server.</p> + +<p>A WebSocket server can be written in any server-side programming language that is capable of <a href="https://en.wikipedia.org/wiki/Berkeley_sockets">Berkeley sockets</a>, such as C(++), Python, <a href="/en-US/docs/PHP">PHP</a>, or <a href="/en-US/docs/Web/JavaScript/Server-Side_JavaScript">server-side JavaScript</a>. This is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server.</p> + +<p>This article assumes you're already familiar with how {{Glossary("HTTP")}} works, and that you have a moderate level of programming experience. Depending on language support, knowledge of TCP sockets may be required. The scope of this guide is to present the minimum knowledge you need to write a WebSocket server.</p> + +<div class="note"> +<p><strong>Note:</strong> Read the latest official WebSockets specification, <a href="http://datatracker.ietf.org/doc/rfc6455/?include_text=1">RFC 6455</a>. Sections 1 and 4-7 are especially interesting to server implementors. Section 10 discusses security and you should definitely peruse it before exposing your server.</p> +</div> + +<p>A WebSocket server is explained on a very low level here. WebSocket servers are often separate and specialized servers (for load-balancing or other practical reasons), so you will often use a <a href="https://en.wikipedia.org/wiki/Reverse_proxy">reverse proxy</a> (such as a regular HTTP server) to detect WebSocket handshakes, pre-process them, and send those clients to a real WebSocket server. This means that you don't have to bloat your server code with cookie and authentication handlers (for example).</p> + +<h2 id="The_WebSocket_handshake">The WebSocket handshake</h2> + +<p>First, the server must listen for incoming socket connections using a standard TCP socket. Depending on your platform, this may be handled for you automatically. For example, let's assume that your server is listening on <code>example.com</code>, port 8000, and your socket server responds to {{HTTPMethod("GET")}} requests at <code>example.com/chat</code>.</p> + +<div class="warning"> +<p><strong>Warning:</strong> The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.</p> +</div> + +<p>The handshake is the "Web" in WebSockets. It's the bridge from HTTP to WebSockets. In the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. The server must be careful to understand everything the client asks for, otherwise security issues can occur.</p> + +<div class="blockIndicator note"> +<p><strong>Tip:</strong> The request-uri (<code>/chat</code> here) has no defined meaning in the spec. So, many people use it to let one server handle multiple WebSocket applications. For example, <code>example.com/chat</code> could invoke a multiuser chat app, while <code>/game</code> on the same server might invoke a multiplayer game.</p> +</div> + +<h3 id="Client_handshake_request">Client handshake request</h3> + +<p>Even though you're building a server, a client still has to start the WebSocket handshake process by contacting the server and requesting a WebSocket connection. So, you must know how to interpret the client's request. The <strong>client</strong> will send a pretty standard HTTP request with headers that looks like this (the HTTP version <strong>must</strong> be 1.1 or greater, and the method <strong>must</strong> be <code>GET</code>):</p> + +<pre class="notranslate">GET /chat HTTP/1.1 +Host: example.com:8000 +<strong>Upgrade: websocket</strong> +<strong>Connection: Upgrade</strong> +Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== +Sec-WebSocket-Version: 13 + +</pre> + +<p>The client can solicit extensions and/or subprotocols here; see <a href="#Miscellaneous">Miscellaneous</a> for details. Also, common headers like {{HTTPHeader("User-Agent")}}, {{HTTPHeader("Referer")}}, {{HTTPHeader("Cookie")}}, or authentication headers might be there as well. Do whatever you want with those; they don't directly pertain to the WebSocket. It's also safe to ignore them. In many common setups, a reverse proxy has already dealt with them.</p> + +<div class="blockIndicator note"> +<p><strong>Tip:</strong> All <strong>browsers</strong> send an <a href="https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Origin"><code>Origin</code> header</a>. You can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a <a href="https://developer.mozilla.org/en-US/docs/HTTP/Response_codes#403">403 Forbidden</a> if you don't like what you see. However, be warned that non-browser agents can send a faked <code>Origin</code>. Most applications reject requests without this header.</p> +</div> + +<p>If any header is not understood or has an incorrect value, the server should send a {{HTTPStatus("400")}} ("Bad Request")} response and immediately close the socket. As usual, it may also give the reason why the handshake failed in the HTTP response body, but the message may never be displayed (browsers do not display it). If the server doesn't understand that version of WebSockets, it should send a {{HTTPHeader("Sec-WebSocket-Version")}} header back that contains the version(s) it does understand. In the example above, it indicates version 13 of the WebSocket protocol.</p> + +<p>The most interesting header here is {{HTTPHeader("Sec-WebSocket-Key")}}. Let's look at that next.</p> + +<div class="note"> +<p><strong>Note:</strong> <a href="https://developer.mozilla.org/en-US/docs/HTTP/Response_codes">Regular HTTP status codes</a> can be used only before the handshake. After the handshake succeeds, you have to use a different set of codes (defined in section 7.4 of the spec).</p> +</div> + +<h3 id="Server_handshake_response">Server handshake response</h3> + +<p>When the <strong>server</strong> receives the handshake request, it should send back a special response that indicates that the protocol will be changing from HTTP to WebSocket. That header looks something like the following (remember each header line ends with <code>\r\n</code> and put an extra <code>\r\n</code> after the last one to indicate the end of the header):</p> + +<pre class="notranslate"><strong>HTTP/1.1 101 Switching Protocols</strong> +Upgrade: websocket +Connection: Upgrade +<strong>Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= + +</strong></pre> + +<p>Additionally, the server can decide on extension/subprotocol requests here; see <a href="#Miscellaneous">Miscellaneous</a> for details. The <code>Sec-WebSocket-Accept</code> header is important in that the server must derive it from the {{HTTPHeader("Sec-WebSocket-Key")}} that the client sent to it. To get it, c<span style="line-height: 1.5em;">oncatenate the client's </span><code style="font-size: 14px;">Sec-WebSocket-Key</code><span style="line-height: 1.5em;"> and the string "</span><code style="font-size: 14px;">258EAFA5-E914-47DA-95CA-C5AB0DC85B11</code><span style="line-height: 1.5em;">" together (it's a "</span><a href="https://en.wikipedia.org/wiki/Magic_string" style="line-height: 1.5em;">magic string</a><span style="line-height: 1.5em;">"), </span><span style="line-height: 1.5em;">take the </span><a href="https://en.wikipedia.org/wiki/SHA-1" style="line-height: 1.5em;">SHA-1 hash</a><span style="line-height: 1.5em;"> of the result, and </span><span style="line-height: 1.5em;">return the </span><a href="https://en.wikipedia.org/wiki/Base64" style="line-height: 1.5em;">base64</a><span style="line-height: 1.5em;"> encoding of that hash.</span></p> + +<div class="note"> +<p><strong>Note:</strong> This seemingly overcomplicated process exists so that it's obvious to the client whether the server supports WebSockets. This is important because security issues might arise if the server accepts a WebSockets connection but interprets the data as a HTTP request.</p> +</div> + +<p>So if the Key was "<code>dGhlIHNhbXBsZSBub25jZQ==</code>", the <code>Sec-WebSocket-Accept</code> header's value is "<code>s3pPLMBiTxaQ9kYGzzhZRbK+xOo=</code>". Once the server sends these headers, the handshake is complete and you can start swapping data!</p> + +<div class="note"> +<p><strong>Note:</strong> The server can send other headers like {{HTTPHeader("Set-Cookie")}}, or ask for authentication or redirects via other status codes, before sending the reply handshake.</p> +</div> + +<h3 id="Keeping_track_of_clients">Keeping track of clients</h3> + +<p>This doesn't directly relate to the WebSocket protocol, but it's worth mentioning here: your server must keep track of clients' sockets so you don't keep handshaking again with clients who have already completed the handshake. The same client IP address can try to connect multiple times. However, the server can deny them if they attempt too many connections in order to save itself from <a href="https://en.wikipedia.org/wiki/Denial_of_service">Denial-of-Service attacks</a>.</p> + +<p>For example, you might keep a table of usernames or ID numbers along with the corresponding {{domxref("WebSocket")}} and other data that you need to associate with that connection.</p> + +<h2 id="Exchanging_data_frames">Exchanging data frames</h2> + +<p>Either the client or the server can choose to send a message at any time — that's the magic of WebSockets. However, extracting information from these so-called "frames" of data is a not-so-magical experience. Although all frames follow the same specific format, data going from the client to the server is masked using <a href="https://en.wikipedia.org/wiki/XOR_cipher">XOR encryption</a> (with a 32-bit key). Section 5 of the specification describes this in detail.</p> + +<h3 id="Format">Format</h3> + +<p>Each data frame (from the client to the server or vice-versa) follows this same format:</p> + +<pre class="notranslate">Frame format: + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-------+-+-------------+-------------------------------+ + |F|R|R|R| opcode|M| Payload len | Extended payload length | + |I|S|S|S| (4) |A| (7) | (16/64) | + |N|V|V|V| |S| | (if payload len==126/127) | + | |1|2|3| |K| | | + +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + | Extended payload length continued, if payload len == 127 | + + - - - - - - - - - - - - - - - +-------------------------------+ + | |Masking-key, if MASK set to 1 | + +-------------------------------+-------------------------------+ + | Masking-key (continued) | Payload Data | + +-------------------------------- - - - - - - - - - - - - - - - + + : Payload Data continued ... : + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + | Payload Data continued ... | + +---------------------------------------------------------------+</pre> + +<p>The MASK bit tells whether the message is encoded. Messages from the client must be masked, so your server must expect this to be 1. (In fact, <a href="http://tools.ietf.org/html/rfc6455#section-5.1">section 5.1 of the spec</a> says that your server must disconnect from a client if that client sends an unmasked message.) When sending a frame back to the client, do not mask it and do not set the mask bit. We'll explain masking later. <em>Note: You must mask messages even when using a secure socket. </em>RSV1-3 can be ignored, they are for extensions.</p> + +<p>The opcode field defines how to interpret the payload data: <span style="font-family: courier new,andale mono,monospace; line-height: 1.5;"><code>0x0</code> </span><span style="line-height: 1.5;">for continuation,</span><span style="font-family: courier new,andale mono,monospace; line-height: 1.5;"> </span><code style="font-style: normal; line-height: 1.5;">0x1</code><span style="line-height: 1.5;"> for text (which is always encoded in UTF-8), </span><code style="font-style: normal; line-height: 1.5;">0x2</code><span style="line-height: 1.5;"> for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, <code>0x3</code> to <code>0x7</code> and <code>0xB</code> to <code>0xF</code> have no meaning.</span></p> + +<p>The FIN bit tells whether this is the last message in a series. If it's 0, then the server keeps listening for more parts of the message; otherwise, the server should consider the message delivered. More on this later.</p> + +<h3 id="Decoding_Payload_Length">Decoding Payload Length</h3> + +<p>To read the payload data, you must know when to stop reading. That's why the payload length is important to know. Unfortunately, this is somewhat complicated. To read it, follow these steps:</p> + +<ol> + <li>Read bits 9-15 (inclusive) and interpret that as an unsigned integer. If it's 125 or less, then that's the length; you're <strong>done</strong>. If it's 126, go to step 2. If it's 127, go to step 3.</li> + <li>Read the next 16 bits and interpret those as an unsigned integer. You're <strong>done</strong>.</li> + <li>Read the next 64 bits and interpret those as an unsigned integer. (The most significant bit <em>must</em> be 0.) You're <strong>done</strong>.</li> +</ol> + +<h3 id="Reading_and_Unmasking_the_Data">Reading and Unmasking the Data</h3> + +<p>If the MASK bit was set (and it should be, for client-to-server messages), read the next 4 octets (32 bits); this is the masking key. <span style="line-height: 1.5;">Once the payload length and masking key is decoded, you can read that number of bytes from the socket. Let's call the data <strong>ENCODED</strong>, and the key <strong>MASK</strong>. To get <strong>DECODED</strong>, loop through the octets (bytes a.k.a. characters for text data) of <strong>ENCODED</strong> and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):</span></p> + +<pre class="notranslate">var DECODED = ""; +for (var i = 0; i < ENCODED.length; i++) { + DECODED[i] = ENCODED[i] ^ MASK[i % 4]; +<span style="line-height: 1.5;">}</span></pre> + +<p><span style="line-height: 1.5;">Now you can figure out what <strong>DECODED</strong> means depending on your application.</span></p> + +<h3 id="Message_Fragmentation">Message Fragmentation</h3> + +<p>The FIN and opcode fields work together to send a message split up into separate frames. This is called message fragmentation. Fragmentation is only available on opcodes <code>0x0</code> to <code>0x2</code>.</p> + +<p><span style="line-height: 1.5;">Recall that the opcode tells what a frame is meant to do. If it's <code>0x1</code>, the payload is text. If it's <code>0x2</code>, the payload is binary data.</span><span style="line-height: 1.5;"> However, if it's </span><code style="font-style: normal; line-height: 1.5;">0x0,</code><span style="line-height: 1.5;"> the frame is a continuation frame; this means the server should concatenate the frame's payload to the last frame it received from that client.</span><span style="line-height: 1.5;"> Here is a rough sketch, in which a server reacts to a client sending text messages. The first message is sent in a single frame, while the second message is sent across three frames. FIN and opcode details are shown only for the client:</span></p> + +<pre style="font-size: 14px;"><strong>Client:</strong> FIN=1, opcode=0x1, msg="hello" +<strong>Server:</strong> <em>(process complete message immediately) </em>Hi. +<strong>Client:</strong> FIN=0, opcode=0x1, msg="and a" +<strong>Server:</strong> <em>(listening, new message containing text started)</em> +<strong>Client:</strong> FIN=0, opcode=0x0, msg="happy new" +<strong>Server:</strong> <em>(listening, payload concatenated to previous message)</em> +<strong>Client:</strong> FIN=1, opcode=0x0, msg="year!" +<strong>Server:</strong> <em>(process complete message) </em>Happy new year to you too!</pre> + +<p>Notice the first frame contains an entire message (has <code>FIN=1</code> and <code>opcode!=0x0</code>), so the server can process or respond as it sees fit. The second frame sent by the client has a text payload (<code>opcode=0x1</code>), but the entire message has not arrived yet (<code>FIN=0</code>). All remaining parts of that message are sent with continuation frames (<code>opcode=0x0</code>), and the final frame of the message is marked by <code>FIN=1</code>. <a href="http://tools.ietf.org/html/rfc6455#section-5.4">Section 5.4 of the spec</a> describes message fragmentation.</p> + +<h2 id="Pings_and_Pongs_The_Heartbeat_of_WebSockets">Pings and Pongs: The Heartbeat of WebSockets</h2> + +<p>At any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.</p> + +<p>A ping or pong is just a regular frame, but it's a <strong>control frame</strong>. Pings have an opcode of <code>0x9</code>, and pongs have an opcode of <code>0xA</code>. When you get a ping, send back a pong with the exact same Payload Data as the ping (for pings and pongs, the max payload length is 125). You might also get a pong without ever sending a ping; ignore this if it happens.</p> + +<div class="note"> +<p>If you have gotten more than one ping before you get the chance to send a pong, you only send one pong.</p> +</div> + +<h2 id="Closing_the_connection">Closing the connection</h2> + +<p>To close a connection either the client or server can send a control frame with data containing a specified control sequence to begin the closing handshake (detailed in <a href="http://tools.ietf.org/html/rfc6455#section-5.5.1">Section 5.5.1</a>). Upon receiving such a frame, the other peer sends a Close frame in response. The first peer then closes the connection. Any further data received after closing of connection is then discarded. </p> + +<h2 id="Miscellaneous_2"><a name="Miscellaneous">Miscellaneous</a></h2> + +<div class="note"> +<p>WebSocket codes, extensions, subprotocols, etc. are registered at the <a href="http://www.iana.org/assignments/websocket/websocket.xml">IANA WebSocket Protocol Registry</a>.</p> +</div> + +<p>WebSocket extensions and subprotocols are negotiated via headers during <a href="#Handshake">the handshake</a>. Sometimes extensions and subprotocols very similar, but there is a clear distinction. Extensions control the WebSocket <em>frame</em> and <em>modify</em> the payload, while subprotocols structure the WebSocket <em>payload</em> and <em>never modify</em> anything. Extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for MMORPG games).</p> + +<h3 id="Extensions">Extensions</h3> + +<div class="note"> +<p><strong>This section needs expansion. Please edit if you are equipped to do so.</strong></p> +</div> + +<p>Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the <em>same</em> data in different forms. The recipient will eventually be able to get the same data as your local copy, but it is sent differently. That's what an extension does. WebSockets defines a protocol and a simple way to send data, but an extension such as compression could allow sending the same data but in a shorter format.</p> + +<div class="note"> +<p>Extensions are explained in sections 5.8, 9, 11.3.2, and 11.4 of the spec.</p> +</div> + +<p><em>TODO</em></p> + +<h3 id="Subprotocols">Subprotocols</h3> + +<p>Think of a subprotocol as a custom <a href="https://en.wikipedia.org/wiki/XML_schema">XML schema</a> or <a href="https://en.wikipedia.org/wiki/Document_Type_Definition">doctype declaration</a>. You're still using XML and its syntax, but you're additionally restricted by a structure you agreed on. WebSocket subprotocols are just like that. They do not introduce anything fancy, they just establish structure. Like a doctype or schema, both parties must agree on the subprotocol; unlike a doctype or schema, the subprotocol is implemented on the server and cannot be externally refered to by the client.</p> + +<div class="note"> +<p>Subprotocols are explained in sections 1.9, 4.2, 11.3.4, and 11.5 of the spec.</p> +</div> + +<p>A client has to ask for a specific subprotocol. To do so, it will send something like this <em>as part of the original handshake</em>:</p> + +<pre class="notranslate">GET /chat HTTP/1.1 +... +Sec-WebSocket-Protocol: soap, wamp + +</pre> + +<p>or, equivalently:</p> + +<pre class="notranslate">... +Sec-WebSocket-Protocol: soap +Sec-WebSocket-Protocol: wamp + +</pre> + +<p>Now the server must pick one of the protocols that the client suggested and it supports. If there is more than one, send the first one the client sent. Imagine our server can use both <code>soap</code> and <code>wamp</code>. Then, in the response handshake, it sends:</p> + +<pre class="notranslate">Sec-WebSocket-Protocol: soap + +</pre> + +<div class="warning"> +<p>The server can't send more than one <code>Sec-Websocket-Protocol</code> header.<br> + <span style="line-height: 1.5;">If the server doesn't want to use a</span><span style="line-height: 1.5;">ny subprotocol, </span><em><strong style="line-height: 1.5;">it shouldn't send any <code>Sec-WebSocket-Protocol</code> header</strong></em><span style="line-height: 1.5;">. Sending a blank header is incorrect. The client may close the connection if it doesn't get the subprotocol it wants.</span></p> +</div> + +<p>If you want your server to obey certain subprotocols, then naturally you'll need extra code on the server. Let's imagine we're using a subprotocol <code>json</code>. In this subprotocol, all data is passed as <a href="https://en.wikipedia.org/wiki/JSON">JSON</a>. If the client solicits this protocol and the server wants to use it, the server needs to have a JSON parser. Practically speaking, this will be part of a library, but the server needs to pass the data around.</p> + +<div class="note"> +<p><strong>Tip:</strong> To avoid name conflict, it's recommended to make your subprotocol name part of a domain string. If you are building a custom chat app that uses a proprietary format exclusive to Example Inc., then you might use this: <code>Sec-WebSocket-Protocol: chat.example.com</code>. Note that this isn't required, it's just an optional convention, and you can use any string you wish.</p> +</div> + +<h2 id="Related">Related</h2> + +<ul> + <li><a href="https://github.com/alexhultman/libwshandshake">WebSocket handshake library in C++</a></li> + <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_client_applications">Writing WebSocket client applications</a></li> + <li><a href="/en-US/docs/WebSockets/Writing_WebSocket_server" title="/en-US/docs/WebSockets/Writing_WebSocket_server">Tutorial: Websocket server in C#</a></li> + <li><a href="/en-US/docs/WebSockets/WebSocket_Server_Vb.NET">Tutorial: Websocket server in VB.NET</a></li> + <li><a href="/en-US/docs/Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java">Tutorial: Websocket server in Java</a></li> +</ul> diff --git a/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html b/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html new file mode 100644 index 0000000000..a76f81d660 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html @@ -0,0 +1,441 @@ +--- +title: Escrever um servidor WebSocket em C# +slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C +tags: + - HTML5 + - Tutorial + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_server +--- +<h2 id="Introdução">Introdução</h2> + +<p>Se desejar utilizar o WebSocket API, é útil dispor de um servidor. Neste artigo pode ver como escrever um em C#. Pode fazê-lo em qualquer língua do lado do servidor, mas para manter as coisas simples e mais compreensíveis, vamos usar a linguagem da Microsoft.</p> + +<p>Este servidor está em conformidade com o <a href="http://tools.ietf.org/html/rfc6455">RFC 6455</a>, pelo que só tratará de ligações a partir das versões de navegadores; Chrome 16, Firefox 11, e IE 10 ou superior.</p> + +<h2 id="Primeiros_passos">Primeiros passos</h2> + +<p>Os WebSockets comunicam através de uma ligação interwiki("wikipedia","Transmission_Control_Protocol","TCP (Transmission Control Protocol)"). Felizmente, C# tem uma classe TcpListener que serve para escutar ligações de TCP. Encontra-se no espaço de nomes <code>System.Net.Sockets</code>.</p> + +<div class="note"> +<p><span style="line-height: 1.572;"><strong>Nota:</strong> É aconselhável incluir o namespace com <code>using</code> a fim de escrever menos. Permite a utilização das classes de um namespace sem escrever sempre o namespace completo.</span></p> +</div> + +<h3 id="TcpListener">TcpListener</h3> + +<h4 id="Construtor">Construtor</h4> + +<dl> + <dt><code>TcpListener(System.Net.IPAddress localaddr, int port)</code></dt> + <dd><code>localaddr</code> indica o endereço IP do ouvinte e <code>port</code> indica a porta.</dd> +</dl> + +<div class="note"> +<p><span style="line-height: 1.572;"><strong>Nota:</strong> Para criar um objeto <code>IPAddress</code> a partir de uma <code>string</code>, use o método <em>static</em> </span><code>Parse</code><span style="line-height: 1.572;"> de </span><code>IPAddress</code><em>.</em></p> +</div> + +<h4 id="Métodos"><span style="line-height: 1.572;">Métodos</span></h4> + +<dl> + <dt><code><span style="line-height: 1.572;">Start()</span></code></dt> + <dd>Começa a escutar os pedidos de ligação recebidos.</dd> +</dl> + +<dl> + <dt><code><span style="line-height: 1.572;">AcceptTcpClient()</span></code></dt> + <dd>Espera por uma ligação TCP, aceita-a e devolve-a como um objeto <a href="https://docs.microsoft.com/pt-pt/dotnet/api/system.net.sockets.tcpclient">TcpClient</a>.</dd> +</dl> + +<h4 class="syntaxbox" id="Exemplo">Exemplo</h4> + +<p><span style="line-height: 1.572;">Aqui tem uma implementação básica do servidor:</span></p> + +<pre class="brush: cpp notranslate">using System.Net.Sockets; +using System.Net; +using System; + +class Server { + public static void Main() { + TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80); + + server.Start(); + Console.WriteLine("O servidor começou com endreço 127.0.0.1:80.{0}Esperando por uma conexão...", Environment.NewLine); + + TcpClient client = server.AcceptTcpClient(); + + Console.WriteLine("Um cliente está conectado."); + } +} +</pre> + +<h3 id="TcpClient"><span style="line-height: 1.572;">TcpClient</span></h3> + +<h4 id="Métodos_2">Métodos</h4> + +<dl> + <dt><code>GetStream()</code></dt> + <dd>Obtém o <em>stream</em> que é o canal de comunicação. Ambos os lados do canal têm capacidade de leitura e escrita.</dd> +</dl> + +<h4 id="Propriedades">Propriedades</h4> + +<dl> + <dt><code>int Available</code></dt> + <dd>Esta propriedade indica quantos bytes de dados foram enviados. O valor é zero até que a propriedade <code>NetworkStream.DataAvailable</code> seja <code>true</code>.</dd> +</dl> + +<h3 id="NetworkStream">NetworkStream</h3> + +<h4 id="Métodos_3">Métodos</h4> + +<dl> + <dt><code>Write(Byte[] buffer, int offset, int size)</code></dt> + <dd>Escreve bytes vindos do <code>buffer</code>. <code>offset</code> e <code>size</code> determinam o comprimento da mensagem.</dd> + <dt><code><span class="brush: cpp" style="line-height: 1.572;">Read(Byte[] buffer, int offset, int size)</span></code></dt> + <dd><span class="brush: cpp" style="line-height: 1.572;">Lê bytes do <code>buffer</code>. <code>offset</code> e <code>size</code> </span>determinam o comprimento da mensagem<span class="brush: cpp" style="line-height: 1.572;">.</span></dd> +</dl> + +<h4 id="Exemplo_2">Exemplo</h4> + +<p>Vamos continuar o nosso exemplo:</p> + +<pre class="brush: cpp notranslate">TcpClient client = server.AcceptTcpClient(); + +Console.WriteLine("Um cliente está conectado."); + +NetworkStream stream = client.GetStream(); + +// entrar num ciclo infinito para poder processar qualquer mudança no stream +while (true) { + while (!stream.DataAvailable); + + Byte[] bytes = new Byte[client.Available]; + + stream.Read(bytes, 0, bytes.Length); +}</pre> + +<h2 id="Handshaking_aperto_de_mão"><em>Handshaking </em>(aperto de mão)</h2> + +<p>Quando um cliente se liga a um servidor, envia um pedido GET para atualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.</p> + +<p>Este código de amostra pode detetar um GET do cliente. Note que isto irá bloquear até que os primeiros 3 bytes de uma mensagem estejam disponíveis. Deverão ser investigadas soluções alternativas para ambientes de produção.</p> + +<pre class="brush: cpp notranslate">using System.Text; +using System.Text.RegularExpressions; + +while(client.Available < 3) +{ + // esperar para que hajam bytes suficientes disponiveis +} + +Byte[] bytes = new Byte[client.Available]; + +stream.Read(bytes, 0, bytes.Length); + +//traduzir bytes do pedido para uma string +String data = Encoding.UTF8.GetString(bytes); + +if (Regex.IsMatch(data, "^GET")) { + +} else { + +}</pre> + +<p>A resposta é fácil de construir, mas pode ser um pouco difícil de compreender. A explicação completa do aperto de mão do servidor pode ser encontrada em <a href="https://tools.ietf.org/html/rfc6455#section-4.2.2">RFC 6455, secção 4.2.2</a>. Para os nossos propósitos, vamos apenas construir uma resposta simples.</p> + +<p>Deve:</p> + +<ol> + <li>Obter o valor do cabeçalho de pedido da <code>Sec-WebSocket-Key</code> sem qualquer espaço em branco</li> + <li>Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (um GUID especificado pela RFC 6455)</li> + <li>Calcule o código SHA-1 e Base64 do mesmo</li> + <li>Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.</li> +</ol> + +<pre class="brush: cpp notranslate"><em> +</em>if (new System.Text.RegularExpressions.Regex("^GET").IsMatch(data)) +{ + const string eol = "\r\n"; // HTTP/1.1 define a sequencia "CR LF" como o marcador de fim de linha + + Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol + + "Connection: Upgrade" + eol + + "Upgrade: websocket" + eol + + "Sec-WebSocket-Accept: " + Convert.ToBase64String( + System.Security.Cryptography.SHA1.Create().ComputeHash( + Encoding.UTF8.GetBytes( + new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + ) + ) + ) + eol + + eol); + + stream.Write(response, 0, response.Length); +} +</pre> + +<h2 id="Descodificar_mensagens">Descodificar mensagens</h2> + +<p>Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.</p> + +<p>Se enviarmos "MDN", recebemos estes bytes:</p> + +<table> + <tbody> + <tr> + <td>129</td> + <td>131</td> + <td>61</td> + <td>84</td> + <td>35</td> + <td>6</td> + <td>112</td> + <td>16</td> + <td>109</td> + </tr> + </tbody> +</table> + +<p>Vejamos o que significam estes bytes.</p> + +<p>O primeiro byte, que tem actualmente um valor de 129, é um bitfield que se decompõe da seguinte forma:</p> + +<table> + <thead> + <tr> + <th scope="col">FIN (Bit 0)</th> + <th scope="col">RSV1 (Bit 1)</th> + <th scope="col">RSV2 (Bit 2)</th> + <th scope="col">RSV3 (Bit 3)</th> + <th scope="col">Opcode (Bit 4:7)</th> + </tr> + </thead> + <tbody> + <tr> + <td>1</td> + <td>0</td> + <td>0</td> + <td>0</td> + <td>0x1=0001</td> + </tr> + </tbody> +</table> + +<ul> + <li>FIN bit: Este bit indica se a mensagem completa foi enviada pelo cliente. As mensagens podem ser enviadas em <em>frames</em>, mas por agora vamos manter as coisas simples.</li> + <li>RSV1, RSV2, RSV3: Estes bits devem ser 0, a menos que seja negociada uma extensão que lhes forneça um valor não nulo.</li> + <li><span style="line-height: 1.572;"><em>Opcode</em>: Estes bits descrevem o tipo de mensagem recebida. O código <em>Opcode </em>0x1 significa que se trata de uma mensagem de texto (ver <a href="http://tools.ietf.org/html/rfc6455#section-5.2">lista completa de <em>Opcodes</em></a>).</span></li> +</ul> + +<p>O segundo byte, que tem atualmente um valor de 131, é outro campo de bits que se decompõe assim:</p> + +<table> + <thead> + <tr> + <th scope="col">MASK (Bit 0)</th> + <th scope="col">Comprimento do conteúdo da mensagem (Bit 1:7)</th> + </tr> + </thead> + <tbody> + <tr> + <td>1</td> + <td>0x83=0000011</td> + </tr> + </tbody> +</table> + +<ul> + <li>MASK bit: Define se os "dados de <em>payload</em>" são mascarados. Se definida como 1, uma chave de máscara está presente em Masking-Key, e é utilizada para desmascarar os "dados de <em>payload</em>". Todas as mensagens do cliente para o servidor têm este bit definido.</li> + <li>Comprimento do <em>payload</em>: Se este valor estiver entre 0 e 125, então é o comprimento da mensagem. Se for 126, os 2 bytes seguintes (inteiro de 16 bits sem assinatura) são o comprimento. Se for 127, os 8 bytes seguintes (inteiro de 64 bits sem assinatura) são o comprimento.</li> +</ul> + +<div class="note"> +<p>Porque o primeiro bit é sempre 1 para mensagens cliente-servidor, pode subtrair 128 deste byte para se livrar do bit MASK.</p> +</div> + +<p>Note que o bit MASK está definido na nossa mensagem. Isto significa que os quatro bytes seguintes (61, 84, 35, e 6) são os bytes de máscara utilizados para descodificar a mensagem. Estes bytes mudam com cada mensagem.</p> + +<p>Os restantes bytes são a <em>payload</em> da mensagem codificada.</p> + +<h3 id="Algoritmo_para_descodificar">Algoritmo para descodificar</h3> + +<p><em>D<sub>i</sub></em> = <em>E<sub>i</sub></em> XOR <em>M</em><sub>(<em>i</em> mod 4)</sub></p> + +<p>onde <em>D</em> é a série de bytes da mensagem descodificados, <em>E</em> é a série de bytes da mensagem codificados, <em>M</em> é a série de bytes da chave, e <em>i</em> é o índice do byte da mensagem a ser descodificado.</p> + +<p>Exemplo em C#:</p> + +<pre class="brush: cpp notranslate">Byte[] decoded = new Byte[3]; +Byte[] encoded = new Byte[3] {112, 16, 109}; +Byte[] mask = new Byte[4] {61, 84, 35, 6}; + +for (int i = 0; i < encoded.Length; i++) { + decoded[i] = (Byte)(encoded[i] ^ mask[i % 4]); +}</pre> + +<h2 id="Exemplo_completo">Exemplo completo</h2> + +<p>Aqui tem o código, que foi explorado, na sua totalidade; isto inclui o código do cliente e do servidor.</p> + +<h3 id="wsserver.cs">wsserver.cs</h3> + +<pre class="notranslate">// +// csc wsserver.cs +// wsserver.exe + +using System; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.RegularExpressions; + +class Server { + public static void Main() { + string ip = "127.0.0.1"; + int port = 80; + var server = new TcpListener(IPAddress.Parse(ip), port); + + server.Start(); + Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection...", ip, port); + + TcpClient client = server.AcceptTcpClient(); + Console.WriteLine("A client connected."); + + NetworkStream stream = client.GetStream(); + + // enter to an infinite cycle to be able to handle every change in stream + while (true) { + while (!stream.DataAvailable); + while (client.Available < 3); // match against "get" + + byte[] bytes = new byte[client.Available]; + stream.Read(bytes, 0, client.Available); + string s = Encoding.UTF8.GetString(bytes); + + if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase)) { + Console.WriteLine("=====Handshaking from client=====\n{0}", s); + + // 1. Obtain the value of the "Sec-WebSocket-Key" request header without any leading or trailing whitespace + // 2. Concatenate it with "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (a special GUID specified by RFC 6455) + // 3. Compute SHA-1 and Base64 hash of the new value + // 4. Write the hash back as the value of "Sec-WebSocket-Accept" response header in an HTTP response + string swk = Regex.Match(s, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim(); + string swka = swk + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + byte[] swkaSha1 = System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(swka)); + string swkaSha1Base64 = Convert.ToBase64String(swkaSha1); + + // HTTP/1.1 defines the sequence CR LF as the end-of-line marker + byte[] response = Encoding.UTF8.GetBytes( + "HTTP/1.1 101 Switching Protocols\r\n" + + "Connection: Upgrade\r\n" + + "Upgrade: websocket\r\n" + + "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n"); + + stream.Write(response, 0, response.Length); + } else { + bool fin = (bytes[0] & 0b10000000) != 0, + mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set" + + int opcode = bytes[0] & 0b00001111, // expecting 1 - text message + msglen = bytes[1] - 128, // & 0111 1111 + offset = 2; + + if (msglen == 126) { + // was ToUInt16(bytes, offset) but the result is incorrect + msglen = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0); + offset = 4; + } else if (msglen == 127) { + Console.WriteLine("TODO: msglen == 127, needs qword to store msglen"); + // i don't really know the byte order, please edit this + // msglen = BitConverter.ToUInt64(new byte[] { bytes[5], bytes[4], bytes[3], bytes[2], bytes[9], bytes[8], bytes[7], bytes[6] }, 0); + // offset = 10; + } + + if (msglen == 0) + Console.WriteLine("msglen == 0"); + else if (mask) { + byte[] decoded = new byte[msglen]; + byte[] masks = new byte[4] { bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3] }; + offset += 4; + + for (int i = 0; i < msglen; ++i) + decoded[i] = (byte)(bytes[offset + i] ^ masks[i % 4]); + + string text = Encoding.UTF8.GetString(decoded); + Console.WriteLine("{0}", text); + } else + Console.WriteLine("mask bit not set"); + + Console.WriteLine(); + } + } + } +}</pre> + +<h3 id="client.html">client.html</h3> + +<pre class="brush: html notranslate"><!doctype html> +<style> + textarea { vertical-align: bottom; } + #output { overflow: auto; } + #output > p { overflow-wrap: break-word; } + #output span { color: blue; } + #output span.error { color: red; } +</style> +<h2>WebSocket Test</h2> +<textarea cols=60 rows=6></textarea> +<button>send</button> +<div id=output></div> +<script> + // http://www.websocket.org/echo.html + + var button = document.querySelector("button"), + output = document.querySelector("#output"), + textarea = document.querySelector("textarea"), + // wsUri = "ws://echo.websocket.org/", + wsUri = "ws://127.0.0.1/", + websocket = new WebSocket(wsUri); + + button.addEventListener("click", onClickButton); + + websocket.onopen = function (e) { + writeToScreen("CONNECTED"); + doSend("WebSocket rocks"); + }; + + websocket.onclose = function (e) { + writeToScreen("DISCONNECTED"); + }; + + websocket.onmessage = function (e) { + writeToScreen("<span>RESPONSE: " + e.data + "</span>"); + }; + + websocket.onerror = function (e) { + writeToScreen("<span class=error>ERROR:</span> " + e.data); + }; + + function doSend(message) { + writeToScreen("SENT: " + message); + websocket.send(message); + } + + function writeToScreen(message) { + output.insertAdjacentHTML("afterbegin", "<p>" + message + "</p>"); + } + + function onClickButton() { + var text = textarea.value; + + text && doSend(text); + textarea.value = ""; + textarea.focus(); + } +</script></pre> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_servidores_de_WebSocket">Escrever servidores de WebSocket</a></li> +</ul> + +<div id="cke_pastebin"><em> </em></div> diff --git a/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html b/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html new file mode 100644 index 0000000000..4181a1cd37 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html @@ -0,0 +1,220 @@ +--- +title: Escrever um servidor WebSocket em Java +slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java +tags: + - HTML5 + - Handshaking + - Tutorial + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +--- +<h2 id="Introdução">Introdução</h2> + +<p>Este exemplo mostra-lhe como criar um servidor com API de WebSocket utilizando Oracle Java.<br> + <br> + Embora outras linguagens do lado do servidor possam ser utilizadas para criar um servidor WebSocket, este exemplo utiliza Oracle Java para simplificar o código do exemplo.</p> + +<p>Este servidor está em conformidade com o <a href="http://tools.ietf.org/html/rfc6455">RFC 6455</a>, pelo que apenas trata de ligações a partir das seguintes versões dos navegadores; Chrome 16, Firefox 11, IE 10 e superior.</p> + +<h2 id="Primeiros_passos">Primeiros passos</h2> + +<p>Os WebSockets comunicam através de uma ligação <em>{{interwiki("wikipedia", "Transmission_Control_Protocol", "TCP (Transmission Control Protocol)")}}</em>. A classe <a href="http://docs.oracle.com/javase/8/docs/api/java/net/ServerSocket.html">ServerSocket</a> do Java está localizada no pacote java.net.</p> + +<h3 id="ServerSocket">ServerSocket</h3> + +<h4 id="Construtor">Construtor</h4> + +<dl> + <dt><code>ServerSocket(int port)</code></dt> + <dd>Quando se instância a classe ServerSocket, esta é ligada ao número da porta que se especificou pelo argumento <code>port</code>.<br> + <br> + Aqui está uma implementação dividida em partes:</dd> +</dl> + +<pre class="brush: java notranslate">import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class WebSocket { + public static void main(String[] args) throws IOException, NoSuchAlgorithmException { + ServerSocket server = new ServerSocket(80); + try { + System.out.println("Server has started on 127.0.0.1:80.\r\nWaiting for a connection..."); + Socket client = server.accept(); + System.out.println("A client connected.");</pre> + +<h3 id="Socket">Socket</h3> + +<h4 id="Métodos">Métodos</h4> + +<dl> + <dt><code><span class="memberNameLink"><a href="http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getInputStream--">getInputStream</a></span>()</code></dt> + <dd>Devolve uma <em>input stream</em> para este socket.</dd> + <dt><code><span class="memberNameLink"><a href="http://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#getOutputStream--">getOutputStream</a></span>()</code></dt> + <dd>Devolve uma <em>output stream</em> para este socket.</dd> +</dl> + +<h3 id="OutputStream">OutputStream</h3> + +<h4 id="Métodos_2">Métodos</h4> + +<dl> + <dt><code>write(byte[] b, int off, int len)</code></dt> + <dd>Escreve o número de bytes especificado por <code>len</code> a partir da matriz de bytes especificada por <code>b</code>, começando no índice indicado por <code>off</code> para este <em>output stream</em>.</dd> +</dl> + +<h3 id="InputStream">InputStream</h3> + +<h4 id="Métodos_3">Métodos</h4> + +<dl> + <dt><code><span class="brush: cpp" style="line-height: 1.572;">read</span>(byte[] b, int off, int len)</code></dt> + <dd>Lê até um número de bytes especificado por <code>len</code> da matriz de bytes especificada por <code>b</code>, começando no índice indicado por <code>off</code> para este <em>input stream</em>.<em> </em></dd> +</dl> + +<p>Vamos continuar o nosso exemplo.</p> + +<pre class="brush: java notranslate"> InputStream in = client.getInputStream(); + OutputStream out = client.getOutputStream(); + Scanner s = new Scanner(in, "UTF-8");</pre> + +<h2 id="Handshaking_aperto_de_mão"><em>Handshaking</em> (a<strong>perto de mão</strong>)</h2> + +<p>Quando um cliente se liga a um servidor, envia um pedido GET para actualizar a ligação do protocolo HTTP a uma ligação WebSocket. Isto é conhecido como aperto de mão.</p> + +<pre class="brush: java notranslate"> try { + String data = s.useDelimiter("\\r\\n\\r\\n").next(); + Matcher get = Pattern.compile("^GET").matcher(data);</pre> + +<p>Criar a resposta é mais fácil do que compreender porque o deve fazer desta forma.</p> + +<p>Você deve,</p> + +<ol> + <li>Obter o valor do cabeçalho de pedido da <code>Sec-WebSocket-Key</code> sem qualquer espaço em branco</li> + <li>Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"</li> + <li>Calcule o código SHA-1 e Base64 do mesmo</li> + <li>Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.</li> +</ol> + +<pre class="brush: java notranslate"> if (get.find()) { + Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data); + match.find(); + byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + + "Connection: Upgrade\r\n" + + "Upgrade: websocket\r\n" + + "Sec-WebSocket-Accept: " + + Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1").digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8"))) + + "\r\n\r\n").getBytes("UTF-8"); + out.write(response, 0, response.length); +</pre> + +<h2 id="Descodificar_mensagens">Descodificar mensagens</h2> + +<p>Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.<br> + <br> + Se enviarmos "abcdef", recebemos estes bytes:</p> + +<table> + <tbody> + <tr> + <td>129</td> + <td>134</td> + <td>167</td> + <td>225</td> + <td>225</td> + <td>210</td> + <td>198</td> + <td>131</td> + <td>130</td> + <td>182</td> + <td>194</td> + <td>135</td> + </tr> + </tbody> +</table> + +<h4 id="129_FIN_RSV1_RSV2_RSV3_opcode">129 (FIN, RSV1, RSV2, RSV3, <em>opcode</em>)</h4> + +<p>Pode enviar a sua mensagem em fragmentos, mas por enquanto o FIN é 1 indicando que a mensagem está toda num fragmento. RSV1, RSV2 e RSV3 são sempre 0, a não ser que um significado para os bytes é negociado. <em>Opcode</em> 0x1 significa que isto é um texto (ver <a href="http://tools.ietf.org/html/rfc6455#section-5.2">lista completa de <em>opcodes</em></a>).</p> + +<table> + <thead> + <tr> + <th scope="col">FIN (É o último fragmento da mensagem?)</th> + <th scope="col">RSV1</th> + <th scope="col">RSV2</th> + <th scope="col">RSV3</th> + <th scope="col"><em>Opcode</em></th> + </tr> + </thead> + <tbody> + <tr> + <td>1</td> + <td>0</td> + <td>0</td> + <td>0</td> + <td>0x1=0001</td> + </tr> + </tbody> +</table> + +<h4 id="134_comprimento_da_mensagem">134 (comprimento da mensagem)</h4> + +<p>O comprimento da mensagem é indicada das seguintes formas:</p> + +<ul> + <li>Se o segundo byte menos 128 estiver entre 0 e 125, este é o comprimento da mensagem,</li> + <li>Se o resultado é 126, os seguintes 2 bytes (inteiro de 16 bits sem assinatura) ditam o comprimento,</li> + <li>E se o resultado é 127, os 8 bytes seguintes (64-bit inteiro não assinado, o bit mais significativo DEVE ser 0) são o comprimento.</li> +</ul> + +<h4 id="167_225_225_e_210_chave_para_descodificar">167, 225, 225 e 210 (chave para descodificar)</h4> + +<p>Estes são os bytes da chave para descodificar. A chave muda para cada mensagem.</p> + +<h4 id="198_131_130_182_194_135_conteúdo_da_mensagem">198, 131, 130, 182, 194, 135 (conteúdo da mensagem)</h4> + +<p>Os restantes bytes codificados são a mensagem.</p> + +<h3 id="Algoritmo_para_descodificar">Algoritmo para descodificar</h3> + +<p>O algoritmo usado para descodificar a mensagem é o seguinte:</p> + +<p><em>D<sub>i</sub></em> = <em>E<sub>i</sub></em> XOR <em>M</em><sub>(<em>i</em> mod 4)</sub></p> + +<p>onde <em>D</em> é a série de bytes da mensagem descodificados, <em>E</em> é a série de bytes da mensagem codificados, <em>M</em> é a série de bytes da chave, e <em>i</em> é o índice do byte da mensagem a ser descodificado.</p> + +<p>Exemplo em Java:</p> + +<pre class="brush: java notranslate"> byte[] decoded = new byte[6]; + byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 }; + byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 }; + for (int i = 0; i < encoded.length; i++) { + decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]); + } + } + } finally { + s.close(); + } + } finally { + server.close(); + } + } +}</pre> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_servidores_de_WebSocket">Escrever servidores de WebSocket</a></li> +</ul> + +<div id="cke_pastebin"></div> diff --git a/files/pt-pt/web/api/websockets_api/index.html b/files/pt-pt/web/api/websockets_api/index.html new file mode 100644 index 0000000000..5fa4e252e2 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/index.html @@ -0,0 +1,113 @@ +--- +title: WebSocket API (WebSockets) +slug: Web/API/WebSockets_API +tags: + - API + - Client + - Comunicação + - Servidor + - Sumario + - Two-Way + - WebSocket + - WebSocket API + - WebSockets + - dados + - interativo +translation_of: Web/API/WebSockets_API +--- +<p>{{DefaultAPISidebar("Websockets API")}}</p> + +<p>A <strong>WebSocket API</strong> é uma tecnologia que permite abrir uma sessão de comunicação interativa bidirecional entre o navegador do utilizador e um servidor. Com esta API, é possível enviar mensagens para um servidor e receber respostas orientadas por eventos sem ter de sondar o servidor para obter uma resposta.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> Enquanto a conexão WebSocket é funcionalmente semelhante aos <em>sockets</em> de estilo Unix, não são relacionados.</p> +</div> + +<h2 id="Interfaces">Interfaces</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/API/WebSocket"><code>WebSocket</code></a></dt> + <dd>A interface principal para fazer conexão a um servidor de WebSocket e depois enviar e receber dados na mesma conexão.</dd> + <dt><code><a href="/pt-PT/docs/Web/API/CloseEvent">CloseEvent</a></code></dt> + <dd>O evento enviado pelo objeto WebSocket quando a conexão termina.</dd> + <dt><a href="/pt-PT/docs/Web/API/MessageEvent"><code>MessageEvent</code></a></dt> + <dd>O evento enviado pelo objeto WebSocket quando uma mensagem é recebida do servidor.</dd> +</dl> + +<h2 id="Guias">Guias</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket">Escrever aplicação cliente de WebSocket </a></li> + <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_servidores_de_WebSocket">Escrever servidores de WebSocket </a></li> + <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C%23">Escrever um servidor WebSocket em C#</a></li> + <li><a href="/pt-PT/docs/Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java">Escrever um servidor WebSocket em Java</a></li> +</ul> + +<h2 id="Tools" name="Tools">Ferramentas</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2017/06/introducing-humblenet-a-cross-platform-networking-library-that-works-in-the-browser/">HumbleNet</a>: Uma biblioteca em rede multi-plataformas que funciona no navegador. Consiste num wrapper em C em torno de WebSockets e WebRTC que abstrai as diferenças entre navegadores, facilitando a criação de funcionalidades de rede multi-utilizador para jogos e outras aplicações.</li> + <li><a href="https://github.com/uWebSockets/uWebSockets">µWebSockets</a>: Implementação de servidor e cliente WebSocket altamente escalável para <a href="https://isocpp.org/">C++11</a> e <a href="https://nodejs.org">Node.js</a>.</li> + <li><a href="https://github.com/ClusterWS/ClusterWS">ClusterWS</a>: Framework leve, rápida e poderosa para construir aplicações WebSocket escaláveis no <a href="https://nodejs.org">Node.js</a>.</li> + <li><a href="https://github.com/ClusterWS/cWS">CWS</a>: Implementação rápida WebSocket de C++ para Node.js (uWebSockets v0.14 fork)</li> + <li><a class="external" href="https://socket.io">Socket.IO</a>: Um protocolo de transferência de terceiros, baseado em long polling/WebSocket para <a href="https://nodejs.org">Node.js</a>.</li> + <li><a href="http://socketcluster.io/">SocketCluster</a>: Uma pub/sub WebSocket framework para <a href="https://nodejs.org">Node.js</a> com foco na escalabilidade.</li> + <li><a class="link-https" href="https://github.com/Worlize/WebSocket-Node">WebSocket-Node</a>: Uma implementação da API de servidores WebSocket para <a href="https://nodejs.org">Node.js</a>.</li> + <li><a href="http://www.totaljs.com">Total.js</a>: Uma <em>framework</em> de aplicações web para <a href="https://www.nodejs.org">Node.js</a> (Example: <a href="https://github.com/totaljs/examples/tree/master/websocket">WebSocket chat</a>)</li> + <li><a href="https://www.npmjs.com/package/faye-websocket">Faye</a>: Uma <a href="/en-US/docs/Web/API/WebSockets_API">WebSocket</a> (ligações bidireccionais) e <a href="/en-US/docs/Web/API/EventSource/">EventSource</a> (ligações unidireccionais) para <a href="https://nodejs.org">Node.js</a> Server e Client.</li> + <li><a href="http://signalr.net/">SignalR</a>: SignalR usa WebSockets quando está disponível, e discretamente volta para outras técnicas e tecnologias quando não está, enquanto o seu código de aplicação permanece o mesmo.</li> + <li><a href="https://caddyserver.com/docs/websocket">Caddy</a>: Um servidor web capaz de substituir comandos arbitrários (stdin/stdout) com uma <em>web socket</em>.</li> + <li><a href="https://github.com/websockets/ws">ws</a>: uma biblioteca de cliente e servidor WebSocket popular para <a href="https://nodejs.org/">Node.js</a>.</li> + <li><a href="https://github.com/bigstepinc/jsonrpc-bidirectional">jsonrpc-bidirectional</a>: RPC assíncrono que, numa única ligação, pode ter funções exportadas no servidor e, e ao mesmo tempo, no cliente (cliente pode chamar servidor, servidor também pode chamar cliente).</li> + <li><a href="https://github.com/ninenines/cowboy">cowboy</a>: Cowboy é um pequeno, rápido e moderno servidor HTTP para Erlang/OTP com suporte para WebSocket.</li> +</ul> + +<h2 id="Related_Topics" name="Related_Topics">Tópicos Relacionados</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/Guide/AJAX">AJAX</a></li> + <li><a href="/pt-PT/docs/Web/JavaScript">JavaScript</a></li> +</ul> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("HTML WHATWG", "web-sockets.html", "WebSocket API")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td></td> + </tr> + <tr> + <td><a href="https://www.w3.org/TR/websockets/">WebSockets</a></td> + <td><span class="spec-CR">Candidate Recommendation</span></td> + <td></td> + </tr> + <tr> + <td>{{RFC(6455, "The WebSocket Protocol")}}</td> + <td><span class="spec-RFC">IETF RFC</span></td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("api.WebSocket")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a class="external" href="http://tools.ietf.org/html/rfc6455">RFC 6455 — O Protocolo WebSocket</a></li> + <li><a class="external" href="https://www.w3.org/TR/websockets/">Especificação da API WebSocket</a></li> + <li><em><a href="/en-US/docs/Server-sent_events">Server-Sent Events</a></em></li> +</ul> diff --git a/files/pt-pt/web/api/window/barra_lateral/index.html b/files/pt-pt/web/api/window/barra_lateral/index.html new file mode 100644 index 0000000000..d35750364d --- /dev/null +++ b/files/pt-pt/web/api/window/barra_lateral/index.html @@ -0,0 +1,60 @@ +--- +title: Window.sidebar +slug: Web/API/Window/barra_lateral +tags: + - DOM + - Janela + - Não Padrão + - Propriedade + - Referencia +translation_of: Web/API/Window/sidebar +--- +<div>{{APIRef}} {{Non-standard_header}}</div> + +<p>Devolve um objeto da barra lateral, que contém vários métodos para registar extras com o navegador.</p> + +<h2 id="Notes" name="Notes">Notas</h2> + +<p>O objeto da barra lateral devolvido tem os seguintes métodos:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Método</th> + <th>Descrição (SeaMonkey)</th> + <th>Descrição (Firefox)</th> + </tr> + <tr> + <td><code>addPanel(<var>title</var>, <var>contentURL</var>, "")</code></td> + <td>Adiciona um painel de barra lateral.</td> + <td rowspan="2">Obsoleto desde o Firefox 23 (apresentado apenas no SeaMonkey).<br> + Em vez disso, os utilizadores finais podem utilizar a opção "carregar este marcador na barra lateral". Consulte também <a href="/pt-PT/docs/Mozilla/Criacao_barra_lateral_Firefox">Criação de uma barra lateral do Firefox.</a></td> + </tr> + <tr> + <td><code>addPersistentPanel(<var>title</var>, <var>contentURL</var>, "")</code></td> + <td>Adiciona um painel de barra lateral, que consegue funcionar em segundo plano.</td> + </tr> + <tr> + <td><code>AddSearchProvider(<em>descriptionURL)</em></code></td> + <td colspan="2">Installs a search provider (OpenSearch). <a href="/en-US/docs/Web/API/Window/sidebar/Adding_search_engines_from_Web_pages#Installing_OpenSearch_plugins" title="Adding_search_engines_from_web_pages">Adding OpenSearch search engines </a>contains more details. Added in Firefox 2.</td> + </tr> + <tr> + <td><code>addSearchEngine(<var>engineURL</var>, <var>iconURL</var>, <var>suggestedTitle</var>, <var>suggestedCategory</var>)</code> {{Obsolete_inline(44)}}</td> + <td colspan="2"> + <p>Installs a search engine (Sherlock). <a href="/en-US/docs/Web/API/Window/sidebar/Adding_search_engines_from_Web_pages#Installing_Sherlock_plugins" title="Adding_search_engines_from_web_pages">Adding Sherlock search engines </a>contains more details.</p> + + <div class="note"> + <p><strong>Note</strong>: This was made obsolete in Firefox 44, and has been removed completely in Firefox 59. You should use <code>AddSearchProvider</code> instead.</p> + </div> + </td> + </tr> + <tr> + <td><code>IsSearchProviderInstalled(<em>descriptionURL)</em></code></td> + <td colspan="2">Indicates if a specific search provider (OpenSearch) is installed.</td> + </tr> + </tbody> +</table> + +<h2 id="Specification" name="Specification">Especificação</h2> + +<p>Específico da Mozilla. Não faz parte de qualquer padrão.</p> diff --git a/files/pt-pt/web/api/window/console/index.html b/files/pt-pt/web/api/window/console/index.html new file mode 100644 index 0000000000..80abc2170c --- /dev/null +++ b/files/pt-pt/web/api/window/console/index.html @@ -0,0 +1,56 @@ +--- +title: Window.console +slug: Web/API/Window/console +tags: + - API + - Consola + - Referencia + - Só-de-leitura + - Window + - console +translation_of: Web/API/Window/console +--- +<p>{{ APIRef }}</p> + +<p>A propriedade só-de-leitura <em><strong><code>Window.console</code></strong></em> devolve uma referência para o objeto {{domxref("Console")}}, que fornece métodos para registar informação na <em>console </em>do navegador. Estes métodos são destinados apenas para fins de depuração e não deverão ser invocados para apresentar informação aos utilizadores finais.</p> + +<h2 id="Syntax" name="Syntax">Sintaxe</h2> + +<pre class="syntaxbox"><em>var consoleObj</em> = <em>window</em>.console; +</pre> + +<h2 id="Example" name="Example">Exemplos</h2> + +<h3 id="Registar_para_console">Registar para console</h3> + +<p>The first example logs text to the console.</p> + +<pre class="brush: js">console.log("An error occurred while loading the content"); +</pre> + +<p>The next example logs an object to the console, with the object's fields expandable using disclosure widgets:</p> + +<pre class="brush: js">console.dir(someObject);</pre> + +<p>See {{SectionOnPage("/en-US/docs/Web/API/Console", "Usage")}} for more thorough examples.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('Console API')}}</td> + <td>{{Spec2('Console API')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p>Currently there are many implementation differences among browsers, but work is being done to bring them together and make them more consistent with one another.</p> +</div> diff --git a/files/pt-pt/web/api/window/index.html b/files/pt-pt/web/api/window/index.html new file mode 100644 index 0000000000..338f4980f1 --- /dev/null +++ b/files/pt-pt/web/api/window/index.html @@ -0,0 +1,479 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - Window +translation_of: Web/API/Window +--- +<p>{{APIRef}}</p> + +<p><span class="seoSummary">O objeto <em><code>window</code></em> representa uma janela contendo um documento DOM; a propriedade <em><code>document</code></em> aponta para o <a href="/en-US/docs/DOM/document">documento DOM</a> carregado nessa janela.</span> Uma janela para um determinado documento pode ser obtida utilizando a propriedade {{Domxref("document.defaultView")}}.</p> + +<p>This section provides a brief reference for all of the methods, properties, and events available through the DOM <code>window</code> object. The <code>window</code> object implements the <code>Window</code> interface, which in turn inherits from the <code><a href="http://www.w3.org/TR/DOM-Level-2-Views/views.html#Views-AbstractView">AbstractView</a></code> interface. Some additional global functions, namespaces, objects, interfaces, and constructors, not typically associated with the window, but available on it, are listed in the <a href="/en-US/docs/JavaScript/Reference">JavaScript Reference</a> and <a href="/en-US/docs/Web/API/Document_Object_Model" title="/en-US/docs/Web/API/Document_Object_Model">DOM Reference</a>.</p> + +<p>In a tabbed browser, such as Firefox, each tab contains its own <code>window</code> object (and if you're writing an extension, the browser window itself is a separate window too - see <a href="/en-US/docs/Working_with_windows_in_chrome_code#Content_windows">Working with windows in chrome code</a> for more information). That is, the <code>window</code> object is not shared between tabs in the same window. Some methods, namely {{Domxref("window.resizeTo")}} and {{Domxref("window.resizeBy")}} apply to the whole window and not to the specific tab the <code>window</code> object belongs to. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.</p> + +<p>{{InheritanceDiagram}}</p> + +<h2 id="Propriedades">Propriedades</h2> + +<p><em>This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.</em></p> + +<p>Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.</p> + +<dl> + <dt>{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}</dt> + <dd>This property indicates whether the current window is closed or not.</dd> + <dt>{{domxref("Window.console")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the console object which provides access to the browser's debugging console.</dd> + <dt>{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.</dd> + <dt>{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns the XUL controller objects for the current chrome window.</dd> + <dt>{{domxref("Window.crypto")}} {{readOnlyInline}}</dt> + <dd>Returns the browser crypto object.</dd> + <dt>{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}</dt> + <dd>Gets/sets the status bar text for the given window.</dd> + <dt>{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns the ratio between physical pixels and device independent pixels in the current display.</dd> + <dt>{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}</dt> + <dd>Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.</dd> + <dt>{{domxref("Window.directories")}} {{obsolete_inline}}</dt> + <dd>Synonym of {{domxref("window.personalbar")}}</dd> + <dt>{{domxref("Window.document")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the document that the window contains.</dd> + <dt>{{domxref("Window.frameElement")}} {{readOnlyInline}}</dt> + <dd>Returns the element in which the window is embedded, or null if the window is not embedded.</dd> + <dt>{{domxref("Window.frames")}} {{readOnlyInline}}</dt> + <dd>Returns an array of the subframes in the current window.</dd> + <dt>{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}</dt> + <dd>This property indicates whether the window is displayed in full screen or not.</dd> + <dt>{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}</dt> + <dd>Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.<br> + Was: Multiple storage objects that are used for storing data across multiple pages.</dd> + <dt>{{domxref("Window.history")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the history object.</dd> + <dt>{{domxref("Window.innerHeight")}} {{readOnlyInline}}</dt> + <dd>Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.</dd> + <dt>{{domxref("Window.innerWidth")}} {{readOnlyInline}}</dt> + <dd>Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.</dd> + <dt>{{domxref("Window.isSecureContext")}} {{readOnlyInline}}</dt> + <dd>Indicates whether a context is capable of using features that require secure contexts.</dd> + <dt>{{domxref("Window.length")}} {{readOnlyInline}}</dt> + <dd>Returns the number of frames in the window. See also {{domxref("window.frames")}}.</dd> + <dt>{{domxref("Window.location")}}</dt> + <dd>Gets/sets the location, or current URL, of the window object.</dd> + <dt>{{domxref("Window.locationbar")}} {{ReadOnlyInline}}</dt> + <dd>Returns the locationbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}</dt> + <dd>Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.</dd> + <dt>{{domxref("Window.menubar")}} {{ReadOnlyInline}}</dt> + <dd>Returns the menubar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the <a href="/en-US/docs/The_message_manager">message manager</a> object for this window.</dd> + <dt>{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}</dt> + <dd>The time in milliseconds since epoch at which the current animation cycle began.</dd> + <dt>{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See <code>mozScreenPixelsPerCSSPixel</code> in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.</dd> + <dt>{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}</dt> + <dd>Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See <code>mozScreenPixelsPerCSSPixel</code> for a conversion factor to adapt to screen pixels if needed.</dd> + <dt>{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.</dd> + <dt>{{domxref("Window.name")}}</dt> + <dd>Gets/sets the name of the window.</dd> + <dt>{{domxref("Window.navigator")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the navigator object.</dd> + <dt>{{domxref("Window.opener")}}</dt> + <dd>Returns a reference to the window that opened this current window.</dd> + <dt>{{domxref("Window.orientation")}}{{non-standard_inline}}{{deprecated_inline}}{{readOnlyInline}}</dt> + <dd>Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.</dd> + <dt>{{domxref("Window.outerHeight")}} {{readOnlyInline}}</dt> + <dd>Gets the height of the outside of the browser window.</dd> + <dt>{{domxref("Window.outerWidth")}} {{readOnlyInline}}</dt> + <dd>Gets the width of the outside of the browser window.</dd> + <dt>{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}</dt> + <dd>An alias for {{domxref("window.scrollX")}}.</dd> + <dt>{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}</dt> + <dd>An alias for {{domxref("window.scrollY")}}</dd> + <dt>{{domxref("Window.sessionStorage")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.</dd> + <dt>{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.</dd> + <dt>{{domxref("Window.parent")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the parent of the current window or subframe.</dd> + <dt>{{domxref("Window.performance")}} {{readOnlyInline}}</dt> + <dd>Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing <a href="/en-US/docs/Navigation_timing">performance-related</a> data. See also <a href="/en-US/docs/Web/API/Navigation_timing_API/Using_Navigation_Timing">Using Navigation Timing</a> for additional information and examples.</dd> + <dt>{{domxref("Window.personalbar")}} {{readOnlyInline}}</dt> + <dd>Returns the personalbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}</dt> + <dd>Formerly provided access to install and remove PKCS11 modules.</dd> + <dt>{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}</dt> + <dd>The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.</dd> + <dt>{{domxref("Window.screen")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the screen object associated with the window.</dd> + + <dt>{{domxref("Window.screenX")}} {{readOnlyInline}}</dt> + <dd>Returns the horizontal distance of the left border of the user's browser from the left side of the screen.</dd> + <dt>{{domxref("Window.screenY")}} {{readOnlyInline}}</dt> + <dd>Returns the vertical distance of the top border of the user's browser from the top side of the screen.</dd> + <dt>{{domxref("Window.scrollbars")}} {{readOnlyInline}}</dt> + <dd>Returns the scrollbars object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.scrollMaxX")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.</dd> + <dt>{{domxref("Window.scrollMaxY")}}{{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).</dd> + <dt>{{domxref("Window.scrollX")}} {{readOnlyInline}}</dt> + <dd>Returns the number of pixels that the document has already been scrolled horizontally.</dd> + <dt>{{domxref("Window.scrollY")}} {{readOnlyInline}}</dt> + <dd>Returns the number of pixels that the document has already been scrolled vertically.</dd> + <dt>{{domxref("Window.self")}} {{ReadOnlyInline}}</dt> + <dd>Returns an object reference to the window object itself.</dd> + <dt>{{domxref("Window.sessionStorage")}} {{Fx_minversion_inline("2.0")}}</dt> + <dd>Returns a storage object for storing data within a single page session.</dd> + <dt>{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}</dt> + <dd>Returns a reference to the window object of the sidebar.</dd> + <dt>{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}</dt> + <dd>Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using <a href="/en-US/docs/Web/API/Web_Speech_API">Web Speech API</a> speech synthesis functionality.</dd> + <dt>{{domxref("Window.status")}}</dt> + <dd>Gets/sets the text in the statusbar at the bottom of the browser.</dd> + <dt>{{domxref("Window.statusbar")}} {{readOnlyInline}}</dt> + <dd>Returns the statusbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.toolbar")}} {{readOnlyInline}}</dt> + <dd>Returns the toolbar object, whose visibility can be toggled in the window.</dd> + <dt>{{domxref("Window.top")}} {{readOnlyInline}}</dt> + <dd>Returns a reference to the topmost window in the window hierarchy. This property is read only.</dd> + <dt>{{domxref("Window.visualViewport")}} {{readOnlyInline}}</dt> + <dd>Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.</dd> + <dt>{{domxref("Window.window")}} {{ReadOnlyInline}}</dt> + <dd>Returns a reference to the current window.</dd> + <dt><code>window[0]</code>,<code> window[1]</code>, etc.</dt> + <dd>Returns a reference to the <code>window</code> object in the frames. See {{domxref("Window.frames")}} for more details.</dd> +</dl> + +<h3 id="Properties_implemented_from_elsewhere">Properties implemented from elsewhere</h3> + +<dl> + <dt>{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}</dt> + <dd>Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}</dt> + <dd>Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}</dt> + <dd>Returns a boolean indicating whether the current context is secure (<code>true</code>) or not (<code>false</code>).</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}</dt> + <dd>Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt>{{domxref("Window.alert()")}}</dt> + <dd>Displays an alert dialog.</dd> + + <dt>{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Moves back one in the window history.</dd> + <dt>{{domxref("Window.blur()")}}</dt> + <dd>Sets focus away from the window.</dd> + <dt>{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}</dt> + <dd>Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.</dd> + <dt>{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}</dt> + <dd>Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.</dd> + <dt>{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}</dt> + <dd>Registers the window to capture all events of the specified type.</dd> + <dt>{{domxref("Window.clearImmediate()")}}</dt> + <dd>Cancels the repeated execution set using <code>setImmediate</code>.</dd> + <dt>{{domxref("Window.close()")}}</dt> + <dd>Closes the current window.</dd> + <dt>{{domxref("Window.confirm()")}}</dt> + <dd>Displays a dialog with a message that the user needs to respond to.</dd> + <dt>{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.dispatchEvent()")}}</dt> + <dd>Used to trigger an event.</dd> + <dt>{{domxref("Window.dump()")}} {{Non-standard_inline}}</dt> + <dd>Writes a message to the console.</dd> + <dt>{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.find()")}}</dt> + <dd>Searches for a given string in a window.</dd> + <dt>{{domxref("Window.focus()")}}</dt> + <dd>Sets focus on the current window.</dd> + <dt>{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Moves the window one document forward in the history.</dd> + <dt>{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Flashes the application icon.</dd> + <dt>{{domxref("Window.getAttentionWithCycleCount()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.getComputedStyle()")}}</dt> + <dd>Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.</dd> + <dt>{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}</dt> + <dd>Gets default computed style for the specified element, ignoring author stylesheets.</dd> + <dt>{{domxref("Window.getSelection()")}}</dt> + <dd>Returns the selection object representing the selected item(s).</dd> + <dt>{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Returns the browser to the home page.</dd> + <dt>{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.</dd> + <dt>{{domxref("Window.maximize()")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.minimize()")}} (top-level XUL windows only)</dt> + <dd>Minimizes the window.</dd> + <dt>{{domxref("Window.moveBy()")}}</dt> + <dd>Moves the current window by a specified amount.</dd> + <dt>{{domxref("Window.moveTo()")}}</dt> + <dd>Moves the window to the specified coordinates.</dd> + <dt>{{domxref("Window.open()")}}</dt> + <dd>Opens a new window.</dd> + <dt>{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>Opens a new dialog window.</dd> + <dt>{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}</dt> + <dd>Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.</dd> + <dt>{{domxref("Window.print()")}}</dt> + <dd>Opens the Print Dialog to print the current document.</dd> + <dt>{{domxref("Window.prompt()")}}</dt> + <dd>Returns the text entered by the user in a prompt dialog.</dd> + <dt>{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}</dt> + <dd>Releases the window from trapping events of a specific type.</dd> + <dt>{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.</dd> + <dt>{{domxref("Window.requestIdleCallback()")}} {{experimental_inline}}</dt> + <dd>Enables the scheduling of tasks during a browser's idle periods.</dd> + <dt>{{domxref("Window.resizeBy()")}}</dt> + <dd>Resizes the current window by a certain amount.</dd> + <dt>{{domxref("Window.resizeTo()")}}</dt> + <dd>Dynamically resizes window.</dd> + <dt>{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.scroll()")}}</dt> + <dd>Scrolls the window to a particular place in the document.</dd> + <dt>{{domxref("Window.scrollBy()")}}</dt> + <dd>Scrolls the document in the window by the given amount.</dd> + <dt>{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}</dt> + <dd>Scrolls the document by the given number of lines.</dd> + <dt>{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}</dt> + <dd>Scrolls the current document by the specified number of pages.</dd> + <dt>{{domxref("Window.scrollTo()")}}</dt> + <dd>Scrolls to a particular set of coordinates in the document.</dd> + <dt>{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)</dt> + <dd>Changes the cursor for the current window</dd> + <dt>{{domxref("Window.setImmediate()")}}</dt> + <dd>Executes a function after the browser has finished other heavy tasks</dd> + <dt>{{domxref("Window.setResizable()")}} {{Non-standard_inline}}</dt> + <dd>Toggles a user's ability to resize a window.</dd> + <dt>{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}</dt> + <dd>Sizes the window according to its content.</dd> + <dt>{{domxref("Window.stop()")}}</dt> + <dd>This method stops window loading.</dd> + <dt>{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}</dt> + <dd>Updates the state of commands of the current chrome window (UI).</dd> +</dl> + +<h3 id="Methods_implemented_from_elsewhere">Methods implemented from elsewhere</h3> + +<dl> + <dt>{{domxref("EventTarget.addEventListener()")}}</dt> + <dd>Register an event handler to a specific event type on the window.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.atob()")}}</dt> + <dd>Decodes a string of data which has been encoded using base-64 encoding.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.btoa()")}}</dt> + <dd>Creates a base-64 encoded ASCII string from a string of binary data.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}</dt> + <dd>Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}</dt> + <dd>Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}</dt> + <dd>Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at <em>(sx, sy)</em> with width sw, and height sh.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.fetch()")}}</dt> + <dd>Starts the process of fetching a resource from the network.</dd> + <dt>{{domxref("EventTarget.removeEventListener")}}</dt> + <dd>Removes an event listener from the window.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}</dt> + <dd>Schedules a function to execute every time a given number of milliseconds elapses.</dd> + <dt>{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}</dt> + <dd>Schedules a function to execute in a given amount of time.</dd> +</dl> + +<h3 id="Métodos_obsoletos">Métodos obsoletos</h3> + +<dl> + <dt>{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}</dt> + <dd>Displays a modal dialog. <strong>This method was removed completely in Chrome 43, and Firefox 55.</strong></dd> +</dl> + +<h2 id="Manipuladores_de_evento">Manipuladores de evento</h2> + +<p>These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.</p> + +<p><em>This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.</em></p> + +<div class="note"> +<p><strong>Nota:</strong> Starting in {{Gecko("9.0")}}, you can now use the syntax <code>if ("onabort" in window)</code> to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See <a href="/en-US/docs/DOM/DOM_event_handlers">DOM event handlers</a> for details.</p> +</div> + +<dl> + <dt>{{domxref("GlobalEventHandlers.onabort")}}</dt> + <dd>Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress</dd> + <dt>{{domxref("WindowEventHandlers.onafterprint")}}</dt> + <dd>Called when the print dialog box is closed. See {{event("afterprint")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeprint")}}</dt> + <dd>Called when the print dialog box is opened. See {{event("beforeprint")}} event.</dd> + <dt>{{domxref("Window.onbeforeinstallprompt")}}</dt> + <dd>An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.</dd> + <dt>{{domxref("WindowEventHandlers.onbeforeunload")}}</dt> + <dd>An event handler property for before-unload events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onblur")}}</dt> + <dd>Called after the window loses focus, such as due to a popup.</dd> + <dt>{{domxref("GlobalEventHandlers.onchange")}}</dt> + <dd>An event handler property for change events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onclick")}}</dt> + <dd>Called after the ANY mouse button is pressed & released</dd> + <dt>{{domxref("GlobalEventHandlers.ondblclick")}}</dt> + <dd>Called when a double click is made with ANY mouse button.</dd> + <dt>{{domxref("GlobalEventHandlers.onclose")}}</dt> + <dd>Called after the window is closed</dd> + <dt>{{domxref("GlobalEventHandlers.oncontextmenu")}}</dt> + <dd>Called when the RIGHT mouse button is pressed</dd> + <dt>{{domxref("Window.ondevicelight")}}</dt> + <dd>An event handler property for any ambient light levels changes</dd> + <dt>{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Called if accelerometer detects a change (For mobile devices)</dd> + <dt>{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}</dt> + <dd>Called when the orientation is changed (For mobile devices)</dd> + <dt>{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only</dt> + <dd>An event handler property for any device orientation changes.</dd> + <dt>{{domxref("Window.ondeviceproximity")}}</dt> + <dd>An event handler property for device proximity event</dd> + <dt>{{domxref("GlobalEventHandlers.onerror")}}</dt> + <dd>Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onfocus")}}</dt> + <dd>Called after the window receives or regains focus. See {{event("focus")}} events.</dd> + <dt>{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}</dt> + <dd>An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.</dd> + <dt>{{domxref("Window.onappinstalled")}}</dt> + <dd>Called when the page is installed as a webapp. See {{event('appinstalled')}} event.</dd> + <dt>{{domxref("Window.ongamepadconnected")}}</dt> + <dd>Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).</dd> + <dt>{{domxref("Window.ongamepaddisconnected")}}</dt> + <dd>Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).</dd> + <dt>{{domxref("Window.oninput")}}</dt> + <dd>Called when the value of an <input> element changes</dd> + <dt>{{domxref("GlobalEventHandlers.onkeydown")}}</dt> + <dd>Called when you begin pressing ANY key. See {{event("keydown")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeypress")}}</dt> + <dd>Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.</dd> + <dt>{{domxref("GlobalEventHandlers.onkeyup")}}</dt> + <dd>Called when you finish releasing ANY key. See {{event("keyup")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onlanguagechange")}}</dt> + <dd>An event handler property for {{event("languagechange")}} events on the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onload")}}</dt> + <dd>Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.</dd> + <dt>{{domxref("WindowEventHandlers.onmessage")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousedown")}}</dt> + <dd>Called when ANY mouse button is pressed.</dd> + <dt>{{domxref("GlobalEventHandlers.onmousemove")}}</dt> + <dd>Called continously when the mouse is moved inside the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseout")}}</dt> + <dd>Called when the pointer leaves the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseover")}}</dt> + <dd>Called when the pointer enters the window</dd> + <dt>{{domxref("GlobalEventHandlers.onmouseup")}}</dt> + <dd>Called when ANY mouse button is released</dd> + <dt>{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>An event handler property for the <code>MozBeforePaint</code> event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.</dd> + <dt>{{domxref("WindowEventHandlers.onoffline")}}</dt> + <dd>Called when network connection is lost. See {{event("offline")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.ononline")}}</dt> + <dd>Called when network connection is established. See {{event("online")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onpagehide")}}</dt> + <dd>Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.</dd> + <dt>{{domxref("WindowEventHandlers.onpageshow")}}</dt> + <dd>Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.</dd> + <dt>{{domxref("Window.onpaint")}}</dt> + <dd>An event handler property for paint events on the window.</dd> + <dt>{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}</dt> + <dd>Called when a back button is pressed.</dd> + <dt>{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}</dt> + <dd>An event handler for handled {{jsxref("Promise")}} rejection events.</dd> + <dt>{{domxref("GlobalEventHandlers.onreset")}}</dt> + <dd>Called when a form is reset</dd> + <dt>{{domxref("GlobalEventHandlers.onresize")}}</dt> + <dd>Called continuously as you are resizing the window.</dd> + <dt>{{domxref("GlobalEventHandlers.onscroll")}}</dt> + <dd>Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked</dd> + <dt>{{domxref("GlobalEventHandlers.onwheel")}}</dt> + <dd>Called when the mouse wheel is rotated around any axis</dd> + <dt>{{domxref("GlobalEventHandlers.onselect")}}</dt> + <dd>Called after text in an input field is selected</dd> + <dt>{{domxref("GlobalEventHandlers.onselectionchange")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.</dd> + <dt>{{domxref("WindowEventHandlers.onstorage")}}</dt> + <dd>Called when there is a change in session storage or local storage. See {{event("storage")}} event</dd> + <dt>{{domxref("GlobalEventHandlers.onsubmit")}}</dt> + <dd>Called when a form is submitted</dd> + <dt>{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}</dt> + <dd>An event handler for unhandled {{jsxref("Promise")}} rejection events.</dd> + <dt>{{domxref("WindowEventHandlers.onunload")}}</dt> + <dd>Called when the user navigates away from the page.</dd> + <dt>{{domxref("Window.onuserproximity")}}</dt> + <dd>An event handler property for user proximity events.</dd> + <dt>{{domxref("Window.onvrdisplayconnect")}}</dt> + <dd>Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplaydisconnect")}}</dt> + <dd>Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplayactivate")}}</dt> + <dd>Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.</dd> + <dt>{{domxref("Window.onvrdisplaydeactivate")}}</dt> + <dd>Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.</dd> + <dt>{{domxref("Window.onvrdisplayblur")}}</dt> + <dd>Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.</dd> + <dt>{{domxref("Window.onvrdisplayfocus")}}</dt> + <dd>Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).</dd> + <dt>{{domxref("Window.onvrdisplaypresentchange")}}</dt> + <dd>represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).</dd> +</dl> + +<h2 id="Construtores">Construtores</h2> + +<p>Consulte também as <a href="/pt-PT/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">Interfaces de DOM</a>.</p> + +<dl> + <dt>{{domxref("DOMParser")}}</dt> + <dd><code>DOMParser</code> can parse XML or HTML source stored in a string into a DOM <a href="https://developer.mozilla.org/en-US/docs/DOM/document" title="document">Document</a>. <code>DOMParser</code> is specified in <a href="https://w3c.github.io/DOM-Parsing/" title="http://html5.org/specs/dom-parsing.html">DOM Parsing and Serialization</a>.</dd> + <dt>{{domxref("Window.GeckoActiveXObject")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Image")}}</dt> + <dd>Used for creating an {{domxref("HTMLImageElement")}}.</dd> + <dt>{{domxref("Option")}}</dt> + <dd>Used for creating an {{domxref("HTMLOptionElement")}}</dd> + <dt>{{domxref("Window.QueryInterface")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.XMLSerializer")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Worker")}}</dt> + <dd>Used for creating a <a href="/en-US/docs/DOM/Using_web_workers">Web worker</a></dd> + <dt>{{domxref("Window.XPCNativeWrapper")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> + <dt>{{domxref("Window.XPCSafeJSObjectWrapper")}}</dt> + <dd>{{todo("NeedsContents")}}</dd> +</dl> + +<h2 id="Interfaces">Interfaces</h2> + +<p>Consulte <a href="/pt-PT/docs/DOM/DOM_Reference" title="/en-US/docs/DOM/DOM_Reference">Referência de DOM</a></p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Mozilla/trabalhar_com_janelas_no_codigo_chrome">Working with windows in chrome code</a></li> +</ul> diff --git a/files/pt-pt/web/api/window/open/index.html b/files/pt-pt/web/api/window/open/index.html new file mode 100644 index 0000000000..bb64902182 --- /dev/null +++ b/files/pt-pt/web/api/window/open/index.html @@ -0,0 +1,748 @@ +--- +title: Window.open() +slug: Web/API/Window/open +tags: + - API + - DOM + - Janela + - Referencia + - abrir + - metodo +translation_of: Web/API/Window/open +--- +<div>{{APIRef}}</div> + +<p>The {{domxref("Window")}} interface's <strong><code>open()</code></strong> method loads the specified resource into the browsing context (window, {{HTMLElement("iframe")}} or tab) with the specified name. If the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>var <em>window</em> = window.open(<em>url</em>, <em>windowName</em>, [<var>windowFeatures</var>]);</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>url</code></dt> + <dd>A {{domxref("DOMString")}} indicating the URL of the resource to be loaded. This can be a path or URL to an HTML page, image file, or any other resource which is supported by the browser. If the empty string ("") is specified as <code>url</code>, a blank page is opened into the targeted browsing context.</dd> + <dt><code>windowName</code></dt> + <dd>A {{domxref("DOMString")}} specifying the name of the browsing context (window, {{HTMLElement("iframe")}} or tab) into which to load the specified resource; if the name doesn't indicate an existing context, a new window is created and is given the name specified by <code>windowName</code>. This name can then be used as the target of links and forms by specifying it as the <code>target</code> attribute of {{HTMLElement("a")}} or {{HTMLElement("form")}} elements. The name should not contain whitespace. Keep in mind that this will <em>not</em> be used as the window's displayed title.</dd> + <dt><code>windowFeatures</code> {{optional_inline}}</dt> + <dd>A {{domxref("DOMString")}} containing a comma-separated list of window features given with their corresponding values in the form "name=value". These features include options such as the window's default size and position, whether or not to include scroll bars, and so forth. There must be no whitespace in the string. See {{anch("Window features")}} below for documentation of each of the features that can be specified.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>A {{domxref("Window")}} object representing to the newly created window. If the window couldn't be opened, the returned value is instead <code>null</code>. The returned <code>Window</code> reference can be used to access properties and methods of the new window as long as it complies with <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">Same-origin policy</a> security requirements.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>The <code>open()</code> method creates a new secondary browser window, similar to choosing New Window from the File menu. The <code>strUrl</code> parameter specifies the URL to be fetched and loaded in the new window. If <code>strUrl</code> is an empty string, then a new blank, empty window (URL <code>about:blank</code>) is created with the default toolbars of the main window.</p> + +<p>Note that remote URLs won't load immediately. When <code>window.open()</code> returns, the window always contains <code>about:blank</code>. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush:js">var windowObjectReference; +var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes"; + +function openRequestedPopup() { + windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures); +}</pre> + +<pre class="brush:js">var windowObjectReference; + +function openRequestedPopup() { + windowObjectReference = window.open( + "http://www.domainname.ext/path/ImageFile.png", + "DescriptiveWindowName", + "resizable,scrollbars,status" + ); +}</pre> + +<p>If a window with the name already exists, then <code>strUrl</code> is loaded into the <em>existing</em> window. In this case the return value of the method is the existing window and <code>strWindowFeatures</code> is ignored. Providing an empty string for <code>strUrl</code> is a way to get a reference to an open window by its name without changing the window's location. To open a <em>new</em> window on every call of <code>window.open()</code>, use the special value <code>_blank</code> for <code>strWindowName</code>.</p> + +<div class="note"> +<p><a href="#Note_on_use_of_window_open" id="Note_on_use_of_window_open">Note on the use of window.open to reopen an existing window</a> with name <code>strWindowName</code> : This functionality is not valid for all browsers and more with variable conditions. Firefox (50.0.1) functions as described: from the same domain+port reopen with same name will access the previously created window. Google Chrome (55.0.2883.87 m ) on the other hand will do it only from the same parent (as if the window was created dependent, which is the "opener"). This is a wide limitation and generates unbelievable complexity of development. Firefox (51.) gets the handle but cannot run any Element.focus() while Chrome can run focus() from opener to child but not between siblings nor, reverse, from child to opener. This function is the lonely key to get back the handle on a window if the developer has access only to its name (the name can be saved with cookies or local storage but not the window object handle). For now 10/01/2017 the differencies of behavior found recently have not still been tested for others Browsers. </p> +</div> + +<h2 id="Funcionalidades_de_janela">Funcionalidades de janela</h2> + +<p><code>strWindowFeatures</code> is an optional string containing a comma-separated list of requested features of the new window. After a window is opened, JavaScript can't be used to change the features. If <code>strWindowName</code> does not specify an existing window and the <code>strWindowFeatures</code> parameter is not provided (or if the <code>strWindowFeatures</code> parameter is an empty string), then the new secondary window will render the default toolbars of the main window.</p> + +<p>If the <code>strWindowFeatures</code> parameter is used and no size features are defined, then the new window dimensions will be the same as the dimensions of the most recently rendered window.</p> + +<p>If the <code>strWindowFeatures</code> parameter is used and if no position features are defined, then the left and top coordinates of the new window dimension will be 22 pixels from where the most recently rendered window was. An offset is universally implemented by browser manufacturers (it is 29 pixels in IE6 SP2 with the default theme) and its purpose is to help users to notice new windows opening. If the most recently used window was maximized, then there is no offset: the new window will be maximized as well.</p> + +<p><strong>If the <code>strWindowFeatures</code> parameter is used, the features that are not listed will be disabled or removed</strong> (except <code>titlebar</code> and <code>close</code>, which are by default <code>yes</code>).</p> + +<div class="note"> +<p><strong>Tip</strong>: If using the <code>strWindowFeatures</code> parameter, only list the features to be enabled or rendered; the others (except <code>titlebar</code> and <code>close</code>) will be disabled or removed. Note that in some browsers, users can override the <code>strWindowFeatures</code> settings and enable (or prevent the disabling of) features.</p> +</div> + +<p><img alt="Firefox Toolbars Illustration" src="/@api/deki/files/210/=FirefoxChromeToolbarsDescription7a.gif" style="display: block; margin: 0px auto;"></p> + +<h3 id="Funcionalidades_de_posição_e_tamanho">Funcionalidades de posição e tamanho</h3> + +<div>{{gecko_minversion_note("1.9.2", "Starting in Gecko 1.9.2 (Firefox 3.6), overriding the position of a window using window features will not change the persisted values saved by the session store feature. That means the next time the window is opened, it will still open in the saved location.")}}</div> + +<p><a href="#Note_on_position_and_dimension_error_correction">Note on position and dimension error correction</a></p> + +<div class="bug">{{bug(176320)}}</div> + +<p><a href="#Note_on_precedence">Note on precedence</a></p> + +<dl> + <dt id="left">left</dt> + <dd>Specifies the distance the new window is placed from the left side of the work area for applications of the user's operating system to the leftmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt id="top">top</dt> + <dd>Specifies the distance the new window is placed from the top side of the work area for applications of the user's operating system to the topmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt id="height">height</dt> + <dd>Specifies the height of the content area, viewing area of the new secondary window in pixels. The height value includes the height of the horizontal scrollbar if present. The minimum required value is 100.</dd> + <dd><a href="#Note_on_outerHeight_versus_height">Note on outerHeight versus height (or innerHeight)</a></dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt id="width">width</dt> + <dd>Specifies the width of the content area, viewing area of the new secondary window in pixels. The width value includes the width of the vertical scrollbar if present. The width value does not include the sidebar if it is expanded. The minimum required value is 100.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt>screenX</dt> + <dd>Deprecated. Same as <a href="#left">left</a> but only supported by Netscape and Mozilla-based browsers.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>screenY</dt> + <dd>Deprecated. Same as <a href="#topS">top</a> but only supported by Netscape and Mozilla-based browsers.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>centerscreen</dt> + <dd>Centers the window in relation to its parent's size and position. Requires chrome=yes.</dd> + <dt>outerHeight</dt> + <dd>Specifies the height of the whole browser window in pixels. This outerHeight value includes any/all present toolbar, window horizontal scrollbar (if present) and top and bottom window resizing borders. Minimal required value is 100.</dd> + <dd><strong>Note</strong>: since titlebar is always rendered, then requesting outerHeight=100 will make the innerHeight of the browser window under the minimal 100 pixels.</dd> + <dd><a href="#Note_on_outerHeight_versus_height">Note on outerHeight versus height (or innerHeight)</a></dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>outerWidth</dt> + <dd>Specifies the width of the whole browser window in pixels. This outerWidth value includes the window vertical scrollbar (if present) and left and right window resizing borders.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>innerHeight</dt> + <dd>Same as <a href="#height">height</a> but only supported by Netscape and Mozilla-based browsers. Specifies the height of the content area, viewing area of the new secondary window in pixels. The <var>innerHeight</var> value includes the height of the horizontal scrollbar if present. Minimal required value is 100.</dd> + <dd><a href="#Note_on_outerHeight_versus_height">Note on outerHeight versus height (or innerHeight)</a></dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>innerWidth</dt> + <dd>Same as <a href="#width">width</a> but only supported by Netscape and Mozilla-based browsers. Specifies the width of the content area, viewing area of the new secondary window in pixels. The innerWidth value includes the width of the vertical scrollbar if present. The innerWidth value does not include the sidebar if it is expanded. Minimal required value is 100.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> +</dl> + +<h3 id="Funcionalidades_da_barra_de_ferramentas_e_chrome">Funcionalidades da barra de ferramentas e chrome</h3> + +<dl> + <dt>NOTE: All features can be set to <var>yes</var> or <var>1</var>, or just be present to be "on". Set them to <var>no</var> or <var>0</var>, or in most cases just omit them, to be "off".</dt> + <dd>Example: "status=yes", "status=1", and "status" have identical results.</dd> + <dt>menubar</dt> + <dd>If this feature is on, then the new secondary window renders the menubar.</dd> + <dd>Mozilla and Firefox users can force new windows to always render the menubar by setting <code>dom.disable_window_open_feature.menubar</code> to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>toolbar</dt> + <dd>If this feature is on, then the new secondary window renders the Navigation Toolbar (Back, Forward, Reload, Stop buttons). In addition to the Navigation Toolbar, Mozilla-based browsers will render the Tab Bar if it is visible, present in the parent window. (If this feature is set to <var>no</var> all toolbars in the window will be invisible, for example extension toolbars).</dd> + <dd>Mozilla and Firefox users can force new windows to always render the Navigation Toolbar by setting <code>dom.disable_window_open_feature.toolbar</code> to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>location</dt> + <dd>If this feature is on, then the new secondary window renders the Location bar in Mozilla-based browsers. MSIE 5+ and Opera 7.x renders the Address Bar.</dd> + <dd>Mozilla and Firefox users can force new windows to always render the location bar by setting <code>dom.disable_window_open_feature.location</code> to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>. {{Fx_minversion_note(3, "In Firefox 3, <code>dom.disable_window_open_feature.location</code> now defaults to <var>true</var>, forcing the presence of the Location Bar much like in IE7. See bug 337344 for more information.")}}</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png">, <img alt="Opera 6+" src="/@api/deki/files/288/=Opera6.gif"></dd> + <dt>personalbar</dt> + <dd>If this feature is on, then the new secondary window renders the Personal Toolbar in Netscape 6.x, Netscape 7.x and Mozilla browser. It renders the Bookmarks Toolbar in Firefox. In addition to the Personal Toolbar, Mozilla browser will render the Site Navigation Bar if such toolbar is visible, present in the parent window.</dd> + <dd>Mozilla and Firefox users can force new windows to always render the Personal Toolbar/Bookmarks toolbar by setting <code>dom.disable_window_open_feature.personalbar</code> to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>directories {{obsolete_inline("2")}}</dt> + <dd>Obsolete synonym of personalbar. In IE, it rendered the Links bar. Supported in Gecko up to 1.9.2 and in IE up to 6.</dd> + <dt>status</dt> + <dd>If this feature is on, then the new secondary window has a status bar. Users can force the rendering of status bar in all Mozilla-based browsers, in MSIE 6 SP2 (<a href="#Note_on_security_issues_of_the_status_bar_presence">Note on status bar in XP SP2</a>) and in Opera 6+. The default preference setting in recent Mozilla-based browser releases and in Firefox 1.0 is to force the presence of the status bar.</dd> + <dd><a href="#Note_on_status_bar">Note on status bar</a></dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> +</dl> + +<h3 id="Funcionalidades_da_função_da_janela">Funcionalidades da função da janela</h3> + +<dl> + <dt>attention {{NonStandardBadge}}</dt> + <dd>If this feature is specified, the window is able to open even if another application is already in the foreground. This feature is for Firefox OS applications only, and is currently restricted to certified applications. See {{SectionOnPage("/en-US/Apps/Build/App_permissions", "Certified app permissions")}} for more information.</dd> + <dd>Supported in: <img alt="" src="https://mdn.mozillademos.org/files/8003/firefox_os_logo_wordmark-75px.png" style="height: 25px; width: 83px;"></dd> + <dt>dependent</dt> + <dd>If on, the new window is said to be dependent of its parent window. A dependent window closes when its parent window closes. A dependent window is minimized on the Windows task bar only when its parent window is minimized. On Windows platforms, a dependent window does not show on the task bar. A dependent window also stays in front of the parent window.</dd> + <dd>Dependent windows are not implemented on MacOS X, this option will be ignored.</dd> + <dd>The dependent feature is currently under revision to be removed ({{Bug(214867)}})</dd> + <dd>In MSIE 6, the nearest equivalent to this feature is the <code>showModelessDialog()</code> method.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>minimizable</dt> + <dd>This setting can only apply to dialog windows; "minimizable" requires <code>dialog=yes</code>. If <code>minimizable</code> is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. Any non-dialog window is always minimizable and <code>minimizable=no</code> will be ignored.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>fullscreen</dt> + <dd>Do not use. Not implemented in Mozilla. There are no plans to implement this feature in Mozilla.</dd> + <dd>This feature no longer works in MSIE 6 SP2 the way it worked in MSIE 5.x. The Windows taskbar, as well as the titlebar and the status bar of the window are not visible, nor accessible when fullscreen is enabled in MSIE 5.x.</dd> + <dd><code>fullscreen</code> always upsets users with large monitor screen or with dual monitor screen. Forcing <code>fullscreen</code> onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users.</dd> + <dd><a href="#Note_on_fullscreen">Note on fullscreen</a></dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png"></dd> + <dd><code>fullscreen</code> does not really work in MSIE 6 SP2.</dd> + <dt><a id="noopener" name="noopener">noopener</a></dt> + <dd>If this feature is set, the newly-opened window will open as normal, except that it will not have access back to the originating window (via {{domxref("Window.opener")}} — it returns <code>null</code>). In addition, the <code>window.open()</code> call will also return <code>null</code>, so the originating window will not have access to the new one either. This is useful for preventing untrusted sites opened via <code>window.open()</code> from tampering with the originating window, and vice versa.</dd> + <dd>Note that when <code>noopener</code> is used, nonempty target names other than <code>_top</code>, <code>_self</code>, and <code>_parent</code> are all treated like <code>_blank</code> in terms of deciding whether to open a new window/tab.<br> + <br> + This is supported in modern browsers including Chrome, and Firefox 52+. See also <code><a href="/en-US/docs/Web/HTML/Link_types#noopener">rel="noopener"</a></code>.</dd> + <dt>resizable</dt> + <dd>If this feature is on, the new secondary window will be resizable.</dd> + <dd><strong>Note</strong>: Starting with version 1.4, Mozilla-based browsers have a window resizing grippy at the right end of the status bar, this ensures that users can resize the browser window even if the web author requested this secondary window to be non-resizable. In such case, the maximize/restore icon in the window's titlebar will be disabled and the window's borders won't allow resizing but the window will still be resizable via that grippy in the status bar. + <p>Starting with Firefox 3, secondary windows are always resizable ({{Bug(177838)}})</p> + + <div class="note"> + <p><strong>Dica</strong>: For accessibility reasons, it is strongly recommended to set this feature always on</p> + </div> + </dd> + <dd>Mozilla and Firefox users can force new windows to be easily resizable by setting <code>dom.disable_window_open_feature.resizable</code> to <code><var>true</var></code> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>scrollbars</dt> + <dd>If this feature is on, the new secondary window will show horizontal and/or vertical scrollbar(s) if the document doesn't fit into the window's viewport. + <div class="note"> + <p><strong>Dica</strong>: For accessibility reasons, it is strongly encouraged to set this feature always on.</p> + </div> + </dd> + <dd>Mozilla and Firefox users can force this option to be always enabled for new windows by setting {{pref("dom.disable_window_open_feature.scrollbars")}} to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>. <strong>Starting in Firefox 49, this feature is on by default, and the {{pref("dom.disable_window_open_feature.scrollbars")}} preference has been removed.</strong></dd> + <dd><a href="#Note_on_scrollbars">Note on scrollbars</a></dd> + <dd>Supported in: <img alt="Internet Explorer 5+" src="/@api/deki/files/260/=MSIE_ico.png">, <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> +</dl> + +<h3 id="Funcionalidades_que_requerem_privilégios">Funcionalidades que requerem privilégios</h3> + +<p>The following features require the <code>UniversalBrowserWrite</code> privilege, otherwise they will be ignored. Chrome scripts have this privilege automatically, others have to request it from the PrivilegeManager.</p> + +<dl> + <dt>chrome</dt> + <dd><strong>Note</strong>: Starting with Mozilla 1.7/Firefox 0.9, this feature requires the <code>UniversalBrowserWrite</code> privilege ({{Bug(244965)}}). Without this privilege, it is ignored.</dd> + <dd>If on, the page is loaded as window's only content, without any of the browser's interface elements. There will be no context menu defined by default and none of the standard keyboard shortcuts will work. The page is supposed to provide a user interface of its own, usually this feature is used to open XUL documents (standard dialogs like the JavaScript Console are opened this way).</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>dialog</dt> + <dd><strong>Note</strong>: Starting with Firefox 44, this feature can only be used with chrome privileges. If content attempts to toggle this feature, it will be ignored.</dd> + <dd><a href="/@api/deki/files/268/=MenuSystemCommands.png" title="MenuSystemCommands.png"><img alt="MenuSystemCommands.png" class="internal lwrap" src="/@api/deki/files/268/=MenuSystemCommands.png?size=webview" style="float: left; height: 170px; width: 170px;"> </a> The <code>dialog</code> feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. Mozilla 1.2+ and Netscape 7.1 will render the other menu system commands (in FF 1.0 and in NS 7.0x, the command system menu is not identified with the Firefox/NS 7.0x icon on the left end of the titlebar: that's probably a bug. You can access the command system menu with a right-click on the titlebar). Dialog windows are windows which have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. They are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. On Mac systems, dialog windows have a different window border and they may get turned into a sheet.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>modal</dt> + <dd><strong>Note</strong>: Starting with Mozilla 1.2.1, this feature requires the <code>UniversalBrowserWrite</code> privilege ({{Bug(180048)}}). Without this privilege, it is ignored.</dd> + <dd>If on, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the <a href="/en-US/docs/DOM/window.alert" title="DOM/window.alert">alert() function</a>.</dd> + <dd>The exact behavior of modal windows depends on the platform and on the Mozilla release version. + <div class="note"> + <p><strong>Nota:</strong> As of {{Gecko("1.9")}}, the Internet Explorer equivalent to this feature is the {{domxref("window.showModalDialog()")}} method. For compatibility reasons, it's now supported in Firefox. Note also that starting in {{Gecko("2.0")}}, you can use {{domxref("window.showModalDialog()")}} without UniversalBrowserWrite privileges.</p> + </div> + </dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>titlebar</dt> + <dd>By default, all new secondary windows have a titlebar. If set to <var>no or 0</var>, this feature removes the titlebar from the new secondary window.</dd> + <dd>Mozilla and Firefox users can force new windows to always render the titlebar by setting<br> + <code>dom.disable_window_open_feature.titlebar</code><br> + to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>alwaysRaised</dt> + <dd>If on, the new window will always be displayed on top of other browser windows, regardless of whether it is active or not.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>alwaysLowered</dt> + <dd>If on, the new created window floats below, under its own parent when the parent window is not minimized. alwaysLowered windows are often referred as pop-under windows. The alwaysLowered window can not be on top of the parent but the parent window can be minimized. In NS 6.x, the alwaysLowered window has no minimize system command icon and no restore/maximize system command.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> + <dt>z-lock</dt> + <dd>Same as <code>alwaysLowered</code>.</dd> + <dt>close</dt> + <dd>When set to <var>no or 0</var>, this feature removes the system close command icon and system close menu item. It will only work for dialog windows (<code>dialog</code> feature set). <code>close=no</code> will override <code>minimizable=yes</code>.</dd> + <dd>Mozilla and Firefox users can force new windows to always have a close button by setting<br> + <code>dom.disable_window_open_feature.close</code><br> + to <var>true</var> in <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#about_config">about:config</a> or in their <a href="http://support.mozilla.com/en-US/kb/Editing+configuration+files#user_js">user.js file</a>.</dd> + <dd>Supported in: <img alt="Netscape 6.x" src="/@api/deki/files/785/=Ns6.gif">, <img alt="Netscape 7.x" src="/@api/deki/files/281/=NS7_ico4.gif">, <img alt="Mozilla 1.x" src="/@api/deki/files/277/=Mozilla1_ico.png">, <img alt="Firefox 1.x" src="/@api/deki/files/200/=FF1x.png"></dd> +</dl> + +<p>The position and size feature elements require a number to be set. The toolbars and window functionalities can be set with a <var>yes</var> or <var>no</var>; you can use <var>1</var> instead of <var>yes</var> and <var>0</var> instead of <var>no</var>. The toolbar and functionality feature elements also accept the shorthand form: you can turn a feature on by simply listing the feature name in the <var>features</var> string. If you supply the <var>features</var> parameter, then the <code>titlebar</code> and <code>close</code> are still <var>yes</var> by default, but the other features which have a <var>yes</var>/<var>no</var> choice will be <var>no</var> by default and will be turned off.</p> + +<p>Example:</p> + +<pre class="brush:js">var windowObjectReference; // global variable + +function openRequestedPopup() { + windowObjectReference = window.open( + "http://www.domainname.ext/path/ImgFile.png", + "DescriptiveWindowName", + "width=420,height=230,resizable,scrollbars=yes,status=1" + ); +}</pre> + +<p>In this example, the window will be resizable, it will render scrollbar(s) if needed, if the content overflows requested window dimensions and it will render the status bar. It will not render the menubar nor the location bar. Since the author knew about the size of the image (400 pixels wide and 200 pixels high), he added the margins applied to the root element in MSIE 6 which is 15 pixels for top margin, 15 pixels for the bottom margin, 10 pixels for the left margin and 10 pixels for the right margin.</p> + +<h2 id="As_melhores_práticas">As melhores práticas</h2> + +<pre class="brush:js"><script type="text/javascript"> +var windowObjectReference = null; // global variable + +function openFFPromotionPopup() { + if(windowObjectReference == null || windowObjectReference.closed) + /* if the pointer to the window object in memory does not exist + or if such pointer exists but the window was closed */ + + { + windowObjectReference = window.open("http://www.spreadfirefox.com/", + "PromoteFirefoxWindowName", "resizable,scrollbars,status"); + /* then create it. The new window will be created and + will be brought on top of any other window. */ + } + else + { + windowObjectReference.focus(); + /* else the window reference must exist and the window + is not closed; therefore, we can bring it back on top of any other + window with the focus() method. There would be no need to re-create + the window or to reload the referenced resource. */ + }; +} +</script> + +(...) + +<p><a + href="http://www.spreadfirefox.com/" + target="PromoteFirefoxWindowName" + onclick="openFFPromotionPopup(); return false;" + title="This link will create a new window or will re-use an already opened one" +>Promote Firefox adoption</a></p> +</pre> + +<p>The above code solves a few usability problems related to links opening secondary window. The purpose of the <code>return false</code> in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. But if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "PromoteFirefoxWindowName". If no frame nor window has the name "PromoteFirefoxWindowName", then the browser will create a new window and will name it "PromoteFirefoxWindowName".</p> + +<p>More reading on the use of the target attribute:</p> + +<p><a href="http://www.w3.org/TR/html401/present/frames.html#h-16.3.2">HTML 4.01 Target attribute specifications</a></p> + +<p><a href="http://www.htmlhelp.com/faq/html/links.html#new-window">How do I create a link that opens a new window?</a></p> + +<p>You can also parameterize the function to make it versatile, functional in more situations, therefore re-usable in scripts and webpages:</p> + +<pre class="brush:js"><script type="text/javascript"> +var windowObjectReference = null; // global variable + +function openRequestedPopup(strUrl, strWindowName) { + if(windowObjectReference == null || windowObjectReference.closed) { + windowObjectReference = window.open(strUrl, strWindowName, + "resizable,scrollbars,status"); + } else { + windowObjectReference.focus(); + }; +} +</script> + +(...) + +<p><a + href="http://www.spreadfirefox.com/" + target="PromoteFirefoxWindow" + onclick="openRequestedPopup(this.href, this.target); return false;" + title="This link will create a new window or will re-use an already opened one" +>Promote Firefox adoption</a></p> +</pre> + +<p>You can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner:</p> + +<pre class="brush:js"><script type="text/javascript"> +var windowObjectReference = null; // global variable +var PreviousUrl; /* global variable which will store the + url currently in the secondary window */ + +function openRequestedSinglePopup(strUrl) { + if(windowObjectReference == null || windowObjectReference.closed) { + windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", + "resizable,scrollbars,status"); + } else if(PreviousUrl != strUrl) { + windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName", + "resizable=yes,scrollbars=yes,status=yes"); + /* if the resource to load is different, + then we load it in the already opened secondary window and then + we bring such window back on top/in front of its parent window. */ + windowObjectReference.focus(); + } else { + windowObjectReference.focus(); + }; + + PreviousUrl = strUrl; + /* explanation: we store the current url in order to compare url + in the event of another call of this function. */ +} +</script> + +(...) + +<p><a + href="http://www.spreadfirefox.com/" + target="SingleSecondaryWindowName" + onclick="openRequestedSinglePopup(this.href); return false;" + title="This link will create a new window or will re-use an already opened one" +>Promote Firefox adoption</a></p> + +<p><a + href="http://www.mozilla.org/support/firefox/faq" + target="SingleSecondaryWindowName" + onclick="openRequestedSinglePopup(this.href); return false;" + title="This link will create a new window or will re-use an already opened one" +>Firefox FAQ</a></p> +</pre> + +<h2 id="Perguntas_Mais_Frequentes">Perguntas Mais Frequentes</h2> + +<dl> + <dt>How can I prevent the confirmation message asking the user whether he wants to close the window?</dt> + <dd>You can not. <strong>New windows not opened by javascript can not as a rule be closed by JavaScript.</strong> The JavaScript Console in Mozilla-based browsers will report the warning message: <code>"Scripts may not close windows that were not opened by script."</code> Otherwise the history of URLs visited during the browser session would be lost.</dd> + <dd><a href="/en-US/docs/DOM/window.close" title="DOM/window.close">More on the window.close()</a> method</dd> + <dt>How can I bring back the window if it is minimized or behind another window?</dt> + <dd>First check for the existence of the window object reference of such window and if it exists and if it has not been closed, then use the <a href="/en-US/docs/DOM/window.focus" title="DOM/window.focus">focus()</a> method. There is no other reliable way. You can examine an <a href="#Best_practices">example explaining how to use the focus() method</a>.</dd> + <dt>How do I force a maximized window?</dt> + <dd>You cannot. All browser manufacturers try to make the opening of new secondary windows noticed by users and noticeable by users to avoid confusion, to avoid disorienting users.</dd> + <dt>How do I turn off window resizability or remove toolbars?</dt> + <dd>You cannot force this. Users with Mozilla-based browsers have absolute control over window functionalities like resizability, scrollability and toolbars presence via user preferences in <code>about:config</code>. Since your users are the ones who are supposed to use such windows (and not you, being the web author), the best is to avoid interfering with their habits and preferences. We recommend to always set the resizability and scrollbars presence (if needed) to yes to insure accessibility to content and usability of windows. This is in the best interests of both the web author and the users.</dd> + <dt>How do I resize a window to fit its content?</dt> + <dd>You can not reliably because the users can prevent the window from being resized by unchecking the <code>Edit/Preferences/Advanced/Scripts & Plug-ins/Allow Scripts to/ Move or resize existing windows</code> checkbox in Mozilla or <code>Tools/Options.../Content tab/Enable Javascript/Advanced button/Move or resize existing windows</code> checkbox in Firefox or by setting <code>dom.disable_window_move_resize</code> to <var>true</var> in <code>about:config</code> or by editing accordingly their <a href="http://www.mozilla.org/support/firefox/edit#user">user.js file</a>.</dd> + <dd>In general, users usually disable moving and resizing of existing windows because allowing authors' scripts to do so has been abused overwhelmingly in the past and the rare scripts that do not abuse such feature are often wrong, inaccurate when resizing the window. 99% of all those scripts disable window resizability and disable scrollbars when in fact they should enable both of these features to allow a cautious and sane fallback mechanism if their calculations are wrong.</dd> + <dd>The window method <a href="/en-US/docs/DOM/window.sizeToContent" title="DOM/window.sizeToContent">sizeToContent()</a> is also disabled if the user unchecks the preference <code>Move or resize existing windows</code> checkbox. Moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best. The web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true.</dd> + <dt>How do I open a referenced resource of a link in a new tab? or in a specific tab?</dt> + <dd>To open a resource in a new tab see <a href="https://developer.mozilla.org/en-US/docs/XUL/tabbrowser">Tabbed browser</a>. Some <a href="https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser?redirectlocale=en-US&redirectslug=Code_snippets%2FTabbed_browser">Code snippets</a> are available. If you are using the SDK, tabs are <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/tabs">handled a bit differently</a></dd> + <dd><a href="http://kmeleon.sourceforge.net/">K-meleon 1.1</a>, a Mozilla-based browser, gives complete control and power to the user regarding how links are opened. Only the user can set his advanced preferences to do that. Some advanced extensions also give Mozilla and Firefox a lot of power over how referenced resources are loaded.</dd> + <dd>In a few years, the <a href="http://www.w3.org/TR/2004/WD-css3-hyperlinks-20040224/#target0">target property of the CSS3 hyperlink module</a> may be implemented (if CSS3 Hyperlink module as it is right now is approved). And even if and when this happens, you can expect developers of browsers with tab-browsing to give the user entire veto power and full control over how links can open web pages. How to open a link should always be entirely under the control of the user.</dd> + <dt>How do I know whether a window I opened is still open?</dt> + <dd>You can test for the existence of the window object reference which is the returned value in case of success of the window.open() call and then verify that <var>windowObjectReference</var>.closed return value is <var>false</var>.</dd> + <dt>How can I tell when my window was blocked by a popup blocker?</dt> + <dd>With the built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 SP2, you have to check the return value of <code>window.open()</code>: it will be <var>null</var> if the window wasn't allowed to open. However, for most other popup blockers, there is no reliable way.</dd> + <dt>What is the JavaScript relationship between the main window and the secondary window?</dt> + <dd>The <code>window.open()</code> method gives a main window a reference to a secondary window; the <a href="/en-US/docs/DOM/window.opener" title="DOM/window.opener">opener</a> property gives a secondary window a reference to its main window.</dd> + <dt>I can not access the properties of the new secondary window. I always get an error in the javascript console saying "Error<span class="nowiki">:</span> uncaught exception<span class="nowiki">:</span> Permission denied to get property <property_name or method_name>. Why is that?</dt> + <dd>It is because of the cross-domain script security restriction (also referred as the "Same Origin Policy"). A script loaded in a window (or frame) from a distinct origin (domain name) <strong>cannot get nor set</strong> properties of another window (or frame) or the properties of any of its HTML objects coming from another distinct origin (domain name). Therefore, before executing a script targeting a secondary window, the browser in the main window will verify that the secondary window has the same domain name.</dd> + <dd>More reading on the cross-domain script security restriction: <a href="http://www.mozilla.org/projects/security/components/same-origin.html" rel="freelink">http://www.mozilla.org/projects/secu...me-origin.html</a></dd> +</dl> + +<h2 id="Problemas_de_usabilidade">Problemas de usabilidade</h2> + +<h3 id="Evitar_o_recurso_a_window.open()">Evitar o recurso a <code>window.open()</code></h3> + +<p>Generally speaking, it is preferable to avoid resorting to window.open() for several reasons:</p> + +<ul> + <li>All Mozilla-based browsers offer <a href="https://developer.mozilla.org/en-US/docs/XUL/tabbrowser">tab-browsing</a> and this is the preferred mode of <a href="https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Tabbed_browser?redirectlocale=en-US&redirectslug=Code_snippets%2FTabbed_browser">opening referenced resources</a> (<a href="https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/tabs">SDK</a>)... not just in Mozilla-based browsers but in all other browsers offering tab-browsing. In other words, tab-capable browser users overall prefer opening new tabs than opening new windows in a majority of webpage situations. Tab-capable browsers have rapidly gained support and enthusiasm on internet in the last 3 years; this trend will not revert back. MSIE 7, released in October 2006, has full support for tab browsing.</li> + <li>There are now <a href="https://addons.mozilla.org/seamonkey/browse/type:1/cat:48/sort:updated">several Mozilla extensions</a> (like Multizilla) and <a href="https://addons.update.mozilla.org/firefox/browse/type:1/cat:14/sort:updated">Firefox extensions</a> (like <a href="https://addons.mozilla.org/firefox/addon/158">Tabbrowser preferences</a>), features, settings and advanced preferences based on tab-browsing and based on converting window.open() calls into opening tabs, based on neutralizing window.open() calls, in particular in neutralizing unrequested openings of new windows (often referred as blocking unrequested popups or as blocking script-initiated windows opening automatically). Such features found in extensions include opening a link in a new window or not, in the same window, in a new tab or not, in "background" or not. Coding carelessly to open new windows can no longer be assured of success, can not succeed by force and, if it does, it will annoy a majority of users.</li> + <li>New windows can have menubar missing, scrollbars missing, status bar missing, window resizability disabled, etc.; new tabs can not be missing those functionalities or toolbars (or at least, the toolbars which are present by default). Therefore, tab-browsing is preferred by a lot of users because the normal user-interface of the browser window they prefer is kept intact, remains stable.</li> + <li>Opening new windows, even with reduced features, uses considerably a lot of the user's system resources (cpu, RAM) and involves considerably a lot of coding in the source code (security management, memory management, various code branchings sometimes quite complex, window frame/chrome/toolbars building, window positioning and sizing, etc.). Opening new tabs is less demanding on the user's system resources (and faster to achieve) than opening new windows.</li> +</ul> + +<h3 id="Oferecer_para_abrir_uma_hiperligação_numa_nova_janela_utilizando_estas_linhas_diretrizes">Oferecer para abrir uma hiperligação numa nova janela, utilizando estas linhas diretrizes</h3> + +<p>If you want to offer to open a link in a new window, then follow tested and recommendable usability and accessibility guidelines:</p> + +<h4 id="Never_use_this_form_of_code_for_links_<a_hrefjavascriptwindow.open(...)_...>"><em>Never</em> use this form of code for links: <code><a href="javascript:window.open(...)" ...></code></h4> + +<p>"javascript:" links break accessibility and usability of webpages in every browser.</p> + +<ul> + <li>"javascript:" pseudo-links become dysfunctional when javascript support is disabled or inexistent. Several corporations allow their employees to surf on the web but under strict security policies: no javascript enabled, no java, no activeX, no Flash. For various reasons (security, public access, text browsers, etc..), about 5% to 10% of users on the web surf with javascript disabled.</li> + <li>"javascript:" links will interfere with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, tab-browsing features in extensions, etc.</li> + <li>"javascript:" links will interfere with the process of indexing webpages by search engines.</li> + <li>"javascript:" links interfere with assistive technologies (e.g. voice browsers) and several web-aware applications (e.g. <abbr title="Personal Digital Assistant">PDAs</abbr> and mobile browsers).</li> + <li>"javascript:" links also interfere with "mouse gestures" features implemented in browsers.</li> + <li>Protocol scheme "javascript:" will be reported as an error by link validators and link checkers.</li> +</ul> + +<p><strong>Further reading:</strong></p> + +<ul> + <li><a href="http://www.useit.com/alertbox/20021223.html">Top Ten Web-Design Mistakes of 2002</a>, 6. JavaScript in Links, Jakob Nielsen, December 2002</li> + <li><a href="http://www.evolt.org/article/Links_and_JavaScript_Living_Together_in_Harmony/17/20938/">Links & JavaScript Living Together in Harmony</a>, Jeff Howden, February 2002</li> + <li><a href="http://jibbering.com/faq/#FAQ4_24">comp.lang.javascript newsgroup discussion FAQ on "javascript:" links</a></li> +</ul> + +<h4 id="Never_use_<a_href_onclickwindow.open(...)>">Never use <code><a href="#" onclick="window.open(...);"></code></h4> + +<p>Such pseudo-link also breaks accessibility of links. <strong>Always use a real URL for the href attribute value</strong> so that if javascript support is disabled or inexistent or if the user agent does not support opening of secondary window (like MS-Web TV, text browsers, etc), then such user agents will still be able to load the referenced resource according to its default mode of opening/handling a referenced resource. This form of code also interferes with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, Ctrl+Enter on links, "mouse gestures" features.</p> + +<h4 id="Always_identify_links_which_will_create_(or_will_re-use)_a_new_secondary_window">Always identify links which will create (or will re-use) a new, secondary window</h4> + +<p>Identify links that will open new windows in a way that helps navigation for users by coding the title attribute of the link, by adding an icon at the end of the link or by coding the cursor accordingly.</p> + +<p>The purpose is to warn users in advance of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (Back toolbar button is disabled).</p> + +<blockquote> +<p>"Users often don't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. So a user who tries to return to the origin will be confused by a grayed out <em>Back</em> button."<br> + quote from <a href="http://www.useit.com/alertbox/990530.html">The Top Ten <em>New</em> Mistakes of Web Design</a>: 2. Opening New Browser Windows, Jakob Nielsen, May 1999</p> +</blockquote> + +<p>When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not).</p> + +<p><strong>Referências</strong></p> + +<ul> + <li>"If your link spawns a new window, or causes another windows to 'pop up' on your display, or move the focus of the system to a new FRAME or Window, then the nice thing to do is to tell the user that something like that will happen." <a href="http://www.w3.org/WAI/wcag-curric/sam77-0.htm">World Wide Web Consortium Accessibility Initiative regarding popups</a></li> + <li>"Use link titles to provide users with a preview of where each link will take them, before they have clicked on it." <a href="http://www.useit.com/alertbox/991003.html">Ten Good Deeds in Web Design</a>, Jakob Nielsen, October 1999</li> + <li><a href="http://www.useit.com/alertbox/980111.html">Using Link Titles to Help Users Predict Where They Are Going</a>, Jakob Nielsen, January 1998</li> +</ul> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header" colspan="4">Example "New Window" Icons & Cursors</td> + </tr> + <tr> + <td><img alt="New window icon from yahoo.com" src="/@api/deki/files/782/=NewwindowYahoo.png"></td> + <td><img alt="New window icon from microsoft.com" src="/@api/deki/files/780/=NewwinMSIE.gif"></td> + <td><img alt="New window icon from webaim.org" src="/@api/deki/files/296/=Popup_requested_new_window.gif"></td> + <td><img alt="New window icon from sun.com" src="/@api/deki/files/811/=PopupImageSun.gif"></td> + </tr> + <tr> + <td><img alt="New window icon from bbc.co.uk" src="/@api/deki/files/795/=Opennews_rb.gif"></td> + <td><img alt="New window icon from Accessible Internet Solutions" src="/@api/deki/files/15/=AIS_NewWindowIcon.png"></td> + <td><img alt="New window icon from accessify.com" src="/@api/deki/files/809/=Pop-up-launcher.gif"></td> + <td><img alt="New window icon from webstyleguide.com" src="/@api/deki/files/417/=Webstyleguide_com_newwind.gif"></td> + </tr> + <tr> + <td><img alt="New window icon from an unknown source" src="/@api/deki/files/810/=Popicon_1.gif"></td> + <td><img alt="New window icon from an unknown source" src="/@api/deki/files/779/=New.gif"></td> + <td><img alt="New window icon from an unknown source" src="/@api/deki/files/419/=WillCreateOrRecycleNewWindow.gif"></td> + <td><img alt="New window icon from gtalbot.org" src="/@api/deki/files/287/=OpenRequestedPopup.png"></td> + </tr> + <tr> + <td colspan="2"><img alt="New window cursor from draig.de" src="/@api/deki/files/169/=Cursor_LinkNewWindowTargetBlank.png"></td> + <td colspan="2"><img alt="New window cursor from mithgol.ru" src="/@api/deki/files/170/=Cursor_newwindowSergeySokoloff.png"></td> + </tr> + </tbody> +</table> + +<h4 id="Utilziar_sempre_o_atributo_target">Utilziar sempre o atributo <em>target</em></h4> + +<p>If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g. some user agents which can not create new windows, like MS Web TV, will fetch the referenced resource and append it at the end of the current document. The goal and the idea is to try to provide - <strong>not impose</strong> - to the user a way to open the referenced resource, a mode of opening the link. Your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user.</p> + +<h4 id="Não_utilizar_target_blank">Não utilizar <code>target="_blank"</code></h4> + +<p>Always provide a meaningful name to your target attribute and try to reuse such target attribute in your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window which is recycled. On the other hand, using "_blank" as the target attribute value will create several new and unnamed windows on the user's desktop which can not be recycled, reused. In any case, if your code is well done, it should not interfere with the user's final choice but rather merely offer him more choices, more ways to open links and more power to the tool he's using (a browser).</p> + +<h2 id="Glossário">Glossário</h2> + +<dl> + <dt>Opener window, parent window, main window, first window</dt> + <dd>Terms often used to describe or to identify the same window. It is the window from which a new window will be created. It is the window on which the user clicked a link which lead to the creation of another, new window.</dd> + <dt>Sub-window, child window, secondary window, second window</dt> + <dd>Terms often used to describe or to identify the same window. It is the new window which was created.</dd> + <dt>Unrequested popup windows</dt> + <dd>Script-initiated windows opening automatically without the user's consent.</dd> +</dl> + +<h2 id="Especificação">Especificação</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'browsers.html#dom-open', 'Window.open()')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{ SpecName('CSSOM View', '#the-features-argument-to-the-open()-method', 'The features argument to the open() method') }}</td> + <td>{{ Spec2('CSSOM View') }}</td> + <td>Defines the effect of the <code>features</code> argument</td> + </tr> + </tbody> +</table> + +<h2 id="Notas">Notas</h2> + +<h3 id="Nota_na_precedência">Nota na precedência</h3> + +<p>In cases where <code>left</code> and <code>screenX</code> (and/or <code>top</code> and <code>screenY</code>) have conflicting values, then <code>left</code> and <code>top</code> have precedence over <code>screenX</code> and <code>screenY</code> respectively. If <code>left</code> and <code>screenX</code> (and/or <code>top</code> and <code>screenY</code>) are defined in the <var>features</var> list, then <code>left</code> (and/or <code>top</code>) will be honored and rendered. In the following example the new window will be positioned at 100 pixels from the left side of the work area for applications of the user's operating system, not at 200 pixels.</p> + +<pre class="brush:js">windowObjectReference = window.open( + "http://news.bbc.co.uk/", + "BBCWorldNewsWindowName", + "left=100,screenX=200,resizable,scrollbars,status" +);</pre> + +<p>If left is set but top has no value and screenY has a value, then left and screenY will be the coordinate positioning values of the secondary window.</p> + +<p>outerWidth has precedence over width and width has precedence over innerWidth. outerHeight has precedence over height and height has precedence over innerHeight. In the following example, Mozilla-browsers will create a new window with an outerWidth of 600 pixels wide and will ignore the request of a width of 500 pixels and will also ignore the request of an innerWidth of 400 pixels.</p> + +<pre class="brush:js">windowObjectReference = window.open( + "http://www.wwf.org/", + "WWildlifeOrgWindowName", + "outerWidth=600,width=500,innerWidth=400,resizable,scrollbars,status" +);</pre> + +<h3 id="Nota_na_correção_de_erro_da_posição_e_dimensão">Nota na correção de erro da posição e dimensão</h3> + +<p>Requested position and requested dimension values in the <var>features</var> list will not be honored and <strong>will be corrected</strong> if any of such requested value does not allow the entire browser window to be rendered within the work area for applications of the user's operating system. <strong>No part of the new window can be initially positioned offscreen. This is by default in all Mozilla-based browser releases.</strong></p> + +<p><a href="http://msdn2.microsoft.com/en-us/library/ms997645.aspx#xpsp_topic5">MSIE 6 SP2 has a similar error correction mechanism</a> but it is not activated by default in all security levels: a security setting can disable such error correction mechanism.</p> + +<h3 id="Nota_nas_scrollbars">Nota nas <em>scrollbars</em></h3> + +<p>When content overflows window viewport dimensions, then scrollbar(s) (or some scrolling mechanism) are necessary to ensure that content can be accessed by users. Content can overflow window dimensions for several reasons which are outside the control of web authors:</p> + +<ul> + <li>user resizes the window</li> + <li>user increases the text size of fonts via View/Text Zoom (%) menuitem in Mozilla or View/Text Size/Increase or Decrease in Firefox</li> + <li>user sets a minimum font size for pages which is bigger than the font-size the web author requested. People over 40 years old or with particular viewing habit or reading preference often set a minimal font size in Mozilla-based browsers.</li> + <li>web author is not aware of default margin (and/or border and/or padding) values applying to root element or body node in various browsers and various browser versions</li> + <li>user uses an user stylesheet (<a href="http://www.mozilla.org/support/firefox/edit#content">userContent.css in Mozilla-based browsers</a>) for his viewing habits which increases document box dimensions (margin, padding, default font size)</li> + <li>user can customize individually the size (height or width) of most toolbars via operating system settings. E.g. window resizing borders, height of browser titlebar, menubar, scrollbars, font size are entirely customizable by the user in Windows XP operating system. These toolbars dimensions can also be set via browser themes and skins or by operating system themes</li> + <li>web author is unaware that the user default browser window has custom toolbar(s) for specific purpose(s); e.g.: prefs bar, web developer bar, accessibility toolbar, popup blocking and search toolbar, multi-feature toolbar, etc.</li> + <li>user uses assistive technologies or add-on features which modify the operating system's work area for applications: e.g. MS-Magnifier</li> + <li>user repositions and/or resizes directly or indirectly the operating system's work area for applications: e.g. user resizes the Windows taskbar, user positions the Windows taskbar on the left side (arabic language based) or right side (Hebrew language), user has a permanent MS-Office quick launch toolbar, etc.</li> + <li>some operating system (Mac OS X) forces presence of toolbars which can then fool the web author's anticipations, calculations of the effective dimensions of the browser window</li> +</ul> + +<h3 id="Nota_na_barra_de_estado">Nota na barra de estado</h3> + +<p>You should assume that a large majority of browsers will have the status bar or that a large majority of users will want to force the status bar presence: best is to always set this feature to yes. Also, if you specifically request to remove the status bar, then Firefox users will not be able to view the Site Navigation toolbar if it is installed. In Mozilla and in Firefox, all windows with a status bar have a window resizing grippy at its right-most side. The status bar also provides info on http connection, hypertext resource location, download progress bar, encryption/secure connection info with <abbr title="Secure Socket Layer">SSL</abbr> connection (displaying a yellow padlock icon), internet/security zone icons, privacy policy/cookie icon, etc. <strong>Removing the status bar usually removes a lot of functionality, features and information considered useful (and sometimes vital) by the users.</strong></p> + +<h3 id="Nota_nos_problemas_de_segurança_da_presença_da_barra_de_estado">Nota nos problemas de segurança da presença da barra de estado</h3> + +<p>In MSIE 6 for XP SP2: For windows opened using <code>window.open()</code>:</p> + +<blockquote> +<p>"For windows opened using window.open():<br> + Expect the status bar to be present, and code for it. <strong>The status bar will be on by default</strong> and is 20-25 pixels in height. (...)"<br> + quote from <a href="http://msdn2.microsoft.com/en-us/library/ms997645.aspx#xpsp_topic5">Fine-Tune Your Web Site for Windows XP Service Pack 2, Browser Window Restrictions in XP SP2</a></p> +</blockquote> + +<blockquote> +<p>"(...) windows that are created using the window.open() method can be called by scripts and used to spoof a user interface or desktop or to hide malicious information or activity by sizing the window so that the status bar is not visible.<br> + Internet Explorer windows provide visible security information to the user to help them ascertain the source of the Web page and the security of the communication with that page. When these elements are not in view, the user might think they are on a more trusted page or interacting with a system process when they are actually interacting with a malicious host. (...)<br> + <strong>Script-initiated windows will be displayed fully, with the Internet Explorer title bar and status bar.</strong> (...)<br> + Script management of Internet Explorer status bar<br> + Detailed description<br> + <strong>Internet Explorer has been modified to not turn off the status bar for any windows. The status bar is always visible for all Internet Explorer windows.</strong> (...) Without this change, windows that are created using the window.open() method can be called by scripts and spoof a user interface or desktop or hide malicious information or activity by hiding important elements of the user interface from the user.<br> + The status bar is a security feature of Internet Explorer windows that provides Internet Explorer security zone information to the user. This zone cannot be spoofed (...)"<br> + quote from <a href="http://technet.microsoft.com/en-us/library/bb457150.aspx#ECAA">Changes to Functionality in Microsoft Windows XP Service Pack 2, Internet Explorer Window Restrictions</a></p> +</blockquote> + +<h3 id="Nota_no_ecrã_completo">Nota no ecrã completo</h3> + +<p>In MSIE 6 for XP SP2:</p> + +<ul> + <li>"window.open() with fullscreen=yes will now result in a maximized window, not a kiosk mode window."</li> + <li>"The definition of the fullscreen=yes specification is changed to mean 'show the window as maximized,' which will keep the title bar, address bar, and status bar visible."</li> +</ul> + +<h4 id="Referências">Referências:</h4> + +<ul> + <li><a href="http://msdn2.microsoft.com/en-us/library/ms997645.aspx#xpsp_topic5">Fine-Tune Your Web Site for Windows XP Service Pack 2</a></li> + <li><a href="http://technet.microsoft.com/en-us/library/bb457150.aspx#ECAA">Changes to Functionality in Microsoft Windows XP Service Pack 2, Script sizing of Internet Explorer windows</a></li> +</ul> + +<h3 id="Nota_em_outerHeight_versus_height">Nota em outerHeight <em>versus </em>height</h3> + +<p><img alt="innerHeight vs outerHeight illustration" src="/@api/deki/files/212/=FirefoxInnerVsOuterHeight.png"></p> + +<h3 id="Nota_na_atualização_(recarregar_página)_vs._abrir_uma_nova_janelaseparador">Nota na atualização (recarregar página) vs. abrir uma nova janela/separador</h3> + +<p>If the <code>strWindowName</code> parameter is omitted, a new window or tab is opened. If a window with the same name already exists, the existing window is refreshed.</p> + +<pre class="brush:js">//Always opens a new window/tab +window.open("map.php"); + +//Refreshes an existing window/tab that was opened with the same name, if one exists +window.open("map.php", "BiggerMap");</pre> + +<h2 id="Tutoriais">Tutoriais</h2> + +<ul> + <li><a href="http://www.infimum.dk/HTML/JSwindows.html">JavaScript windows (tutorial)</a> by Lasse Reichstein Nielsen</li> + <li><a href="http://accessify.com/features/tutorials/the-perfect-popup/" title="http://accessify.com/features/tutorials/the-perfect-popup/">The perfect pop-up (tutorial)</a> by Ian Lloyd</li> + <li><a href="http://www.gtalbot.org/FirefoxSection/Popup/PopupAndFirefox.html">Popup windows and Firefox (interactive demos)</a> by Gérard Talbot</li> +</ul> + +<h2 id="Referências_2">Referências</h2> + +<ul> + <li><a href="http://www.cs.tut.fi/~jkorpela/www/links.html">Links Want To Be Links</a> by Jukka K. Korpela</li> + <li><a href="http://www.evolt.org/article/Links_and_JavaScript_Living_Together_in_Harmony/17/20938/">Links & JavaScript Living Together in Harmony</a> by Jeff Howden</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/window/postmessage/index.html b/files/pt-pt/web/api/window/postmessage/index.html new file mode 100644 index 0000000000..50e5c91a5d --- /dev/null +++ b/files/pt-pt/web/api/window/postmessage/index.html @@ -0,0 +1,337 @@ +--- +title: Window.postMessage() +slug: Web/API/Window/postMessage +tags: + - API + - DOM + - Janela + - Referencia + - metodo +translation_of: Web/API/Window/postMessage +--- +<div>{{ApiRef("HTML DOM")}}</div> + +<p>O método <strong><code>window.postMessage()</code></strong> permite a comunicação segura de origem cruzada. Normalmente, é permitido que os <em>scripts </em>em páginas diferentes podem aceder a cada uma delas, se e apenas se as páginas que os executaram estão em localizações com o mesmo protocolo (normalmente ambas <code>https</code>), número da porta (<code>443</code>, por predefinição para <code>https</code>), e anfitrião (módulo {{domxref("Document.domain")}}, sendo definidos por ambas as páginas para o mesmo valor). <code>window.postMessage()</code> fornece um mecanismo para contornar esta restrição de um modo que é seguro quando utilizado corretamente.</p> + +<p>The <code>window.postMessage()</code> method, when called, causes a {{domxref("MessageEvent")}} to be dispatched at the target window when any pending script that must be executed completes (e.g., remaining event handlers if <code>window.postMessage()</code> is called from an event handler, previously-set pending timeouts, etc.) The {{domxref("MessageEvent")}} has the type <code>message</code>, a <code>data</code> property which is set to the value of the first argument provided to <code>window.postMessage()</code>, an <code>origin</code> property corresponding to the origin of the main document in the window calling <code>window.postMessage</code> at the time <code>window.postMessage()</code> was called, and a <code>source</code> property which is the window from which <code>window.postMessage()</code> is called. (Other standard properties of events are present with their expected values.)</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><em>otherWindow</em>.postMessage(<em>message</em>, <em>targetOrigin</em>, [<em>transfer</em>]);</pre> + +<dl> + <dt><code><em>otherWindow</em></code></dt> + <dd>A reference to another window; such a reference may be obtained, for example, using the <code>contentWindow</code> property of an <code>iframe</code> element, the object returned by <a href="/en-US/docs/DOM/window.open">window.open</a>, or by named or numeric index on {{domxref("Window.frames")}}, if you're trying to start the communication from iframe to parent window then <a href="/en-US/docs/Web/API/Window/parent">parent</a> is also a valid reference</dd> + <dt><code><em>message</em></code></dt> + <dd>Data to be sent to the other window. The data is serialized using <a href="/en-US/docs/DOM/The_structured_clone_algorithm">the structured clone algorithm</a>. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [<a href="/en-US/docs/">1</a>]</dd> + <dt><code><em>targetOrigin</em></code></dt> + <dd>Specifies what the origin of <code>otherWindow</code> must be for the event to be dispatched, either as the literal string <code>"*"</code> (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of <code>otherWindow</code>'s document does not match that provided in <code>targetOrigin</code>, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if <code>postMessage()</code> was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. <strong>Always provide a specific <code>targetOrigin</code>, not <code>*</code>, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.</strong></dd> + <dt><code><em><strong>transfer</strong></em></code> {{optional_Inline}}</dt> + <dd>Is a sequence of {{domxref("Transferable")}} objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.</dd> +</dl> + +<h2 id="O_evento_expedido">O evento expedido</h2> + +<p><code>otherWindow</code> can listen for dispatched messages by executing the following JavaScript:</p> + +<pre class="brush: js">window.addEventListener("message", receiveMessage, false); + +function receiveMessage(event) +{ + if (event.origin !== "http://example.org:8080") + return; + + // ... +} +</pre> + +<p>The properties of the dispatched message are:</p> + +<dl> + <dt><code>data</code></dt> + <dd>The object passed from the other window.</dd> + <dt><code>origin</code></dt> + <dd>The <a href="/en-US/docs/Origin">origin</a> of the window that sent the message at the time <code>postMessage</code> was called. This string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given protocol. Examples of typical origins are <code class="nowiki">https://example.org</code> (implying port <code>443</code>), <code class="nowiki">http://example.net</code> (implying port <code>80</code>), and <code class="nowiki">http://example.com:8080</code>. Note that this origin is <em>not</em> guaranteed to be the current or future origin of that window, which might have been navigated to a different location since <code>postMessage</code> was called.</dd> + <dt><code>source</code></dt> + <dd>A reference to the <code><a href="/en-US/docs/DOM/window">window</a></code> object that sent the message; you can use this to establish two-way communication between two windows with different origins.</dd> +</dl> + +<h2 id="Preocupações_de_segurança">Preocupações de segurança</h2> + +<p><strong>If you do not expect to receive messages from other sites, <em>do not</em> add any event listeners for <code>message</code> events.</strong> This is a completely foolproof way to avoid security problems.</p> + +<p>If you do expect to receive messages from other sites, <strong>always verify the sender's identity</strong> using the <code>origin</code> and possibly <code>source</code> properties. Any window (including, for example, <code class="nowiki">http://evil.example.com</code>) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should <strong>always verify the syntax of the received message</strong>. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.</p> + +<p><strong>Always specify an exact target origin, not <code>*</code>, when you use <code>postMessage</code> to send data to other windows.</strong> A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using <code>postMessage</code>.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: js">/* + * In window A's scripts, with A being on <http://example.com:8080>: + */ + +var popup = window.open(...popup details...); + +// When the popup has fully loaded, if not blocked by a popup blocker: + +// This does nothing, assuming the window hasn't changed its location. +popup.postMessage("The user is 'bob' and the password is 'secret'", + "https://secure.example.net"); + +// This will successfully queue a message to be sent to the popup, assuming +// the window hasn't changed its location. +popup.postMessage("hello there!", "http://example.com"); + +function receiveMessage(event) +{ + // Do we trust the sender of this message? (might be + // different from what we originally opened, for example). + if (event.origin !== "http://example.com") + return; + + // event.source is popup + // event.data is "hi there yourself! the secret response is: rheeeeet!" +} +window.addEventListener("message", receiveMessage, false); +</pre> + +<pre class="brush: js">/* + * In the popup's scripts, running on <http://example.com>: + */ + +// Called sometime after postMessage is called +function receiveMessage(event) +{ + // Do we trust the sender of this message? + if (event.origin !== "http://example.com:8080") + return; + + // event.source is window.opener + // event.data is "hello there!" + + // Assuming you've verified the origin of the received message (which + // you must do in any case), a convenient idiom for replying to a + // message is to call postMessage on event.source and provide + // event.origin as the targetOrigin. + event.source.postMessage("hi there yourself! the secret response " + + "is: rheeeeet!", + event.origin); +} + +window.addEventListener("message", receiveMessage, false); +</pre> + +<h3 id="Notas">Notas</h3> + +<p>Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages <strong>must</strong> first check the identity of the sender of the message, using the <code>origin</code> and possibly <code>source</code> properties. This cannot be overstated: <strong>Failure to check the <code>origin</code> and possibly <code>source</code> properties enables cross-site scripting attacks.</strong></p> + +<p>As with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of <code>postMessage</code> to detect when an event handler listening for events sent by <code>postMessage</code> throws an exception.</p> + +<p>The value of the <code>origin</code> property of the dispatched event is not affected by the current value of <code>document.domain</code> in the calling window.</p> + +<p>For IDN host names only, the value of the <code>origin</code> property is not consistently Unicode or punycode; for greatest compatibility check for both the IDN and punycode values when using this property if you expect messages from IDN sites. This value will eventually be consistently IDN, but for now you should handle both IDN and punycode forms.</p> + +<p>The value of the <code>origin</code> property when the sending window contains a <code>javascript:</code> or <code>data:</code> URL is the origin of the script that loaded the URL.</p> + +<h3 id="Utilizar_window.postMessage_nas_extensões_Non-standard_inline">Utilizar window.postMessage nas extensões {{Non-standard_inline}}</h3> + +<p><code>window.postMessage</code> is available to JavaScript running in chrome code (e.g., in extensions and privileged code), but the <code>source</code> property of the dispatched event is always <code>null</code> as a security restriction. (The other properties have their expected values.)</p> + +<p>It is not possible for content or web context scripts to specify a <code>targetOrigin</code> to communicate directly with an extension (either the background script or a contet script). Web or content scripts <em>can</em> use <code>window.postMessage</code> with a <code>targetOrigin</code> of <code>"*"</code> to broadcast to every listener, but this is discouraged, since an extension cannot be certain the origin of such messages, and other listeners (including those you do not control) can listen in.</p> + +<p>Content scripts should use <a href="/en-US/Add-ons/WebExtensions/API/runtime">runtime.sendMessage</a> to communicate with the background script. Web context scripts can use custom events to communicate with content scripts (with randomly generated event names, if needed, to prevent snooping from the guest page).</p> + +<p>Lastly, posting a message to a page at a <code>file:</code> URL currently requires that the <code>targetOrigin</code> argument be <code>"*"</code>. <code>file://</code> cannot be used as a security restriction; this restriction may be modified in the future.</p> + +<h2 id="Especificacações">Especificacações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th><strong>Especificação</strong></th> + <th><strong>Estado</strong></th> + <th><strong>Comentário</strong></th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "web-messaging.html#dom-window-postmessage", "postMessage()")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th><strong>Funcionalidade</strong></th> + <th><strong>Chrome</strong></th> + <th><strong>Edge</strong></th> + <th><strong>Firefox (Gecko)</strong></th> + <th><strong>Internet Explorer</strong></th> + <th><strong>Opera</strong></th> + <th><strong>Safari (WebKit)</strong></th> + </tr> + <tr> + <td>Suporte básico</td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(6.0)}}<sup>[1]</sup><br> + {{CompatGeckoDesktop(8.0)}}<sup>[2]</sup></td> + <td>8.0<sup>[3]</sup><br> + 10.0<sup>[4]</sup></td> + <td>9.5</td> + <td>4.0</td> + </tr> + <tr> + <td><code>transfer</code> argument</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(20.0)}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th><strong>Funcionalidade</strong></th> + <th><strong>Android</strong></th> + <th><strong>Edge</strong></th> + <th><strong>Firefox Mobile (Gecko)</strong></th> + <th><strong>IE Phone</strong></th> + <th><strong>Opera Mobile</strong></th> + <th><strong>Safari Mobile</strong></th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop(6.0)}}<sup>[1]</sup><br> + {{CompatGeckoDesktop(8.0)}}<sup>[2]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}[5]</td> + </tr> + <tr> + <td><code>transfer</code> argument</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(20.0)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Prior to Gecko 6.0 {{geckoRelease("6.0")}}, the <code>message</code> parameter must be a string. Starting in Gecko 6.0 {{geckoRelease("6.0")}}, the <code>message</code> parameter is serialized using <a href="/en-US/docs/DOM/The_structured_clone_algorithm">the structured clone algorithm</a>. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself.</p> + +<p>[2] Gecko 8.0 introduced support for sending {{domxref("File")}} and {{domxref("FileList")}} objects between windows. This is only allowed if the recipient's principal is contained within the sender's principal for security reasons.</p> + +<p>[3] IE8 and IE9 only support it for {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.</p> + +<p>[4] IE10 has important limitations: see this <a href="http://stackoverflow.com/questions/16226924/is-cross-origin-postmessage-broken-in-ie10">article</a> for details.</p> + +<p>[5] Due to security reasons, to work properly on Safari, use construction with document.getElementId('your-frame').contentWindow</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{domxref("Document.domain")}}</li> + <li>{{domxref("CustomEvent")}}</li> + <li><a href="/pt-PT/docs/Archive/Add-ons/Interaction_between_privileged_and_non-privileged_pages">Interação entre páginas privilegiadas e não privilegiadas</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/worker/index.html b/files/pt-pt/web/api/worker/index.html new file mode 100644 index 0000000000..cdeee23a8a --- /dev/null +++ b/files/pt-pt/web/api/worker/index.html @@ -0,0 +1,270 @@ +--- +title: Worker +slug: Web/API/Worker +translation_of: Web/API/Worker +--- +<p>{{APIRef("Web Workers API")}}</p> + +<p>A interface do <em><strong><code>Worker</code></strong> </em>da <a href="/en-US/docs/Web/API/Web_Workers_API">API de Workers da Web </a>representa uma tarefa em segundo palno que pode ser criada facilmente e pode enviar mensagens de volta para o seu criador. Criar um <em>worker </em>é tão simples como chamar o criador de <code>Worker()</code> e especificar um script para ser executado na sequência do <em>worker</em>.</p> + +<p>Os <em>workers</em> podem, por sua vez, gerar novos <em>workers</em> enquanto esses <em>workers</em> estiverem alojados dentro da mesma <a href="/en-US/docs/Web/Security/Same-origin_policy">origem</a> como a página original (Nota: os <em>workers</em> integrados <a href="https://groups.google.com/a/chromium.org/forum/#!topic/blink-dev/5R3B4RN4GHU">não estão atualmente implementados no Blink</a>). Em adição os <em>workers</em> poderão utilizar <a class="internal" href="/en/DOM/XMLHttpRequest" title="En/XMLHttpRequest"><code>XMLHttpRequest</code></a> para I/O rede, com a estipulação que a <code>responseXML</code> e os atributos <code>channel</code> no <code>XMLHttpRequest</code> retornam sempre <code>null</code>.</p> + +<p><a href="/En/DOM/Worker/Functions_available_to_workers" title="En/DOM/Worker/Functions available to workers">Nem todas as interfaces e funções estão disposníveis</a> para o <em>script</em> associado com um <em><code>Worker</code></em>.</p> + +<p>No Firefox, se quiser utilziar os <em>workers</em> nas extensões e pretender ter acesso a <a href="/en/js-ctypes" title="en/js-ctypes">js-ctypes</a>, então deverá utilizar o objeto {{ domxref("ChromeWorker") }}.</p> + +<h2 id="Criadores">Criadores</h2> + +<dl> + <dt>{{domxref("Worker.Worker", "Worker()")}}</dt> + <dd>Creates a dedicated web worker that executes the script at the specified URL. Workers can also be constructed using <a href="/en-US/docs/Web/API/Blob">Blobs</a>.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<p><em>Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.</em></p> + +<h3 id="Manipuladores_de_evento">Manipuladores de evento</h3> + +<dl> + <dt>{{domxref("AbstractWorker.onerror")}}</dt> + <dd>An {{ domxref("EventListener") }} called whenever an {{domxref("ErrorEvent")}} of type <code>error</code> bubbles through to the worker. This is inherited from {{domxref("AbstractWorker")}}.</dd> + <dt>{{domxref("Worker.onmessage")}}</dt> + <dd>An {{ domxref("EventListener") }} called whenever a {{domxref("MessageEvent")}} of type <code>message</code> bubbles through the worker — i.e. when a message is sent to the parent document from the worker via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}. The message is stored in the event's {{domxref("MessageEvent.data", "data")}} property.</dd> + <dt>{{domxref("Worker.onmessageerror")}}</dt> + <dd>Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("messageerror")}} event is raised.</dd> +</dl> + +<dl> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p><em>Inherits methods from its parent, {{domxref("EventTarget")}}, and implements methods from {{domxref("AbstractWorker")}}.</em></p> + +<dl> + <dt>{{domxref("Worker.postMessage()")}}</dt> + <dd>Sends a message — which can consist of <code>any</code> JavaScript object — to the worker's inner scope.</dd> + <dt>{{domxref("Worker.terminate()")}}</dt> + <dd>Immediately terminates the worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once. ServiceWorker instances do not support this method.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<p>The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor and usage of the object:</p> + +<pre class="brush: js">var myWorker = new Worker('worker.js'); +var first = document.querySelector('#number1'); +var second = document.querySelector('#number2'); + +first.onchange = function() { + myWorker.postMessage([first.value,second.value]); + console.log('Message posted to worker'); +}</pre> + +<p>For a full example, see our<a class="external external-icon" href="https://github.com/mdn/simple-web-worker">Basic dedicated worker example</a> (<a class="external external-icon" href="http://mdn.github.io/simple-web-worker/">run dedicated worker</a>).</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "#worker", "Worker")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>Support varies for different types of workers. See each worker type's page for specifics.</p> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>4</td> + <td>{{CompatVersionUnknown}}</td> + <td>3.5</td> + <td>10.0</td> + <td>10.6</td> + <td>4</td> + </tr> + <tr> + <td>Constructor <code>name</code> option</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(55)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>onmessageerror</code></td> + <td>60</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop(57)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.4</td> + <td>{{CompatVersionUnknown}}</td> + <td>3.5</td> + <td>10.0</td> + <td>11.5</td> + <td>5.1</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Constructor <code>name</code> option</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(55)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>onmessageerror</code></td> + <td>60</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(57)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Cross-origin_worker_error_behaviour">Cross-origin worker error behaviour</h3> + +<p>In earlier browser versions, trying to load a cross-origin worker script threw a <code>SecurityError</code>; in newer browsers an {{event("error")}} event is thrown instead due to a spec change. Find out more information on how to deal with this in <a href="https://www.fxsitecompat.com/en-CA/docs/2016/loading-cross-origin-worker-now-fires-error-event-instead-of-throwing-worker-in-sandboxed-iframe-no-longer-allowed/">Loading cross-origin worker now fires error event instead of throwing; worker in sandboxed iframe no longer allowed</a>.</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a class="internal" href="/pt-PT/docs/Web/API/Web_Workers_API/Utilizacao_de_web_workers" title="en/Using DOM workers">Utilziar <em>workers</em> da Web</a></li> + <li><a href="/pt-PT/docs/Web/API/Web_Workers_API/Functions_and_classes_available_to_workers" title="https://developer.mozilla.org/En/DOM/Worker/Functions_available_to_workers">Funções disponíveis para os <em>workers</em></a></li> + <li>Outros tipos de <em>workers</em>: {{ domxref("SharedWorker") }} e <a href="/pt-PT/docs/Web/API/Service_Worker_API">ServiceWorker</a>.</li> + <li><em>Workers </em>não padrão, específicos Gecko: {{ domxref("ChromeWorker") }}, utilizados pelas extensões.</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/api/xmlhttprequest/index.html b/files/pt-pt/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..3e5489f088 --- /dev/null +++ b/files/pt-pt/web/api/xmlhttprequest/index.html @@ -0,0 +1,174 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - API + - HTTP + - Interface + - Referencia + - Web + - XHR +translation_of: Web/API/XMLHttpRequest +--- +<div>{{APIRef("XMLHttpRequest")}}</div> + +<p><span class="seoSummary">Utilize os objetos <code>XMLHttpRequest</code> (XHR) para interagir com os servidores. Pode obter os dados de um URL sem ter que recarregar toda a página. Isto permite que uma página da Web atualize apenas parte da mesma, </span> sem interromper o que o utilizador está a fazer<span class="seoSummary">.</span> <code>XMLHttpRequest</code> é totalmente utilizado na programação <a href="/pt-PT/docs/Web/Guide/AJAX">Ajax</a>.</p> + +<p>{{InheritanceDiagram}}</p> + +<h5 id="História">História</h5> + +<p><code>XMLHttpRequest</code> was originally designed by Microsoft around 1999 and later adopted by Mozilla, Apple, and Google. Since October 2014, it has been <a class="external" href="https://xhr.spec.whatwg.org/">standardized at the <abbr title="Web Hypertext Application Technology Working Group">WHATWG</abbr></a>, <a href="https://fetch.spec.whatwg.org/">together</a> with the new promise-based {{domxref("WindowOrWorkerGlobalScope.fetch()", "fetch()")}} method.</p> + +<p>Despite its name, <code>XMLHttpRequest</code> can be used to retrieve any type of data, not just XML, and it supports protocols other than <a href="/en-US/docs/Web/HTTP">HTTP</a> (including <code>file</code> and <code>ftp</code>).</p> + +<h2 id="Constructor">Constructor</h2> + +<dl> + <dt>{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}</dt> + <dd>The constructor initializes an XMLHttpRequest. It must be called before any other method calls.</dd> +</dl> + +<h2 id="Propriedades">Propriedades</h2> + +<p><em>This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.</em></p> + +<dl> + <dt id="xmlhttprequest-onreadystatechange">{{domxref("XMLHttpRequest.onreadystatechange")}}</dt> + <dd>An {{domxref("EventHandler")}} that is called whenever the <code>readyState</code> attribute changes.</dd> + <dt id="xmlhttprequest-readystate">{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}</dt> + <dd>Returns an <code>unsigned short</code>, the state of the request.</dd> + <dt>{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}</dt> + <dd>Returns an {{domxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript object, or a {{domxref("DOMString")}}, depending on the value of {{domxref("XMLHttpRequest.responseType")}}. that contains the response entity body.</dd> + <dt id="xmlhttprequest-responsetext">{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref("DOMString")}} that contains the response to the request as text, or <code>null</code> if the request was unsuccessful or has not yet been sent.</dd> + <dt id="xmlhttprequest-responsetype">{{domxref("XMLHttpRequest.responseType")}}</dt> + <dd>Is an enumerated value that defines the response type.</dd> + <dt id="xmlhttprequest-responsexml">{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}</dt> + <dd>Returns the serialized URL of the response or the empty string if the URL is null.</dd> + <dt id="xmlhttprequest-responsexml">{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref("Document")}} containing the response to the request, or <code>null</code> if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.</dd> + <dt id="xmlhttprequest-status">{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}</dt> + <dd>Returns an <code>unsigned short</code> with the status of the response of the request.</dd> + <dt id="xmlhttprequest-statustext">{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}</dt> + <dd>Returns a {{domxref("DOMString")}} containing the response string returned by the HTTP server. Unlike {{domxref("XMLHTTPRequest.status")}}, this includes the entire text of the response message ("<code>200 OK</code>", for example).</dd> +</dl> + +<div class="note"> +<p><strong>Nota:</strong> via HTTP/2 specification (<a href="https://http2.github.io/http2-spec/#rfc.section.8.1.2.4">8.1.2.4</a> <a href="https://http2.github.io/http2-spec/#HttpResponse">Response Pseudo-Header Fields</a>), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.</p> +</div> + +<dl> + <dt id="xmlhttprequest-timeout">{{domxref("XMLHttpRequest.timeout")}}</dt> + <dd>Is an <code>unsigned long</code> representing the number of milliseconds a request can take before automatically being terminated.</dd> + <dt id="xmlhttprequesteventtarget-ontimeout">{{domxref("XMLHttpRequestEventTarget.ontimeout")}}</dt> + <dd>Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}</dd> + <dt id="xmlhttprequest-upload">{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}</dt> + <dd>Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.</dd> + <dt id="xmlhttprequest-withcredentials">{{domxref("XMLHttpRequest.withCredentials")}}</dt> + <dd>Is a {{domxref("Boolean")}} that indicates whether or not cross-site <code>Access-Control</code> requests should be made using credentials such as cookies or authorization headers.</dd> +</dl> + +<h3 id="Proriedades_não_padrão">Proriedades não padrão</h3> + +<dl> + <dt>{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}</dt> + <dd>Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.</dd> + <dt>{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}</dt> + <dd>Is a boolean. If true, the request will be sent without cookie and authentication headers.</dd> + <dt>{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}</dt> + <dd>Is a boolean. If true, the same origin policy will not be enforced on the request.</dd> + <dt>{{domxref("XMLHttpRequest.mozBackgroundRequest")}}</dt> + <dd>Is a boolean. It indicates whether or not the object represents a background service request.</dd> + <dt>{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}</dt> + <dd>Is an <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer"><code>ArrayBuffer</code></a>. The response to the request, as a JavaScript typed array.</dd> + <dt>{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}</dt> + <dd><strong>This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22.</strong> Please use <a href="/en-US/docs/Web/API/Server-sent_events">Server-Sent Events</a>, <a href="/en-US/docs/Web/API/WebSockets_API">Web Sockets</a>, or <code>responseText</code> from progress events instead.</dd> +</dl> + +<h3 id="Manipuladores_de_evento">Manipuladores de evento</h3> + +<p><code>onreadystatechange</code> as a property of the <code>XMLHttpRequest</code> instance is supported in all browsers.</p> + +<p>Since then, a number of additional event handlers were implemented in various browsers (<code>onload</code>, <code>onerror</code>, <code>onprogress</code>, etc.). These are supported in Firefox. In particular, see <code><a href="https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIXMLHttpRequestEventTarget" title="">nsIXMLHttpRequestEventTarget</a></code> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a>.</p> + +<p>More recent browsers, including Firefox, also support listening to the <code>XMLHttpRequest</code> events via standard <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener">addEventListener</a></code> APIs in addition to setting <code>on*</code> properties to a handler function.</p> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{domxref("XMLHttpRequest.abort()")}}</dt> + <dd>Aborts the request if it has already been sent.</dd> + <dt>{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}</dt> + <dd>Returns all the response headers, separated by <a href="https://developer.mozilla.org/en-US/docs/Glossary/CRLF">CRLF</a>, as a string, or <code>null</code> if no response has been received.</dd> + <dt>{{domxref("XMLHttpRequest.getResponseHeader()")}}</dt> + <dd>Returns the string containing the text of the specified header, or <code>null</code> if either the response has not yet been received or the header doesn't exist in the response.</dd> + <dt>{{domxref("XMLHttpRequest.open()")}}</dt> + <dd>Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use <a class="internal" href="/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIXMLHttpRequest#openRequest()"><code>openRequest()</code></a> instead.</dd> + <dt>{{domxref("XMLHttpRequest.overrideMimeType()")}}</dt> + <dd>Overrides the MIME type returned by the server.</dd> + <dt>{{domxref("XMLHttpRequest.send()")}}</dt> + <dd>Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.</dd> + <dt>{{domxref("XMLHttpRequest.setRequestHeader()")}}</dt> + <dd>Sets the value of an HTTP request header. You must call <code>setRequestHeader()</code>after <a href="#open"><code>open()</code></a>, but before <code>send()</code>.</dd> +</dl> + +<h3 id="Métodos_não_padrão">Métodos não padrão</h3> + +<dl> + <dt>{{domxref("XMLHttpRequest.init()")}}</dt> + <dd>Initializes the object for use from C++ code.</dd> +</dl> + +<div class="warning"><strong>Aviso:</strong> este método <strong>não </strong>deve ser chamado do JavaScript.</div> + +<dl> + <dt>{{domxref("XMLHttpRequest.openRequest()")}}</dt> + <dd>Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use <a class="internal" href="/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIXMLHttpRequest#open()"><code>open()</code></a> instead. See the documentation for <code>open()</code>.</dd> + <dt>{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}</dt> + <dd>A variant of the <code>send()</code> method that sends binary data.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('XMLHttpRequest')}}</td> + <td>{{Spec2('XMLHttpRequest')}}</td> + <td>Live standard, latest version</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<div>{{Compat("api.XMLHttpRequest")}}</div> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>Tutoriais da MDN abrangendo XMLHttpRequest: + <ul> + <li><a href="/en-US/docs/AJAX/Getting_Started">Ajax — Getting Started</a></li> + <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a></li> + <li><a href="/en-US/docs/Web/API/XMLHttpRequest/HTML_in_XMLHttpRequest">HTML in XMLHttpRequest</a></li> + <li><a href="/en-US/docs/Web/API/FormData"><code>FormData</code></a></li> + </ul> + </li> + <li><a class="external" href="http://www.html5rocks.com/en/tutorials/file/xhr2/">HTML5 Rocks — New Tricks in XMLHttpRequest2</a></li> + <li><code>Chrome scope availability</code> — how to access XMLHttpRequest from JSM modules etc., which do not have access to DOM + <ul> + <li><a href="/en-US/docs/Mozilla/Tech/XPCOM/Language_Bindings/Components.utils.importGlobalProperties">Components.utils.importGlobalProperties</a></li> + <li><a href="/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIXMLHttpRequest">nsIXMLHttpRequest</a></li> + </ul> + </li> +</ul> diff --git a/files/pt-pt/web/componentes_web/index.html b/files/pt-pt/web/componentes_web/index.html new file mode 100644 index 0000000000..3a0dd68ffd --- /dev/null +++ b/files/pt-pt/web/componentes_web/index.html @@ -0,0 +1,226 @@ +--- +title: Componentes da Web +slug: Web/Componentes_Web +tags: + - Artigo da Web + - Componentes + - Componentes da Web + - Desenvolvimento da Web + - Importações HTML + - JavaScript + - Landing + - Modelo + - Resumo + - Sinopse + - elementos personalizados + - shadow dom + - slot +translation_of: Web/Web_Components +--- +<div>{{DefaultAPISidebar("Componentes Web")}}</div> + +<div></div> + +<div class="summary"> +<p>Componentes Web é uma suite de diferentes tecnologias que permite a criação de elementos reutilizáveis — com a sua funcionalidade encapsulada longe do restante código — E utilizá-las nas suas aplicações web.</p> +</div> + +<h2 id="Conceitos_e_utilização">Conceitos e utilização</h2> + +<p>Como programadores, todos sabemos que é boa ideia reutilizar código tanto como possível. Tradicionalmente, esta ideia não tem sido tão fácil para estruturas de marcação — pense no complexo HTML (e seus estilos e scripts associados) em que por vezes é necessário escrever controlos personalizados de UI e usá-los múltiplas vezes pode tornar a página numa desordem se não tiver cuidado</p> + +<p>Componentes Web visa resolver tais problemas — consiste em três grandes tecnologias, que usadas em conjunto, permitem criar elementos versáteis com funcionalidade encapsulada e que podem ser reutilizados onde se queira sem medo de colisões de código.</p> + +<ul> + <li><strong>Custom elements</strong>: A set of JavaScript APIs that allow you to define custom elements and their behaviour, which can then be used as desired in your user interface.</li> + <li><strong>Shadow DOM</strong>: A set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element — which is rendered separately from the main document DOM — and controlling associated functionality. In this way, you can keep an element's features private, so they can be scripted and styled without the fear of collision with other parts of the document.</li> + <li><strong>HTML templates</strong>: The {{HTMLElement("template")}} and {{HTMLElement("slot")}} elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element's structure.</li> +</ul> + +<p>The basic approach for implementing a web component generally looks something like this:</p> + +<ol> + <li>Create a class or a function in which you specify your web component functionality. If using a class, use the ECMAScript 2015 class syntax (see <a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a> for more information). </li> + <li>Register your new custom element using the {{domxref("CustomElementRegistry.define()")}} method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, what element it inherits from.</li> + <li>If required, attach a shadow DOM to the custom element using {{domxref("Element.attachShadow()")}} method. Add child elements, event listeners, etc., to the shadow DOM using regular DOM methods.</li> + <li>If required, define an HTML template using {{htmlelement("template")}} and {{htmlelement("slot")}}. Again use regular DOM methods to clone the template and attach it to your shadow DOM.</li> + <li>Use your custom element wherever you like on your page, just like you would any regular HTML element.</li> +</ol> + +<h2 id="Tutoriais">Tutoriais</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Web_Components/Using_custom_elements">Using custom elements</a></dt> + <dd>A guide showing how to use the features of custom elements to create simple web components, as well as looking into lifecycle callbacks and some other more advanced features.</dd> + <dt><a href="/en-US/docs/Web/Web_Components/Using_shadow_DOM">Using shadow DOM</a></dt> + <dd>A guide that looks at shadow DOM fundamentals, showing how to attach a shadow DOM to an element, add to the shadow DOM tree, style it, and more.</dd> + <dt><a href="/en-US/docs/Web/Web_Components/Using_templates_and_slots">Using templates and slots</a></dt> + <dd>A guide showing how to define a reusable HTML structure using {{htmlelement("template")}} and {{htmlelement("slot")}} elements, and then use that structure inside your web components.</dd> +</dl> + +<h2 id="Referência">Referência</h2> + +<h3 id="Elementos_de_Custom">Elementos de <em>Custom</em></h3> + +<dl> + <dt>{{domxref("CustomElementRegistry")}}</dt> + <dd>Contains functionality related to custom elements, most notably the {{domxref("CustomElementRegistry.define()")}} method used to register new custom elements so they can then be used in your document.</dd> + <dt>{{domxref("Window.customElements")}}</dt> + <dd>Returns a reference to the <code>CustomElementRegistry</code> object.</dd> + <dt><a href="/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks">Life cycle callbacks</a></dt> + <dd>Special callback functions defined inside the custom element's class definition, which affect its behavior: + <ul> + <li><code>connectedCallback</code>: Invoked when the custom element is first connected to the document's DOM.</li> + <li><code>disconnectedCallback</code>: Invoked when the custom element is disconnected from the document's DOM.</li> + <li><code>adoptedCallback</code>: Invoked when the custom element is moved to a new document.</li> + <li><code>attributeChangedCallback</code>: Invoked when one of the custom element's attributes is added, removed, or changed.</li> + </ul> + </dd> + <dd> + <ul> + </ul> + </dd> +</dl> + +<dl> + <dt>Extensions for creating custom built-in elements</dt> + <dd> + <ul> + <li>The {{htmlattrxref("is")}} global HTML attribute: Allows you to specify that a standard HTML element should behave like a registered custom built-in element.</li> + <li>The "is" option of the {{domxref("Document.createElement()")}} method: Allows you to create an instance of a standard HTML element that behaves like a given registered custom built-in element.</li> + </ul> + </dd> + <dt>CSS pseudo-classes</dt> + <dd>Pseudo-classes relating specifically to custom elements: + <ul> + <li>{{cssxref(":defined")}}: Matches any element that is defined, including built in elements and custom elements defined with <code>CustomElementRegistry.define()</code>).</li> + <li>{{cssxref(":host")}}: Selects the shadow host of the <a href="/en-US/docs/Web/Web_Components/Using_shadow_DOM">shadow DOM</a> containing the CSS it is used inside.</li> + <li>{{cssxref(":host()")}}: Selects the shadow host of the <a href="/en-US/docs/Web/Web_Components/Using_shadow_DOM">shadow DOM</a> containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host.</li> + <li>{{cssxref(":host-context()")}}: Selects the shadow host of the <a href="/en-US/docs/Web/Web_Components/Using_shadow_DOM">shadow DOM</a> containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the DOM hierarchy.</li> + </ul> + </dd> +</dl> + +<h3 id="Shadow_DOM">Shadow DOM</h3> + +<dl> + <dt>{{domxref("ShadowRoot")}}</dt> + <dd>Represents the root node of a shadow DOM subtree.</dd> + <dt>{{domxref("DocumentOrShadowRoot")}}</dt> + <dd>A mixin defining features that are available across document and shadow roots.</dd> + <dt>{{domxref("Element")}} extensions</dt> + <dd>Extensions to the <code>Element</code> interface related to shadow DOM: + <ul> + <li>The {{domxref("Element.attachShadow()")}} method attaches a shadow DOM tree to the specified element.</li> + <li>The {{domxref("Element.shadowRoot")}} property returns the shadow root attached to the specified element, or <code>null</code> if there is no shadow root attached.</li> + </ul> + </dd> + <dt>Relevant {{domxref("Node")}} additions</dt> + <dd>Additions to the <code>Node</code> interface relevant to shadow DOM: + <ul> + <li>The {{domxref("Node.getRootNode()")}} method returns the context object's root, which optionally includes the shadow root if it is available.</li> + <li>The {{domxref("Node.isConnected")}} property returns a boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the {{domxref("Document")}} object in the case of the normal DOM, or the {{domxref("ShadowRoot")}} in the case of a shadow DOM.</li> + </ul> + </dd> + <dt>{{domxref("Event")}} extensions</dt> + <dd>Extensions to the <code>Event</code> interface related to shadow DOM: + <ul> + <li>{{domxref("Event.composed")}}: Returns a {{jsxref("Boolean")}} which indicates whether the event will propagate across the shadow DOM boundary into the standard DOM (<code>true</code>), or not (<code>false</code>).</li> + <li>{{domxref("Event.composedPath")}}: Returns the event’s path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with {{domxref("ShadowRoot.mode")}} closed.</li> + </ul> + </dd> +</dl> + +<h3 id="Modelos_de_HTML">Modelos de HTML</h3> + +<dl> + <dt>{{htmlelement("template")}}</dt> + <dd>Contains an HTML fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using JavaScript, mainly used as the basis of custom element structures. The associated DOM interface is {{domxref("HTMLTemplateElement")}}.</dd> + <dt>{{htmlelement("slot")}}</dt> + <dd>A placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. The associated DOM interface is {{domxref("HTMLSlotElement")}}.</dd> + <dt>The <code><a href="/en-US/docs/Web/HTML/Global_attributes/slot">slot</a></code> global HTML attribute</dt> + <dd>Assigns a slot in a shadow DOM shadow tree to an element.</dd> + <dt>{{domxref("Slotable")}}</dt> + <dd>A mixin implemented by both {{domxref("Element")}} and {{domxref("Text")}} nodes, defining features that allow them to become the contents of an {{htmlelement("slot")}} element. The mixin defines one attribute, {{domxref("Slotable.assignedSlot")}}, which returns a reference to the slot the node is inserted in.</dd> +</dl> + +<dl> + <dt>{{domxref("Element")}} extensions</dt> + <dd>Extensions to the <code>Element</code> interface related to slots: + <ul> + <li>{{domxref("Element.slot")}}: Returns the name of the shadow DOM slot attached to the element.</li> + </ul> + </dd> + <dt>CSS pseudo-elements</dt> + <dd>Pseudo-elements relating specifically to slots: + <ul> + <li>{{cssxref("::slotted")}}: Matches any content that is inserted into a slot.</li> + </ul> + </dd> + <dt>The {{event("slotchange")}} event</dt> + <dd>Fired on an {{domxref("HTMLSlotElement")}} instance ({{htmlelement("slot")}} element) when the node(s) contained in that slot change.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>We are building up a number of examples in our <a href="https://github.com/mdn/web-components-examples">web-components-examples</a> GitHub repo. More will be added as time goes on.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName("HTML WHATWG","scripting.html#the-template-element","<template> element")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>The definition of {{HTMLElement("template")}}.</td> + </tr> + <tr> + <td>{{SpecName("HTML WHATWG","custom-elements.html#custom-elements","custom elements")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>The definition of <a href="/en-US/docs/Web/Web_Components/Using_custom_elements">HTML Custom Elements</a>.</td> + </tr> + <tr> + <td>{{SpecName("DOM WHATWG","#shadow-trees","shadow trees")}}</td> + <td>{{Spec2("DOM WHATWG")}}</td> + <td>The definition of <a href="/en-US/docs/Web/Web_Components/Using_shadow_DOM">Shadow DOM</a>.</td> + </tr> + <tr> + <td>{{SpecName("HTML Imports", "", "")}}</td> + <td>{{Spec2("HTML Imports")}}</td> + <td>Initial <a href="/en-US/docs/Web/Web_Components/HTML_Imports">HTML Imports</a> definition.</td> + </tr> + <tr> + <td>{{SpecName("Shadow DOM", "", "")}}</td> + <td>{{Spec2("Shadow DOM")}}</td> + <td>Initial <a href="/en-US/docs/Web/Web_Components/Using_shadow_DOM">Shadow DOM</a> definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>In general:</p> + +<ul> + <li>Web components are supported by default in Firefox (version 63), Chrome, and Opera.</li> + <li>Safari supports a number of web component features, but less than the above browsers.</li> + <li>Edge is working on an implementation.</li> +</ul> + +<p>For detailed browser support of specific features, you'll have to consult the reference pages listed above.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="https://www.webcomponents.org/">webcomponents.org</a> — site featuring web components examples, tutorials, and other information.</li> + <li><a href="https://github.com/hybridsjs/hybrids">Hybrids</a> — Open source web components library, which favors plain objects and pure functions over <code>class</code> and <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">this</span></font> syntax. It provides a simple and functional API for creating custom elements.</li> + <li><a href="https://www.polymer-project.org/">Polymer</a> — Google's web components framework — a set of polyfills, enhancements, and examples. Currently the easiest way to use web components cross-browser.</li> + <li><a href="https://github.com/devpunks/snuggsi#readme">Snuggsi.es</a> — Easy Web Components in ~1kB <em>Including polyfill</em> — All you need is a browser and basic understanding of HTML, CSS, and JavaScript classes to be productive.</li> + <li><a href="https://github.com/slimjs/slim.js">Slim.js</a> — Open source web components library — a high-performant library for rapid and easy component authoring; extensible and pluggable and cross-framework compatible.</li> + <li><a href="https://www.htmlelements.com/">Smart.js</a> — Web Components library with simple API for creating cross-browser custom elements. </li> +</ul> diff --git a/files/pt-pt/web/css/@font-face/index.html b/files/pt-pt/web/css/@font-face/index.html new file mode 100644 index 0000000000..8a150d736c --- /dev/null +++ b/files/pt-pt/web/css/@font-face/index.html @@ -0,0 +1,143 @@ +--- +title: '@font-face' +slug: Web/CSS/@font-face +translation_of: Web/CSS/@font-face +--- +<p>{{ CSSRef() }}</p> + +<h2 id="Resumo">Resumo</h2> + +<p><code>@font-face </code>permite que autores especifiquem fontes online para exibir texto em suas páginas web. Permitindo autores a proporcionar suas próprias fontes,<code> @font-face </code>elimina a necessidade de depender do limitado número de fontes que os usuários tem instalado em seus computadores.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre>@font-face { + font-family: <a-remote-font-name>; + src: <source> [,<source>]*; + [font-weight: <weight>]; + [font-style: <style>]; +} +</pre> + +<h3 id="Valores">Valores</h3> + +<dl> + <dt><a-remote-font-name> </dt> + <dd>Especifica um nome para a fonte que será usado como valor de <code>font-face</code> na propriedade <code>font</code>.</dd> + <dt><source> </dt> + <dd>URL para a localização remota do arquivo da fonte ou o nome da fonte no computador do usuário na forma <code>local("Nome da Font")</code>.</dd> + <dt><weight> </dt> + <dd>Um valor para a espessura da fonte (<a class="internal" href="/en/CSS/font-weight" title="en/CSS/font-weight">font weight</a> (en)).</dd> + <dt><style> </dt> + <dd>Um valor para o estilo da fonte (<a class="internal" href="/en/CSS/font-style" title="en/CSS/font-style">font style</a> (en)).</dd> +</dl> + +<p>Você pode especificar uma fonte local no computador do usuário através do nome, usando a sintaxe <code>local()</code>. Se esta fonte não for encontrada, outras fontes serão tentadas até que uma seja encontrada.</p> + +<h2 id="Formatos_de_fontes_suportados">Formatos de fontes suportados</h2> + +<ul style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 25px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"> + <li style="margin-bottom: 0.25em;">O Gecko 1.9.1 (Firefox 3.5) suporta fontes True Type e OpenType.</li> + <li style="margin-bottom: 0.25em;">O Gecko 1.9.2 (Firefox 3.6) adiciona suporte para <a href="/en/About_WOFF" style="text-decoration: none; color: rgb(4, 137, 183) !important; cursor: default;" title="en/About WOFF">WOFF</a> (en).</li> +</ul> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Este simples exemplo especifica uma fonte baixável para uso, aplicando-a ao corpo do documento.</p> + +<p><a class="internal" href="/@api/deki/files/2935/=webfont-sample.html" title="/@api/deki/files/2935/=webfont-sample.html">Ver amostra</a></p> + +<pre><html> +<head> + <title>Web Font Sample</title> + <style type="text/css" media="screen, print"> + @font-face { + font-family: "Bitstream Vera Serif Bold"; + src: url("http://developer.mozilla.org/@api/deki/files/2934/=VeraSeBd.ttf"); + } + + body { font-family: "Bitstream Vera Serif Bold", serif } + </style> +</head> +<body> + This is Bitstream Vera Serif Bold. +</body> +</html> +</pre> + +<p>Neste exemplo, a cópia local do usuário de "Helvetica Neue Bold" é usada; se o usuário não possuir a fonte instalada (dois diferentes nomes são tentados), então, a fonte baixável, chamada "MgOpenModernaBold.ttf" é usada em seu lugar:</p> + +<pre class="brush: css">@font-face { + font-family: MyHelvetica; + src: local("Helvetica Neue Bold"), + local("HelveticaNeue-Bold"), + url(MgOpenModernaBold.ttf); + font-weight: bold; +} +</pre> + +<h2 id="Notas">Notas</h2> + +<ul> + <li>No Gecko, fontes web estão sujeitas à mesma restrição de domínio (arquivos de fontes precisam estar no mesmo domínio da página que os está utilizando), a menos que <a class="internal" href="/En/HTTP_access_control" title="En/HTTP access control">HTTP access controls</a> (EN) seja usado para relaxar esta restrição.</li> + <li> + <div class="note"><strong>Nota:</strong> O tipo MIME do arquivo especificado não é considerado porque não há tipos MIME definidos parar fontes TrueType e OpenType.</div> + </li> + <li>Quando o Gecko exibe uma página que usa fontes web, ele inicialmente exibe o texto usando a melhor fonte <strong>fallback</strong> CSS disponível no computador do usuário enquanto aguarda o fim do download da fonte web. Conforme as fontes web são baixadas, o Gecko atualiza o texto que use essa fonte. Isto permite que o usuário leia o texto da página mais rapidamente.</li> +</ul> + +<h2 id="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + <th>Suporte a</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td><strong>4.0</strong></td> + <td>Somente fontes OpenType embutidas</td> + </tr> + <tr> + <td rowspan="2">Firefox (Gecko)</td> + <td><strong>3.5</strong> (1.9.1)</td> + <td>Somente fontes TrueType e OpenType</td> + </tr> + <tr> + <td><strong>3.6</strong> (1.9.2)</td> + <td>Formato de fonte web aberta (WOFF)</td> + </tr> + <tr> + <td>Opera</td> + <td><strong>10.0</strong></td> + <td>Somente fontes TrueType e OpenType</td> + </tr> + <tr> + <td>Safari (WebKit)</td> + <td><strong>3.1</strong> (525)</td> + <td>Somente fontes TrueType e OpenType</td> + </tr> + </tbody> +</table> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Veja também <a class="external" href="http://msdn.microsoft.com/en-us/library/ms530757(VS.85).aspx" title="http://msdn.microsoft.com/en-us/library/ms530757(VS.85).aspx">MSDN Microsoft library @font-face</a> (EN).</p> + +<h2 id="Especificações">Especificações</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/1998/REC-CSS2-19980512/fonts.html#font-descriptions" title="http://www.w3.org/TR/1998/REC-CSS2-19980512/fonts.html#font-descriptions">CSS 2 Fonts</a> 12/05/1998 - Obsoleto</li> + <li><a class="external" href="http://www.w3.org/TR/css3-fonts/#font-resources" title="http://www.w3.org/TR/css3-fonts/#font-resources">CSS 3 Fonts</a> 2009 - Rascunho em trabalho</li> + <li><a class="external" href="http://people.mozilla.com/~jkew/woff/woff-2009-09-16.html" title="http://people.mozilla.com/~jkew/woff/woff-2009-09-16.html">WOFF file format specification</a> - Rascunho</li> +</ul> + +<h2 id="Veja_também">Veja também</h2> + +<ul style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 25px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"> + <li style="margin-bottom: 0.25em;"><a class="external" href="http://www.fontsquirrel.com/fontface/generator" title="http://www.fontsquirrel.com/fontface/generator">FontSquirrel @font-face generator</a> (en)</li> + <li style="margin-bottom: 0.25em;"><a href="/en/About_WOFF" style="text-decoration: none; color: rgb(4, 137, 183) !important; cursor: default;" title="en/About WOFF">About WOFF</a> (en)</li> + <li style="margin-bottom: 0.25em;"><a class="external" href="http://hacks.mozilla.org/2009/06/beautiful-fonts-with-font-face/" title="http://hacks.mozilla.org/2009/06/beautiful-fonts-with-font-face/">Beautiful fonts with @font-face </a>(en)</li> + <li style="margin-bottom: 0.25em;"><a class="external" href="http://openfontlibrary.org/" title="http://openfontlibrary.org/">Open Font Library</a> (en)</li> + <li style="margin-bottom: 0.25em;"><a class="external" href="http://opentype.info/demo/webfontdemo.html" title="http://opentype.info/demo/webfontdemo.html">10 Great Free Fonts for @font-face embedding</a> (en)</li> +</ul> diff --git a/files/pt-pt/web/css/@import/index.html b/files/pt-pt/web/css/@import/index.html new file mode 100644 index 0000000000..b67776898e --- /dev/null +++ b/files/pt-pt/web/css/@import/index.html @@ -0,0 +1,53 @@ +--- +title: '@import' +slug: Web/CSS/@import +tags: + - At-rule + - CSS + - Referencia + - Referencia_CSS + - import +translation_of: Web/CSS/@import +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p><code>@import</code> é utilizado para importar regras de estilo de outros folhas de estilo.</p> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">@import "<em>url</em>"; +@import "<em>url</em>"<em>media1</em>,<em>media2</em>,<em>...</em>; +@import url("<em>url</em>"); +@import url("<em>url</em>")<em>media1</em>; +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>De modo que agentes do usuário possam evitar recuperar recursos para tipos não suportados de mídia, autores podem especificar regras <code>@import</code> dependentes de mídia. A importação destas condicionais especifica separado por vírgulas os <a href="pt/CSS/@media#Media_types">tipos de mídia</a> depois da URL. No <code>all</code> para o médio tem o mesmo efeito.</p> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<pre class="eval">@import url("fineprint.css") print; +@import url("bluish.css") projection, tv; +</pre> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/REC-CSS1#the-cascade">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/cascade.html#at-import">CSS 2.1</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("@media") }}, {{ Cssxref("@font-face") }}, {{ Cssxref("@import") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/@import", "fr": "fr/CSS/@import", "pl": "pl/CSS/@import" } ) }}</p> diff --git a/files/pt-pt/web/css/@media/index.html b/files/pt-pt/web/css/@media/index.html new file mode 100644 index 0000000000..959cc3c59f --- /dev/null +++ b/files/pt-pt/web/css/@media/index.html @@ -0,0 +1,276 @@ +--- +title: '@media' +slug: Web/CSS/@media +tags: + - CSS + - Referencia + - Referencia_CSS +translation_of: Web/CSS/@media +--- +<p>{{ CSSRef() }}</p> + +<p id="Resumo">A <a href="/pt-PT/docs/Web/CSS/At-rule" title="en/CSS/At-rule">regra "at"</a> <code>@media</code> de <a href="/pt-PT/docs/Web/CSS" title="CSS">CSS</a> permite aplicar parte de uma folha de estilos com a condição definida por uma ou mais consultas de média.</p> + +<p>Pode utilizar-se tanto no início do código como dentro de qualquer outra regra "at" condicional.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> Em JavaScript, a funcionalidade desta regra está disponível através da interface {{domxref("CSSMediaRule")}} do modelo/objeto CSS.</p> +</div> + +<h2 id="Sintaxe" name="Sintaxe">Sintaxe</h2> + +<pre class="brush: css"><code>/* No nível mais abrangente do código */ +@media screen and (min-width: 900px) { + article { + padding: 1rem 3rem; + } +} + +/* Dentro de outra regra-"at" condicional */ +@supports (display: flex) { + @media screen and (min-width: 900px) { + article { + display: flex; + } + } +}</code></pre> + +<p>Para aprofundar a sintaxe de consultas de média, por favor leia <a href="/pt-PT/docs/Web/CSS/Consulta_de_mídia">Utilizar consultas de média</a>.</p> + +<h2 id="Tipos_de_m.C3.ADdia" name="Tipos_de_m.C3.ADdia">Tipos de média</h2> + +<dl> + <dt><code>all</code> (todos)</dt> + <dd>Destinado para todos os dispositivos.</dd> + <dt><code>print</code> (impressão)</dt> + <dd>Destinado para material paginado e para documentos visualizados no ecrã no modo de pré-visualizar impressão. Por favor, consulte a secção de <a href="/pt-PT/docs/Web/CSS/Média_paginada" title="https://developer.mozilla.org/en/CSS/Paged_Media">média paginada,</a> e a <a href="/pt-PT/docs/Web/CSS/Como_começar/Mídia" title="https://developer.mozilla.org/en/CSS/Getting_Started/Media">secção de média do tutorial de Como Começar </a>para informação sobre a formatação de problemas que são específicos para a média paginada.</dd> + <dt><code>screen</code> (ecrã)</dt> + <dd>Destinado primariamente para os ecrãs de computador a cores.</dd> + <dt><code>speech</code> (elocução)</dt> + <dd> + <p>Pretendido para sintetizadores de fala. Nota: CSS2 tem um tipo de mídia similar chamado 'aural' para esta proposta. Veja o apêndice em folhas de estilo aural para detalhes.</p> + </dd> +</dl> + +<h3 id="Grupos_de_m.C3.ADdia" name="Grupos_de_m.C3.ADdia">Grupos de Média</h3> + +<div class="blockIndicator note"> +<p><strong>Nota: </strong>Esta secção aplica-se a CSS 2.1. Há vários tipos de média, introduzidos nas especificações do CSS2.1 e <a href="https://drafts.csswg.org/mediaqueries-3/#background" rel="noopener">Media Queries 3</a>, que foram descontinuados, como <code>tty</code>, <code>tv</code>, <code>projection</code>, <code>handheld</code>, <code>braille</code>, <code>embossed</code>, and <code>aural</code>. O tipo <code>aural</code> foi substituído pelo <code>speech</code>, que é semelhante.</p> +</div> + +<p>Tipos de média são também parte de diferentes grupos de média. A seguinte tabela indica que tipos estão em cada grupo.</p> + +<table class="standard-table"> + <tbody> + <tr> + <td></td> + <td class="header" colspan="10" style="text-align: center;">Grupos</td> + </tr> + <tr> + <td class="header">Tipos</td> + <td class="header">continuous</td> + <td class="header">paged</td> + <td class="header">visual</td> + <td class="header">audio</td> + <td class="header">speech</td> + <td class="header">tactile</td> + <td class="header">grid</td> + <td class="header">bitmap</td> + <td class="header">interactive</td> + <td class="header">static</td> + </tr> + <tr> + <td class="header">braille</td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td>X</td> + <td></td> + <td>X</td> + <td>X</td> + </tr> + <tr> + <td class="header">embossed</td> + <td></td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td>X</td> + <td></td> + <td></td> + <td>X</td> + </tr> + <tr> + <td class="header">handheld</td> + <td>X</td> + <td>X</td> + <td>X</td> + <td>X</td> + <td>X</td> + <td></td> + <td>X</td> + <td>X</td> + <td>X</td> + <td>X</td> + </tr> + <tr> + <td class="header">print</td> + <td></td> + <td>X</td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td></td> + <td>X</td> + </tr> + <tr> + <td class="header">projection</td> + <td></td> + <td>X</td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td>X</td> + <td></td> + </tr> + <tr> + <td class="header">screen</td> + <td>X</td> + <td></td> + <td>X</td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td>X</td> + <td>X</td> + </tr> + <tr> + <td class="header">aural</td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td>X</td> + </tr> + <tr> + <td class="header">tty</td> + <td>X</td> + <td></td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td></td> + <td>X</td> + <td>X</td> + </tr> + <tr> + <td class="header">tv</td> + <td>X</td> + <td>X</td> + <td>X</td> + <td>X</td> + <td></td> + <td></td> + <td></td> + <td>X</td> + <td>X</td> + <td>X</td> + </tr> + </tbody> +</table> + +<h2 id="Exemplos" name="Exemplos">Exemplos</h2> + +<pre> @media print { + body { font-size: 10pt } + } + @media screen { + body { font-size: 13px } + } + @media screen, print { + body { line-height: 1.2 } + } +</pre> + +<h2 id="Notas" name="Notas">Questões de acessibilidade</h2> + +<p>Para comodidade das pessoas que ampliam o tamanho do texto, deve-se utilizar medidas em <code>em</code> na definição de {{cssxref("<length>")}}. Esta medida funciona melhor do que <code>px</code> quando o utilizar muda o tamanho do texto no navegador.</p> + +<p>Considere usar consulta de média Level 4 (Nível 4) para melhorar experiência de utilização. Por exemplo, <code>prefers-reduced-motion</code> para detetar se o utilizador<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion"> pediu ao sistema para minimizar a quantidade de animaçõe ou movimentos</a>.</p> + +<h2 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h2> + +<table> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS5 Media Queries', '#at-media5', '@media')}}</td> + <td>{{Spec2('CSS5 Media Queries')}}</td> + <td>Reinstituída consultas de média <code>light-level</code>, <code>inverted-colors</code> e consultas média personalizadas, as quais foram removidas do Level 4 (Nível 4).<br> + Adicionados recursos de média <code>prefers-reduced-motion</code>, <code>prefers-reduced-transparency</code>, <code>prefers-contrast</code>, e <code>prefers-color-scheme</code>.</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Conditional', '#at-media', '@media')}}</td> + <td>{{Spec2('CSS3 Conditional')}}</td> + <td>Definida sintaxe básica da regra <code>@media</code>.</td> + </tr> + <tr> + <td>{{SpecName('CSS4 Media Queries', '#media', '@media')}}</td> + <td>{{Spec2('CSS4 Media Queries')}}</td> + <td> + <p>Adicionados recursos média <code>scripting</code>, <code>pointer</code>, <code>hover</code>, <code>update</code>, <code>overflow-block</code>, e <code>overflow-inline</code>.<br> + Descontinuação de todos os tipos de média excepto <code>screen</code>, <code>print</code>, <code>speech</code>, e <code>all</code>.<br> + Tornou a sintaxe mais flexível com adição, entre outras coisas, da palavra-chave <code>or</code>.</p> + </td> + </tr> + <tr> + <td>{{SpecName('CSS3 Media Queries', '#media0', '@media')}}</td> + <td>{{Spec2('CSS3 Media Queries')}}</td> + <td>Sem alterações.</td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'media.html#at-media-rule', '@media')}}</td> + <td>{{Spec2('CSS2.1')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<p><span class="comment">== Compatibilidade com navegadores ==</span></p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Consulte também</h3> + +<ul> + <li><a class="internal" href="/pt-PT/docs/Web/CSS/Consulta_de_mídia" title="En/CSS/Media queries">Consultas de média</a></li> + <li>Em JavaScript, {{ domxref("CSSMediaRule") }} está associado a esta regra-at.</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Mozilla_Extensions#Media_features">Recursos de média em extensões da Mozilla</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Webkit_Extensions#Media_features">Recursos de média em extensões WebKit</a></li> +</ul> + +<p>{{ languages( { "en": "en/CSS/@media", "fr": "fr/CSS/@media", "pl": "pl/CSS/@media" } ) }}</p> diff --git a/files/pt-pt/web/css/_colon_after/index.html b/files/pt-pt/web/css/_colon_after/index.html new file mode 100644 index 0000000000..f59fbcd5dd --- /dev/null +++ b/files/pt-pt/web/css/_colon_after/index.html @@ -0,0 +1,34 @@ +--- +title: ':after | ::after' +slug: 'Web/CSS/:after' +tags: + - Referencia_CSS +translation_of: 'Web/CSS/::after' +--- +<p>{{ CSSRef() }}</p> +<h3 id="Resumo" name="Resumo">Resumo</h3> +<p><code>:after </code>cria um pseudo-elemento que é a última criança do elemento selecionado. Tipicamente usado para adicionar conteúdo cosmético a um elemento, pelo uso da propriedade CSS {{ cssxref("content") }}. Este elemento é <code>inline</code> por padrão.</p> +<p>{{ fx_minversion_note("3.5", "A versão do Firefox anterior à 3.5 somente tinha implementada a propriedade <code>:after</code> do CSS 2.0. Não foram permitidas <code>position, float, list-style-*</code> e algumas propriedades de exibição. O Firefox 3.5 removeu estas restrições. Note que isto independe da notação com :: mencionada anteriormente.") }}</p> +<h3 id="Sintaxe">Sintaxe</h3> +<pre>element:after { propriedades do estilo } /* sintaxe CSS2 */ + +element::after { <em>propriedades do estilo</em> } /* sintaxe CSS3, não suportada pelo IE8 */</pre> +<p>A notação<code> ::after </code>foi introduzida no CSS3 com o objetivo de estabelecer uma diferença entre pseudo-classes e pseudo-elementos. Navegadores também aceitam a notação<code> :after </code>introduzida no CSS 2.</p> +<div class="note"><strong>Nota:</strong> O Microsoft Internet Explorer 8 suporta somente a notação <code>:after</code>.</div> +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> +<pre>.boringtext:after { + content: " Obrigado por ler tudo isto!"; + font-size: small; + color: red; + background: gray; +} +</pre> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> +<ul> <li><a class="external" href="http://www.w3.org/TR/CSS21/generate.html" title="http://www.w3.org/TR/CSS21/generate.html">CSS 2.1 Generated Content</a> (EN)</li> <li><a class="external" href="http://www.w3.org/TR/CSS21/selector.html#before-and-after" title="http://www.w3.org/TR/CSS21/selector.html#before-and-after">CSS 2.1 Selectors</a> (EN)</li> <li><a class="external" href="http://www.w3.org/TR/css3-selectors/#gen-content" rel="external nofollow" title="http://www.w3.org/TR/css3-selectors/#gen-content">CSS 3 Selectors</a> (EN) Rascunho em produção</li> +</ul> +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> +<table class="standard-table"> <tbody> <tr> <th>Navegador</th> <th>Versão mais antiga</th> <th>Suporte a</th> </tr> <tr> <td>Internet Explorer</td> <td>8.0</td> <td><code>:after</code></td> </tr> <tr> <td rowspan="2">Firefox (Gecko)</td> <td>1.0 (1.0)</td> <td><code>:after</code></td> </tr> <tr> <td>1.0 (1.5)</td> <td><code>:after | ::after</code></td> </tr> <tr> <td rowspan="2">Opera</td> <td>4.0</td> <td><code>:after</code></td> </tr> <tr> <td>7.0</td> <td><code>:after | ::after</code></td> </tr> <tr> <td>Safari (WebKit)</td> <td>1.0 (85)</td> <td><code>:after | ::after</code></td> </tr> </tbody> +</table> +<h3 id="Veja_também">Veja também</h3> +<p>{{ Cssxref(":before") }}, {{ cssxref("content") }}</p> +<p>{{ languages( { "fr": "fr/CSS/:after", "pl": "pl/CSS/:after", "es": "es/CSS/after", "pt": "pt/CSS/:after" } ) }}</p> diff --git a/files/pt-pt/web/css/_colon_before/index.html b/files/pt-pt/web/css/_colon_before/index.html new file mode 100644 index 0000000000..5572a818ef --- /dev/null +++ b/files/pt-pt/web/css/_colon_before/index.html @@ -0,0 +1,63 @@ +--- +title: ':before | ::before' +slug: 'Web/CSS/:before' +tags: + - Referencia_CSS +translation_of: 'Web/CSS/::before' +--- +<p>{{ CSSRef() }}</p> +<h3 id="Resumo" name="Resumo">Resumo</h3> +<p>:before cria um pseudo-elemento que é a primeira criança do elemento selecionado. Tipicamente usado para adicionar conteúdo cosmético a um elemento. Este elemento é <code>inline</code> por padrão.</p> +<p>{{ fx_minversion_note("3.5", "A versão do Firefox anterior à 3.5 somente tinha implementada a propriedade <code>:before</code> do CSS 2.0. Não foram permitidas <code>position, float, list-style-*</code> e algumas propriedades de exibição. O Firefox 3.5 removeu estas restrições. Note que isto independe da notação com :: mencionada anteriormente.") }}</p> +<h3 id="Sintaxe">Sintaxe</h3> +<pre>element:before { propriedades do estilo } /* sintaxe CSS2 */ + +element::before { <em>propriedades do estilo</em> } /* sintaxe CSS3, não suportada pelo IE8 */</pre> +<p>A notação<code> ::before </code>foi introduzida no CSS3 com o objetivo de estabelecer uma diferença entre pseudo-classes e pseudo-elementos. Navegadores também aceitam a notação<code> :before </code>introduzida no CSS 2.</p> +<div class="note"><strong>Nota:</strong> O Microsoft Internet Explorer 8 suporta somente a notação <code>:<span style="font-family: Verdana,Tahoma,sans-serif;">before</span></code>.</div> +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> +<pre>q:before { content: "»" } +q:after { content: '«' } + +<q>Algumas citações</q>, ele disse, <q>são melhores que nenhuma</q>.</pre> +<p>Resultado: »Algumas citações«, ele disse, »são melhores que nenhuma«.</p> +<h3 id="Notas">Notas</h3> +<p>Apesar das correções de posicionamento, o Firefox 3.5 não permite que o conteúdo seja gerado como um irmão anteriormente separado (como a declaração das <a class="external" href="http://www.w3.org/TR/CSS21/generate.html#before-after-content">CSS spec</a>(EN) "Os pseudo-elementos <code>:before</code> e <code>:after</code> interagem com outras caixas...como se fossem elementos reais inseridos dentro de seu elemento associado."), eles podem ser usados para proporcionar uma ligeira melhora nos arranjos sem tabelas (isto é, para alcançar o centro), tão longo como o conteúdo a ser centralizado é envolto em outro elemento criança, uma coluna antes e depois do conteúdo pode ser introduzida sem a adição de um irmão anterior ou posterior (por exemplo, talvez seja mais semanticamente correto adicionar um span a mais como anteriormente, que seria para adicionar um <code><div/></code> vazio antes e depois). (E sempre lembrar de adicionar uma largura para um flututante, uma vez que de outra forma ele não flutuará!)</p> +<pre class="brush: html"><style type="text/css"> + +#floatme {float:left; width:50%;} + +.example:before { + content: "Floated Before"; /* To get an empty column, just indicate a hex code for a non-breaking space: \a0 as the content (use \0000a0 when following such a space with other characters) */ + float: left; + width:25% +} +.example:after { + content: "Floated After"; + float: right; + width:25% +} + +/* For styling */ +.example:before, .example:after, .first { + background: yellow; + color: red; +} + + +</style> +<div class="example"> +<span id="floatme">"Floated Before" should be generated on the left of the +viewport and not allow overflow in this line to flow under it. Likewise +should "Floated After" appear on the right of the viewport and not allow this +line to flow under it.</span> +</div></pre> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> +<ul> <li><a class="external" href="http://www.w3.org/TR/CSS21/generate.html" title="http://www.w3.org/TR/CSS21/generate.html">CSS 2.1 Generated Content</a> (EN)</li> <li><a class="external" href="http://www.w3.org/TR/CSS21/selector.html#before-and-after" title="http://www.w3.org/TR/CSS21/selector.html#before-and-after">CSS 2.1 Selectors</a> (EN)</li> <li><a class="external" href="http://www.w3.org/TR/css3-selectors/#gen-content" rel="external nofollow" title="http://www.w3.org/TR/css3-selectors/#gen-content">CSS 3 Selectors</a> (EN) Rascunho em produção</li> +</ul> +<h3 id="Browser_compatibility" name="Browser_compatibility">Compatibilidade com navegadores</h3> +<table class="standard-table"> <tbody> <tr> <th>Navegador</th> <th>Versão mais antiga</th> <th>Suporte a</th> </tr> <tr> <td>Internet Explorer</td> <td>8.0<code> <br> </code></td> <td><code>:before</code></td> </tr> <tr> <td rowspan="2">Firefox (Gecko)</td> <td>1.0 (1.0)</td> <td><code>:before<br> </code></td> </tr> <tr> <td><strong>1.0</strong> (1.5)</td> <td><code>:before | ::before</code></td> </tr> <tr> <td>Safari (WebKit)</td> <td><strong>1.0</strong> (85)</td> <td><code><span style="font-family: Verdana,Tahoma,sans-serif;"><span style="font-family: monospace;">:</span></span>before | ::before</code></td> </tr> <tr> <td rowspan="2">Opera</td> <td>4.0</td> <td><code>:before<br> </code></td> </tr> <tr> <td><strong>7.0</strong></td> <td><code>:before | ::before</code></td> </tr> </tbody> +</table> +<h3 id="Examples" name="Examples">Veja também</h3> +<p>{{ Cssxref(":after") }}</p> +<p>{{ languages( { "en": "en/CSS/:before", "fr": "fr/CSS/:before", "pl": "pl/CSS/:before", "es": "es/CSS/before" } ) }}</p> diff --git a/files/pt-pt/web/css/at-rule/index.html b/files/pt-pt/web/css/at-rule/index.html new file mode 100644 index 0000000000..bbf7651358 --- /dev/null +++ b/files/pt-pt/web/css/at-rule/index.html @@ -0,0 +1,83 @@ +--- +title: Regra "At" +slug: Web/CSS/At-rule +tags: + - AT + - CSS + - Referencia + - Regra +translation_of: Web/CSS/At-rule +--- +<div>{{cssref}}</div> + +<p><span class="seoSummary">Uma <strong>regra "at"</strong> is a <a href="/en-US/docs/Web/CSS/Syntax#CSS_statements">CSS statement</a> beginning with an at sign, '<code>@</code>' (<code>U+0040 COMMERCIAL AT</code>), followed by an identifier and includes everything up to the next semi-colon, '<code>;</code>' (<code>U+003B SEMICOLON</code>), or the next <a href="/en-US/docs/Web/CSS/Syntax#CSS_declarations_blocks">CSS block</a>, whichever comes first.</span></p> + +<pre class="brush: css">/* General structure */ +@IDENTIFIER (RULE); + +/* Example: tells browser to use UTF-8 character set */ +@charset "utf-8";</pre> + +<p>There are several at-rules, designated by their identifiers, each with a different syntax:</p> + +<ul> + <li>{{cssxref("@charset")}} — Defines the character set used by the style sheet.</li> + <li>{{cssxref("@import")}} — Tells the CSS engine to include an external style sheet.</li> + <li>{{cssxref("@namespace")}} — Tells the CSS engine that all its content must be considered prefixed with an XML namespace.</li> + <li><strong><em>at-rules integradas</em></strong> — A subset of nested statements, which can be used as a statement of a style sheet as well as inside of conditional group rules: + <ul> + <li>{{cssxref("@media")}} — A conditional group rule which will apply its content if the device meets the criteria of the condition defined using a <em>media query</em>.</li> + <li>{{cssxref("@supports")}} {{experimental_inline}} — A conditional group rule which will apply its content if the browser meets the criteria of the given condition.</li> + <li>{{cssxref("@document")}} {{experimental_inline}} — A conditional group rule which will apply its content if the document in which the style sheet is applied meets the criteria of the given condition. <em>(deferred to Level 4 of CSS Spec)</em></li> + <li>{{cssxref("@page")}} — Describes the aspect of layout changes which will be applied when printing the document.</li> + <li>{{cssxref("@font-face")}} — Describes the aspect of an external font to be downloaded.</li> + <li>{{cssxref("@keyframes")}} {{experimental_inline}} — Describes the aspect of intermediate steps in a CSS animation sequence.</li> + <li>{{cssxref("@viewport")}} {{experimental_inline}} — Describes the aspects of the viewport for small screen devices. <em>(currently at the Working Draft stage)</em></li> + <li>{{cssxref("@counter-style")}} — Defines specific counter styles that are not part of the predefined set of styles. <em>(at the Candidate Recommendation stage, but only implemented in Gecko as of writing)</em></li> + <li>{{cssxref("@font-feature-values")}} (plus <code>@swash</code>, <code>@ornaments</code>, <code>@annotation</code>, <code>@stylistic</code>, <code>@styleset</code> and <code>@character-variant</code>)<br> + — Define common names in {{cssxref("font-variant-alternates")}} for feature activated differently in OpenType. <em>(at the Candidate Recommendation stage, but only implemented in Gekko as of writing)</em></li> + </ul> + </li> +</ul> + +<h2 id="Regras_de_grupo_condicionais">Regras de grupo condicionais</h2> + +<p>Much like the values of properties, each at-rule has a different syntax. Nevertheless, several of them can be grouped into a special category named <strong>conditional group rules</strong>. These statements share a common syntax and each of them can include <em>nested statements</em>—either <em>rulesets</em> or <em>nested at-rules</em>. Furthermore, they all convey a common semantic meaning—they all link some type of condition, which at any time evaluates to either <strong>true</strong> or <strong>false</strong>. If the condition evaluates to <strong>true</strong>, then all of the statements within the group will be applied.</p> + +<p>Conditional group rules are defined in <a href="http://dev.w3.org/csswg/css3-conditional/">CSS Conditionals Level 3</a> and are:</p> + +<ul> + <li>{{cssxref("@media")}},</li> + <li>{{cssxref("@supports")}},</li> + <li>{{cssxref("@document")}}. <em>(deferred to Level 4 of CSS Spec) </em></li> +</ul> + +<p>Since each conditional group may also contain nested statements, there may be an unspecified amount of nesting.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('CSS3 Conditional')}}</td> + <td>{{Spec2('CSS3 Conditional')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('Compat', '#css-at-rules', 'CSS At-rules')}}</td> + <td>{{Spec2('Compat')}}</td> + <td>Standardizes <code>@-webkit-keyframes</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="Consultar_também">Consultar também:</h2> + +<ul> + <li>{{CSS_key_concepts}}</li> +</ul> diff --git a/files/pt-pt/web/css/azimuth/index.html b/files/pt-pt/web/css/azimuth/index.html new file mode 100644 index 0000000000..24e469dc63 --- /dev/null +++ b/files/pt-pt/web/css/azimuth/index.html @@ -0,0 +1,72 @@ +--- +title: azimuth +slug: Web/CSS/azimuth +tags: + - Referencia_CSS +translation_of: Archive/Web/CSS/azimuth +--- +<p>{{ CSSRef() }}</p> +<h3 id="Resumo" name="Resumo">Resumo</h3> +<p>Em combinação com <code><a href="/pt/CSS/elevation" title="pt/CSS/elevation">elevation</a></code>, <code>azimuth</code> habilita diferentes fontes de áudio para serem posicionadas espacialmente para apresentações aurais. Isto é importante porque proporciona uma maneira natural de contar várias vozes a parte, como cada uma pode ser posicionada para originar em uma localização diferente no estágio de som. Saída estéreo produz um estágio de som lateral, enquanto instalações de fones de ouvido e microfones permitem um estágio tridimencional completo.</p> +<ul> + <li>Valor inicial: center</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: sim</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="/pt/CSS/Media/Aural" title="pt/CSS/Media/Aural">aural</a></li> + <li>Valor computado: ângulo normalizado</li> +</ul> +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> +<pre class="eval">azimuth: <em>angle</em> | [[ left-side | far-left | left | + center-left | center | center-right | right | + far-right | right-side ] || behind ] | leftwards | + rightwards | inherit +</pre> +<h3 id="Valores" name="Valores">Valores</h3> +<dl> + <dt> + angle </dt> + <dd> + Posição de fonte audível é descrita como um ângulo dentro da faixa de <code>-360deg</code> até <code>360deg</code>. O valor <code>0deg</code> significa diretamente adiante do centro do estágio de som (este é o valor padrão). <code>90deg</code> é para a direita, <code>180deg</code> é atrás e <code>270deg</code> ou <code>-90deg</code> é para a esquerda.</dd> +</dl> +<p><img alt="Image:Azimuth.png"></p> +<h4 id="Palavras-chave_relativas_a_posi.C3.A7.C3.A3o" name="Palavras-chave_relativas_a_posi.C3.A7.C3.A3o">Palavras-chave relativas a posição</h4> +<ul> + <li><strong>left-side</strong>: O mesmo que <code>270deg</code>.</li> + <li><strong>left-side behind</strong>: O mesmo que <code>270deg</code>.</li> + <li><strong>far-left</strong>: O mesmo que <code>300deg</code>.</li> + <li><strong>far-left behind</strong>: O mesmo que <code>240deg</code>.</li> + <li><strong>left</strong>: O mesmo que <code>320deg</code>.</li> + <li><strong>left behind</strong>: O mesmo que <code>220deg</code>.</li> + <li><strong>center-left</strong>: O mesmo que <code>340deg</code>.</li> + <li><strong>center-left behind</strong>: O mesmo que <code>200deg</code>.</li> + <li><strong>center</strong>: O mesmo que <code>0deg</code>.</li> + <li><strong>center behind</strong>: O mesmo que <code>180deg</code>.</li> + <li><strong>center-right</strong>: O mesmo que <code>20deg</code>.</li> + <li><strong>center-right behind</strong>: O mesmo que <code>160deg</code>.</li> + <li><strong>right</strong>: O mesmo que <code>40deg</code>.</li> + <li><strong>right behind</strong>: O mesmo que <code>140deg</code>.</li> + <li><strong>far-right</strong>: O mesmo que <code>60deg</code>.</li> + <li><strong>far-right behind</strong>: O mesmo que <code>120deg</code>.</li> + <li><strong>right-side</strong>: O mesmo que <code>90deg</code>.</li> + <li><strong>right-side behind</strong>: O mesmo que <code>90deg</code>.</li> + <li><strong>behind</strong>: O mesmo que <code>180deg</code>. Também é usado como um modificador para outros valores de palavras-chave posicionais, como acima.</li> + <li><strong>leftwards</strong>: Move o som no sentido anti-horário em 20 graus, relativo ao ângulo corrente.</li> + <li><strong>rightwards</strong>: Move o som no sentido horário em 20 graus, relatico ao ângulo corrente.</li> +</ul> +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> +<pre>h1 { azimuth: 30deg } +td.a { azimuth: far-right } /* 60deg */ +#12 { azimuth: behind far-right } /* 120deg */ +p.comment { azimuth: behind } /* 180deg */ +</pre> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS21/aural.html#spatial-props">CSS 2.1</a></li> +</ul> +<p><span class="comment">== Compatibilidade com navegadores == TBD (this might be abandoned in favour of a centralized compatibility chart)</span></p> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> +<p>{{ Cssxref("elevation") }}</p> +<p><span class="comment">Categorias</span></p> +<p><span class="comment">Interwiki Language Links</span></p> +<p>{{ languages( { "en": "en/CSS/azimuth", "fr": "fr/CSS/azimuth", "pl": "pl/CSS/azimuth" } ) }}</p> diff --git a/files/pt-pt/web/css/background-attachment/index.html b/files/pt-pt/web/css/background-attachment/index.html new file mode 100644 index 0000000000..ca851ae58c --- /dev/null +++ b/files/pt-pt/web/css/background-attachment/index.html @@ -0,0 +1,140 @@ +--- +title: background-attachment +slug: Web/CSS/background-attachment +tags: + - Referencia_CSS +translation_of: Web/CSS/background-attachment +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>Se um {{ Cssxref("background-image") }} é especificado, <code>background-attachment</code> determina se a posição da imagem é fixa na tela, ou rola junto com o bloco que a contém.</p> + +<ul> + <li>Valor inicial: scroll</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: como especificado</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">background-attachment: scroll | fixed | inherit +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>scroll </dt> + <dd>Se <code>scroll</code> é especificado, a imagem de fundo irá rolar na tela com o bloco de imagem que a contém.</dd> + <dt>fixed </dt> + <dd>Se <code>fixed</code> é especificado, a imagem de fundo não rolará com o elemento que a contém, em vez disso, continua estacionária no mesmo lugar da tela.</dd> +</dl> +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Simple_example">Simple example</h3> + +<h4 id="CSS">CSS</h4> + +<pre class="brush:css; highlight:[3];">p { + background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif"); + background-attachment: fixed; +} +</pre> + +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><p> + There were doors all round the hall, but they were all locked; and when + Alice had been all the way down one side and up the other, trying every + door, she walked sadly down the middle, wondering how she was ever to + get out again. +</p></pre> + +<h4 id="Result">Result</h4> + +<p>{{EmbedLiveSample("Simple_example")}}</p> + +<h3 id="Multiple_background_image_support">Multiple background image support</h3> + +<p>This property supports multiple background images. You can specify a different <code><attachment></code> for each background, separated by commas. Each image is matched with the corresponding attachment type, from first specified to last.</p> + +<h4 id="CSS_2">CSS</h4> + +<pre class="brush:css; highlight:[3];">p { + background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif"), url("https://mdn.mozillademos.org/files/12059/startransparent.gif"); + background-attachment: fixed, scroll; + background-repeat: no-repeat, repeat-y; +}</pre> + +<h4 id="HTML_2">HTML</h4> + +<pre class="brush: html"><p> + There were doors all round the hall, but they were all locked; and when + Alice had been all the way down one side and up the other, trying every + door, she walked sadly down the middle, wondering how she was ever to + get out again. + + Suddenly she came upon a little three-legged table, all made of solid + glass; there was nothing on it except a tiny golden key, and Alice's + first thought was that it might belong to one of the doors of the hall; + but, alas! either the locks were too large, or the key was too small, + but at any rate it would not open any of them. However, on the second + time round, she came upon a low curtain she had not noticed before, and + behind it was a little door about fifteen inches high: she tried the + little golden key in the lock, and to her great delight it fitted! +</p></pre> + +<h4 id="Result_2">Result</h4> + +<p>{{EmbedLiveSample("Multiple_background_image_support")}}</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#background-attachment">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/colors.html#propdef-background-attachment">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/2005/WD-css3-background-20050216/#background-attachment">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Netscape</td> + <td>6</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p> </p> + +<p>{{ languages( { "en": "en/CSS/background-attachment", "fr": "fr/CSS/background-attachment", "pl": "pl/CSS/background-attachment" } ) }}</p> diff --git a/files/pt-pt/web/css/background-color/index.html b/files/pt-pt/web/css/background-color/index.html new file mode 100644 index 0000000000..4d713de239 --- /dev/null +++ b/files/pt-pt/web/css/background-color/index.html @@ -0,0 +1,108 @@ +--- +title: background-color +slug: Web/CSS/background-color +tags: + - Referencia_CSS +translation_of: Web/CSS/background-color +--- +<p>{{CSSRef}}</p> + +<h2 id="Resumo" name="Resumo">Resumo</h2> + +<p><code>background-color</code> configura a cor de fundo de um elemento, com qualquer valor de cor ou a palavra-chave <code>transparent</code>.</p> + +<p>{{cssinfo}}</p> + +<h2 id="Sintaxe" name="Sintaxe">Sintaxe</h2> + +<pre class="eval">background-color: <em>color</em> | transparent | inherit +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>color </dt> + <dd>A cor pode ser especificada com um valor RGB hexadecimal, um valor RGB regular ou usando umas das palavras-chave pré-definidas.</dd> + <dt>transparent </dt> + <dd>O valor padrão para <code>background-color</code> é <code>transparent</code>, o que significa que o elemento não tem cor própria, em vez disso ele exibe a cor do elemento de trás.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><div class="exampleone"> + Lorem ipsum dolor sit amet, consectetuer +</div> + +<div class="exampletwo"> + Lorem ipsum dolor sit amet, consectetuer +</div> + +<div class="examplethree"> + Lorem ipsum dolor sit amet, consectetuer +</div></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css; highlight:[2,7,12,17];">.exampleone { + background-color: teal; + color: white; +} + +.exampletwo { + background-color: rgb(153,102,153); + color: rgb(255,255,204); +} + +.examplethree { + background-color: #777799; + color: #FFFFFF; +} +</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample("Exemplos","200","150")}}</p> + + +<h2 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#background-color">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/colors.html#propdef-background-color">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/2005/WD-css3-background-20050216/#background-color">CSS 3</a></li> +</ul> + +<h2 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegadores</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4.0</td> + </tr> + <tr> + <td>Firefox (Gecko)</td> + <td>1.0 (1.0)</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + <tr> + <td>Safari (WebKit)</td> + <td>1.0 (85)</td> + </tr> + </tbody> +</table> + +<h2 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h2> + +<ul> + <li style="margin-bottom: 0.25em;"><a href="/en/CSS/Multiple_backgrounds" style="text-decoration: none; color: rgb(4, 137, 183) !important; cursor: default;" title="en/CSS/Multiple backgrounds">Multiple backgrounds</a></li> +</ul> diff --git a/files/pt-pt/web/css/background-image/index.html b/files/pt-pt/web/css/background-image/index.html new file mode 100644 index 0000000000..fd513e19b1 --- /dev/null +++ b/files/pt-pt/web/css/background-image/index.html @@ -0,0 +1,131 @@ +--- +title: background-image +slug: Web/CSS/background-image +tags: + - CSS_1 + - CSS_2.1 + - CSS_3 + - Referencia_CSS +translation_of: Web/CSS/background-image +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade <code>background-image</code> configura a imagem de fundo para um elemento.</p> + +<ul> + <li>Valor inicial: none</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: URI absoluta ou none</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">background-image:<em>uri</em> | none | inherit +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>uri </dt> + <dd>A localização da imagem de recurso para ser usada como imagem de fundo.</dd> + <dt>none </dt> + <dd>Usado para especificar que um elemento não tem imagem de fundo.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Note that the star image is partially transparent and is layered over the cat image.</p> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><div> + <p class="catsandstars"> + This paragraph is full of cats<br />and stars. + </p> + <p>This paragraph is not.</p> + <p class="catsandstars"> + Here are more cats for you.<br />Look at them! + </p> + <p>And no more.</p> +</div></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">pre, p { + font-size: 1.5em; + color: #FE7F88; + background-color: transparent; +} + +div { + background-image: url("https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png"); +} + +p { + background-image: none; +} + +.catsandstars { + background-image: url("https://mdn.mozillademos.org/files/11991/startransparent.gif"), + url("https://mdn.mozillademos.org/files/7693/catfront.png"); + background-color: transparent; +} +</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample('Exemplos')}}</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Desenvolvedores devem assegurar-se de especificar um {{ Cssxref("background-color") }} para ser usado se uma imagem não estiver disponível. Imagens de fundo são renderizadas sobre a cor de fundo.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#background-image">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/colors.html#propdef-background-image">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/2005/WD-css3-background-20050216/#the-background-image">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/background-image", "fr": "fr/CSS/background-image", "pl": "pl/CSS/background-image" } ) }}</p> diff --git a/files/pt-pt/web/css/background-position/index.html b/files/pt-pt/web/css/background-position/index.html new file mode 100644 index 0000000000..5445184e42 --- /dev/null +++ b/files/pt-pt/web/css/background-position/index.html @@ -0,0 +1,85 @@ +--- +title: background-position +slug: Web/CSS/background-position +tags: + - Referencia_CSS +translation_of: Web/CSS/background-position +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>background-position</code> configura a posição inicial de qualquer imagem de fundo que seja configurada. +</p> +<ul><li> Valor inicial: 0% 0% +</li><li> Aplica-se a: todos os elementos +</li><li> Herdado: não +</li><li> Porcentagens: refere-se ao tamanho da própria caixa +</li><li> Mídia: <a href="pt/CSS/Media/Visual">visual</a> +</li><li> Valor computado: para <length> o valor absoluto, se não uma porcentagem +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<pre class="eval">background-position: [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] | [ [ left | center | right ] || [ top | center | bottom ] ] | inherit +</pre> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> <percentage> <percentage></dt><dd> Com um par de valores de '0% 0%', o canto superior esquerdo da imagem é alinhado com o canto superior esquerdo do enchimento da borda da caixa. Um par de valores de '100% 100%' coloca o canto inferior direito da imagem no canto inferior direito da área de enchimento. Com um par de valores de '14% 84%', o ponto de 14% na horizontal e 84% na vertical da imagem é colocado no ponto 14% na horizontal e 84% na vertical da área de enchimento. +</dd><dt> <length> <length></dt><dd> Com um par de valores de '2cm 1cm', o canto superior esquerdo da imagem é colocado 2cm para a direita e 1cm abaixo do canto superior esquerdo da área de enchimento. +</dd><dt>top left e left top</dt><dd> O mesmo que '0% 0%'. +</dd><dt>top, top center e center top</dt><dd> O mesmo que '50% 0%'. +</dd><dt>right top e top right</dt><dd> O mesmo que '100% 0%'. +</dd><dt>left, left center e center left</dt><dd> O mesmo que '0% 50%'. +</dd><dt>center e center center</dt><dd> O mesmo que '50% 50%'. +</dd><dt>right, right center e center right</dt><dd> O mesmo que '100% 50%'. +</dd><dt>bottom left e left bottom</dt><dd> O mesmo que '0% 100%'. +</dd><dt>bottom, bottom center e center bottom</dt><dd> O mesmo que '50% 100%'. +</dd><dt>bottom right e right bottom</dt><dd> O mesmo que '100% 100%'. +</dd></dl> +<p>Se somente um valor é especificado, então ele configura a posição horizontal, com a posição vertical em 50%. Caso contrário, o primeiro valor especifica a posição horizontal. Combinações são permitidas de valores de palavras-chave, comprimento ou porcentagens, mas se palavras-chave forem misturadas com outros valores, <code>'left'</code> e <code>'right'</code> podem somente ser usados como o primeiro valor, e <code>'top'</code> e <code>'down'</code> podem somente ser usados como o segundo valor. Posições negativas são permitidas. +</p> +<h3 id="Exemplos" name="Exemplos"> Exemplos </h3> +<pre>.exampleone { + background-image: url("logo.png"); + background-position: top center; +} + +.exampletwo { + background-image: url("logo.png"); + background-position: 25% 75%; +} + +.examplethree { + background-image: url("logo.png"); + background-position: 2cm bottom; +} + +.examplefour { + background-image: url("logo.png"); + background-position: center 10%; +} + +.examplefive { + background-image: url("logo.png"); + background-position: 2cm 50%; +} + +</pre> +<p><span class="comment">== Notas ==</span> +</p> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es"> Especificações </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS1#background-position">CSS 1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/CSS21/colors.html#propdef-background-position">CSS 2.1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/2005/WD-css3-background-20050216/#background-position">CSS 3</a> +</li></ul> +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores"> Compatibilidade com navegadores </h3> +<table class="standard-table"> <tbody><tr> <th>Navegador</th> <th>Versão mais antiga</th> </tr> <tr> <td>Internet Explorer</td> <td>4</td> </tr> <tr> <td>Firefox</td> <td>1</td> </tr> <tr> <td>Netscape</td> <td>6</td> </tr> <tr> <td>Opera</td> <td>3.5</td> </tr> +</tbody></table> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m"> Veja também </h3> +<p>{{ Cssxref("background") }}, +{{ Cssxref("background-attachment") }}, +{{ Cssxref("background-color") }}, +{{ Cssxref("background-image") }}, +{{ Cssxref("background-position") }}, +{{ Cssxref("background-repeat") }} +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/background-position", "fr": "fr/CSS/background-position", "pl": "pl/CSS/background-position" } ) }} diff --git a/files/pt-pt/web/css/background-repeat/index.html b/files/pt-pt/web/css/background-repeat/index.html new file mode 100644 index 0000000000..582f6f86f8 --- /dev/null +++ b/files/pt-pt/web/css/background-repeat/index.html @@ -0,0 +1,138 @@ +--- +title: background-repeat +slug: Web/CSS/background-repeat +tags: + - Referencia_CSS +translation_of: Web/CSS/background-repeat +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p><code>background-repeat</code> specifies whether the image is repeated (tiled), and how.</p> + +<ul> + <li>Valor inicial: repeat</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: como especificado</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">background-repeat: repeat | repeat-x | repeat-y | no-repeat | inherit +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>repeat</dt> + <dd>A imagem é repetida vertical e horizontalmente.</dd> + <dt>repeat-x</dt> + <dd>A imagem é repetida somente horizontalmente.</dd> + <dt>repeat-y</dt> + <dd>A imagem é repetida somente verticalmente.</dd> + <dt>no-repeat</dt> + <dd>A imagem não é repetida: somente uma cópia da imagem é desenhada.</dd> +</dl> + + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><ol> + <li>no-repeat + <div class="one">&nbsp;</div> + </li> + <li>repeat + <div class="two">&nbsp;</div> + </li> + <li>repeat-x + <div class="three">&nbsp;</div> + </li> + <li>repeat-y + <div class="four">&nbsp;</div> + </li> + <li>repeat-x, repeat-y (multiple images) + <div class="five">&nbsp;</div> + </li> +</ol></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">/* Shared for all DIVS in example */ +li {margin-bottom: 12px;} +div { + background-image: url(https://mdn.mozillademos.org/files/12005/starsolid.gif); + width: 144px; + height: 84px; +} + +/* background repeat CSS */ +.one { + background-repeat: no-repeat; +} +.two { + background-repeat: repeat; +} +.three { + background-repeat: repeat-x; +} +.four { + background-repeat: repeat-y; +} + +/* Multiple images */ +.five { + background-image: url(https://mdn.mozillademos.org/files/12005/starsolid.gif), + url(https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png); + background-repeat: repeat-x, + repeat-y; + height: 144px; +}</pre> + +<h3 id="Result">Result</h3> + +<p>In this example, each list item is matched with a different value of <code>background-repeat</code>.</p> + +<p>{{EmbedLiveSample('Exemplos', 240, 360)}}</p> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/background-repeat", "fr": "fr/CSS/background-repeat", "pl": "pl/CSS/background-repeat" } ) }}</p> diff --git a/files/pt-pt/web/css/background/index.html b/files/pt-pt/web/css/background/index.html new file mode 100644 index 0000000000..3118d1b239 --- /dev/null +++ b/files/pt-pt/web/css/background/index.html @@ -0,0 +1,117 @@ +--- +title: background +slug: Web/CSS/background +tags: + - Referencia_CSS +translation_of: Web/CSS/background +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Introdu.C3.A7.C3.A3o" name="Introdu.C3.A7.C3.A3o">Introdução</h3> + +<p>A propriedade <code>background</code> é usada para ajustar os valores do fundo em um único lugar na folha de estilos. <code>background</code> pode ser usada com os seguintes valores adicionais: {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}.</p> + +<ul> + <li>Valor inicial: veja as propriedades individuais para detalhes;</li> + <li>Aplica-se a: todos os elementos;</li> + <li>Herdado: não;</li> + <li>Porcentagens: reservado para {{ Cssxref("background-position") }};</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a>;</li> + <li>Valor computado: veja as propriedades individuais para detalhes.</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">background: [<em>background-color</em> ||<em>background-image</em> ||<em>background-repeat</em> ||<em>background-attachment</em> ||<em>background-position</em>] |<em>inherit</em>] +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>background-color</dt> + <dd>Veja <code><a href="pt/CSS/background-color">background-color</a></code>.</dd> + <dt>background-image </dt> + <dd>Veja <code><a href="pt/CSS/background-image">background-image</a></code>.</dd> + <dt>background-repeat </dt> + <dd>Veja <code><a href="pt/CSS/background-repeat">background-repeat</a></code>.</dd> + <dt>background-attachment </dt> + <dd>Veja <code><a href="pt/CSS/background-attachment">background-attachment</a></code>.</dd> + <dt>background-position </dt> + <dd>Veja <code><a href="pt/CSS/background-position">background-position</a></code>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><p class="topbanner"> + Starry sky<br/> + Twinkle twinkle<br/> + Starry sky +</p> +<p class="warning">Here is a paragraph<p></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush:css' highlight:[2,6];">.warning { + background: red; +} + +.topbanner { + background: url("https://mdn.mozillademos.org/files/11983/starsolid.gif") #00D repeat-y fixed; +} +</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample("Exemplos")}}</p> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Sendo uma declaração válida, a propriedade <code>background</code> ajusta primeiramente o background (fundo) individual para seus valores iniciais, e depois, atribui então os valores especificados na declaração. Você não precisa definir um valor para cada uma das propriedades, apenas para aquelas que você deseja alterar os valores padrões.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#background">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/colors.html#propdef-background">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/2005/WD-css3-background-20050216/#the-background">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Netscape</td> + <td>6</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}</p> + +<p><br> + <span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/background", "fr": "fr/CSS/background", "pl": "pl/CSS/background" } ) }}</p> diff --git a/files/pt-pt/web/css/border-bottom-color/index.html b/files/pt-pt/web/css/border-bottom-color/index.html new file mode 100644 index 0000000000..0a6c79941e --- /dev/null +++ b/files/pt-pt/web/css/border-bottom-color/index.html @@ -0,0 +1,110 @@ +--- +title: border-bottom-color +slug: Web/CSS/border-bottom-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-bottom-color +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p><code>border-bottom-color</code> configura a cor da borda inferior de um elemento, com o nome da cor ou a palavra-chave <code>transparent</code>.</p> + +<ul> + <li>Valor inicial: propriedade 'color'</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: quando pego da propriedade 'color', o valor computado de 'color'; caso contrário, como especificado</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">border-bottom-color:<em>color</em> | transparent | inherit +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>color </dt> + <dd>A cor pode ser especificada como um valor RGB hexadecimal, um valor RGB regular ou usando uma das palavras-chave de cor pré-definidas.</dd> + <dt>transparent </dt> + <dd>O elemento não tem cor própria, dessa forma exibe a cor do elemento que fica atrás dele.</dd> +</dl> + +<h3 id="Propriedades_relacionadas" name="Propriedades_relacionadas">Propriedades relacionadas</h3> + +<ul> + <li>{{ Cssxref("border-color") }}</li> + <li>{{ Cssxref("border-left-color") }}</li> + <li>{{ Cssxref("border-right-color") }}</li> + <li>{{ Cssxref("border-top-color") }}</li> +</ul> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/border.html">View Live Examples</a></p> + +<pre>element { + width: 300px; + padding: 15px; + border-bottom-size: 1px; + border-bottom-style: solid; + border-bottom-color: #000; +} + +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<ul> + <li><a class="external" href="http://html-color-codes.com/">Color Chart by VisiBone</a></li> +</ul> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS21/box.html#propdef-border-bottom-color">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-background/#border-bottom">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Netscape</td> + <td>6</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<p> </p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-width") }},</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/border-bottom-color", "fr": "fr/CSS/border-bottom-color", "pl": "pl/CSS/border-bottom-color" } ) }}</p> diff --git a/files/pt-pt/web/css/border-bottom-style/index.html b/files/pt-pt/web/css/border-bottom-style/index.html new file mode 100644 index 0000000000..be873908d9 --- /dev/null +++ b/files/pt-pt/web/css/border-bottom-style/index.html @@ -0,0 +1,94 @@ +--- +title: border-bottom-style +slug: Web/CSS/border-bottom-style +tags: + - Referencia_CSS +translation_of: Web/CSS/border-bottom-style +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p><code>border-bottom-style</code> configura o estilo da linha da borda inferior de uma caixa.</p> + +<ul> + <li>Valor inicial: none</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: como especificado</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">border-bottom-style: <border-style> | inherit +</pre> + +<h3 id=".3Cborder-style.3E_Valores" name=".3Cborder-style.3E_Valores"><border-style> Valores</h3> + +<dl> + <dt>none </dt> + <dd>Sem borda.</dd> + <dt>hidden </dt> + <dd>O mesmo que 'none', exceto em termos de conflitos na resolução de bordas para elementos de tabela.</dd> + <dt>dotted </dt> + <dd>Série de pontos.</dd> + <dt>dashed </dt> + <dd>Série de traços ou segmentos de linha.</dd> + <dt>solid </dt> + <dd>Simples, reto, linha contínua.</dd> + <dt>double </dt> + <dd>Duas linhas retas que adicionam uma quantidade de pixels definida por <code>border-width</code>.</dd> + <dt>groove </dt> + <dd>Efeito entalhado.</dd> + <dt>ridge </dt> + <dd>Contrário de 'groove'.</dd> + <dt>inset </dt> + <dd>Faz a caixa aparecer em baixo relevo.</dd> + <dt>outset </dt> + <dd>Contrário de 'inset'. Faz a caixa aparecer em alto relevo.</dd> +</dl> + +<h3 id="Propriedades_relacionadas" name="Propriedades_relacionadas">Propriedades relacionadas</h3> + +<ul> + <li>{{ Cssxref("border-left-style") }}</li> + <li>{{ Cssxref("border-right-style") }}</li> + <li>{{ Cssxref("border-top-style") }}</li> + <li>{{ Cssxref("border-style") }}</li> +</ul> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/border.html">View Live Examples</a></p> + +<pre>element { + border-bottom-size: 1px; + border-bottom-style: dotted; + border-bottom-color: #000; +} +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>A menos que seja configurado um valor para <code>border-style</code>, sua borda não aparecerá, pois o valor padrão configurado é 'none'.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS21/box.html#propdef-border-bottom-style">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-background/#border-style">CSS 3</a></li> +</ul> + +<p><span class="comment">== Compatibilidade com navegadores ==</span></p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-color") }}, {{ Cssxref("border-bottom-width") }},</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/border-bottom-style", "fr": "fr/CSS/border-bottom-style", "pl": "pl/CSS/border-bottom-style" } ) }}</p> diff --git a/files/pt-pt/web/css/border-bottom-width/index.html b/files/pt-pt/web/css/border-bottom-width/index.html new file mode 100644 index 0000000000..299636a962 --- /dev/null +++ b/files/pt-pt/web/css/border-bottom-width/index.html @@ -0,0 +1,112 @@ +--- +title: border-bottom-width +slug: Web/CSS/border-bottom-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-bottom-width +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p><code>border-bottom-width</code> configura a largura da borda inferior de uma caixa.</p> + +<ul> + <li>Valor inicial: medium</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: comprimento absoluto; '0' se o estilo da borda for 'none' ou 'hidden'</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">border-bottom-width: <border-width> | inherit +</pre> + +<h3 id="Valores_de_.3Cborder-width.3E" name="Valores_de_.3Cborder-width.3E">Valores de <border-width></h3> + +<dl> + <dt>thin </dt> + <dd>Uma borda fina.</dd> + <dt>medium </dt> + <dd>Uma borda média.</dd> + <dt>thick </dt> + <dd>Uma borda grossa.</dd> + <dt><length> </dt> + <dd>A espessura da borda tem um valor explícito. Valores explícitos de borda não podem ser negativos.</dd> + <dt><percentage> </dt> + <dd>A espessura da borda tem um valor em porcentagem, porcentagens da largura do bloco em que está contida. Larguras explícitas de borda não podem ser negativos.</dd> +</dl> + +<p>Nota: Um valor <code>em</code> também é suportado.</p> + +<h3 id="Propriedades_relacionadas" name="Propriedades_relacionadas">Propriedades relacionadas</h3> + +<ul> + <li>{{ Cssxref("border-left-width") }}</li> + <li>{{ Cssxref("border-right-width") }}</li> + <li>{{ Cssxref("border-top-width") }}</li> + <li>{{ Cssxref("border-width") }}</li> +</ul> + +<p> </p> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/border.html">View Live Examples</a></p> + +<pre>element { + border-bottom-width: thin; + border-bottom-style: solid; + border-bottom-color: #000; +} +</pre> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#border-width">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/box.html#border-width-properties">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-background/#border-width">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td> </td> + </tr> + <tr> + <td>Firefox</td> + <td> </td> + </tr> + <tr> + <td>Netscape</td> + <td> </td> + </tr> + <tr> + <td>Opera</td> + <td> </td> + </tr> + </tbody> +</table> + +<p> </p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-width") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-color") }},</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/border-bottom-width", "fr": "fr/CSS/border-bottom-width", "pl": "pl/CSS/border-bottom-width" } ) }}</p> diff --git a/files/pt-pt/web/css/border-bottom/index.html b/files/pt-pt/web/css/border-bottom/index.html new file mode 100644 index 0000000000..08da201a5f --- /dev/null +++ b/files/pt-pt/web/css/border-bottom/index.html @@ -0,0 +1,109 @@ +--- +title: border-bottom +slug: Web/CSS/border-bottom +tags: + - Referencia_CSS +translation_of: Web/CSS/border-bottom +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade <code>border-bottom</code> é uma propriedade<em>shorthand</em> que configura os valores de {{ Cssxref("border-bottom-color") }}, {{ Cssxref("border-bottom-style") }} e {{ Cssxref("border-bottom-width") }}. Estas propriedades descrevem a borda inferior de elementos.</p> + +<ul> + <li>Valor inicial: veja as propriedades individuais para detalhes</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: ver propriedades individuais</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">border-bottom: [ <border-width> || <border-style> || <border-color> ] |<em>inherit</em> +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt><border-width> </dt> + <dd>Veja {{ Cssxref("border-bottom-width") }}.</dd> + <dt><border-style> </dt> + <dd>Veja {{ Cssxref("border-bottom-style") }}.</dd> + <dt><border-color> </dt> + <dd>Veja {{ Cssxref("border-bottom-color") }}.</dd> +</dl> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/border.html">View Live Examples</a></p> + +<pre>element { + border-bottom-width: 1px solid #000; +} +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>Os três valores da propriedade<em>shorthand</em> podem ser especificados em qualquer ordem e um ou dois deles podem ser omitidos.</p> + +<p>Como com todas as propriedades<em>shorthand</em>, <code>border-bottom</code> sempre configura os valores de todas as propriedades que ele pode configurar, ainda que elas não sejam especificadas. Ele configura as que não especificadas para os seus valores padrão. De maneira que:</p> + +<pre> border-bottom-style: dotted; + border-bottom: thick green;</pre> + +<p>é realmente o mesmo que</p> + +<pre> border-bottom-style: dotted; + border-bottom: none thick green;</pre> + +<p>e o valor de {{ Cssxref("border-bottom-style") }} dado antes <code>border-bottom</code> é ignorado.</p> + +<p>Desde que o valor padrão de {{ Cssxref("border-bottom-style") }} seja <code>none</code>, não especificar o <border-style> torna o valor, o mesmo que a propriedade especifica na borda.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#border-bottom">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/box.html#border-shorthand-properties">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-background/#the-border-shorthands">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-width") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-color") }},</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/border-bottom", "fr": "fr/CSS/border-bottom", "pl": "pl/CSS/border-bottom" } ) }}</p> diff --git a/files/pt-pt/web/css/border-collapse/index.html b/files/pt-pt/web/css/border-collapse/index.html new file mode 100644 index 0000000000..0f1acaaf50 --- /dev/null +++ b/files/pt-pt/web/css/border-collapse/index.html @@ -0,0 +1,87 @@ +--- +title: border-collapse +slug: Web/CSS/border-collapse +tags: + - Referencia_CSS +translation_of: Web/CSS/border-collapse +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>The border-collapse property is used to make the border collapse. This has a big influence on the look and style of the table cells. The rendering of table borders is divided into two categories in CSS2 - "collapsed" and "separated". This property specifies which border rendering mode to use. In the collapsed border model, adjacent table cells share borders. In the separated model, adjacent cells each have their own distinct borders (the distance between them given by the 'border-spacing' property.)</p> + +<ul> + <li>Valor inicial: separate</li> + <li>Herdado: sim</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">border-collapse: value +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<ul> + <li><strong>inherit</strong> : Explicitly sets the value of this property to that of the parent.</li> + <li><strong>separate</strong> : Use the "separated borders" rendering model</li> + <li><strong>collapse</strong> : Use the "collapsed borders" rendering model</li> +</ul> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/border-collapse.html">View Live Examples</a></p> + +<pre><table border="1" style="border-collapse: collapse" bordercolor="#111111" width="500"> +</pre> + +<pre><table border="1" style="border-collapse: separate" bordercolor="#111111" width="500"> +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>In the "collapsed border" rendering model, the 'border-style' value of "inset" behaves like "groove", and "outset" behaves like "ridge." CSS2 specifies that the initial value for this property is "collapse", but CSS2.1 and Mozilla/Opera all state or behave such that the initial value is "separate."</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS21/tables.html#collapsing-borders">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/REC-CSS2/tables.html#borders">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>5.5</td> + </tr> + <tr> + <td>Netscape</td> + <td>7</td> + </tr> + <tr> + <td>Opera</td> + <td>5</td> + </tr> + </tbody> +</table> + +<p> </p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("border-collapse") }}, {{ Cssxref("border-spacing") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/border-collapse", "fr": "fr/CSS/border-collapse" } ) }}</p> diff --git a/files/pt-pt/web/css/border-color/index.html b/files/pt-pt/web/css/border-color/index.html new file mode 100644 index 0000000000..e97253bd58 --- /dev/null +++ b/files/pt-pt/web/css/border-color/index.html @@ -0,0 +1,116 @@ +--- +title: border-color +slug: Web/CSS/border-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-color +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade <code>border-color</code> é muito útil para ajustar a cor dos quatro lados da borda do elemento.</p> + +<ul> + <li>Valor inicial: os elementos da propriedade {{ Cssxref("color") }}</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="/pt/CSS/Media/Visual" title="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: O valor computado de <code>color</code> por padrão, ou como especificado.</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">border-color: [ <color> || transparent ]{1,4} | <em>inherit</em> +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt><color> </dt> + <dd>A cor pode ser especificada como um valor RGB hexadecimal, um valor RGB regular ou usando uma das palavras-chave de cores pré-definidas.</dd> +</dl> + +<dl> + <dt>transparent </dt> + <dd>A borda não é desenhada, mas ainda continua ocupando espaço na página.</dd> +</dl> + +<p>Até quatro valores podem ser fornecidos;</p> + +<p>Se um valor de cor é fornecido, então todas as quatros bordas ficam daquela cor.<br> + Se dois valores são fornecidos, as bordas inferior e superior utilizam-se do primeiro valor e as esquerda e direita do segundo valor.<br> + Se três valores são fornecidos, o primeiro é para a borda superior, o segundo para a esquerda e direita e o terceiro para a inferior.<br> + Se quatro valores são dados, o primeiro é para a borda superior, o segundo para a direita, o terceiro para a inferior e o quarto para a esquerda.</p> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/border.html">View Live Examples</a></p> + +<pre>element { + border-width: 1px; + border-style: solid; + border-color: black; +} +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>No caso de querer ver a borda, você deve ajustar o {{ Cssxref("border-width") }} para um valor positivo e o {{ Cssxref("border-style") }} para algo visível.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#border-color">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/box.html#border-color-properties">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-background/#the-border-color">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Extens.C3.B5es_Mozilla" name="Extens.C3.B5es_Mozilla">Extensões Mozilla</h3> + +<p>As seguintes Extensões da Mozilla ajustam os respectivos lados da borda para múltiplas cores para navegadores Gecko.</p> + +<ul> + <li>{{ Cssxref("-moz-border-bottom-colors") }}</li> + <li>{{ Cssxref("-moz-border-left-colors") }}</li> + <li>{{ Cssxref("-moz-border-right-colors") }}</li> + <li>{{ Cssxref("-moz-border-top-colors") }}</li> +</ul> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("border") }}, {{ Cssxref("border-color") }}, {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/border-color", "fr": "fr/CSS/border-color", "pl": "pl/CSS/border-color" } ) }}</p> diff --git a/files/pt-pt/web/css/border-left-color/index.html b/files/pt-pt/web/css/border-left-color/index.html new file mode 100644 index 0000000000..f358f01aa0 --- /dev/null +++ b/files/pt-pt/web/css/border-left-color/index.html @@ -0,0 +1,16 @@ +--- +title: border-left-color +slug: Web/CSS/border-left-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-left-color +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-left-color</code> configura a cor da borda esquerda de um elemento. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-color">border-bottom-color</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-left-color", "fr": "fr/CSS/border-left-color", "pl": "pl/CSS/border-left-color" } ) }} diff --git a/files/pt-pt/web/css/border-left-style/index.html b/files/pt-pt/web/css/border-left-style/index.html new file mode 100644 index 0000000000..f482151b58 --- /dev/null +++ b/files/pt-pt/web/css/border-left-style/index.html @@ -0,0 +1,16 @@ +--- +title: border-left-style +slug: Web/CSS/border-left-style +tags: + - Referencia_CSS +translation_of: Web/CSS/border-left-style +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-left-style</code> configura o estilo da linha da borda esquerda de uma caixa. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-style">border-bottom-style</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-left-style", "fr": "fr/CSS/border-left-style" } ) }} diff --git a/files/pt-pt/web/css/border-left-width/index.html b/files/pt-pt/web/css/border-left-width/index.html new file mode 100644 index 0000000000..caf87d5d71 --- /dev/null +++ b/files/pt-pt/web/css/border-left-width/index.html @@ -0,0 +1,16 @@ +--- +title: border-left-width +slug: Web/CSS/border-left-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-left-width +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-left-width</code> configura a largura da borda esquerda de um elemento. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-width">border-bottom-width</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-left-width", "fr": "fr/CSS/border-left-width" } ) }} diff --git a/files/pt-pt/web/css/border-left/index.html b/files/pt-pt/web/css/border-left/index.html new file mode 100644 index 0000000000..e0cd0e9f6f --- /dev/null +++ b/files/pt-pt/web/css/border-left/index.html @@ -0,0 +1,50 @@ +--- +title: border-left +slug: Web/CSS/border-left +tags: + - Referencia_CSS +translation_of: Web/CSS/border-left +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p>A propriedade <code>border-left</code> é uma propriedade <i>shorthand</i> para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-left-width") }}, {{ Cssxref("border-left-style") }} e {{ Cssxref("border-left-color") }}. Valores omitidos são configurados com o valor inicial. +</p> +<ul><li> Valor inicial: veja as propriedades individuais para detalhes +</li><li> Aplica-se a: todos os elementos +</li><li> Herdado: não +</li><li> Porcentagens: N/A +</li><li> Mídia: <a href="pt/CSS/Media/Visual">visual</a> +</li><li> Valor computado: veja propriedades individuais +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<pre class="eval">border-left: [<i>border-width</i> || <i>border-style</i> || <i>border-color</i> | <i>inherit</i>] ; +</pre> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> border-width </dt><dd> Veja {{ Cssxref("border-width") }}. +</dd><dt> border-style </dt><dd> Veja {{ Cssxref("border-style") }}. +</dd><dt> border-color </dt><dd> Veja {{ Cssxref("border-color") }}. +</dd></dl> +<h3 id="Exemplos" name="Exemplos"> Exemplos </h3> +<pre>element { + border-left: 1px solid #000; +} +</pre> +<h3 id="Notas" name="Notas"> Notas </h3> +<p>Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. +</p> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es"> Especificações </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS1#border-left">CSS 1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/CSS21/box.html#propdef-border-left">CSS 2.1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/css3-background/#the-border-shorthands">CSS 3</a> +</li></ul> +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores"> Compatibilidade com navegadores </h3> +<table class="standard-table"> <tbody><tr> <th>Navegador</th> <th>Versão mais antiga</th> </tr> <tr> <td>Internet Explorer</td> <td>4</td> </tr> <tr> <td>Firefox</td> <td>1</td> </tr> <tr> <td>Netscape</td> <td>4</td> </tr> <tr> <td>Opera</td> <td>3.5</td> </tr> +</tbody></table> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m"> Veja também </h3> +<p>{{ Cssxref("border") }}, +{{ Cssxref("border-left") }} +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-left", "fr": "fr/CSS/border-left", "pl": "pl/CSS/border-left" } ) }} diff --git a/files/pt-pt/web/css/border-right-color/index.html b/files/pt-pt/web/css/border-right-color/index.html new file mode 100644 index 0000000000..9a58ad9d69 --- /dev/null +++ b/files/pt-pt/web/css/border-right-color/index.html @@ -0,0 +1,16 @@ +--- +title: border-right-color +slug: Web/CSS/border-right-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-right-color +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-right-color</code> configura a cor da borda direita de um elemento. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-color">border-bottom-color</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-right-color", "fr": "fr/CSS/border-right-color", "pl": "pl/CSS/border-right-color" } ) }} diff --git a/files/pt-pt/web/css/border-right-style/index.html b/files/pt-pt/web/css/border-right-style/index.html new file mode 100644 index 0000000000..0aa34c58bd --- /dev/null +++ b/files/pt-pt/web/css/border-right-style/index.html @@ -0,0 +1,16 @@ +--- +title: border-right-style +slug: Web/CSS/border-right-style +tags: + - Referencia_CSS +translation_of: Web/CSS/border-right-style +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-right-style</code> configura o estilo da linha da borda direita de uma caixa. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-style">border-bottom-style</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-right-style", "fr": "fr/CSS/border-right-style" } ) }} diff --git a/files/pt-pt/web/css/border-right-width/index.html b/files/pt-pt/web/css/border-right-width/index.html new file mode 100644 index 0000000000..60840f3117 --- /dev/null +++ b/files/pt-pt/web/css/border-right-width/index.html @@ -0,0 +1,16 @@ +--- +title: border-right-width +slug: Web/CSS/border-right-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-right-width +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-right-width</code> configura a largura da borda direita de uma caixa. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-width">border-bottom-width</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-right-width", "fr": "fr/CSS/border-right-width" } ) }} diff --git a/files/pt-pt/web/css/border-right/index.html b/files/pt-pt/web/css/border-right/index.html new file mode 100644 index 0000000000..964e932736 --- /dev/null +++ b/files/pt-pt/web/css/border-right/index.html @@ -0,0 +1,49 @@ +--- +title: border-right +slug: Web/CSS/border-right +tags: + - Referencia_CSS +translation_of: Web/CSS/border-right +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p>A propriedade <code>border-right</code> é uma propriedade <i>shorthand</i> para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-right-width") }}, {{ Cssxref("border-right-style") }} e {{ Cssxref("border-right-color") }}. Valores omitidos são configurados com o valor inicial. +</p> +<ul><li> Valor inicial: veja as propriedades individuais para detalhes +</li><li> Aplica-se a: todos os elementos +</li><li> Herdado: não +</li><li> Porcentagens: N/A +</li><li> Mídia: <a href="pt/CSS/Media/Visual">visual</a> +</li><li> Valor computado: veja as propriedades individuais +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<pre class="eval">border-right: [<i>border-width</i> || <i>border-style</i> || <i>border-color</i> | <i>inherit</i>] ; +</pre> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> border-width </dt><dd> Veja {{ Cssxref("border-width") }}. +</dd><dt> border-style </dt><dd> Veja {{ Cssxref("border-style") }}. +</dd><dt> border-color </dt><dd> Veja {{ Cssxref("border-color") }}. +</dd></dl> +<h3 id="Exemplos" name="Exemplos"> Exemplos </h3> +<pre>element { + border-right: 1px solid #000; +} +</pre> +<h3 id="Notas" name="Notas"> Notas </h3> +<p>Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. +</p> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es"> Especificações </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS1#border-right">CSS 1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/CSS21/box.html#propdef-border-right">CSS 2.1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/css3-background/#the-border-shorthands">CSS 3</a> +</li></ul> +<p><span class="comment">== Compatibilidade com navegadores ==</span> +</p> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m"> Veja também </h3> +<p>{{ Cssxref("border") }}, +{{ Cssxref("border-right") }} +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-right", "fr": "fr/CSS/border-right", "pl": "pl/CSS/border-right" } ) }} diff --git a/files/pt-pt/web/css/border-spacing/index.html b/files/pt-pt/web/css/border-spacing/index.html new file mode 100644 index 0000000000..36747dc64d --- /dev/null +++ b/files/pt-pt/web/css/border-spacing/index.html @@ -0,0 +1,100 @@ +--- +title: border-spacing +slug: Web/CSS/border-spacing +tags: + - Referencia_CSS +translation_of: Web/CSS/border-spacing +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>The border-spacing property specifies the distance between the borders of adjacent cells (only for the <a href="pt/CSS/border-collapse">separated borders model</a>). This is equivalent to the cellspacing attribute in presentational HTML.</p> + +<ul> + <li>Valor inicial: 0</li> + <li>Aplica-se a: tabelas e tabelas em linha</li> + <li>Herdado: sim</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> + <li>Valor computado: dois comprimentos absolutos</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<p>border-spacing: <length> | <length> <length> | inherit</p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<ul> + <li><strong><length></strong> : A length to be used for both horizontal and vertical border spacing.</li> + <li><strong><length> <length></strong> : The first length gives the horizontal spacing (space between cells in adjacent columns) and the second length gives the vertical spacing (space between cells in adjacent rows).</li> +</ul> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/border-spacing.html">View Live Examples</a></p> + +<pre>table#space { + border-collapse: separate; + border-spacing: 10px 5px; +} +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>This property applies only when {{ Cssxref("border-collapse") }} is "separate".</p> + +<p>The border-spacing is also used along the outside edge of the table, where the distance between the table's border and the cells in the first/last column or row is the sum of the relevant (horizontal or vertical) border-spacing and the relevant (top, right, bottom, or left) padding on the table.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS21/tables.html#propdef-border-spacing">CSS 2.1</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Netscape</td> + <td>6</td> + </tr> + <tr> + <td>Internet Explorer</td> + <td>7</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Mozilla</td> + <td>1</td> + </tr> + <tr> + <td>Safari</td> + <td>1</td> + </tr> + <tr> + <td>Opera</td> + <td>6</td> + </tr> + </tbody> +</table> + +<p> </p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("border-collapse") }}, {{ Cssxref("border-spacing") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/border-spacing", "fr": "fr/CSS/border-spacing" } ) }}</p> diff --git a/files/pt-pt/web/css/border-top-color/index.html b/files/pt-pt/web/css/border-top-color/index.html new file mode 100644 index 0000000000..5df05465a6 --- /dev/null +++ b/files/pt-pt/web/css/border-top-color/index.html @@ -0,0 +1,16 @@ +--- +title: border-top-color +slug: Web/CSS/border-top-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-top-color +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-top-color</code> configura a cor da borda superior de um elemento. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-color">border-bottom-color</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-top-color", "fr": "fr/CSS/border-top-color" } ) }} diff --git a/files/pt-pt/web/css/border-top-style/index.html b/files/pt-pt/web/css/border-top-style/index.html new file mode 100644 index 0000000000..b5132d5a35 --- /dev/null +++ b/files/pt-pt/web/css/border-top-style/index.html @@ -0,0 +1,16 @@ +--- +title: border-top-style +slug: Web/CSS/border-top-style +tags: + - Referencia_CSS +translation_of: Web/CSS/border-top-style +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-top-style</code> configura o estilo da linha da borda superior de uma caixa. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-style">border-bottom-style</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-top-style", "fr": "fr/CSS/border-top-style" } ) }} diff --git a/files/pt-pt/web/css/border-top-width/index.html b/files/pt-pt/web/css/border-top-width/index.html new file mode 100644 index 0000000000..45fcd9b374 --- /dev/null +++ b/files/pt-pt/web/css/border-top-width/index.html @@ -0,0 +1,16 @@ +--- +title: border-top-width +slug: Web/CSS/border-top-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-top-width +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p><code>border-top-width</code> configura a largura da borda superiror de uma caixa. +</p><p>Veja a propriedade <code><a href="pt/CSS/border-bottom-width">border-bottom-width</a></code> para mais informações. +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-top-width", "fr": "fr/CSS/border-top-width" } ) }} diff --git a/files/pt-pt/web/css/border-top/index.html b/files/pt-pt/web/css/border-top/index.html new file mode 100644 index 0000000000..d284e0bc7a --- /dev/null +++ b/files/pt-pt/web/css/border-top/index.html @@ -0,0 +1,49 @@ +--- +title: border-top +slug: Web/CSS/border-top +tags: + - Referencia_CSS +translation_of: Web/CSS/border-top +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p>A propriedade <code>border-top</code> é uma propriedade <i>shorthand</i> para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-top-width") }}, {{ Cssxref("border-top-style") }} e {{ Cssxref("border-top-color") }}. Valores omitidos são configurados com o falor inicial. +</p> +<ul><li> Valor inicial: veja as propriedades individuais para detalhes +</li><li> Aplica-se a: todos os elementos +</li><li> Herdado: não +</li><li> Porcentagens: N/A +</li><li> Mídia: <a href="pt/CSS/Media/Visual">visual</a> +</li><li> Valor computado: veja as propriedades individuais +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<pre class="eval">border-top: [<i>border-width</i> || <i>border-style</i> || <i>border-color</i> | <i>inherit</i>] ; +</pre> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> border-width </dt><dd> Veja {{ Cssxref("border-width") }}. +</dd><dt> border-style </dt><dd> Veja {{ Cssxref("border-style") }}. +</dd><dt> border-color </dt><dd> Veja {{ Cssxref("border-color") }}. +</dd></dl> +<h3 id="Exemplos" name="Exemplos"> Exemplos </h3> +<pre>element { + border-top: 1px solid #000; +} +</pre> +<h3 id="Notas" name="Notas"> Notas </h3> +<p>Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. +</p> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es"> Especificações </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS1#border-top">CSS 1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/CSS21/box.html#propdef-border-top">CSS 2.1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/css3-background/#the-border-shorthands">CSS 3</a> +</li></ul> +<p><span class="comment">== Compatibilidade com navegadores ==</span> +</p> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m"> Veja também </h3> +<p>{{ Cssxref("border") }}, +{{ Cssxref("border-top") }} +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border-top", "fr": "fr/CSS/border-top", "pl": "pl/CSS/border-top" } ) }} diff --git a/files/pt-pt/web/css/border-width/index.html b/files/pt-pt/web/css/border-width/index.html new file mode 100644 index 0000000000..c3cd9915f2 --- /dev/null +++ b/files/pt-pt/web/css/border-width/index.html @@ -0,0 +1,112 @@ +--- +title: border-width +slug: Web/CSS/border-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-width +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p><code>border-width</code> configura a largura da borda de uma caixa.</p> + +<ul> + <li>Valor inicial: medium</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li>Valor computado: comprimento absoluto; '0' se o estilo da borda for 'none' ou 'hidden'</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval">border-width: <border-width> {1,4} | inherit +</pre> + +<h3 id="Valores_de_.3Cborder-width.3E" name="Valores_de_.3Cborder-width.3E">Valores de <border-width></h3> + +<dl> + <dt>thin </dt> + <dd>Uma borda fina.</dd> + <dt>medium </dt> + <dd>Uma borda média.</dd> + <dt>thick </dt> + <dd>Uma borda grossa.</dd> + <dt><length> </dt> + <dd>A espessura da borda tem um valor explícito. Valores explícitos de borda não podem ser negativos.</dd> + <dt><percentage> </dt> + <dd>A espessura da borda tem um valor em porcentagem, porcentagens da largura do bloco em que está contida. Larguras explícitas de borda não podem ser negativos.</dd> +</dl> + +<p>Nota: Um valor <code>em</code> também é suportado.</p> + +<h3 id="Propriedades_relacionadas" name="Propriedades_relacionadas">Propriedades relacionadas</h3> + +<ul> + <li>{{ Cssxref("border-bottom-width") }}</li> + <li>{{ Cssxref("border-left-width") }}</li> + <li>{{ Cssxref("border-right-width") }}</li> + <li>{{ Cssxref("border-top-width") }}</li> +</ul> + +<p> </p> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/border.html">View Live Examples</a></p> + +<pre>element { + border-width: thin; + border-style: solid; + border-color: #000; +} +</pre> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#border-width">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/box.html#border-width-properties">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-background/#border-width">CSS 3</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td> </td> + </tr> + <tr> + <td>Firefox</td> + <td> </td> + </tr> + <tr> + <td>Netscape</td> + <td> </td> + </tr> + <tr> + <td>Opera</td> + <td> </td> + </tr> + </tbody> +</table> + +<p> </p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("border") }}, {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, {{ Cssxref("border-color") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/border-width", "fr": "fr/CSS/border-width" } ) }}</p> diff --git a/files/pt-pt/web/css/border/index.html b/files/pt-pt/web/css/border/index.html new file mode 100644 index 0000000000..7110cc6c8d --- /dev/null +++ b/files/pt-pt/web/css/border/index.html @@ -0,0 +1,51 @@ +--- +title: border +slug: Web/CSS/border +tags: + - Referencia_CSS +translation_of: Web/CSS/border +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p>A propriedade <code>border</code> é uma propriedade para ajustar os valores de propriedades individuais da borda em um único elemento na folha do estilo. <code>border</code> pode ser usado com as seguintes propriedades adicionais: {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, {{ Cssxref("border-color") }}. +</p> +<ul><li> Valor inicial: veja propriedades individuais para detalhes; +</li><li> Aplica-se a: todos elementos; +</li><li> Herdado: não; +</li><li> Porcentagem: N/A; +</li><li> Mídia: <a href="pt/CSS/Media/Visual">visual</a>; +</li><li> Valor computado: veja propriedades individuais para detalhes. +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<pre class="eval">border: [<i>border-width</i> || <i>border-style</i> || <i>border-color</i> | <i>inherit</i>] ; +</pre> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> border-width</dt><dd> Ver {{ Cssxref("border-width") }}. +</dd><dt> border-style </dt><dd> Ver {{ Cssxref("border-style") }}. +</dd><dt> border-color </dt><dd> Ver {{ Cssxref("border-color") }}. +</dd></dl> +<h3 id="Exemplos" name="Exemplos"> Exemplos </h3> +<p><a class="external" href="http://developer.mozilla.org/samples/cssref/border.html">Exemplos</a> +</p> +<pre>elemento { + border: 1px solid #000; +} +</pre> +<h3 id="Notas" name="Notas"> Notas </h3> +<p>Quando as propriedades {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, e {{ Cssxref("border-color") }} aceitarem acima de quatro valores, esta propriedade aceitará somente um valor para cada propriedade. +</p> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es"> Especificações </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS1#border">CSS 1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/CSS21/box.html#box-border-area">CSS 2.1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/css3-background/#the-border-shorthands">CSS 3</a> +</li></ul> +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores"> Compatibilidade com navegadores </h3> +<table class="standard-table"> <tbody><tr> <th>Navegador</th> <th>Versões mais antigas</th> </tr> <tr> <td>Internet Explorer</td> <td>4</td> </tr> <tr> <td>Firefox</td> <td>1</td> </tr> <tr> <td>Netscape</td> <td>4</td> </tr> <tr> <td>Opera</td> <td>3.5</td> </tr> +</tbody></table> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m"> Veja também </h3> +<p>{{ Cssxref("border") }} +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/border", "fr": "fr/CSS/border", "pl": "pl/CSS/border" } ) }} diff --git a/files/pt-pt/web/css/bottom/index.html b/files/pt-pt/web/css/bottom/index.html new file mode 100644 index 0000000000..2aa2e1e2f7 --- /dev/null +++ b/files/pt-pt/web/css/bottom/index.html @@ -0,0 +1,81 @@ +--- +title: bottom +slug: Web/CSS/bottom +tags: + - Referencia_CSS +translation_of: Web/CSS/bottom +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p>The <code>bottom</code> property specifies part of the position of positioned elements. +</p><p>For absolutely positioned elements (those with <code>position: absolute</code> or <code>position: fixed</code>), it specifies the distance between the bottom margin edge of the element and the bottom edge of its containing block. +</p><p>For relatively positioned elements (those with <code>position: relative</code>), it specifies the amount the element is moved above its normal position. However, the {{ Cssxref("top") }} property overrides the bottom property, so if <code>top</code> is not <code>auto</code>, the computed value of <code>bottom</code> is the negative of the computed value of <code>top</code>. +</p> +<ul><li> Valor inicial: auto +</li><li> Aplica-se a: elementos posicionados +</li><li> Herdado: não +</li><li> Porcentagens: referente à altura do bloco que o contêm. +</li><li> Mídia: <a href="pt/CSS/Media/visual">visual</a> +</li><li> Valor computado: comprimento absoluto, porcentagem ou automático +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<pre class="eval"> bottom: <length> | <percentage> | auto | inherit +</pre> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> <length> </dt><dd> A length, used as described in the <a href="#Summary">summary</a>. Can be negative, zero, or positive. +</dd><dt> <percentage> </dt><dd> A percentage of the containing block's height, used as described in the <a href="#Summary">summary</a>. +</dd><dt> <code>auto</code> </dt><dd> For absolutely positioned elements, position the element based on the {{ Cssxref("top") }} property and treat <code>height: auto</code> as a height based on the content. For relatively positioned elements, offset the element from its original position based on the {{ Cssxref("top") }} property, or if <code>top</code> is also <code>auto</code>, do not offset it at all. +</dd><dt> <code>inherit</code> </dt><dd> Inherits the computed value from its parent element (which may not be its containing block). This computed value is then handled like it was a <length>, a <percentage>, or <code>auto</code> +</dd></dl> +<h3 id="Exemplos" name="Exemplos"> Exemplos </h3> +<pre>element { + position: absolute; + bottom: 20px; + height: 200px; + border: 1px solid #000; +} +</pre> +<p>The following sample page contrasts <code>position:absolute</code> and <code>position:fixed</code>. When the regular text becomes taller than the viewable portion of the page (the browser window's viewport), blocks positioned with <code>position:absolute</code> will scroll with the page, while blocks positioned with <code>position:fixed</code> will not. Note that IE6 does not support <code>position:fixed</code>. +</p> +<pre><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" + "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> +<meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> +<title>Position at bottom, absolute or fixed</title> +<style type="text/css"> +p {font-size:30px; line-height:3em;} +div.pos {width:49%; text-align:center; border:2px solid #00f;} +div#abs {position:absolute; bottom:0; left:0;} +div#fix {position:fixed; bottom:0; right:0;} +</style> +</head> +<body> + <p>This<br>is<br>some<br>tall,<br>tall, + <br>tall,<br>tall,<br>tall<br>content.</p> + <div id="fix" class="pos"><p>Fixed</p></div> + <div id="abs" class="pos"><p>Absolute</p></div> +</body> +</html></pre> +<h3 id="Notas" name="Notas"> Notas </h3> +<p>For absolutely positioned elements whose containing block is based on a block-level element, this property is an offset from the padding edge of that element. +</p><p>For absolutely positioned elements, the <code>bottom</code> property has no visible effect when all of {{ Cssxref("top") }}, {{ Cssxref("height") }}, and {{ Cssxref("margin-top") }} are <i>not</i> <code>auto</code> (which is the default value for <code>top</code> and <code>height</code>). +</p> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es"> Especificações </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS21/visuren.html#propdef-bottom">CSS 2.1</a> +</li><li> <a class="external" href="http://www.w3.org/Style/CSS/current-work#positioning">CSS 3</a> +</li></ul> +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores"> Compatibilidade com navegadores </h3> +<span class="comment">This is as far back as the documentaion goes.</span><table class="standard-table"> <tbody><tr> <th>Navegador</th> <th>Versão mais antiga</th> </tr> <tr> <td>Internet Explorer</td> <td>5</td> </tr> <tr> <td>Firefox</td> <td>1</td> </tr> <tr> <td>Netscape</td> <td>6</td> </tr> <tr> <td>Opera</td> <td>6</td> </tr> +</tbody></table> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m"> Veja também </h3> +<p>{{ Cssxref("bottom") }}, +{{ Cssxref("position") }}, +{{ Cssxref("top") }}, +{{ Cssxref("left") }}, +{{ Cssxref("right") }} +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/bottom", "fr": "fr/CSS/bottom", "pl": "pl/CSS/bottom" } ) }} diff --git a/files/pt-pt/web/css/clear/index.html b/files/pt-pt/web/css/clear/index.html new file mode 100644 index 0000000000..8fcfd728ca --- /dev/null +++ b/files/pt-pt/web/css/clear/index.html @@ -0,0 +1,93 @@ +--- +title: clear +slug: Web/CSS/clear +tags: + - Referencia_CSS +translation_of: Web/CSS/clear +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade<em>clear</em> especifica se um elemento deve ser posicionado ao lado dos elementos <a href="pt/CSS/float">flutuantes</a> ou se devem ser colocados abaixo deles, "forçando" os elementos com float para cima.</p> + +<ul> + <li>Valor inicial: nenhum;</li> + <li>Aplica-se a: elementos de bloco de nível (incluindo flutuantes);</li> + <li>Herdado: não;</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<p>clear: none | left | right | both | <a href="pt/CSS/inherit">inherit</a></p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<ul> + <li><strong>none</strong> : O elemento<em>não</em> é abaixado para o espaço livre após elementos flutuantes.</li> + <li><strong>left</strong> : O elemento é movido abaixo dos elementos que estão com float a<em>esquerda</em>.</li> + <li><strong>right</strong> : O elemento é movido abaixo dos elementos que estão com float a<em>direita</em>.</li> + <li><strong>both</strong> : O elemento é abaixado para o espaço livre após elementos flutuando à<em>esquerda</em> e à<em>direita</em>.<em>Both</em> signifca<em>Ambos</em>.</li> +</ul> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/clear.html">View Live Examples</a></p> + +<pre>h1 { clear: none } +h2 { clear: right }</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>The clear property applies to both floating and non-floating elements.</p> + +<p>When it applies to non-floating blocks, it moves the <a href="pt/CSS/box_edges">border edge</a> of the element down until it is below the <a href="pt/CSS/box_edges">margin edge</a> of all relevant floats. This movement (when it happens) causes <a href="pt/CSS/margin_collapsing">margin collapsing</a> not to occur.</p> + +<p>When it applies to floating elements, it moves the <a href="pt/CSS/box_edges">margin edge</a> of the element below the <a href="pt/CSS/box_edges">margin edge</a> of all relevant floats. This affects the position of later floats, since later floats cannot be positioned higher than earlier ones.</p> + +<p>The floats that are relevant to be cleared are the earlier floats within the same <a href="pt/CSS/block_formatting_context">block formatting context</a>.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/REC-CSS1#clear">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/visuren.html#propdef-clear">CSS 2.1</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Mozilla</td> + <td>1</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("float") }}, {{ Cssxref("clear") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/clear", "fr": "fr/CSS/clear", "pl": "pl/CSS/clear" } ) }}</p> diff --git a/files/pt-pt/web/css/color/index.html b/files/pt-pt/web/css/color/index.html new file mode 100644 index 0000000000..bd7fe973b2 --- /dev/null +++ b/files/pt-pt/web/css/color/index.html @@ -0,0 +1,47 @@ +--- +title: color +slug: Web/CSS/color +tags: + - Referencia_CSS +translation_of: Web/CSS/color +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p>A propriedade <code>color</code> ajusta a cor de primeiro plano de um texto contido no elemento. +</p> +<ul><li> Valor inicial: depende do agente do usuário; +</li><li> Aplica-se a: todos elementos; +</li><li> Herdado: sim; +</li><li> Porcentagens: N/A; +</li><li> {{ Cssxref("@media") }}: <a href="pt/CSS/Media/Visual">visual</a>; +</li><li> Valor computado: como especificado. +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<pre class="eval">border-bottom-color: <i>color</i> | inherit +</pre> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> color </dt><dd> O <code>color</code> pode ser especificado como valor hexadecimal RGB, valor RGB regular, ou usando as cores pre-definidas. +</dd></dl> +<h3 id="Exemplos" name="Exemplos"> Exemplos </h3> +<p>As maneiras seguintes são todas um exemplo de como deixar um elemento de texto com a cor vermelho: +</p> +<pre>element { color: red } +element { color: #f00 } +element { color: #ff0000 } +element { color: rgb(255,0,0) } +element { color: rgb(100%, 0%, 0%) } +</pre> +<h3 id="Notas" name="Notas"> Notas </h3> +<ul><li> <a class="external" href="http://html-color-codes.com/">Color Chart by VisiBone</a> +</li></ul> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es"> Especificações </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS1#color">CSS 1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/CSS21/colors.html#propdef-color">CSS 2.1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/2003/CR-css3-color-20030514/#color">CSS 3</a> +</li></ul> +<p><span class="comment">== Compatibilidade com navegadores ==</span> +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/color", "fr": "fr/CSS/color", "pl": "pl/CSS/color" } ) }} diff --git a/files/pt-pt/web/css/como_começar/caixas/index.html b/files/pt-pt/web/css/como_começar/caixas/index.html new file mode 100644 index 0000000000..b3906acb4f --- /dev/null +++ b/files/pt-pt/web/css/como_começar/caixas/index.html @@ -0,0 +1,358 @@ +--- +title: Caixas +slug: Web/CSS/Como_começar/Caixas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks +--- +<p>{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}</p> + +<p>Esta página descreve como você pode usar as CSS para controlar o espaço que um elemento ocupa quando é exibido.</p> + +<p>Em seu documento de amostra, você muda o espaçamento e adiciona regras decorativas.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Caixas" name="Informa.C3.A7.C3.A3o:_Caixas">Informação: Caixas</h2> + +<p>Quando seu navegador exibe um elemento, o elemento ocupa um espaço. Existem quatro partes do espaço que ele ocupa.</p> + +<p>No meio, está o espaço que o elemento precisa para exibir seu conteúdo. Em torno disso, está o enchimento. Em torno disso, está a borda. Em torno disso, está a margem.</p> + +<table> + <tbody> + <tr> + <td style="width: 22em;"> + <div style="background-color: #eee; padding: 0px 2em 2em 2em; width: 16em;"> + <p style="text-align: center; margin: 0px;">margin</p> + + <p style="text-align: center; margin: 0px 0px -.75em 0px;">border</p> + + <div style="background-color: #fff; padding: 0px 2em 2em 2em; border: 4px solid #fd9;"> + <p style="text-align: center;">padding</p> + + <div style="background-color: #eee;"> + <p style="text-align: center; padding: 0px; margin: 0px; font-size: 200%; font-weight: bold; color: #999;">element</p> + </div> + </div> + </div> + + <p><em>A paleta cinza mostra partes da disposição.</em></p> + </td> + <td> + <div style="background-color: #fff; padding: 0px 2em 2em 2em; width: 16em;"> + <p style="text-align: center; margin: 0px;"> </p> + + <p style="text-align: center; margin: 0px 0px -.75em 0px;"> </p> + + <div style="background-color: #fff; padding: 0px 2em 2em 2em; border: 4px solid #fd9;"> + <p style="text-align: center;"> </p> + + <div style="background-color: #fff;"> + <p style="text-align: center; padding: 0px; margin: 0px; font-size: 200%; font-weight: bold; color: #999;">element</p> + </div> + </div> + </div> + + <p><em>Isto é o que você vê em seu navegador.</em></p> + </td> + </tr> + </tbody> +</table> + +<p>O enchimento, a borda e a margem podem ter diferentes tamanhos no topo, na direita, em baixo e na esquerda do elemento. Qualquer ou todos estes tamanhos podem ser zero.</p> + +<p>O enchimento é sempre da mesma cor do fundo do elemento. Então quando você configura a cor de fundo, você vê a cor aplicada ao próprio elemento e ao seu enchimento. A margem é sempre transparente.</p> + +<table> + <tbody> + <tr> + <td style="width: 22em;"> + <div style="background-color: #eee; padding: 0px 2em 2em 2em; width: 16em;"> + <p style="text-align: center; margin: 0px;">margin</p> + + <p style="text-align: center; margin: 0px 0px -.75em 0px;">border</p> + + <div style="background-color: #efe; padding: 0px 2em 2em 2em; border: 4px solid #fd9;"> + <p style="text-align: center;">padding</p> + + <div style="background-color: #ded;"> + <p style="text-align: center; padding: 0px; margin: 0px; font-size: 200%; font-weight: bold; color: #898;">element</p> + </div> + </div> + </div> + + <p><em>O elemento tem um fundo verde.</em></p> + </td> + <td> + <div style="background-color: #fff; padding: 0px 2em 2em 2em; width: 16em;"> + <p style="text-align: center; margin: 0px;"> </p> + + <p style="text-align: center; margin: 0px 0px -.75em 0px;"> </p> + + <div style="background-color: #efe; padding: 0px 2em 2em 2em; border: 4px solid #fd9;"> + <p style="text-align: center;"> </p> + + <div style="background-color: #efe;"> + <p style="text-align: center; padding: 0px; margin: 0px; font-size: 200%; font-weight: bold; color: #898;">element</p> + </div> + </div> + </div> + + <p><em>É isto que você vê no seu navegador.</em></p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Bordas" name="Bordas">Bordas</h3> + +<p>Você pode usar bordas para decorar elementos com linhas ou caixas.</p> + +<p>Para especificar a mesma borda em torno de todo o elemento, use a propriedade <code>border</code>. Especifique a largura (usualmente em pixels para exibir na tela), o estilo, e a cor.</p> + +<p>Os estilos são:</p> + +<table style="margin-left: 2em;"> + <tbody> + <tr> + <td style="width: 6em;"> + <div style="border: 2px solid #4a4; margin: .5em; padding: .5em; width: 5em; text-align: center;"><code>solid</code></div> + </td> + <td style="width: 6em;"> + <div style="border: 2px dotted #4a4; margin: .5em; padding: .5em; width: 5em; text-align: center;"><code>dotted</code></div> + </td> + <td style="width: 6em;"> + <div style="border: 2px dashed #4a4; margin: .5em; padding: .5em; width: 5em; text-align: center;"><code>dashed</code></div> + </td> + <td style="width: 6em;"> + <div style="border: 4px double #4a4; margin: .5em; padding: .5em; width: 5em; text-align: center;"><code>double</code></div> + </td> + </tr> + <tr> + <td style="width: 6em;"> + <div style="border: 2px inset #4a4; margin: .5em; padding: .5em; width: 5em; text-align: center;"><code>inset</code></div> + </td> + <td style="width: 6em;"> + <div style="border: 2px outset #4a4; margin: .5em; padding: .5em; width: 5em; text-align: center;"><code>outset</code></div> + </td> + <td style="width: 6em;"> + <div style="border: 4px ridge #4a4; margin: .5em; padding: .5em; width: 5em; text-align: center;"><code>ridge</code></div> + </td> + <td style="width: 6em;"> + <div style="border: 4px groove #4a4; margin: .5em; padding: .5em; width: 5em; text-align: center;"><code>groove</code></div> + </td> + </tr> + </tbody> +</table> + +<p>Você pode também configurar o estilo para <code>none</code> ou <code>hidden</code> para remover a borda explicitamente, ou configurar a cor para <code>transparent</code> para fazer a borda invisível sem mudar a disposição.</p> + +<p>Para especificar bordas em um lado de cada vez, use as propriedades: <code>border-top</code>, <code>border-right</code>, <code>border-bottom</code>, <code>border-left</code>. Você pode usar isto para especificar uma borda em somente um lado, ou diferentes bordas em diferentes lados.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplos</caption> + <tbody> + <tr> + <td>Esta regra configura a cor de fundo e a borda do topo dos elementos do cabeçalho: + <div style="width: 40em;"> + <pre class="eval"> +h3 { + border-top: 4px solid #7c7; /* mid green */ + background-color: #efe; /* pale green */ + color: #050; /* dark green */ + } +</pre> + </div> + + <p>O resultado deve ser como este:</p> + + <table> + <tbody> + <tr> + <td> + <p style="font-size: 133%; font-weight: bold; background-color: #efe; border-top: 4px solid #7c7; color: #050; padding-right: 6em;">Cabeçalho elegante</p> + </td> + </tr> + </tbody> + </table> + + <p><br> + Esta regra faz as imagens fáceis de ver dando-as uma borda com um cinza-médio em toda a volta:</p> + + <div style="width: 30em;"> + <pre class="eval"> +img {border: 2px solid #ccc;} +</pre> + </div> + + <p>O resultado deve ser como este:</p> + + <table> + <tbody> + <tr> + <td>Imagem:</td> + <td style="border: 2px solid #ccc;"><img alt="Image:Blue-rule.png" class="internal" src="/@api/deki/files/2528/=Blue-rule.png"></td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="Margens_e_enchimento" name="Margens_e_enchimento">Margens e enchimento</h3> + +<p>Use margens e enchimento para ajustar a posição dos elementos e para criar espaços ao redor deles.</p> + +<p>Use a propriedade <code>margin</code> ou a propriedade <code>padding</code> para configurar a largura da margem ou do enchimento respectivamente.</p> + +<p>Se você especificar uma largura, isto se aplicará em torno de todo o elemento (topo, direita, baixo e esquerda).</p> + +<p>Se você especificar duas larguras, a primeira se aplicará ao topo e à baixo, e a segunda à direita e à esquerda.</p> + +<p>Você pode especificar todas as quatro larguras na ordem: topo, direita, baixo, esquerda.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Esta regra diferencia parágrafos com a classe <code>remark</code> dando-os uma borda vermelha em toda a sua volta. + <p>O Enchimento em toda a volta separa um pouco a borda do texto.</p> + + <p>Uma margem esquerda identifica o parágrafo relativo ao resto do texto:</p> + + <div style="width: 30em;"> + <pre class="eval"> +p.remark { + border: 2px solid red; + padding: 4px; + margin-left: 24px; + } +</pre> + </div> + + <p>O resultado deve ser como este:</p> + + <table> + <tbody> + <tr> + <td> + <p>Aqui está um parágrafo normal.</p> + + <p style="border: 2px solid red; padding: 4px 6em 4px 4px; margin: 0px 0px 0px 24px;">Aqui está um com observação.</p> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Quando você usa margens e enchimento para ajustar o modo como os elementos são exibidos, suas regras de estilo interagem com o padrão dos navegadores de maneiras que podem ser complexas. + <p>Navegadores diferentes exibem os elementos diferentemente. Os resultados podem ser similares antes de sua folha de estilo mudar coisas. Algumas vezes isto pode fazer sua folha de estilo dar resultados surpreendedores.</p> + + <p>Para ter o resultado que você precisa, você pode ter que mudar a marcação do seu documento. A próxima página deste tutorial tem mais informações sobre isto.</p> + + <p>Para informações detalhas sobre enchimento, margens e bordas, veja <a class="external" href="http://www.w3.org/TR/CSS21/box.html">Box model</a> em CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Adicionando_bordas" name="A.C3.A7.C3.A3o:_Adicionando_bordas">Ação: Adicionando bordas</h2> + +<p>Edite seu arquivo CSS. Adicione esta regra para desenhar uma linha até o fim da página sobre cada cabeçalho:</p> + +<div style="width: 30em;"> +<pre class="eval">h3 {border-top: 1px solid gray;} +</pre> +</div> + +<p>Se você pegou o desafio na página anterior, modifique a regra que você criou, se não, adicione esta nova regra para adicionar um espaço em baixo de cada item da lista:</p> + +<div style="width: 30em;"> +<pre class="eval">li { + list-style: lower-roman; + margin-bottom: 8px; + } +</pre> +</div> + +<p>Atualize seu navegador para ver o resultado:</p> + +<table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray;">(A) Os oceanos</p> + + <ul style=""> + <li style="margin-bottom: 8px;">Ártico</li> + <li style="margin-bottom: 8px;">Atlântico</li> + <li style="margin-bottom: 8px;">Pacífico</li> + <li style="margin-bottom: 8px;">Índico</li> + <li style="margin-bottom: 8px;">Antártico</li> + </ul> + + <p style="font-weight: bold; font-size: 133%; margin-top: 1em; margin-bottom: .3em; padding: .4em 4em .16em 0; border-top: 1px solid gray;">(B) Parágrafos numerados</p> + + <p><strong>1: </strong>Lorem ipsum</p> + + <p><strong>2: </strong>Dolor sit</p> + + <p><strong>3: </strong>Amet consectetuer</p> + + <p><strong>4: </strong>Magna aliquam</p> + + <p><strong>5: </strong>Autem veleum</p> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Adicione uma regra à sua folha de estilo, fazendo um borda larga em toda a volta dos oceanos em uma cor que te lembre o mar — algo como isto: + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray;">(A) Os oceanos</p> + + <div style="border: 12px solid #69b; padding-left: 1em;"> + <ul style=""> + <li style="margin-bottom: 8px;">Ártico</li> + <li style="margin-bottom: 8px;">Atlântico</li> + <li style="margin-bottom: 8px;">Pacífico</li> + <li style="margin-bottom: 8px;">Índico</li> + <li style="margin-bottom: 8px;">Antártico</li> + </ul> + </div> + + <p style="font-weight: bold; font-size: 133%; margin-top: 1em; margin-bottom: .3em; padding: .4em 4em .16em 0; border-top: 1px solid gray;">(B) Parágrafos numerados</p> + + <p><strong>. . .</strong></p> + </td> + </tr> + </tbody> + </table> + + <p>(Não é necessário fazer exatamente com a largura e a cor que usadas aqui.)</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois" name="O_que_vem_depois">O que vem depois</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Caixas" title="Talk:pt/CSS/Como_começar/Caixas">Discussão</a>.</p> + +<p>Especificando margens e enchimento, você modificou a disposição do seu documento. Na próxima página você poderá mudar a disposição do seu documento de outras maneiras: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Disposi%C3%A7%C3%A3o" title="pt/CSS/Como_começar/Disposição">Disposição</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}</p> diff --git a/files/pt-pt/web/css/como_começar/cascata_e_herança/index.html b/files/pt-pt/web/css/como_começar/cascata_e_herança/index.html new file mode 100644 index 0000000000..ee12da94f0 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/cascata_e_herança/index.html @@ -0,0 +1,134 @@ +--- +title: Cascata e herança +slug: Web/CSS/Como_começar/Cascata_e_herança +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Cascade_and_inheritance +--- +<p>{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}</p> + +<p>Esta página esboça como folhas de estilo interagem numa cascata, e como os elementos subordinados herdam o estilo do elementos primários.</p> + +<p>Você alterará à sua folha de estilo de amostra, usando herança para mudar o estilo de muitas partes do seu documento em um passo.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Cascata_e_heran.C3.A7a" name="Informa.C3.A7.C3.A3o:_Cascata_e_heran.C3.A7a">Informação: Cascata e herança</h2> + +<p>O estilo final para um elemento pode ser especificado em muitos lugares diferentes, que pode interagir num meio complexo. Esta interação complexa faz CSS poderoso, mas às vezes isto pode deixar confuso e difícil de depurar.</p> + +<p>Três códigos principais de informação de estilo formam uma cascata. Eles são:</p> + +<ul> + <li>O estilo padrão do navegador para a linguagem de marcação</li> + <li>O estilo especificado por um usuário que está lendo o documento</li> + <li>O estilo ligado ao documento pelo seu autor</li> +</ul> + +<p>O estilo do usuário modifica o estilo padrão do navegador. O estilo do autor do documento então modifica algum outro estilo. Neste tutorial, você é o autor do seu documeto de amostra, e você trabalha somente com folhas de estilo do autor.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Quando você lê este documento no seu navegador Mozilla, parte do estilo que você vê, vem do padrão do seu navegador para HTML. + <p>Parte do estilo deve vir das configurações do seu navegador em Opções, ou de um arquivo <code>userConten.css</code> no seu perfil no navegador.</p> + + <p>Parte do seu estilo vem de folhas de estilo ligadas ao documento pelo server do wiki.</p> + </td> + </tr> + </tbody> +</table> + +<p><br> + Quando você abre seu documento de amostra no seu navegador, os elementos STRONG são mais fortes do que o resto do texto. Isto vem do estilo padrão do seu navegador para o HTML.</p> + +<p>Os elementos STRONG são vermelhos, Isto vem da sua folha de estilo de amostra.</p> + +<p>Os elementos STRONG as vezes também herdam muito do estilo de elemento P, pois eles são subordinados. No mesmo caminho, o elemento P herda muito do estilo do elemento BODY.</p> + +<p>Para estilos em cascata, o autor das folhas de estilo tem prioridade, depois o leitor das folhas de estilo, e por último o padrão do navegador.</p> + +<p>Para estilos em herança, um nó subordinado tem prioridade sobre o estilo que herdou do nó principal.</p> + +<p>Estas não são as únicas propriedades que se aplicam. Uma página posterior neste turorial explicará mais.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>CSS às vezes providencia um meio para o leitor anular o estilo do autor do documento, usando a palavra-chave <code>!important</code>. + <p>Este meio é para o autor do documento, você não pode sempre predizer exatamente o que os leitores verão.</p> + + <p>Se você quer saber todos os detalhes sobre cascata e herança, veja <a class="external" href="http://www.w3.org/TR/CSS21/cascade.html">Assigning property values, Cascading, and Inheritance</a> na CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Usando_heran.C3.A7a" name="A.C3.A7.C3.A3o:_Usando_heran.C3.A7a">Ação: Usando herança</h2> + +<p>Edite seu arquivo de amostra CSS.</p> + +<p>Adicione esta linha copiando e colando isto. Não importa realmente se você adicionar a linha antes ou depois da que já está lá. Entretando, adicionar isto no topo é mais lógico pois no seu documento o elemento P é primário ao elemento STRONG:</p> + +<pre class="brush: css">p {color: blue; text-decoration: underline;} +</pre> + +<p>Agora atualize seu navegador para ver o efeito no seu documento de amostra. O sublinhado afeta todo o texto no parágrafo, incluindo as letras iniciais. Os elementos STRONG herdaram o estilo sublinhado do elemento primário P.</p> + +<p>Mas os elementos STRONG ainda são vermelhos. A cor vermelha é própria do estilo, então isto tem prioridade sobre a cor azul do seu elemento primário P.</p> + +<table> + <tbody> + <tr> + <td> + <table style="border: 2px outset #36b; padding: 1em; margin-right: 2em;"> + <caption>Antes</caption> + <tbody> + <tr> + <td><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> + </table> + </td> + <td> + <table style="border: 2px outset #36b; padding: 1em;"> + <caption>Depois</caption> + <tbody> + <tr> + <td style="color: blue; text-decoration: underline;"><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<p> </p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Mude sua folha de estilo deixando somente as letras vermelhas sublinhadas: + <table style="border: 2px outset #36b; padding: 1em;"> + <tbody> + <tr> + <td style="color: blue;"><strong style="color: red; text-decoration: underline;">C</strong>ascading <strong style="color: red; text-decoration: underline;">S</strong>tyle <strong style="color: red; text-decoration: underline;">S</strong>heets</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<p> </p> + +<h2 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h2> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Cascata_e_heran%C3%A7a" title="Talk:pt/CSS/Como_começar/Cascata_e_herança">Discussão</a>.</p> + +<p>Sua folha de estilo de amostra especifica o estilo para os tags, <code>P</code> e <code>STRONG</code>, mudando o estilo dos elementos correspondentes em todo o seu documento original. A próxima página descreve como espeficar estilos em meios mais seletivos: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Seletores" title="pt/CSS/Como_começar/Seletores">Seletores</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}</p> diff --git a/files/pt-pt/web/css/como_começar/como_o_css_trabalha/index.html b/files/pt-pt/web/css/como_começar/como_o_css_trabalha/index.html new file mode 100644 index 0000000000..d291b92e03 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/como_o_css_trabalha/index.html @@ -0,0 +1,129 @@ +--- +title: Como o CSS trabalha +slug: Web/CSS/Como_começar/Como_o_CSS_trabalha +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +<p>{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}</p> + +<p>Esta página explica como o CSS trabalha no seu navegador. Você analiza seu documento de amostra, reavaliando os detalhes do seu estilo.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Como_o_CSS_trabalha" name="Informa.C3.A7.C3.A3o:_Como_o_CSS_trabalha">Informação: Como o CSS trabalha</h2> + +<p>Quando o Mozilla exibe um documento, é necessário combinar o conteúdo do documento com seu estilo de informação. Então o documento é processado em dois estágios:</p> + +<ul> + <li>No primeiro estágio, o Mozilla converte a linguagem de marcação e o CSS em <em>DOM</em> (Document Object Model - Modelo de Objeto de Documento). O DOM representa o documento na memória do computador. Isto combina o conteúdo do documento com seu estilo.</li> +</ul> + +<ul> + <li>No segundo estágio, o Mozilla exibe o DOM.</li> +</ul> + +<p>Uma linguagem de marcação usa tags para definir a estrutura do documento. Uma tag pode armazenar outras tags entre seu início e fim.</p> + +<p>Um DOM tem a estrutura como a de uma árvore. Cada tag e período do texto na linguagem de marcação torna-se um <em>nó</em> na estrutura da árvore. Os nós do DOM não são armazenadores. Em substituição, eles são primários aos nós subordinados.</p> + +<p>Os nós que correspondem a tags também são conhecidos por <em>elementos</em>.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>No seu documento de amostra, a tag <code><p></code> e seu fim <code></p></code> criam um armazenamento: + <div style="width: 24em;"> + <pre class="eval"> +<p> + <strong>C</strong>ascading + <strong>S</strong>tyle + <strong>S</strong>heets +</p> +</pre> + </div> + + <p>No DOM, o corespondente ao nó P é um primário. Os subordinados são os nós <small>STRONG</small> e os nós do texto. Os nós <small>STRONG</small> são os primários, e os nós do texto são os subordinados.</p> + + <div style="width: 24em; color: #47c; white-space: pre; padding: 0 0 0 2em;"> + <p><span style="color: black;">P</span> ├─<span style="color: black;">STRONG</span> │ │ │ └─"<span style="color: black;">C</span>"<br> + │<br> + ├─"<span style="color: black;">ascading</span>"<br> + │<br> + ├─<span style="color: black;">STRONG</span> │ │ │ └─"<span style="color: black;">S</span>"<br> + │<br> + ├─"<span style="color: black;">tyle</span>"<br> + │<br> + ├─<span style="color: black;">STRONG</span> │ │ │ └─"<span style="color: black;">S</span>"<br> + │<br> + └─"<span style="color: black;">heets</span>"</p> + </div> + </td> + </tr> + </tbody> +</table> + +<p>O entendimento do DOM ajuda-o a projetar, depurar e manter seu CSS, pois o DOM é onde o seu CSS e o conteúdo do documento se unem.</p> + +<h2 id="A.C3.A7.C3.A3o:_Analizando_um_DOM" name="A.C3.A7.C3.A3o:_Analizando_um_DOM">Ação: Analizando um DOM</h2> + +<p>Para analizar um DOM, você precisa de um software especial. Aqui, você usa o <a href="/pt/DOM_Inspector" title="pt/DOM_Inspector">DOM Inspector</a> (DOMi) da Mozilla para analizar um DOM.</p> + +<p>Use seu navegador Mozilla para abrir seu documento simples.</p> + +<p>Na barra de menu do seu navegador, escolha Ferramentas – DOM Inspector, ou talvez Ferramentas – Desenvolvimento Web – DOM Inspector.</p> + +<table style="border: 1px solid #36b; background-color: #f4f4f4; padding: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Se seu navegador Mozilla não tem o DOMi, você pode reinstalá-lo assegurando-se de escolher para instalar o componente de ferramentas da web. Então retorne a este tutorial. + <p>Se você não quiser instalar o DOMi, você pode pular esta seção e ir diretamente para a próxima página. Pulando esta seção você não interfere com o resto deste tutorial.</p> + </td> + </tr> + </tbody> +</table> + +<p><br> + No DOMi, expanda os nós do seu documento clicando em suas flechas.</p> + +<p><strong>Nota:</strong> O espaçamento em seu arquivo HTML faz com que o DOMi mostre alguns nós de texto vazios, que você pode ignorar.</p> + +<p>O resultado deve ser parecido com isto, dependendo do que você tenha expandido:</p> + +<table style="border: 2px outset #36b; padding: 0 0 0 2em;"> + <tbody> + <tr> + <td> + <div style="width: 30em; background-color: transparent; margin: 0px; border: 0px; padding: 0px; color: gray; white-space: pre;"> + <p>│<br> + <span style="font-size: 133%;">▼</span>╴<span style="color: black;">P</span> │ │ │ <span style="font-size: 133%;">▼</span>╴<span style="color: black;">STRONG</span> │ │ └<span style="color: darkblue;">#text</span> │ ├╴<span style="color: darkblue;">#text</span> │ <span style="font-size: 133%;">▶</span>╴<span style="color: black;">STRONG</span> │ │</p> + </div> + </td> + </tr> + </tbody> +</table> + +<p>Quando você seleciona algum nó, você pode usar o painel direito do DOMi para achar mais sobre ele. Por exemplo, quando você seleciona um nó do texto, DOMi mostra para você o texto no painel da direita.</p> + +<p>Quando você seleciona um elemento nó, DOMi o analiza e fornece uma enorme quantidade de informações no seu painel direito. A informação sobre estilo é somente uma parte das informações que ele fornece.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #ffe;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>No DOMi, clique no nó <small>STRONG</small>. + <p>Use o painel direito do DOMi para achar onde fica a cor do nó (vermelho) e onde sua aparência é mais forte que o texto normal (negrito).</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Como_o_CSS_trabalha" title="Talk:pt/CSS/Como_começar/Como_o_CSS_trabalha">Discussão</a>.</p> + +<p>Se você tomou o desafio, você viu o estilo da informação em mais de um lugar interagir para criar o estilo final para um elemento.</p> + +<p>A próxima página explica mais sobre estas interações: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Cascata_e_heran%C3%A7a" title="pt/CSS/Como_começar/Cascata_e_herança">Cascata e herança</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}</p> diff --git a/files/pt-pt/web/css/como_começar/conteúdo/index.html b/files/pt-pt/web/css/como_começar/conteúdo/index.html new file mode 100644 index 0000000000..523c408aad --- /dev/null +++ b/files/pt-pt/web/css/como_começar/conteúdo/index.html @@ -0,0 +1,188 @@ +--- +title: Conteúdo +slug: Web/CSS/Como_começar/Conteúdo +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Howto/Generated_content +--- +<p>{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}</p> + +<p>Esta página descreve algumas maneiras que você pode usar no CSS para adicionar conteúdo quando um documento é exibido.</p> + +<p>Você modifica sua folha de estilo para adicionar conteúdo de texto e uma imagem.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Conte.C3.BAdo" name="Informa.C3.A7.C3.A3o:_Conte.C3.BAdo">Informação: Conteúdo</h2> + +<p>Uma das vantagens importantes das CSS é que ele o ajuda a separar o estilo do documento do seu conteúdo. Mas há situações onde faz sentido especificar certo conteúdo como parte de sua folha de estilo, não como parte do seu documento.</p> + +<p>O conteúdo especificado em uma folha de estilo pode consistir em texto ou imagens. Você especifica o conteúdo em sua folha de estilo quando o conteúdo tem uma ligação próxima à estrutura do documento.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Especificar o conteúdo em uma folha de estilo pode causar complicações. Por exemplo, você pode ter versões diferentes da língua do seu documento que compartilham uma folha de estilo. Se parte da folha de estilo tem que ser traduzida, isto mostra que você precisa por estas partes da folha de estilo em arquivos separados e arrumá-los para então ligá-los com a versão apropriada da língua do seu documento. + <p>Estas complicações não surgem se o conteúdo que você especificou consistir em símbolos ou imagens que se aplicam em todas as línguas e culturas.</p> + + <p><br> + O conteúdo especificado em uma folha de estilo não se tornará parte do DOM.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Conte.C3.BAdo_do_texto" name="Conte.C3.BAdo_do_texto">Conteúdo do texto</h3> + +<p>CSS pode inserir um texto antes ou depois de um elemento. Para especificar isto, faça uma regra e adicione <code>:before</code> ou <code>:after</code> ao seletor. Na declaração, especifique a propriedade <code>content</code> com o conteúdo do texto como seu valor.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Esta regra adiciona o texto <span style="font-weight: bold; color: navy;">Referência:</span> antes de todo elemento com a classe <code>ref</code>: + <div style="width: 30em;"> + <pre class="eval"> +.ref:before { + font-weight: bold; + color: navy; + content: "Referência: "; + } +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>O caractere de configuração de uma folha de estilo é por padrão o UTF-8, mas isto pode ser especificado na ligação, na própria folha de estilo ou por outras maneiras. Para detalhes, veja <a class="external" href="http://www.w3.org/TR/CSS21/syndata.html#q23">4.4 CSS style sheet representation</a> na CSS Specification. + <p>Caracteres individuais podem às vezes ser especificados por um mecanismo de escape que use o contra barra (\) com o caráter de escape. Por exemplo, \265B é um símbolo do xadrez para a rainha preta ♛. Para detalhes, veja <a class="external" href="http://www.w3.org/TR/CSS21/syndata.html#q24">Referring to characters not represented in a character encoding</a> e também <a class="external" href="http://www.w3.org/TR/CSS21/syndata.html#q6">Characters and case</a> em CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Conte.C3.BAdo_da_imagem" name="Conte.C3.BAdo_da_imagem">Conteúdo da imagem</h3> + +<p>Para adicionar uma imagem antes ou depois de um elemento, você pode especificar a URL de um arquivo de imagem no valor da propriedade <code>content</code>.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Esta regra adiciona um espaço e um ícone depois de cada ligação da classe <code>glossary</code>: + <div style="width: 45em;"> + <pre class="eval"> +a.glossary:after {content: " " url("../images/glossary-icon.gif");} +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<p><br> + Para adicionar uma imagem ao fundo de um elemento, especifique a URL de um arquivo de imagem no valor da propriedade <code>background</code>. Isto é uma propriedade que especifica a cor do fundo, a imagem, como a imagem repete, e alguns outros detalhes.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Esta regra configura o fundo de um elemento específico, usando uma URL para especificar um arquivo de imagem. + <p>O seletor especifica o id do elemento. O valor <code>no-repeat</code> faz a imagem aparecer apenas uma vez:</p> + + <div style="width: 50em;"> + <pre class="eval"> +#sidebar-box {background: url("../images/sidebar-ground.png") no-repeat;} +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Para informações sobre propriedades individuais que afetam o fundo, e sobre outras opções que você pode especificar para as imagens de fundo, veja <a class="external" href="http://www.w3.org/TR/CSS21/colors.html#q2">The background</a> na CSS Specification.</td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Adicionando_uma_imagem_de_fundo" name="A.C3.A7.C3.A3o:_Adicionando_uma_imagem_de_fundo">Ação: Adicionando uma imagem de fundo</h2> + +<p>Esta imagem é um quadrado branco com uma linha azul em baixo. Baixe o arquivo desta imagem no mesmo diretório do seu arquivo CSS:</p> + +<table style="border: 2px solid #ccc;"> + <tbody> + <tr> + <td><img alt="Image:Blue-rule.png" class="internal" src="/@api/deki/files/2528/=Blue-rule.png"></td> + </tr> + </tbody> +</table> + +<p>(Por exemplo, clique com o botão direito sobre isto para abrir o menu de contexto, então escolha Salvar Imagem Como... e especifique o diretório que você está usando para este tutorial.)</p> + +<p>Edite o seu arquivo CSS e adicione esta regra ao corpo, configurando a imagem de fundo para a página inteira.</p> + +<div style="width: 40em;"> +<pre class="eval">background: url("Blue-rule.png"); +</pre> +</div> + +<p>O valor <code>repeat</code> é o padrão, então isto não precisa ser especificado. A imagem é repetida horizontal e verticalmente, dando a aparência parecida com a de um papel de escrita com linhas:</p> + +<div style="position: relative; width: 24em; height: 11em; border: 2px outset #36b; overflow: hidden;"> +<p style="margin: 0px;"><img alt="Image:Blue-rule-ground.png" class="internal" src="/@api/deki/files/2527/=Blue-rule-ground.png"></p> + +<div style="position: absolute; top: 0px; left: 0px; border: none; margin: 0px; padding: .5em 0px 0px 1em; font: 16px 'Comic Sams MS', cursive; color: blue; background-color: transparent;"> +<div style="font-style: italic; width: 24em;"> +<p><strong style="color: red; background-color: #ddf; font: 200% serif;">C</strong>ascading <strong style="color: green; background-color: #ddf; font: 200% serif;">S</strong>tyle <strong style="color: green; background-color: #ddf; font: 200% serif;">S</strong>heets</p> +</div> + +<div style="font-style: normal; padding-top: 2px; height: 8em;"> +<p><strong style="color: red; background-color: #ddf; font: 200% serif;">C</strong>ascading <strong style="color: red; background-color: #ddf; font: 200% serif;">S</strong>tyle <strong style="color: red; background-color: #ddf; font: 200% serif;">S</strong>heets</p> +</div> +</div> +</div> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Baixe esta imagem: + <table style="border: 2px solid #ccc;"> + <tbody> + <tr> + <td><img alt="Image:Yellow-pin.png" class="internal" src="/@api/deki/files/2557/=Yellow-pin.png"></td> + </tr> + </tbody> + </table> + + <p>Adicione uma regra à sua folha de estilo então isto mostrará a imagem no começo de cada linha:</p> + + <div style="position: relative; width: 24em; height: 11em; border: 2px outset #36b; overflow: hidden;"> + <p style="margin: 0px;"><img alt="Image:Blue-rule-ground.png" class="internal" src="/@api/deki/files/2527/=Blue-rule-ground.png"></p> + + <div style="position: absolute; top: 0px; left: 0px; border: none; margin: 0px; padding: .5em 0px 0px 1em; font: 16px 'Comic Sams MS', cursive; color: blue; background-color: transparent;"> + <div style="font-style: italic; width: 24em; padding-top: 8px;"><img alt="image:Yellow-pin.png" class="internal" src="/@api/deki/files/2557/=Yellow-pin.png"> <strong style="color: red; background-color: #ddf; font: 200% serif;">C</strong>ascading <strong style="color: green; background-color: #ddf; font: 200% serif;">S</strong>tyle <strong style="color: green; background-color: #ddf; font: 200% serif;">S</strong>heets</div> + + <div style="font-style: normal; padding-top: 12px; height: 8em;"><img alt="image:Yellow-pin.png" class="internal" src="/@api/deki/files/2557/=Yellow-pin.png"> <strong style="color: red; background-color: #ddf; font: 200% serif;">C</strong>ascading <strong style="color: red; background-color: #ddf; font: 200% serif;">S</strong>tyle <strong style="color: red; background-color: #ddf; font: 200% serif;">S</strong>heets</div> + </div> + </div> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Uma maneira comum de adicionar conteúdo à folha de estilo é marcar os itens em listas. Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Conte%C3%BAdo" title="Talk:pt/CSS/Como_começar/Conteúdo">Discussão</a>.</p> + +<p>A próxima página descreve como especificar o estilo para elementos de listas: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Listas" title="pt/CSS/Como_começar/Listas">Listas</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}</p> diff --git a/files/pt-pt/web/css/como_começar/cor/index.html b/files/pt-pt/web/css/como_começar/cor/index.html new file mode 100644 index 0000000000..6ebb2347b9 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/cor/index.html @@ -0,0 +1,340 @@ +--- +title: Cor +slug: Web/CSS/Como_começar/Cor +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Introduction_to_CSS/Values_and_units#Colors +--- +<p>{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}</p> + +<p>Esta página explica mais sobre como você pode especificar cores no CSS.</p> + +<p>Em sua folha de estilo de amostra, você é introduzido nas cores de fundo.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Cor" name="Informa.C3.A7.C3.A3o:_Cor">Informação: Cor</h2> + +<p>Neste tutorial até agora, você usou um limitado número de cores nomeadas. CSS 2 suporta ao todo 17 cores nomeadas. Alguns dos nomes podem não ser o que você espera:</p> + +<table style="border: 0px; margin-left: 2em; text-align: right;"> + <tbody> + <tr> + <td> </td> + <td>black</td> + <td style="width: 2em; height: 2em; background-color: black;"> </td> + <td>gray</td> + <td style="width: 2em; height: 2em; background-color: gray;"> </td> + <td>silver</td> + <td style="width: 2em; height: 2em; background-color: silver;"> </td> + <td>white</td> + <td style="width: 2em; height: 2em; background-color: white; border: 1px dotted gray;"> </td> + </tr> + <tr> + <td>primárias</td> + <td>red</td> + <td style="width: 2em; height: 2em; background-color: red;"> </td> + <td>lime</td> + <td style="width: 2em; height: 2em; background-color: lime;"> </td> + <td>blue</td> + <td style="width: 2em; height: 2em; background-color: blue;"> </td> + </tr> + <tr> + <td>secundárias</td> + <td>yellow</td> + <td style="width: 2em; height: 2em; background-color: yellow;"> </td> + <td>aqua</td> + <td style="width: 2em; height: 2em; background-color: aqua;"> </td> + <td>fuchsia</td> + <td style="width: 2em; height: 2em; background-color: fuchsia;"> </td> + </tr> + <tr> + <td> </td> + <td>maroon</td> + <td style="width: 2em; height: 2em; background-color: maroon;"> </td> + <td>orange</td> + <td style="width: 2em; height: 2em; background-color: orange;"> </td> + <td>olive</td> + <td style="width: 2em; height: 2em; background-color: olive;"> </td> + <td>purple</td> + <td style="width: 2em; height: 2em; background-color: purple;"> </td> + <td>green</td> + <td style="width: 2em; height: 2em; background-color: green;"> </td> + <td>navy</td> + <td style="width: 2em; height: 2em; background-color: navy;"> </td> + <td>teal</td> + <td style="width: 2em; height: 2em; background-color: teal;"> </td> + </tr> + </tbody> +</table> + +<p> </p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Seu navegador pode suportar muitas cores nomeadas, como: + <table style="border: 0px; margin: .5em 0px .5em 2em; text-align: right; background-color: inherit;"> + <tbody> + <tr> + <td>dodgerblue</td> + <td style="width: 2em; height: 2em; background-color: dodgerblue;"> </td> + <td>peachpuff</td> + <td style="width: 2em; height: 2em; background-color: peachpuff;"> </td> + <td>tan</td> + <td style="width: 2em; height: 2em; background-color: tan;"> </td> + <td>firebrick</td> + <td style="width: 2em; height: 2em; background-color: firebrick;"> </td> + <td>aquamarine</td> + <td style="width: 2em; height: 2em; background-color: aquamarine;"> </td> + </tr> + </tbody> + </table> + + <p>Para detalhes sobre esta lista extendida, veja: <a class="external" href="http://www.w3.org/TR/2003/CR-css3-color-20030514/#svg-color">SVG color keywords</a> no CSS 3 Color Module. Cuidado ao usar cores nomeadas, pois seu navegador pode não suportar.</p> + </td> + </tr> + </tbody> +</table> + +<p><br> + Para uma paleta maior, específica de cores de componentes vermelho, verde ou azul você precisa usar um sinal numérico (#) e três digitos <em>hexadecimais</em> na faixa de 0 – 9 e a – f. As letras a – f representam os valores 10 – 15:</p> + +<table style="border: 0px; margin-left: 2em;"> + <tbody> + <tr> + <td>black</td> + <td style="width: 2em; height: 2em; background-color: #000;"> </td> + <td><code>#000</code></td> + </tr> + <tr> + <td>pure red</td> + <td style="width: 2em; height: 2em; background-color: #f00;"> </td> + <td><code>#f00</code></td> + </tr> + <tr> + <td>pure green</td> + <td style="width: 2em; height: 2em; background-color: #0f0;"> </td> + <td><code>#0f0</code></td> + </tr> + <tr> + <td>pure blue</td> + <td style="width: 2em; height: 2em; background-color: #00f;"> </td> + <td><code>#00f</code></td> + </tr> + <tr> + <td>white</td> + <td style="width: 2em; height: 2em; background-color: #fff; border: 1px dotted gray;"> </td> + <td><code>#fff</code></td> + </tr> + </tbody> +</table> + +<p><br> + Para a paleta total, especifique dois digitos hexadecimais por cada componente:</p> + +<table style="border: 0px; margin-left: 2em;"> + <tbody> + <tr> + <td>black</td> + <td style="width: 2em; height: 2em; background-color: #000;"> </td> + <td><code>#000000</code></td> + </tr> + <tr> + <td>pure red</td> + <td style="width: 2em; height: 2em; background-color: #f00;"> </td> + <td><code>#ff0000</code></td> + </tr> + <tr> + <td>pure green</td> + <td style="width: 2em; height: 2em; background-color: #0f0;"> </td> + <td><code>#00ff00</code></td> + </tr> + <tr> + <td>pure blue</td> + <td style="width: 2em; height: 2em; background-color: #00f;"> </td> + <td><code>#0000ff</code></td> + </tr> + <tr> + <td>white</td> + <td style="width: 2em; height: 2em; background-color: #fff; border: 1px dotted gray;"> </td> + <td><code>#ffffff</code></td> + </tr> + </tbody> +</table> + +<p>Você pode usualmente pegar estes seis digitos em código hexadeximal de seu programa de imagens ou alguma outra ferramenta.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4;"> + <caption>Exemplos</caption> + <tbody> + <tr> + <td>Com uma pequena prática, você pode ajustar as cores de três digitos manualmente para a maioria dos propósitos: + <table style="border: 0px; margin-left: 2em; background-color: #fffff4;"> + <tbody> + <tr> + <td>Começe com vermelho puro:</td> + <td style="width: 2em; height: 2em; background-color: #f00;"> </td> + <td><code>#f00</code></td> + </tr> + <tr> + <td>Para tornar isto mais pálido, adicione um pouco de verde e azul:</td> + <td style="width: 2em; height: 2em; background-color: #f77;"> </td> + <td><code>#f77</code></td> + </tr> + <tr> + <td>Para tornar isto mais alaranjado, adicione um pouquinho mais de verde:</td> + <td style="width: 2em; height: 2em; background-color: #fa7;"> </td> + <td><code>#fa7</code></td> + </tr> + <tr> + <td>Para tornar isto mais escuro, reduza todos os componentes:</td> + <td style="width: 2em; height: 2em; background-color: #c74;"> </td> + <td><code>#c74</code></td> + </tr> + <tr> + <td>Para reduzir a saturação, faça os componentes mais parecidos:</td> + <td style="width: 2em; height: 2em; background-color: #c98;"> </td> + <td><code>#c98</code></td> + </tr> + <tr> + <td>Se você quiser deixar todos os componentes iguais, você obterá cinza:</td> + <td style="width: 2em; height: 2em; background-color: #ccc;"> </td> + <td><code>#ccc</code></td> + </tr> + </tbody> + </table> + </td> + </tr> + <tr> + <td>Para uma sombra pastel como azul pálido: + <table style="border: 0px; margin-left: 2em; background-color: #fffff4;"> + <tbody> + <tr> + <td>Começe com branco puro:</td> + <td style="width: 2em; height: 2em; background-color: #fff; border: 1px dotted gray;"> </td> + <td><code>#fff</code></td> + </tr> + <tr> + <td>Reduza um pouco os outros componentes:</td> + <td style="width: 2em; height: 2em; background-color: #eef; border: 1px dotted gray;"> </td> + <td><code>#eef</code></td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Você pode também especificar uma cor usando valores decimais RGB na faixa de 0 – 255, ou porcentagens. + <p>Por exemplo, este marrom (vermelho escuro):</p> + + <div style="width: 24em;"> + <pre> +rgb(128, 0, 0) +</pre> + </div> + + <p><br> + Para maiores detalhes sobre como especificar cores, veja: <a class="external" href="http://www.w3.org/TR/CSS21/syndata.html#color-units">Colors</a> na CSS Specification.</p> + + <p>Para informação sobre sistema de cores combinadas como o Menu and ThreeDFace, veja: <a class="external" href="http://www.w3.org/TR/CSS21/ui.html#system-colors">CSS2 System Colors</a> na CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Propriedades_de_cor" name="Propriedades_de_cor">Propriedades de cor</h3> + +<p>Você já usou a propriedade <code>color</code> para textos.</p> + +<p>Você também já usou a propriedade <code>background-color</code> para mudar elementos de fundo.</p> + +<p>Fundos podem ser configurados para <code>transparent</code> para remover qualquer cor explicitamente, reavaliando os elementos principais do fundo.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>As caixas de <strong>Exemplo</strong> neste tutorial usam este fundo amarelo pálido: + <div style="width: 24em;"> + <pre> +background-color: #fffff4; +</pre> + </div> + + <p>As caixas de <strong>Mais detalhes</strong> usam esta paleta cinza:</p> + + <div style="width: 24em;"> + <pre> +background-color: #f4f4f4; +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Usando_c.C3.B3digos_de_cor" name="A.C3.A7.C3.A3o:_Usando_c.C3.B3digos_de_cor">Ação: Usando códigos de cor</h2> + +<p>Edite seu arquivo CSS. Faça a mudança mostrada aqui em negrito, para dar às letras iniciais um fundo azul pálido. (O layout e os comentários no seu arquivo irão provavelmente diferir do arquivo mostrado aqui. Mantenha o layout e os comentários como você preferir.)</p> + +<div style="width: 32em;"> +<pre class="eval">/*** CSS Tutorial: Página de Cor ***/ + +/* Fonte da Página */ +body {font: 16px "Comic Sans MS", cursive;} + +/* Parágrafos */ +p {color: blue;} +#first {font-style: italic;} + +/* Letras Iniciais */ +strong { + color: red; + <strong>background-color: #ddf;</strong> + font: 200% serif; + } + +.carrot {color: red;} +.spinach {color: green;} +</pre> +</div> + +<p>Atualize seu navegador para ver o resultado:</p> + +<table> + <tbody> + <tr> + <td style="font: italic 16px 'Comic Sans MS', cursive; color: blue;"><strong style="color: red; background-color: #ddf; font: 200% serif;">C</strong>ascading <strong style="color: green; background-color: #ddf; font: 200% serif;">S</strong>tyle <strong style="color: green; background-color: #ddf; font: 200% serif;">S</strong>heets</td> + </tr> + <tr> + <td style="font: 16px 'Comic Sans MS', cursive; color: blue;"><strong style="color: red; background-color: #ddf; font: 200% serif;">C</strong>ascading <strong style="color: red; background-color: #ddf; font: 200% serif;">S</strong>tyle <strong style="color: red; background-color: #ddf; font: 200% serif;">S</strong>heets</td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #ffe; width: 100%;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>No seu arquivo CSS, mude todos os nomes das cores para o código de cor com três digitos sem afetar o resultado. + <p>(Isto não pode ser feito exatamente, mas você pode deixar parecido. Para fazer isso exatamente você precisa do código com seis dígitos, e você precisa olhar a Especificação CSS ou usar uma ferramenta gráfica para converter as cores.)</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Cor" title="Talk:pt/CSS/Como_começar/Cor">Discussão</a>.</p> + +<p>Seu documento de amostra e sua folha de estilo de amostra separam rigorosamente o conteúdo do estilo.</p> + +<p>A próxima página explica como você pode fazer exceções para separar rigorosamente: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Conte%C3%BAdo" title="pt/CSS/Como_começar/Conteúdo">Conteúdo</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}</p> diff --git a/files/pt-pt/web/css/como_começar/css_legível/index.html b/files/pt-pt/web/css/como_começar/css_legível/index.html new file mode 100644 index 0000000000..7edd9f859e --- /dev/null +++ b/files/pt-pt/web/css/como_começar/css_legível/index.html @@ -0,0 +1,187 @@ +--- +title: CSS legível +slug: Web/CSS/Como_começar/CSS_legível +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Introduction_to_CSS/Syntax#Beyond_syntax_make_CSS_readable +--- +<p>{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}</p> + +<p>Esta página discute o estilo e a gramática da linguagem CSS.</p> + +<p>Você muda a maneira em que seu arquivo de amostra CSS é exibido, para torná-lo mais legível.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_CSS_leg.C3.ADvel" name="Informa.C3.A7.C3.A3o:_CSS_leg.C3.ADvel">Informação: CSS legível</h2> + +<p>Você pode adicionar espaço em branco e comentários na sua folha de estilo para fazê-la mais legível. Você pode também juntar seletores de grupo, quando as mesmas regras de estilo se aplicam aos elementos selecionados em meios diferentes.</p> + +<h3 id="Espa.C3.A7o_em_branco" name="Espa.C3.A7o_em_branco">Espaço em branco</h3> + +<p>Espaços em branco significam espaços reais, tabs e quebras de linha. Você pode adicionar espaços em branco para tornar suas folhas de estilo mais legíveis.</p> + +<p>Seu arquivo de amostra de CSS atualmente tem uma regra por linha, e quase o mínimo de espaço em branco. Em uma uma folha de estilo complexa esta disposição pode dificultar a leitura, dificultando também a manutenção da sua folha de estilo.</p> + +<p>A disposição que você escolhe é usualmente um preferência pessoal, mas se suas folhas de estilo são parte de projetos compartilhados, estes projetos podem ter suas próprias convenções.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplos</caption> + <tbody> + <tr> + <td>Algumas pessoas gostam de uma diposição compacta que temos usado, somente dividindo a linha quando ela se torna muito longa: + <pre> +.carrot {color: orange; text-decoration: underline; font-style: italic;} +</pre> + + <p>Algumas pessoas preferem uma propriedade-valor por linha:</p> + + <div style="width: 45em;"> + <pre class="eval"> +.carrot +{ +color: orange; +text-decoration: underline; +font-style: italic; +} +</pre> + </div> + + <p>Algumas pessoas usam tabs – dois espaços, quatro espaços, ou um tab são comuns:</p> + + <div style="width: 45em;"> + <pre class="eval"> +.carrot { + color: orange; + text-decoration: underline; + font-style: italic; +} +</pre> + </div> + + <p>Algumas pessoas gostam de enfileirar a linha verticalmente (mas é difícil de manter uma disposição assim):</p> + + <div style="width: 45em;"> + <pre class="eval"> +.carrot + { + color : orange; + text-decoration : underline; + font-style : italic; + } +</pre> + </div> + + <p>Algumas pessoas usam tabs para a disposição. Algumas pessoas usam somente espaços.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Coment.C3.A1rios" name="Coment.C3.A1rios">Comentários</h3> + +<p>Comentários em CSS começam com <code>/*</code> e terminam com <code>*/</code>.</p> + +<p>Você pode usar comentários para fazer comentários reais na sua folha de estilo, e também para <em>descomentar</em> partes que estiverem temporariamente para propósito de testes.</p> + +<p>Para comentar parte da folha de estilo, coloque a parte em um comentário então o navegador ignorará isso. Tome cuidado onde você começa e termina o seu comentário. O resto da sua folha de estilo ainda deve ter a sintaxe correta.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td> + <div style="width: 45em;"> + <pre class="eval"> +/* Estilo para a letra C inicial no primeiro parágrafo */ +.carrot { + color: orange; + text-decoration: underline; + font-style: italic; + } +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<h3 id="Seletores_agrupados" name="Seletores_agrupados">Seletores agrupados</h3> + +<p>Quando muitos elementos tiverem o mesmo estilo, você pode especificar um grupo de seletores, separando-os com comentários. A declaração se aplica a todos os elementos selecionados.</p> + +<p>Em outra parte da sua folha de estilo você pode especificar os mesmos seletores, de novo individualmente, para aplicar estilo individual às suas regras.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Esta regra faz os elementos <small>H1</small>, <small>H2</small> and <small>H3</small> da mesma cor. + <p>Isto é conveniente para especificar a cor em somente um lugar, no caso em que precisa ser alterado.</p> + + <div style="width: 30em;"> + <pre class="eval"> +/* cores para os cabeçalhos */ +h1, h2, h3 {color: navy;} +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Adicionando_coment.C3.A1rios_e_melhorando_o_arranjo" name="A.C3.A7.C3.A3o:_Adicionando_coment.C3.A1rios_e_melhorando_o_arranjo">Ação: Adicionando comentários e melhorando o arranjo</h2> + +<p>Edite seu arquivo CSS, e assegure-se que ele tem todas as regras nele (em qualquer ordem):</p> + +<div style="width: 30em;"> +<pre class="eval">strong {color: red;} +.carrot {color: orange;} +.spinach {color: green;} +#first {font-style: italic;} +p {color: blue;} +</pre> +</div> + +<p>Faça isto mais legível rearranjando isto em um meio que possa ser achado lógicamente, adicionando espaços em branco e comentários da maneira que você achar melhor.</p> + +<p>Salve o arquivo e atualize a tela do seu navegador, assegure-se que as mudanças que você fez não afetaram o modo como a folha de estilo trabalha:</p> + +<table style="border: 2px outset #36b; padding: 1em;"> + <tbody> + <tr> + <td style="font-style: italic; color: blue;"><strong style="color: orange;">C</strong>ascading <strong style="color: green;">S</strong>tyle <strong style="color: green;">S</strong>heets</td> + </tr> + <tr> + <td style="color: blue;"><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #ffe;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Comente parte de sua folha de estilo, sem mudar qualquer coisa, para fazer a primeira letra de seu documento vermelha: + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td style="font-style: italic; color: blue;"><strong style="color: red;">C</strong>ascading <strong style="color: green;">S</strong>tyle <strong style="color: green;">S</strong>heets</td> + </tr> + <tr> + <td style="color: blue;"><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> + </table> + + <p>(Existe mais de uma maneira de fazer isto.)</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/CSS_leg%C3%ADvel" title="Talk:pt/CSS/Como_começar/CSS_legível">Discussão</a>.</p> + +<p>Seu documento de amostra usou o texto em itálico e o texto com sublinhado. A próxima página descreve mais caminhos para especificar a aparência do texto no seu documento: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Estilos_de_texto" title="pt/CSS/Como_começar/Estilos_de_texto">Estilos de texto</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}</p> diff --git a/files/pt-pt/web/css/como_começar/dados_xml/index.html b/files/pt-pt/web/css/como_começar/dados_xml/index.html new file mode 100644 index 0000000000..d0245353fa --- /dev/null +++ b/files/pt-pt/web/css/como_começar/dados_xml/index.html @@ -0,0 +1,239 @@ +--- +title: Dados XML +slug: Web/CSS/Como_começar/Dados_XML +tags: + - 'CSS:Como_começar' +translation_of: Archive/Beginner_tutorials/XML_data +--- +<p>{{ Previous("Web/CSS/Como_começar/Gráficos_SVG") }}</p> + +<p> </p> + +<p>Esta página contém um exemplo de como você pode usar o CSS com dados XML.</p> + +<p>Você cria um documento XML de amostra e uma folha de estilo que você pode usar para exibí-lo em seu navegador.</p> + +<h3 id="Informa.C3.A7.C3.A3o:_Dados_XML" name="Informa.C3.A7.C3.A3o:_Dados_XML">Informação: Dados XML</h3> + +<p><em><a href="/pt/XML" title="pt/XML">XML</a></em> (eXtensible Markup Language) é uma linguagem de propósito geral para qualquer tipo de dados estruturados.</p> + +<p>Por padrão, seu navegador Mozilla mostra o XML em um formato muito similar aos dados originais no arquivo XML. Você vê as tags reais que definem a estrutura dos dados.</p> + +<p>Ligando a folha de estilo CSS com o documento XML, você pode definir outras maneiras para mostrá-lo. Para fazer isto, sua folha de estilo usa regras que mapeiam os tags no documento XML para mostrar tipos usados pelo HTML.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Dados em um documento XML usando tags <code><INFO></code>. Você quer que os elementos <small>INFO</small> do documento sejam mostrados como parágrafos no HTML. + <p>Na folha de estilo do documento, você especifica como os elementos <small>INFO</small> serão exibidos:</p> + + <div style="width: 30em;"> + <pre class="eval"> +INFO { + display: block; + margin: 1em 0; + } +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<p>Os valores mais comuns para a propriedade <code>display</code> são:</p> + +<table style="margin-left: 2em;"> + <tbody> + <tr> + <td style="padding-right: 2em;"><code>block</code></td> + <td>Monstrado como <small>DIV</small> do HTML (para cabeçalhos, parágrafos)</td> + </tr> + <tr> + <td><code>inline</code></td> + <td>Mostrado como <small>SPAN</small> do HTML (para ênfases no texto)</td> + </tr> + </tbody> +</table> + +<p>Adicione seu próprio estilo de regras para especificar a fonte, espaçamento e outros detalhes da mesma maneira que no HTML.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Outros valores de <code>display</code> mostram o elemento como o item de uma lista, ou como o componente de uma tabela. + <p>Para a lista completa de tipos de exibição, veja <a class="external" href="http://www.w3.org/TR/CSS21/visuren.html#propdef-display">The display property</a> em CSS Specification.</p> + + <p>Usando CSS sozinho, a estrutura de exibição precisa ser a mesma da estrutura do documento. Outras tecnologias pode modificar a estrutura da exibição — por exemplo, o XBL pode adicionar conteúdo, e o JavaScript pode modificar o DOM.</p> + + <p>Para mais informações sobre o XML no Mozilla, veja a página <a href="/pt/XML" title="pt/XML">XML</a> neste wiki.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="A.C3.A7.C3.A3o:_Uma_demonstra.C3.A7.C3.A3o_XML" name="A.C3.A7.C3.A3o:_Uma_demonstra.C3.A7.C3.A3o_XML">Ação: Uma demonstração XML</h3> + +<p>Crie um novo arquivo XML, <code>doc9.xml</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre><?xml version="1.0"?> +<!-- XML demonstration --> + +<?xml-stylesheet type="text/css" href="style9.css"?> + +<!DOCTYPE planet> +<planet> + +<ocean> +<name>Arctic</name> +<area>13,000</area> +<depth>1,200</depth> +</ocean> + +<ocean> +<name>Atlantic</name> +<area>87,000</area> +<depth>3,900</depth> +</ocean> + +<ocean> +<name>Pacific</name> +<area>180,000</area> +<depth>4,000</depth> +</ocean> + +<ocean> +<name>Indian</name> +<area>75,000</area> +<depth>3,900</depth> +</ocean> + +<ocean> +<name>Southern</name> +<area>20,000</area> +<depth>4,500</depth> +</ocean> + +</planet> +</pre> +</div> + +<p>Crie um novo arquivo CSS, <code>style9.css</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre>/*** XML demonstration ***/ + +planet:before { + display: block; + width: 8em; + font-weight: bold; + font-size: 200%; + content: "Oceans"; + margin: -.75em 0px .25em -.25em; + padding: .1em .25em; + background-color: #cdf; + } + +planet { + display: block; + margin: 2em 1em; + border: 4px solid #cdf; + padding: 0px 1em; + background-color: white; + } + +ocean { + display: block; + margin-bottom: 1em; + } + +name { + display: block; + font-weight: bold; + font-size: 150%; + } + +area { + display: block; + } + +area:before { + content: "Area: "; + } + +area:after { + content: " million km\B2"; + } + +depth { + display: block; + } + +depth:before { + content: "Mean depth: "; + } + +depth:after { + content: " m"; + } +</pre> +</div> + +<p>Abra o documento em seu navegador:</p> + +<table style="border: 2px outset #36b; padding: 1em;"> + <tbody> + <tr> + <td> + <div style="border: 2px solid #cdf; border-bottom: none; padding: .5em 8em 1em .5em;"> + <p style="font-size: 150%; font-weight: bold; margin: -1em 0px 0px 0px; padding: .1em .25em; background-color: #cdf; width: 8em;">Oceans</p> + + <p style="font-size: 75%; margin: .25em 0px 0px 0px; line-height: 110%;"><strong>Arctic</strong><br> + Area: 13,000 million km²<br> + Mean depth: 1,200 m</p> + + <p style="font-size: 75%; margin: .5em 0px 0px 0px; line-height: 110%;"><strong>Atlantic</strong><br> + Area: 87,000 million km²<br> + Mean depth: 3,900 m</p> + + <p style="font-size: 75%; margin: .5em 0px 0px 0px; line-height: 110%;"><strong>. . .</strong></p> + </div> + </td> + </tr> + </tbody> +</table> + +<p><br> + Notas sobre esta demonstração:</p> + +<ul> + <li>O 2 sobre-escrito (em "million km²") um caractér Unicode, é codificado com <code>\B2</code> no arquivo CSS.</li> + <li>O cabeçalho, "Oceans", tem uma margem negativa no topo, movendo-o para cima quando exibido no topo da borda.</li> +</ul> + +<p> </p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Mude a folha de estilo de modo que ela mostre o documento como uma tabela. + <p>(Veja o capítulo <a class="external" href="http://www.w3.org/TR/CSS21/tables.html">Tables</a> em CSS Specification para exemplos que você pode adaptar.)</p> + </td> + </tr> + </tbody> +</table> + +<h4 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h4> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Dados_XML" title="Talk:pt/CSS/Como_começar/Dados_XML">Discussão</a>.</p> + +<p>Esta é a última página do tutorial. Para mais informações sobre CSS no Mozilla, veja a página principal <a href="/pt/CSS" title="pt/CSS">CSS</a> neste wiki.</p> + +<p>{{ Previous("Web/CSS/Como_começar/Gráficos_SVG") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> diff --git a/files/pt-pt/web/css/como_começar/disposição/index.html b/files/pt-pt/web/css/como_começar/disposição/index.html new file mode 100644 index 0000000000..e4efedf77a --- /dev/null +++ b/files/pt-pt/web/css/como_começar/disposição/index.html @@ -0,0 +1,452 @@ +--- +title: Disposição +slug: Web/CSS/Como_começar/Disposição +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/CSS_layout +--- +<p>{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}</p> + +<p>Esta página descreve algumas maneiras para ajustar a disposição do seu documento.</p> + +<p>Você muda a disposição do seu documento de amostra...</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Disposi.C3.A7.C3.A3o" name="Informa.C3.A7.C3.A3o:_Disposi.C3.A7.C3.A3o">Informação: Disposição</h2> + +<p>Você pode usar as CSS para especificar vários efeitos visuais que mudam a disposição do seu documento. Algumas técnicas para especificação da disposição são avançadas,e além do alcance deste tutorial básico.</p> + +<p>Quando você desenha uma disposição que aparece similar em vários navegadores, sua folha de estilo interage com a folha de estilo padrão do navegador e o motor de disposição em alguns caminhos pode se tornar complexo. Isto é também uma matéria avançada, além do alcance deste tutorial básico.</p> + +<p>Esta página descreve algumas técnicas simples que você pode tentar.</p> + +<h4 id="Estrutura_do_documento" name="Estrutura_do_documento">Estrutura do documento</h4> + +<p>Se você quer controlar a disposição do seu documento, então você pode ter que mudar sua estrutura.</p> + +<p>A linguagem de marcação do seu documento pode ter tags com propósito geral para criar a estrutura. Por exemplo, no HTML você pode usar a tag <code>DIV</code> para criar a estrutura.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>No seu documento de amostra, os parágrafos numerados sob o segundo título não tem um "recipiente" próprio. + <p>Sua folha de estilo não pode desenhar uma borda ao redor destes parágrafos, porque não há elemento especificado no seletor.</p> + + <p>Para fixar este problema estrutural, você pode adicionar uma tag <code>DIV</code> em torno dos parágrafos. Esta tag é única, então isto pode ser identificado por um atributo <code>id</code>:</p> + + <div style="width: 40em; color: gray;"> + <pre class="eval"> +<H3 class="numbered">Parágrafos numerados</H3> +<strong style="color: black;"><DIV id="numbered"></strong> +<P class="numbered">Lorem ipsum</P> +<P class="numbered">Dolor sit</P> +<P class="numbered">Amet consectetuer</P> +<P class="numbered">Magna aliquam</P> +<P class="numbered">Autem veleum</P> +<strong style="color: black;"></DIV></strong> +</pre> + </div> + + <p>Agora sua folha de estilo pode use uma regra para especificar bordas em tordo de ambas as listas:</p> + + <div style="width: 30em;"> + <pre class="eval"> +ul, #numbered { + border: 1em solid #69b; + padding-right:1em; + } +</pre> + </div> + + <p>O resultado deve ser como este:</p> + + <table style="border: 2px outset #36b; padding: 1em; width: 30em; background-color: white;"> + <tbody> + <tr> + <td> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray;">(A) Os oceanos</p> + + <div style="border: 12px solid #69b; margin-bottom: 16px; padding: 1em;"> + <ul style=""> + <li>Ártico</li> + <li>Atlântico</li> + <li>Pacífico</li> + <li>Índico</li> + <li>Antártico</li> + </ul> + </div> + + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray;">(B) Parágrafos numerados</p> + + <div style="border: 12px solid #69b; margin-bottom: 8px; padding: 0px 12em 0px .5em;"> + <p><strong>1: </strong>Lorem ipsum</p> + + <p><strong>2: </strong>Dolor sit</p> + + <p><strong>3: </strong>Amet consectetuer</p> + + <p><strong>4: </strong>Magna aliquam</p> + + <p><strong>5: </strong>Autem veleum</p> + </div> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="Tamanhos_das_unidades" name="Tamanhos_das_unidades">Tamanhos das unidades</h3> + +<p>Anteriormente neste tutorial, você especificou tamanhos em pixels (<code>px</code>). Estes são apropriados para alguns propósitos em um dispositivo de exposição como uma tela de computador. Mas quando o usuário muda o tamanho da fonte, sua disposição pode ficar errada.</p> + +<p>Para muitos propósitos é melhor especificar tamanhos com porcentagem ou em ems (<code>em</code>). Um em é nominalmente o tamanho da fonte corrente (a largura de uma letra m). Quando o usuário muda o tamanho da fonte, sua disposição ajusta-se automaticamente.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>A borda da esquerda deste texto tem o tamanho especificado em pixels. + <p>A borda da direita tem o tamanho especificado em ems. No seu navegador, mude o tamanho da fonte para ver como a borda da direita se ajusta mas a borda da esquerda não:</p> + + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td> + <div style="">Redimensione-me por favor</div> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Para outros dispositivos, outras unidades de comprimento são apropriadas. + <p>Há mais informação sobre isto em uma página anterior deste tutorial.</p> + + <p>Para detalhes completos sobre os valores e unidades que você pode usar, veja <a class="external" href="http://www.w3.org/TR/CSS21/syndata.html#values">Values</a> em CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Disposi.C3.A7.C3.A3o_do_texto" name="Disposi.C3.A7.C3.A3o_do_texto">Disposição do texto</h3> + +<p>Duas propriedades especificam como o conteúdo de um elemento é alinhado. Você pode usá-las para ajustes simples na disposição:</p> + +<ul> + <li><code>text-align</code></li> +</ul> + +<dl> + <dd>Alinha o conteúdo. Use um destes valores: <code>left</code>, <code>right</code>, <code>center</code>, <code>justify</code></dd> +</dl> + +<ul> + <li><code>text-indent</code></li> +</ul> + +<dl> + <dd>Indenta o conteúdo, colocando o espaço que você especificar.</dd> +</dl> + +<p>Estas propriedades aplicam-se a qualquer conteúdo como texto no elemento, não somente ao texto atual. Lembre-se que elas são herdadas pelo elemento filho, então você pode ter que desativá-las nos elementos filhos para não se surpreender com os resultados.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Para centralizar títulos: + <div style="width: 30em;"> + <pre class="eval"> +h3 { + border-top: 1px solid gray; + text-align: center; + } +</pre> + </div> + + <p>Resulta em:</p> + + <table style="border: 2px outset #36b; padding: 1em; width: 30em; background-color: white;"> + <tbody> + <tr> + <td> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray; text-align: center;">(A) Os oceanos</p> + </td> + </tr> + </tbody> + </table> + + <p>Em um documento HTML, o conteúdo que você vê abaixo do título não é contido estruturalmente pelo título. Então quando você alinha um título como isto, as tags abaixo do título não são afetadas pela herança.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Flutuantes" name="Flutuantes">Flutuantes</h3> + +<p>A propriedade <code>float</code> força um elemento para a esquerda ou direita. Isto é uma maneira simples de controlar sua posição e tamanho.</p> + +<p>O resto do conteúdo do documento normalmente flui ao redor do elemento flutuado. Você pode controlar isto usando a propriedade <code>clear</code> em outros elementos para fazê-los permanecer sem flutuantes.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Em seu documento de amostra, as listas esticam através da janela. Você pode prevenir isto flutuando-os para a esquerda. + <p>Para manter os títulos no lugar, você precisa também especificar que eles permaneçam limpos de flutuantes à sua esquerda:</p> + + <div style="width: 30em;"> + <pre class="eval"> +ul, #numbered {float: left;} +h3 {clear: left;} +</pre> + </div> + + <p>O resultado deve se parecer com isto:</p> + + <table style="border: 2px outset #36b; padding: 1em; width: 30em; background-color: white;"> + <tbody> + <tr> + <td> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray;">(A) Os oceanos</p> + + <div style="float: left; border: 12px solid #69b; margin-bottom: 16px; padding-left: 1em;"> + <ul style=""> + <li>Ártico</li> + <li>Atlântico</li> + <li>Pacífico</li> + <li>Índico</li> + <li>Antártico</li> + </ul> + </div> + + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray;">(B) Parágrafos numerados</p> + + <div style="float: left; border: 12px solid #69b; margin-bottom: 8px; padding-left: .5em;"> + <p><strong>1: </strong>Lorem ipsum</p> + + <p><strong>2: </strong>Dolor sit</p> + + <p><strong>3: </strong>Amet consectetuer</p> + + <p><strong>4: </strong>Magna aliquam</p> + + <p><strong>5: </strong>Autem veleum</p> + </div> + </td> + </tr> + </tbody> + </table> + + <p>(Um pequeno enchimento é necessário à direita das caixas, onde a borda fica muito perto do texto.)</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Posicionamento" name="Posicionamento">Posicionamento</h3> + +<p>Você pode especificar a posição dos elementos de quatro maneiras, especificando a propriedade <code>position</code> e um dos valores seguintes:</p> + +<p>Estas são propriedades avançadas. É possível usá-las de maneiras simples — esta é a razão pela qual elas são mencionadas neste tutorial básico. Mas usando-as para disposições complexas pode-se dificultar.</p> + +<ul> + <li><code>relative</code></li> +</ul> + +<dl> + <dd>A posição do elemento é alterada relativamente à sua posição normal.</dd> + <dd>Use-o para mover um elemento por uma quantidade especificada. Às vezes você pode usar a margem do elemento para obter o mesmo efeito.</dd> +</dl> + +<ul> + <li><code>fixed</code></li> +</ul> + +<dl> + <dd>A posição do elemento é fixa.</dd> + <dd>Especifique a posição do elemento relativa à janela do documento. Mesmo que o resto do documento seja rolado, o elemento permanece fixo.</dd> +</dl> + +<ul> + <li><code>absolute</code></li> +</ul> + +<dl> + <dd>A posição do documento é fixada relativamente a um elemento pai.</dd> + <dd>Somente um elemento pai que esteja posicionado com <code>relative</code>, <code>fixed</code> ou <code>absolute</code> o fará.</dd> +</dl> + +<dl> + <dd>Você pode tornar qualquer elemento principal apropriado, especificando <code>position: relative;</code> sem especificar qualquer movimento.</dd> +</dl> + +<ul> + <li><code>static</code></li> +</ul> + +<dl> + <dd>O padrão. Use este valor caso precise desativar a posição explicitamente.</dd> +</dl> + +<p>Agora, com estes valores da propriedade <code>position</code> (exeto para <code>static</code>), especifique uma ou mais propriedades: <code>top</code>, <code>right</code>, <code>bottom</code>, <code>left</code>, <code>width</code>, <code>height</code> para identificar onde você quer que o elemento apareça, e talvez também seu tamanho.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Para posicionar dois elementos no topo, crie um "recipiente" principal em seu documento com os dois elementos dentre dele: + <div style="width: 30em;"> + <pre class="eval"> +<DIV id="parent-div"> +<P id="forward">/</P> +<P id="back">\</P> +</DIV> +</pre> + </div> + + <p>Na sua folha de estilo, faça a posição principal <code>relative</code>. Ela não precisa que seja especificado qualquer movimento atual. Faça a posição subordinada <code>absolute</code>:</p> + + <div style="width: 30em;"> + <pre> +#parent-div { + position: relative; + font: bold 200% sans-serif; + } + +#forward, #back { + position: absolute; + margin:0px; + top: 0px; + left: 0px; + } + +#forward { + color: blue; + } + +#back { + color: red; + } +</pre> + </div> + + <p>O resultado deve ser como isto, com a contra barra (\) sobre a barra (/):</p> + + <div style="position: relative; left: .33em; font: bold 300% sans-serif;"> + <p style="position: absolute; margin: 0px; top: 0px; left: 0px; color: blue;">/</p> + + <p style="position: absolute; margin: 0px; top: 0px; left: 0px; color: red;">\</p> + </div> + + <table style="border: 2px outset #36b; padding: 1em; width: 30em; height: 5em; background-color: white;"> + <tbody> + <tr> + <td> </td> + </tr> + </tbody> + </table> + + <p> </p> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>A história completa sobre posicionamento toma dois complexos capítulos em CSS Specification: <a class="external" href="http://www.w3.org/TR/CSS21/visuren.html">Visual formatting model</a> e <a class="external" href="http://www.w3.org/TR/CSS21/visudet.html">Visual formatting model details</a>. + <p>Se você está desenhando folhas de estilo para trabalharem em vários navegadores, então você também precisa levar em conta as diferenças na maneira em que os navegadores interpretam o padrão, e talvez bugs em algumas versões de alguns navegadores.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Especificando_a_disposi.C3.A7.C3.A3o" name="A.C3.A7.C3.A3o:_Especificando_a_disposi.C3.A7.C3.A3o">Ação: Especificando a disposição</h2> + +<p>Mude seu documento de amostra e sua folha de estilo usando os exemplos anteriores nas seções <strong>Estrutura do documento</strong> e <strong>Flutuantes</strong>.</p> + +<p>No exemplo dos <strong>Flutuantes</strong>, adicione enchimento para separar o texto da borda direita por 0,5 em.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Mude seu documento de amostra, adicionando esta tag perto do fim, somente antes de <code></BODY></code> + <pre> +<IMG id="fixed-pin" src="Yellow-pin.png" alt="Yellow map pin"> +</pre> + + <p>Se você não baixou o arquivo de imagem anteriormente neste tutorial, baixe-o agora:</p> + + <table style="border: 2px solid #ccc;"> + <tbody> + <tr> + <td><img alt="Image:Yellow-pin.png" class="internal" src="/@api/deki/files/2557/=Yellow-pin.png"></td> + </tr> + </tbody> + </table> + + <p>Prediga onde a imagem irá aparecer no seu documento. Então atualize seu navegador para ver se você estava certo.</p> + + <p>Adicione uma regra à sua folha de estilo que fixe a imagem no topo e a direita do seu documento.</p> + + <p>Atualize seu navegador e diminua o tamanho da janela. Cheque se a imagem permanece no topo e a direita mesmo que você role seu documento:</p> + + <div style="position: relative; width: 29.5em; height: 18em;"> + <div style="overflow: auto; border: 2px outset #36b; padding: 1em; width: 29em; height: 16em; background-color: white;"> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray;">(A) Os oceanos</p> + + <div style="float: left; border: 12px solid #69b; margin-bottom: 16px; padding: 0px .5em 0px 1em;"> + <ul style=""> + <li>Ártico</li> + <li>Atlântico</li> + <li>Pacífico</li> + <li>Índico</li> + <li>Antártico</li> + </ul> + </div> + + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em; border-top: 1px solid gray;">(B) Parágrafos numerados</p> + + <div style="float: left; border: 12px solid #69b; padding: 0 .5em 0 .5em;"> + <p><strong>1: </strong>Lorem ipsum</p> + + <p><strong>2: </strong>Dolor sit</p> + + <p><strong>3: </strong>Amet consectetuer</p> + + <p><strong>4: </strong>Magna aliquam</p> + + <p><strong>5: </strong>Autem veleum</p> + </div> + + <p style=""> </p> + + <div style="position: absolute; top: 2px; right: 0px;"><img alt="Yellow map pin" class="internal" src="/@api/deki/files/2557/=Yellow-pin.png"></div> + </div> + </div> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Disposi%C3%A7%C3%A3o" title="Talk:pt/CSS/Como_começar/Disposição">Discussão</a>.</p> + +<p>A próxima página descreve seletores para regras mais avançadas das CSS, e algumas maneiras específicas de estilizar tabelas: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Tabelas" title="pt/CSS/Como_começar/Tabelas">Tabelas</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}</p> diff --git a/files/pt-pt/web/css/como_começar/estilos_de_texto/index.html b/files/pt-pt/web/css/como_começar/estilos_de_texto/index.html new file mode 100644 index 0000000000..2e32166761 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/estilos_de_texto/index.html @@ -0,0 +1,157 @@ +--- +title: Estilos de texto +slug: Web/CSS/Como_começar/Estilos_de_texto +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Styling_text/Fundamentals +--- +<p>{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}</p> + +<p>Esta página dá mais exemplos de estilos de texto.</p> + +<p>Você modifica sua folha de estilo de amostra para usar diferentes fontes.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Estilos_de_texto" name="Informa.C3.A7.C3.A3o:_Estilos_de_texto">Informação: Estilos de texto</h2> + +<p>CSS tem várias propriedades para estilos de texto.</p> + +<p>Há uma conveniente propriedade de abreviação de caracteres/palavras que facilitam a escrita, <code>font</code>, que você pode usar para especificar várias coisas de uma vez — por exemplo:</p> + +<ul> + <li>Negrito, itálico e letras minúsculas</li> + <li>O tamanho</li> + <li>A altura da linha</li> + <li>O tipo da fonte</li> +</ul> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td> + <div style="width: 40em;"> + <pre class="eval"> +p {font: italic 75%/125% "Comic Sans MS", cursive;} +</pre> + </div> + + <p>Esta regra coloca várias propriedades da fonte, fazendo todos os parágrafos em itálico.</p> + + <p>O tamanho da fonte é três quartos (75%) do tamanho em cada elemento do paragrafo principal e a altura da linha é 125% (um pouco mais espaçada que o normal).</p> + + <p>O tipo da fonte é Comic Sans MS, mas se a fonte não estiver disponível então o navegador usará sua fonte cursiva padrão (escrita a mão).</p> + + <p>A regra tem o efeito colateral de desativar o negrito e as letras minúsculas (colocando-os no estilo <code>normal</code>)</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Tipos_de_fonte" name="Tipos_de_fonte">Tipos de fonte</h3> + +<p>Você não pode predizer quais fontes os leitores do seu documento terão. Então quando você especifica tipos de fonte é uma boa idéia colocar uma lista de alternativas em ordem de preferência.</p> + +<p>Acabe a lista com um dos tipos de fontes internas padrão: <code>serif</code>, <code>sans-serif</code>, <code>cursive</code>, <code>fantasy</code> ou <code>monospace</code>. (Algumas destas podem ser configuradas nas Opções do seu navegador.)</p> + +<p>Se o tipo não for suportado por algumas características no documento, então o navegador pode substituí-lo por um tipo diferente. Por exemplo, o documento pode conter caracteres especiais que a fonte não suporte. Se o navegador puder encontrar outra fonte que tenha os caracteres, então ele usará a outra fonte.</p> + +<p>Para especificar um tipo de fonte por conta própria, use a propriedade <code>font-family</code>.</p> + +<h3 id="Tamanho_da_fonte" name="Tamanho_da_fonte">Tamanho da fonte</h3> + +<p>Leitores que usam os navegadores Mozilla podem configurar o tamanho padrão das fontes em Opções, e mudar o tamanho do texto quando lêem uma página, isso a torna boa para você usá-la com tamanho relativos onde você puder.</p> + +<p>Você pode usar alguns valores internos para o tamanho das fontes, como: <code>small</code>, <code>medium</code> e <code>large</code>. Você pode também usar valores relativos para o tamanho das fontes do elemento primário, como: <code>smaller</code>, <code>larger</code>, <code>150%</code> ou <code>1.5em</code>.</p> + +<p>Se necessário você pode especificar um tamanho atual, como: <code>12px</code> (12 pixels) para um instrumento de exibição ou <code>12pt</code> (12 pontos) para uma impressora. Este tamanho é nominalmente a largura de uma letra m, mas fontes variam na maneira do tamanho, você vê relatos do tamanho que você especifica.</p> + +<p>Para especificar um tamanho de fonte por conta própria, use a propriedade <code>font-size</code>.</p> + +<h3 id="Altura_da_linha" name="Altura_da_linha">Altura da linha</h3> + +<p>A altura da linha especifica o espaçamento entre linhas. Se seu documento tem longos parágrafos com muitas linhas, um espaçamento mais largo que o normal faz com que a leitura seja mais fácil, especialmente se o tamanho da fonte for pequeno.</p> + +<p>Para especificar a altura da linha por conta própria, use a propriedade <code>line-height</code>.</p> + +<h3 id="Decora.C3.A7.C3.A3o" name="Decora.C3.A7.C3.A3o">Decoração</h3> + +<p>A propriedade separada <code>text-decoration</code> pode especificar outros estilos, como <code>underline</code> ou <code>line-through</code>. Você pode configurar isto para <code>none</code> removendo explicitamente qualquer decoração.</p> + +<h3 id="Outras_propriedades" name="Outras_propriedades">Outras propriedades</h3> + +<p>Para especificar itálico por conta própria, use <code>font-style: italic;</code><br> + Para especificar negrito por conta própria, use <code>font-weight: bold;</code><br> + Para especificar letras minúsculas por conta própria, use <code>font-variant: small-caps;</code></p> + +<p>Para tornar qualquer destes valores individualmente desativado, você pode especificar o valor <code>normal</code> ou <code>inherit</code>.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Você pode especificar os estilos do texto em uma variedade de outras maneiras. + <p>Por exemplo, algumas propriedades mencionadas aqui têm outros valores que podem ser usados.</p> + + <p>Em uma folha de estilo complexa, evite usar a propriedade de abreviação de caracteres/palavras que facilitam a escrita <code>font</code>, por causa de seus efeitos colaterais (o re-escolher de outras propriedades individuais).</p> + + <p>Para maiores detalhes sobre as propriedades relacionadas às fontes, veja <a class="external" href="http://www.w3.org/TR/CSS21/fonts.html">Fonts</a> na especificação do CSS. Para maiores detalhes sobre decoração de textos, veja <a class="external" href="http://www.w3.org/TR/CSS21/text.html">Text</a>.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Especificando_fontes" name="A.C3.A7.C3.A3o:_Especificando_fontes">Ação: Especificando fontes</h2> + +<p>Para um documento de amostra, você pode escolher a fonte do elemento <small>BODY</small> e o resto do documento herda as configurações.</p> + +<p>Edite seu arquivo CSS. Adicione esta regra para mudar a fonte completamente. O topo do arquivo CSS é um local lógico para isto, mas isto terá o mesmo efeito em qualquer lugar que for posicionado:</p> + +<div style="width: 40em;"> +<pre class="eval">body {font: 16px "Comic Sans MS", cursive;} +</pre> +</div> + +<p>Adicione um comentário à regra, e deixe um espaço em branco para fazer sua disposição preferido.</p> + +<p>Atualize seu navegador para ver o efeito. Se o seu sistema tem Comic Sans MS, ou outra fonte cursiva que não suporta itálico, então seu navegador escolhe um tipo diferente de fonte para o texto em itálico na primeira linha:</p> + +<table style="border: 2px outset #36b; padding: 1em;"> + <tbody> + <tr> + <td style="font: italic 16px 'Comic Sans MS', cursive; color: blue;"><strong style="color: red;">C</strong>ascading <strong style="color: green;">S</strong>tyle <strong style="color: green;">S</strong>heets</td> + </tr> + <tr> + <td style="font: 16px 'Comic Sans MS', cursive; color: blue;"><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> +</table> + +<p>Da barra de menu do seu navegador, escolha Exibir – Tamanho do Texto – Aumentar. Mesmo que o estilo especificado seja 16 pixels, um usuário lendo o documento pode mudar o tamanho.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #ffe;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Sem mudar mais nada, faça todas as seis letras iniciais duas vezes o tamanho na fonte serifada padrão do navegador: + <table> + <tbody> + <tr> + <td style="font: italic 16px 'Comic Sans MS', cursive; color: blue;"><strong style="color: red; font: 200% serif;">C</strong>ascading <strong style="color: green; font: 200% serif;">S</strong>tyle <strong style="color: green; font: 200% serif;">S</strong>heets</td> + </tr> + <tr> + <td style="font: 16px 'Comic Sans MS', cursive; color: blue;"><strong style="color: red; font: 200% serif;">C</strong>ascading <strong style="color: red; font: 200% serif;">S</strong>tyle <strong style="color: red; font: 200% serif;">S</strong>heets</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Estilos_de_texto" title="Talk:pt/CSS/Como_começar/Estilos_de_texto">Discussão</a>.</p> + +<p>Seu documento de amostra está pronto para usar várias cores nomeadas. A próxima página lista os nomes das cores padrão e explica como você pode especificar outras: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Cor" title="pt/CSS/Como_começar/Cor">Cor</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}</p> diff --git a/files/pt-pt/web/css/como_começar/gráficos_svg/index.html b/files/pt-pt/web/css/como_começar/gráficos_svg/index.html new file mode 100644 index 0000000000..074f78c92d --- /dev/null +++ b/files/pt-pt/web/css/como_começar/gráficos_svg/index.html @@ -0,0 +1,215 @@ +--- +title: Gráficos SVG +slug: Web/CSS/Como_começar/Gráficos_SVG +tags: + - 'CSS:Como_começar' +translation_of: Web/SVG/Tutorial/SVG_and_CSS +--- +<p>{{ PreviousNext("CSS:Como começar:Interfaces de usuário XUL", "CSS:Como começar:Dados XML") }}</p> + +<p>Esta página ilustra a linguagem especializada para criação de gráficos: SVG.</p> + +<p>Você cria uma simples demonstração que roda em seu navegador Mozilla com SVG ativado.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_SVG" name="Informa.C3.A7.C3.A3o:_SVG">Informação: SVG</h2> + +<p><em>SVG</em> (Scalable Vector Graphics) é uma linguagem baseada em XML para criação de gráficos.</p> + +<p>Ela pode ser usada para imagens estáticas, e também para animações e interfaces de usuário.</p> + +<p>Como outras linguagens baseadas em XML, SVG suporta folhas de estilo CSS então você pode separar o estilo de um gráfico do seu conteúdo.</p> + +<p>As folhas de estilo que você usa com linguagens de marcação em outros documentos também podem especificar o URL de um gráfico SVG onde uma imagem é requerida. Por exemplo, uma folha de estilo que você usa com documentos HTML pode especificar uma URL de um gráfico SVG no valor da propriedade <code>background</code>.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em; width: 100%;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td><span class="comment">Enquanto escrevo (metade de 2005), somente algumas novas construções dos navegadores Mozilla tem suporte a SVG contruída. Você pode adicionar suporte ao SVG à outras versões instalando um plugin tal como este fornecido pela {{ mediawiki.external('http://www.adobe.com/svg/viewer/install/main.html Adobe') }}.</span> + <p>Para mais informações sobre SVG no Mozilla, veja a página <a href="/pt/SVG" title="pt/SVG">SVG</a> neste wiki.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Uma_demonstra.C3.A7.C3.A3o_SVG" name="A.C3.A7.C3.A3o:_Uma_demonstra.C3.A7.C3.A3o_SVG">Ação: Uma demonstração SVG</h2> + +<p>Crie um novo documento SVG de um arquivo de texto simples, <code>doc8.svg</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre><?xml version="1.0" standalone="no"?> + +<?xml-stylesheet type="text/css" href="style8.css"?> + +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" + "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> + +<svg width="600px" height="600px" viewBox="-300 -300 600 600" + xmlns="http://www.w3.org/2000/svg" version="1.1" + xmlns:xlink="http://www.w3.org/1999/xlink"> + +<title>SVG demonstration</title> +<desc>Mozilla CSS Getting Started - SVG demonstration</desc> + +<defs> + <g id="segment" class="segment"> + <path class="segment-fill" d="M0,0 v-200 a40,40 0 0,0 -62,10 z"/> + <path class="segment-edge" d="M0,-200 a40,40 0 0,0 -62,10"/> + </g> + <g id="quadrant"> + <use xlink:href="#segment"/> + <use xlink:href="#segment" transform="rotate(18)"/> + <use xlink:href="#segment" transform="rotate(36)"/> + <use xlink:href="#segment" transform="rotate(54)"/> + <use xlink:href="#segment" transform="rotate(72)"/> + </g> + <g id="petals"> + <use xlink:href="#quadrant"/> + <use xlink:href="#quadrant" transform="rotate(90)"/> + <use xlink:href="#quadrant" transform="rotate(180)"/> + <use xlink:href="#quadrant" transform="rotate(270)"/> + </g> + <radialGradient id="fade" cx="0" cy="0" r="200" + gradientUnits="userSpaceOnUse"> + <stop id="fade-stop-1" offset="33%"/> + <stop id="fade-stop-2" offset="95%"/> + </radialGradient> + </defs> + +<text id="heading" x="-280" y="-270"> + SVG demonstration</text> +<text id="caption" x="-280" y="-250"> + Move your mouse pointer over the flower.</text> + +<g id="flower"> + <circle id="overlay" cx="0" cy="0" r="200" + stroke="none" fill="url(#fade)"/> + <use id="outer-petals" xlink:href="#petals"/> + <use id="inner-petals" xlink:href="#petals" + transform="rotate(9) scale(0.33)"/> + </g> + +</svg> +</pre> +</div> + +<p>Crie um novo arquivo CSS, <code>style8.css</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre>/*** Demonstração SVG ***/ + +/* página */ +svg { + background-color: beige; + } + +#heading { + font-size: 24px; + font-weight: bold; + } + +#caption { + font-size: 12px; + } + +/* flor */ +#flower:hover { + cursor: crosshair; + } + +/* gradiente */ +#fade-stop-1 { + stop-color: blue; + } + +#fade-stop-2 { + stop-color: white; + } + +/* outras pétalas */ +#outer-petals { + opacity: .75; + } + +#outer-petals .segment-fill { + fill: azure; + stroke: lightsteelblue; + stroke-width: 1; + } + +#outer-petals .segment-edge { + fill: none; + stroke: deepskyblue; + stroke-width: 3; + } + +#outer-petals .segment:hover > .segment-fill { + fill: plum; + stroke: none; + } + +#outer-petals .segment:hover > .segment-edge { + stroke: slateblue; + } + +/* pétalas internas */ +#inner-petals .segment-fill { + fill: yellow; + stroke: yellowgreen; + stroke-width: 1; + } + +#inner-petals .segment-edge { + fill: none; + stroke: yellowgreen; + stroke-width: 9; + } + +#inner-petals .segment:hover > .segment-fill { + fill: darkseagreen; + stroke: none; + } + +#inner-petals .segment:hover > .segment-edge { + stroke: green; + } +</pre> +</div> + +<p>Abra o documento no seu navegador com SVG ativado. Mova o ponteiro do seu mouse sobre o gráfico.</p> + +<p>Este wiki não suporta página com SVG, então não é possível demonstrá-lo aqui. Os gráficos deverão parecer com isto:</p> + +<table style="border: 2px outset #36b;"> + <tbody> + <tr> + <td><img alt="SVG demonstration" class="internal" src="/@api/deki/files/2553/=SVG-flower.png"></td> + </tr> + </tbody> +</table> + +<p>Notas sobre esta demonstração:</p> + +<ul> + <li>O documento SVG é ligado à folha de estilo normalmente.</li> + <li>O SVG tem suas propriedades e valores CSS. Alguns deles são similares às propriedades do CSS para o HTML.</li> +</ul> + +<p> </p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Mude a folha de estilo de modo que as pétalas interiores tornem-se todas rosa quando o ponteiro do mouse estiver sobre alguma delas, sem mudar a maneira como as outras pétalas trabalham.</td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Gr%C3%A1ficos_SVG" title="Talk:pt/CSS/Como_começar/Gráficos_SVG">Discussão</a>.</p> + +<p>Nesta demonstração, seu navegador com SVG ativado já sabe como mostrar elementos SVG. A folha de estilo somente modifica a exibição em certos caminhos. Isto também é verdade para documentos HTML e XUL. Mas você pode usar o CSS para propósitos gerais em documentos XML, onde não é predefinido um caminho para exibir os elementos. A próxima página demonstra isto: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Dados_XML" title="pt/CSS/Como_começar/Dados_XML">Dados XML</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Interfaces de usuário XUL", "CSS:Como começar:Dados XML") }}</p> diff --git a/files/pt-pt/web/css/como_começar/index.html b/files/pt-pt/web/css/como_começar/index.html new file mode 100644 index 0000000000..a0cf76e018 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/index.html @@ -0,0 +1,91 @@ +--- +title: Como começar +slug: Web/CSS/Como_começar +tags: + - CSS + - 'CSS:Como_começar' + - Todas_as_Categorias +translation_of: Learn/CSS/First_steps +--- +<p> </p> + +<h3 id="Introdu.C3.A7.C3.A3o" name="Introdu.C3.A7.C3.A3o">Introdução</h3> + +<p>Este tutorial o introduz às CSS (Cascading Style Sheets - Folhas de Estilo em Cascata).</p> + +<p>Este tutorial o orienta nos recursos básicos de CSS com exemplos práticos que você pode experimentar sozinho em seu computador. Ele é dividido em duas partes:</p> + +<ul> + <li>A Parte I ilustra os recursos básicos das CSS que funcionam nos navegadores Mozilla e também na maioria dos navegadores modernos.</li> +</ul> + +<ul> + <li>A Parte II contém alguns exemplos de recursos especiais que funcionam no Mozilla, mas não necessariamente em outros ambientes.</li> +</ul> + +<p>Este tutorial é baseado na <a class="external" href="http://www.w3.org/TR/CSS21/">CSS 2.1 Specification</a>.</p> + +<h4 id="Quem_deve_ler_este_tutorial.3F" name="Quem_deve_ler_este_tutorial.3F">Quem deve ler este tutorial?</h4> + +<p>Este tutorial é direcionado para iniciantes em CSS, mas você também poderá usá-lo caso tenha alguma experiência em CSS.</p> + +<p>Se você é um iniciante em CSS, leia a Parte I deste tutorial para entender CSS e aprender a usá-lo. Em seguida, leia a Parte II para entender o escopo de CSS no Mozilla.</p> + +<p>Se você conhece CSS, poderá ignorar as partes desse tutorial que já conhece e ler apenas as partes que lhe interessam.</p> + +<p>Se você já tem experiência em CSS mas não no Mozilla, pode ir direto para a Parte II.</p> + +<h4 id="O_que_voc.C3.AA_precisa_antes_de_come.C3.A7ar.3F" name="O_que_voc.C3.AA_precisa_antes_de_come.C3.A7ar.3F">O que você precisa antes de começar?</h4> + +<p>Para melhor aproveitar este tutorial, você precisa de um editor de arquivos de texto e um navegador Mozilla (Firefox, Mozilla Suite ou Seamonkey). Você também deve saber como utilizá-los de um modo básico.</p> + +<p>Se não deseja editar arquivos, você pode apenas ler o tutorial e observar as imagens, mas este não é o melhor modo de aprendizado.</p> + +<p>Poucas partes deste tutorial podem requerer outro software Mozilla. Essas partes são opcionais. Você pode ignorar essas partes se não desejar fazer o download de outro software Mozilla.</p> + +<p><strong>Nota:</strong> As CSS oferece modos de se trabalhar com cores, de modo que partes deste tutorial dependem de cores. Você poderá utilizar essas partes facilmente somente se tiver um monitor colorido e uma visão colorida normal.</p> + +<h4 id="Como_utilizar_este_tutorial" name="Como_utilizar_este_tutorial">Como utilizar este tutorial</h4> + +<p>Para utilizar este tutorial, leia cuidadosamente as páginas e em seqüência. Se perder uma página, você poderá ter dificuldades para entender as páginas posteriores.</p> + +<p>Em cada página, utilize a seção<em>Informações</em> para entender como o CSS funciona. Utilize a seção<em>Ações</em> para tentar usar o CSS em seu próprio computador.</p> + +<p>Para testar seus conhecimentos, faça o teste ao final de cada página. As soluções para alguns testes são reveladas nas páginas posteriores no tutorial.</p> + +<p>Para se aprofundar em CSS, leia as informações nas caixas entituladas<em>Mais detalhes</em>. Utilize os links para localizar informações referentes às CSS.</p> + +<h3 id="Tutorial_Parte_I" name="Tutorial_Parte_I">Tutorial Parte I</h3> + +<p>Um guia passo-a-passo para CSS.</p> + +<ol> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/O_que_%c3%a9_CSS">O que é CSS</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Porque_usar_CSS">Porque usar CSS</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Como_o_CSS_trabalha">Como o CSS trabalha</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Cascata_e_heran%c3%a7a">Cascata e herança</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Seletores">Seletores</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/CSS_leg%c3%advel">CSS legível</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Estilos_de_texto">Estilos de texto</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Cor">Cor</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Conte%c3%bado">Conteúdo</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Listas">Listas</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Caixas">Caixas</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Disposi%c3%a7%c3%a3o">Disposição</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Tabelas">Tabelas</a></strong></li> + <li><strong><a href="/pt-PT/docs/Web/CSS/Como_começar/Mídia">Média</a></strong></li> +</ol> + +<h3 id="Tutorial_Parte_II" name="Tutorial_Parte_II">Tutorial Parte II</h3> + +<p>Exemplos que mostram o escopo da CSS no Mozilla.</p> + +<ol> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/JavaScript">JavaScript</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/XBL_bindings">XBL bindings</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Interfaces_de_usu%c3%a1rio_XUL">Interfaces de usuário XUL</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Gr%c3%a1ficos_SVG">Gráficos SVG</a></strong></li> + <li><strong><a href="pt/CSS/Como_come%c3%a7ar/Dados_XML">Dados XML</a></strong></li> +</ol> + +<p>{{ languages( { "en": "en/CSS/Getting_Started", "fr": "fr/CSS/Premiers_pas", "it": "it/Conoscere_i_CSS", "ja": "ja/CSS/Getting_Started", "nl": "nl/CSS/Voor_Beginners", "pl": "pl/CSS/Na_pocz\u0105tek", "zh-cn": "cn/CSS/\u5f00\u59cb" } ) }}</p> diff --git a/files/pt-pt/web/css/como_começar/interfaces_de_usuário_xul/index.html b/files/pt-pt/web/css/como_começar/interfaces_de_usuário_xul/index.html new file mode 100644 index 0000000000..46408abaa8 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/interfaces_de_usuário_xul/index.html @@ -0,0 +1,336 @@ +--- +title: Interfaces de usuário XUL +slug: Web/CSS/Como_começar/Interfaces_de_usuário_XUL +tags: + - 'CSS:Como_começar' +translation_of: Archive/Beginner_tutorials/XUL_user_interfaces +--- +<p>{{ PreviousNext("CSS:Como começar:XBL bindings", "CSS:Como começar:Gráficos SVG") }}</p> + +<p>Esta página ilustra a linguagem especializada do Mozilla para criação de interfaces de usuário.</p> + +<p>Você cria uma simples demonstração que roda no seu navegador Mozilla.</p> + +<h2 id="Informa.C3.A7.C3.A3o_Intefaces_de_usu.C3.A1rio" name="Informa.C3.A7.C3.A3o:_Intefaces_de_usu.C3.A1rio">Informação: Interfaces de usuário</h2> + +<p>Embora o HTML tenha algum suporte à interfaces de usuário, ele não suporta todas as características que você precisa para fazer uma aplicação autônoma.</p> + +<p>O Mozilla supera esta limitação providenciando uma linguagem especializada para criar interfaces de usuário: <em>XUL</em> (XML User-interface Language, usualmente pronunciada como "<em>zool</em>").</p> + +<p>Em XUL, muitas características comuns de interfaces de usuário podem ser construídas. Por exemplo, XUL proporciona janelas especializadas como diálogos, assim como barras de estado, menus, barras de ferramenta, e mesmo navegadores.</p> + +<p>Mais características especializadas podem ser construídas em partes usando XUL juntamente com outras tecnologias que você viu neste tutorial: estilo CSS, código JavaScript e XBL bindings.</p> + +<p>Como outras linguagens baseadas em XML, XUL usa folhas de estilo CSS.</p> + +<table style="background-color: #f4f4f4; border: 1px solid #3366bb; margin-bottom: 1em; padding: 1em; width: 100%;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Para maiores informações sobre interfaces de usuário XUL, veja a página <a href="/pt/XUL" title="pt/XUL">XUL</a> neste wiki.</td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o_Uma_demonstra.C3.A7.C3.A3o_XUL" name="A.C3.A7.C3.A3o:_Uma_demonstra.C3.A7.C3.A3o_XUL">Ação: Uma demonstração XUL</h2> + +<p>Crie um novo documento XUL de um simples arquivo de texto, <code>doc7.xul</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela para pegar tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre><?xml version="1.0"?> +<?xml-stylesheet href="chrome://global/skin/" type="text/css"?> +<?xml-stylesheet type="text/css" href="style7.css"?> + +<window + xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" + title="CSS Getting Started - XUL demonstration" + onload="init();"> + +<script type="application/x-javascript" src="script7.js"/> + +<label class="head-1" value="XUL demonstration"/> + +<vbox> + + <groupbox class="demo-group"> + <caption label="Day of week calculator"/> + <grid> + <columns> + <column/> + <column/> + </columns> + <rows> + <row> + <label class="text-prompt" value="Date:" + accesskey="D" control="date-text"/> + <textbox id="date-text" type="timed" + timeout="750" oncommand="refresh();"/> + </row> + <row> + <label value="Day:"/> + <hbox id="day-box"> + <label class="day" value="Sunday" disabled="true"/> + <label class="day" value="Monday" disabled="true"/> + <label class="day" value="Tuesday" disabled="true"/> + <label class="day" value="Wednesday" disabled="true"/> + <label class="day" value="Thursday" disabled="true"/> + <label class="day" value="Friday" disabled="true"/> + <label class="day" value="Saturday" disabled="true"/> + </hbox> + </row> + </rows> + </grid> + <hbox class="buttons"> + <button id="clear" label="Clear" accesskey="C" + oncommand="clearDate();"/> + <button id="today" label="Today" accesskey="T" + oncommand="setToday();"/> + </hbox> + </groupbox> + + <statusbar> + <statusbarpanel id="status"/> + </statusbar> + +</vbox> + +</window> +</pre> +</div> + +<p>Crie um novo arquivo CSS, <code>style7.css</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela para pegar tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre>/*** XUL demonstration ***/ +window { + -moz-box-align: start; + background-color: -moz-dialog; + font: -moz-dialog; + padding: 2em; + } + +.head-1 { + font-weight: bold; + font-size: 200%; + padding-left: 5px; + } + + +/* the group box */ +.demo-group { + padding: 1em; + } + +.demo-group grid { + margin-bottom: 1em; + } + +.demo-group column { + margin-right: .5em; + } + +.demo-group row { + margin-bottom: .5em; + } + +.demo-group .buttons { + -moz-box-pack: end; + } + + +/* the day-of-week labels */ +.day { + margin-left: 1em; + } + +.day[disabled] { + color: #777; + } + +.day:first-child { + margin-left: 4px; + } + + +/* the left column labels */ +.text-prompt { + padding-top: .25em; + } + + +/* the date input box */ +#date-text { + max-width: 8em; + } + + +/* the status bar */ +statusbar { + width: 100%; + border: 1px inset -moz-dialog; + margin: 4px; + padding: 0px 4px; + } + +#status { + padding: 4px; + } + +#status[warning] { + color: red; + } +</pre> +</div> + +<p>Crie um novo arquivo de texto, <code>script7.js</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego todo o conteúdo daqui:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre>// XUL demonstration + +var dateBox, dayBox, currentDay, status; // elements + +// called by window onLoad +function init() { + dateBox = document.getElementById("date-text") + dayBox = document.getElementById("day-box") + status = document.getElementById("status") + setToday(); + } + +// called by Clear button +function clearDate() { + dateBox.value = "" + refresh() + } + +// called by Today button +function setToday() { + var d = new Date() + dateBox.value = (d.getMonth() + 1) + + "/" + d.getDate() + + "/" + d.getFullYear() + refresh() + } + +// called by Date textbox +function refresh() { + var d = dateBox.value + var theDate = null + + showStatus(null) + if (d != "") { + try { + var a = d.split("/") + var theDate = new Date(a[2], a[0] - 1, a[1]) + showStatus(theDate) + } + catch (ex) {} + } + setDay(theDate) + } + +// internal +function setDay(aDate) { + if (currentDay) currentDay.setAttribute("disabled", "true") + if (aDate == null) currentDay = null + else { + var d = aDate.getDay() + currentDay = dayBox.firstChild + while (d-- > 0) currentDay = currentDay.nextSibling + currentDay.removeAttribute("disabled") + } + dateBox.focus(); + } + +function showStatus(aDate) { + if (aDate == null) { + status.removeAttribute("warning") + status.setAttribute("label", "") + } + else if (aDate === false || isNaN(aDate.getTime())) { + status.setAttribute("warning", "true") + status.setAttribute("label", "Date is not valid") + } + else { + status.removeAttribute("warning") + status.setAttribute("label", aDate.toLocaleDateString()) + } + } +</pre> +</div> + +<p>Para ver o resultado exatamente como pretendido use o tema padrão do seu navegador. Se você usa um tema diferente, isto mode mudar alguns estilos da interface do usuário e a demonstração pode parecer estranha.</p> + +<p>Abra o documento no seu navegador Mozilla e use a interface.</p> + +<p>Este wiki não suporta XUL e JavaScript nas páginas, então não é possível fazer a demonstração aqui. Deve se parecer com isto:</p> + +<table style="background-color: threedface; border: 2px outset #3366bb; cursor: default; margin: .5em 0; padding: 1em; white-space: nowrap;"> + <tbody> + <tr> + <td> + <p style="font-size: 150%; font-weight: bold; margin: 0; padding: 0;">XUL demonstration</p> + + <div style="position: relative; border: 2px groove threedhighlight; margin-top: 1em;"> + <p style="float: left; margin: -1em 0 0 .5em; padding: 0; background-color: threedface;">Day of week calculator</p> + + <table style="background-color: threedface; margin: .5em; padding-right: .5em;"> + <tbody> + <tr> + <td style="padding-right: .5em;"><u>D</u>ate:</td> + <td style="background-color: white; border: 1px solid #000; width: 8em; float: left; cursor: text; padding: .15em .25em;">6/27/2005</td> + </tr> + <tr> + <td>Day:</td> + <td style="color: graytext;">Sunday <span style="color: #000000;">Monday</span> Tuesday Wednesday Thurdsay Friday Saturday</td> + </tr> + <tr> + <td></td> + <td> + <div style="float: right; margin-top: .5em;"> + <p><span style="border: 2px outset threedface; padding: .25em 1em;"><u>C</u>lear</span> <span style="border: 2px outset threedface; padding: .25em 1em;"><u>T</u>oday</span></p> + </div> + </td> + </tr> + </tbody> + </table> + </div> + + <div style="border: 1px inset threedface; margin-top: 1em;"> + <p style="margin: 0; padding: .25em .5em;">June 27, 2005</p> + </div> + </td> + </tr> + </tbody> +</table> + +<p>Notas sobre esta demonstração:</p> + +<ul> + <li>O documento XUL é ligado à folha de estilo normalmente, e também ligado ao script.</li> + <li>O script não é importante nesta demonstração.</li> + <li>Muito do estilo que você vê é determinado pelo tema do seu navegador.</li> +</ul> + +<p>Examine a folha de estilo do documento para ver se você entende todas as regras dele. Se houver alguma regra que você não entende, comente-a e atualize o seu navegador para ver o efeito no documento.</p> + +<table style="background-color: #fffff4; border: 1px solid #3366bb; margin-bottom: 1em; padding: 1em;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Use a ferramenta DOM Inspector para examinar a caixa de texto Date. Ela é feita de outros elementos que são gerados por seu XBL binding. + <p>Descubra a <em>classe</em> do elemento <code>html:input</code>. Este é o elemento que atualmente recebe a entrada do usuário.</p> + + <p>Usando este conhecimento, adicione uma regra à sua folha de estilo que faça o fundo da caixa Date de um azul pálido quando ele tiver o foco do teclado (mas branco quando o foco do teclado estiver em outro lugar).</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Intefaces_de_usu%C3%A1rio" title="Talk:pt/CSS/Como_começar/Intefaces_de_usuário">Discussão</a>.</p> + +<p>Nesta demonstração, você viu que as formas retangulares padrão são comuns na maioria das interfaces de usuário. Mozilla também suporta uma linguagem especializada de gráficos para criar padrões, usando folhas de estilo CSS para especificar o estilo. A próxima página demonstra isto: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Gr%C3%A1ficos_SVG" title="pt/CSS/Como_começar/Gráficos_SVG">Gráficos SVG</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:XBL bindings", "CSS:Como começar:Gráficos SVG") }}</p> diff --git a/files/pt-pt/web/css/como_começar/javascript/index.html b/files/pt-pt/web/css/como_começar/javascript/index.html new file mode 100644 index 0000000000..5cb8faf696 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/javascript/index.html @@ -0,0 +1,159 @@ +--- +title: JavaScript +slug: Web/CSS/Como_começar/JavaScript +tags: + - 'CSS:Como_começar' +translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents +--- +<p>{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}</p> + +<p>Esta é a Parte II do tutorial. A Parte II contém alguns exemplos que mostram o escopo do CSS no Mozilla.</p> + +<p>Cada página na Parte II ilustra como o CSS interage com algumas outras tecnologias. Estas páginas não são desenhadas para ensinar como usar estas outras tecnologias. Vá para outros tutorias para aprender isto em detalhes.</p> + +<p>Em vez disso, estas páginas são desenhadas para ilustrar os muitos usos do CSS. Para usar estas páginas, você deve ter um conhecimento em CSS, mas você não precisa qualquer conhecimento em outras tecnologias.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_JavaScript" name="Informa.C3.A7.C3.A3o:_JavaScript">Informação: JavaScript</h2> + +<p>JavaScript é uma <em>linguagem de programação</em>. Quando você usa alguma aplicação Mozilla (por exemplo, seu naverador Mozilla) muito do código que o seu computador roda é escrito em JavaScript.</p> + +<p>JavaScript pode interagir com folhas de estilo, permitindo a você escrever programas que mudem o estilo do documento dinamicamente.</p> + +<p>Existem três maneiras para fazer isto:</p> + +<ul> + <li>Trabalhando com uma lista de folhas de estilo no documento — por exemplo: adicionando, removendo ou modificando uma folha de estilo.</li> + <li>Trabalhando com as regras de uma folha de estilo — por exemplo: adicionando, removendo ou modificando uma regra.</li> + <li>Trabalhando com um elemento individual no DOM — modificando seu estilo independentemente da folha de estilo do seu documento.</li> +</ul> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em; width: 100%;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Para mais informações sobre JavaScript no Mozilla, veja a página <a href="/pt/JavaScript" title="pt/JavaScript">JavaScript</a> neste wiki.</td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Uma_demonstra.C3.A7.C3.A3o_de_JavaScript" name="A.C3.A7.C3.A3o:_Uma_demonstra.C3.A7.C3.A3o_de_JavaScript">Ação: Uma demonstração de JavaScript</h2> + +<p>Criei um novo documento HTML, <code>doc5.html</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<HTML> + +<HEAD> +<TITLE>Como Começar Mozilla CSS - Demonstração JavaScript</TITLE> +<LINK rel="stylesheet" type="text/css" href="style5.css"> +<SCRIPT type="text/javascript" src="script5.js"></SCRIPT> +</HEAD> + +<BODY> +<H1>JavaScript de amostra</H1> + +<DIV id="square"></DIV> + +<BUTTON type="button" onclick="doDemo(this);">Clique Aqui</BUTTON> + +</BODY> +</HTML> +</pre> +</div> + +<p>Crie um novo arquivo CSS, <code>style5.css</code>. Copie e cole o conteúdo daqui:</p> + +<div style="width: 48em;"> +<pre>/*** Demonstração JavaScript ***/ +#square { + width: 20em; + height: 20em; + border: 2px inset gray; + margin-bottom: 1em; + } + +button { + padding: .5em 2em; + } +</pre> +</div> + +<p>Crie um novo arquivo de texo, <code>script5.js</code>. Copie e cole o conteúdo daqui:</p> + +<div style="width: 48em;"> +<pre>// Demonstração JavaScript +function doDemo (button) { + var square = document.getElementById("square") + square.style.backgroundColor = "#fa4" + button.setAttribute("disabled", "true") + setTimeout(clearDemo, 2000, button) + } + +function clearDemo (button) { + var square = document.getElementById("square") + square.style.backgroundColor = "transparent" + button.removeAttribute("disabled") + } +</pre> +</div> + +<p>Abra o documento no seu navegador e pressione o botão.</p> + +<p>Este wiki não suporta o JavaScript nas páginas, então não é possível mostrar a demonstração aqui. Deve se parecer como isto, antes e depois de você pressionar o botão:</p> + +<table> + <tbody> + <tr> + <td style="padding-right: 2em;"> + <table style="border: 2px outset #36b; padding: 0 1em .5em .5em;"> + <tbody> + <tr> + <td> + <p><strong>Demonstração JavaScript</strong></p> + </td> + </tr> + </tbody> + </table> + </td> + <td> + <table style="border: 2px outset #36b; padding: 0 1em .5em .5em;"> + <tbody> + <tr> + <td> + <p><strong>Demonstração JavaScript</strong></p> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<p>Notas sobre esta demonstração:</p> + +<ul> + <li>O documento HTML é ligado à folha de estilo normalmente, e também é ligado ao script.</li> + <li>O script trabalha com elementos individuais no DOM. Isto modifica o estilo dos quadrados diretamente, porém, modifica o estilo do botão indiretamente mudando um atributo.</li> + <li>Em JavaScript, <code>document.getElementById("square")</code> é similar em função ao seletor CSS <code>#square</code>.</li> + <li>Em JavaScript, <code>backgroundColor</code> corresponde à propriedade <code>background-color</code> do CSS.</li> + <li>Seu navegador tem uma regra construída das CSS para <code>button{{ mediawiki.external('disabled=\"true\"') }}</code> que muda a aparência do botão quando ele está desabilitado.</li> +</ul> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: .5em;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Mude o script de modo que o quadrado salte para a direita em 20 em quando sua cor mudar, e salte para trás mais tarde.</td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/JavaScript" title="Talk:pt/CSS/Como_começar/JavaScript">Discussão</a>.</p> + +<p>Nesta demonstração, o documento HTML linka o script mesmo que somente o elemento button use o script. Mozilla extende o CSS para que possa ser ligado ao código JavaScript (e também conteúdo e outras folhas de estilo) para elementos selecionados. A próxima página demonstra isto: <strong><a href="/pt/CSS/Como_come%C3%A7ar/XBL_bindings" title="pt/CSS/Como_começar/XBL_bindings">XBL bindings</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}</p> diff --git a/files/pt-pt/web/css/como_começar/listas/index.html b/files/pt-pt/web/css/como_começar/listas/index.html new file mode 100644 index 0000000000..5d6ca00f01 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/listas/index.html @@ -0,0 +1,361 @@ +--- +title: Listas +slug: Web/CSS/Como_começar/Listas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Styling_text/Styling_lists +--- +<p>{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}</p> + +<p>Esta página descreve como você pode usar as CSS para especificar a aparência das listas.</p> + +<p>Você cria um novo documento de amostra contendo listas, e uma nova folha de estilo que estiliza as listas.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Listas" name="Informa.C3.A7.C3.A3o:_Listas">Informação: Listas</h2> + +<p>Se você resolveu o desafio da última página (<strong><a href="/pt/CSS/Como_come%C3%A7ar/Conte%C3%BAdo" title="pt/CSS/Como_começar/Conteúdo">Conteúdo</a></strong>), então você viu como você pode adicionar conteúdo antes de qualquer elemento para mostrar isto como o item de uma lista.</p> + +<p>CSS proporciona propriedades especiais que foram designadas para listas. Geralmente é mais conveniente usar estas propriedades sempre que você puder.</p> + +<p>Para especificar o estilo para uma lista, use a propriedade <code>list-style</code> para especificar o tipo de marcador.</p> + +<p>O seletor nas regras do seu CSS pode selecionar qualquer um dos elementos na sua lista de itens (por exemplo, <code>LI</code>), ou isto pode selecionar o elemento primário da lista (por exemplo, <code>UL</code>). Então os elementos da lista herdam o estilo.</p> + +<h3 id="Listas_n.C3.A3o_ordenadas" name="Listas_n.C3.A3o_ordenadas">Listas não ordenadas</h3> + +<p>Em uma lista <em>não ordenada</em>, cada item da lista é marcado da mesma maneira.</p> + +<p>CSS tem três tipos de marcador. Aqui está como seu navegador os mostra:</p> + +<ul style="padding-left: 2em;"> + <li style=""><code>disc</code></li> + <li style=""><code>circle</code></li> + <li style=""><code>square</code></li> +</ul> + +<p>Alternativamente, você pode especificar a URL de uma imagem.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Estas regras especificam diferentes marcadores para diferentes classes de itens da lista: + <div style="width: 30em;"> + <pre class="eval"> +li.open {list-style: circle;} +li.closed {list-style: disc;} +</pre> + </div> + + <p>Quando estas classes são usadas em uma lista, elas distinguem entre os itens aberto (open) e fechado (closed):</p> + + <div style="width: 30em;"> + <pre class="eval"> +<UL> + <LI class="open">Lorem ipsum</LI> + <LI class="closed">Dolor sit</LI> + <LI class="closed">Amet consectetuer</LI> + <LI class="open">Magna aliquam</LI> + <LI class="closed">Autem veleum</LI> +</UL> +</pre> + </div> + + <p>O resultado será parecido com:</p> + + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td> + <ul style="padding-right: 6em;"> + <li style="">Lorem ipsum</li> + <li style="">Dolor sit</li> + <li style="">Amet consectetuer</li> + <li style="">Magna aliquam</li> + <li style="">Autem veleum</li> + </ul> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="Listas_ordenadas" name="Listas_ordenadas">Listas ordenadas</h3> + +<p>Em uma lista <em>ordenada</em>, cada item da lista é marcado diferentemente para mostrar a posição em seqüência.</p> + +<p>Use a propriedade <code>list-style</code> para especificar o tipo de marcador:</p> + +<ul style="padding-left: 2em;"> + <li style=""><code>decimal</code></li> + <li style=""><code>lower-roman</code></li> + <li style=""><code>upper-roman</code></li> + <li style=""><code>lower-latin</code></li> + <li style=""><code>upper-latin</code></li> +</ul> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Esta regra especifica os elementos <small>OL</small> com a classe <code>info</code>, os itens são identificados com letras maiúsculas. + <div style="width: 30em;"> + <pre class="eval"> +ol.info {list-style: upper-latin;} +</pre> + </div> + + <p>Os elementos <small>LI</small> na lista herdam este estilo:</p> + + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td> + <ul> + <li style="padding-right: 6em;">Lorem ipsum</li> + <li style="padding-right: 6em;">Dolor sit</li> + <li style="padding-right: 6em;">Amet consectetuer</li> + <li style="padding-right: 6em;">Magna aliquam</li> + <li style="padding-right: 6em;">Autem veleum</li> + </ul> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>A propriedade <code>list-style</code> é uma propriedade "abreviada". Em folhas de estilo complexas você pode preferir usar propriedades separadas para configurar valores separados. Para detalhes sobre estas propriedades separadas, e mais detalhes sobre como as CSS especificam listas, veja <a class="external" href="http://www.w3.org/TR/CSS21/generate.html#q10">Lists</a> na CSS Specification. + <p>Se você está usando a linguagem de marcação como o HTML que proporciona tags convecionais para listas não ordenadas (<small>UL</small>) e ordenadas (<small>OL</small>), então é bom praticar usando tags da maneira que foi explicado. Contudo, você pode usar as CSS para fazer <small>UL</small> mostrar ordenado e <small>OL</small> para mostrar não ordenado se você precisar.</p> + + <p>Os navegadores diferem no modo como implementam os estilos das listas. Não espere que sua folha de estilo dê resultados idênticos em todos os navegadores.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Contadores" name="Contadores">Contadores</h3> + +<div style="border: 1px solid red; padding: 6px; margin: 0 0 .5em -6px; width: 100%;"> +<p><strong>Note: </strong> Alguns navegadores não suportam contadores.</p> +</div> + +<p>Você pode usar contadores para numerar quaisquer elementos, não somente itens listados. Por exemplo, em alguns documentos você pode querer numerar cabeçalhos ou parágrafos.</p> + +<p>Para especificar uma numeração, você precisa de um <em>contador</em> com um nome que você especifica.</p> + +<p>Em alguns elementos antes da contagem começar, re-inicie o contador com a propriedade <code>counter-reset</code> e o nome do seu contador. O principal dos elementos que você estiver contando é um bom lugar para isto, mas você pode usar qualquer elemento que esteja antes da lista de itens.</p> + +<p>Em cada elemento que o contador incrementar, use a propriedade <code>counter-increment</code> e o nome do seu contador.</p> + +<p>Para mostrar seu contador, adicione <code>:before</code> ou <code>:after</code> ao seletor e use a propriedade <code>content</code> (como fez na página anterior, <strong><a href="/pt/CSS/Como_come%C3%A7ar/Conte%C3%BAdo" title="pt/CSS/Como_começar/Conteúdo">Conteúdo</a></strong>).</p> + +<p>No valor da propriedade <code>content</code>, especifique <code>counter()</code> com o nome do seu contador. Opcionalmente especifique um tipo. Os tipos são como na seção passada em <strong>Listas ordenadas</strong>.</p> + +<p>Normalmente o elemento que mostra o contador também incrementa isto.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Esta regra inicializa um contador para cada elemento <small>H3</small> com a classe <code>numbered</code>: + <div style="width: 30em;"> + <pre class="eval"> +h3.numbered {counter-reset: mynum;} +</pre> + </div> + + <p>Esta regra mostra e incrementa o contador para cada elemento <small>P</small> com a classe <code>numbered</code>:</p> + + <div style="width: 30em;"> + <pre class="eval"> +p.numbered:before { + content: counter(mynum) ": "; + counter-increment: mynum; + font-weight: bold;} +</pre> + </div> + + <p>O resultado se parece com isto:</p> + + <table style="border: 2px outset #36b; padding: .5em 6em .5em 1em; background-color: white;"> + <tbody> + <tr> + <td><strong>Cabeçalho</strong> + + <p><strong>1: </strong>Lorem ipsum</p> + + <p><strong>2: </strong>Dolor sit</p> + + <p><strong>3: </strong>Amet consectetuer</p> + + <p><strong>4: </strong>Magna aliquam</p> + + <p><strong>5: </strong>Autem veleum</p> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Você não pode usar contadores a menos que você saiba que todos os que lêem o seu documento têm um navegador que os suporta. + <p>Se você puder usar contadores, eles tem a vantagem de que você pode estilizar os contadores separadamente da lista de itens. No exemplo anterior, os contadores estão em negrito mas a os itens da lista não.</p> + + <p>Você pode também usar contadores em meios mais complexos — por exemplo, para numerar seções, cabeçalhos, sub-cabeçalhos e parágrafos em documentos formais. Para detalhes, veja <a class="external" href="http://www.w3.org/TR/CSS21/generate.html#counters">Automatic counters and numbering</a> em CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Listas_denominadas" name="A.C3.A7.C3.A3o:_Listas_denominadas">Ação: Listas denominadas</h2> + +<p>Crie um novo documento HTML, <code>doc2.html</code>. Copie e cole o conteúdo daqui, tendo certeza de que você rola o mouse para pegar tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre class="eval"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<HTML> +<HEAD> +<TITLE>Documento de amostra 2</TITLE> +<LINK rel="stylesheet" type="text/css" href="style2.css"> +</HEAD> +<BODY> + +<H3 id="oceans">Os oceanos</H3> +<UL> +<LI>Ártico</LI> +<LI>Atlântico</LI> +<LI>Pacífico</LI> +<LI>Índico</LI> +<LI>Antártico</LI> +</UL> + +<H3 class="numbered">Numbered paragraphs</H3> +<P class="numbered">Lorem ipsum</P> +<P class="numbered">Dolor sit</P> +<P class="numbered">Amet consectetuer</P> +<P class="numbered">Magna aliquam</P> +<P class="numbered">Autem veleum</P> + +</BODY> +</HTML> +</pre> +</div> + +<p>Faça uma nova folha de estilo, <code>style2.css</code>. Copie e cole o conteúdo daqui:</p> + +<div style="width: 48em;"> +<pre class="eval">/* parágrafos numerados */ +h3.numbered {counter-reset: mynum;} + +p.numbered:before { + content: counter(mynum) ": "; + counter-increment: mynum; + font-weight: bold;} +</pre> +</div> + +<p>Se a disposição e o comentário não estiver ao seu gosto, mude-os.</p> + +<p>Abra o documento no seu navegador. Se o seu navegador suporta contadores, você verá algo semelhante ao exemplo abaixo. Se o seu navegador não suporta contadores, então você não verá os números (e provavelmente nem sequer os dois pontos (:)):</p> + +<table style="border: 2px outset #36b; padding: 0 6em 1em 1em; background-color: white;"> + <tbody> + <tr> + <td> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em;">Os oceanos</p> + + <ul style=""> + <li>Ártico</li> + <li>Atlântico</li> + <li>Pacífico</li> + <li>Índico</li> + <li>Antártico</li> + </ul> + + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em;">Parágrafos numerados</p> + + <p><strong>1: </strong>Lorem ipsum</p> + + <p><strong>2: </strong>Dolor sit</p> + + <p><strong>3: </strong>Amet consectetuer</p> + + <p><strong>4: </strong>Magna aliquam</p> + + <p><strong>5: </strong>Autem veleum</p> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #ffe; width: 60%;"> + <caption>Desafios</caption> + <tbody> + <tr> + <td>Adicione uma regra à sua folha de estilo, para numerar os oceanos usando numerais Romanos de i até v: + <table style="border: 2px outset #36b; padding: 0 6em 1em 1em; background-color: white;"> + <tbody> + <tr> + <td> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em;">Os oceanos</p> + + <ul style=""> + <li>Ártico</li> + <li>Atlântico</li> + <li>Pacífico</li> + <li>Índico</li> + <li>Antártico</li> + </ul> + </td> + </tr> + </tbody> + </table> + + <p><br> + Se o seu navegador suporta contadores, mude sua folha de estilo para identificar o cabeçalho com letras maiúsculas em parênteses como isto:</p> + + <table style="border: 2px outset #36b; padding: 0 6em 1em 1em; background-color: white;"> + <tbody> + <tr> + <td> + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em;">(A) Os oceanos</p> + + <p><strong>. . .</strong></p> + + <p style="font-weight: bold; font-size: 133%; margin-bottom: .3em; padding-top: .4em; padding-bottom: .16em;">(B) Parágrafos numerados</p> + + <p><strong>. . .</strong></p> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Listas" title="Talk:pt/CSS/Como_começar/Listas">Discussão</a>.</p> + +<p>Quando seu navegador exibe seu documento de amostra, cria espaços ao redor dos elementos quando eles são exibidos na página.</p> + +<p>A próxima página descreve como você pode usar as CSS para trabalhar com formas subjacentes de elementos: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Caixas" title="pt/CSS/Como_começar/Caixas">Caixas</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}</p> diff --git a/files/pt-pt/web/css/como_começar/mídia/index.html b/files/pt-pt/web/css/como_começar/mídia/index.html new file mode 100644 index 0000000000..0038962474 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/mídia/index.html @@ -0,0 +1,433 @@ +--- +title: Média +slug: Web/CSS/Como_começar/Mídia +tags: + - 'CSS:Como_começar' +translation_of: Web/Progressive_web_apps/Responsive/Media_types +--- +<p>{{ PreviousNext("CSS:Como começar:Tabelas", "CSS:Como começar:JavaScript") }}</p> + +<p>Muitas das páginas neste tutorial focalizaram nas propriedades e nos valores das CSS que você pode usar para especificar o modo de exibir o documento.</p> + +<p>Esta página mostra novamente a proposta e a estrutura das folhas de estilo CSS.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_M.C3.ADdia" name="Informa.C3.A7.C3.A3o:_M.C3.ADdia">Informação: Média</h2> + +<p>A proposta das CSS é especificar como os documentos são apresentados ao usuário. A apresentação pode tomar mais de uma forma.</p> + +<p>Por exemplo, você provavelmente está lendo esta página em um dispositivo de exibição. Mas você pode também querer projetá-lo em uma tela para uma grande audiência, ou imprimi-la. Estas diferentes mídias podem ter diferentes características. CSS proporciona maneiras para apresenter um documento diferentemente em diferentes mídias.</p> + +<p>Para especificar regras específicas para um tipo de mídia, use <code>@media</code> seguido do tipo de mídia e de chaves para incluir as regras</p> + +<table style="background-color: #fffff4; border: 1px solid #3366bb; padding: 1em; width: 100%;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Um documento em um site na web tem uma área de navegação para permitir ao usuário mover em torno do site. + <p>Na linguagem de marcação, o elemento principal da área de navegação tem o id <code>nav-area</code>.</p> + + <p>Quando o documento é impresso a área de navegação não tem propósito, então a folha de estilo remove-a completamente:</p> + + <div style="width: 30em;"> + <pre class="eval"> +@media print { + #nav-area {display: none;} + } +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<p>Alguns tipos de mídia comuns são:</p> + +<table style="margin-left: 2em;"> + <tbody> + <tr> + <td><code>screen</code></td> + <td>Exposição na tela do computador</td> + </tr> + <tr> + <td><code>print</code></td> + <td>Mídias paginadas</td> + </tr> + <tr> + <td style="padding-right: 1em;"><code>projection</code></td> + <td>Exposição projetada</td> + </tr> + <tr> + <td><code>all</code></td> + <td>Todas as mídias (o padrão)</td> + </tr> + </tbody> +</table> + +<table style="background-color: #f4f4f4; border: 1px solid #3366bb; padding: 1em; width: 100%;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Existem outras maneiras para especificar o tipo de mídia com uma série de regras. + <p>A linguagem de marcação do documento permite o tipo de mídia tornar-se específico quando a folha de estilo é ligada ao documento. Por exemplo, em HTML você pode opcionalmente especificar o tipo de mídia com o atributo <code>media</code> na tag <code>LINK</code>.</p> + + <p>Em CSS você pode usar <code>@import</code> no começo da folha de estilo para importar outras folhas de estilo de uma URL, opcionalmente especificando o tipo de mídia.</p> + + <p>Usando estas técnicas você pode separar regras de estilo para diferentes tipos de mídia em diferentes aquivos. Esta é algumas vezes uma maneira útil para estruturar sua folha de estilos.</p> + + <p>Para detalhes completos sobre tipos de mídia, veja <a class="external" href="http://www.w3.org/TR/CSS21/media.html">Media</a> em CSS Specification.</p> + + <p>Existem mais exemplos da propriedade <code>display</code> em uma página posterior neste tutorial: <a href="/pt/CSS/Como_começar/Dados_XML" title="pt/CSS/Como_começar/Dados_XML">Dados XML</a>.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Imprimindo" name="Imprimindo">Impressão</h3> + +<p>CSS possui suporte específico para impressão e para mídias paginadas em geral.</p> + +<p>Uma regra <code>@page</code> pode configurar as margens da página. Para imprimir frente e verso, você pode especificar as margens separadamente para <code>@page:left</code> e <code>@page:right</code>.</p> + +<p>Para mídias impressas, você normalmente usa unidades de comprimento apropriadas em polegadas (<code>in</code>) e pontos (<code>pt</code> = 1/72 polegadas), ou centímetros (<code>cm</code>) e milímetros (<code>mm</code>). É igualmente apropriado o uso de ems (<code>em</code>) para combinar tamanhos de fontes, e porcentagens (<code>%</code>).</p> + +<p>Você pode controlar como o conteúdo do documento quebra através de limites de página, usando as propriedades <code>page-break-before</code>, <code>page-break-after</code> e <code>page-break-inside</code>.</p> + +<table style="background-color: #fffff4; border: 1px solid #3366bb; padding: 1em; width: 100%;"> + <caption>Exemplos</caption> + <tbody> + <tr> + <td>Esta regra configura as margens da página para uma polegada em todos os quatro lados: + <div style="width: 30em;"> + <pre class="eval"> +@page {margin: 1in;} +</pre> + </div> + + <p>Esta regra assegura que todos os elementos <small>H1</small> comecem em uma nova página:</p> + + <div style="width: 30em;"> + <pre class="eval"> +h1 {page-break-before: always;} +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<table style="background-color: #f4f4f4; border: 1px solid #3366bb; padding: 1em; width: 100%;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Para detalhes completos sobre o suporte das CSS para páginas de mídia, veja <a class="external" href="http://www.w3.org/TR/CSS21/page.html">Paged media</a> em CSS Specification. + <p>Como outras características das CSS, imprimir depende do seu navegador e de suas configurações. Por exemplo, seu navegador Mozilla proporciona por padrão margens, cabeçalhos e rodapés quando é impresso. Quando outros usuários imprimem seu documento, você provavelmente não poderá predizer o navegador e as configurações que eles usarão, então você provavelmente não poderá controlar os resultados completamente.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="Interfaces_de_usu.C3.A1rio" name="Interfaces_de_usu.C3.A1rio">Interfaces do utilizador</h3> + +<p>CSS tem algumas propriedades especiais para dispositivos que suportem a interface de usuário, como a tela do computador. Isto faz a aparência do documento mudar dinamicamente como o usuário trabalha com a interface.</p> + +<p>Não existe um tipo de mídia especial para dispositivos com interfaces de usuários.</p> + +<p>Existem cinco seletores especiais:</p> + +<table style="margin-left: 2em;"> + <tbody> + <tr> + <td style="width: 10em;"><strong>Seletor</strong></td> + <td><strong>Seleciona</strong></td> + </tr> + <tr> + <td><code>E:hover</code></td> + <td>Qualquer elemento E que tenha um ponteiro sobre ele</td> + </tr> + <tr> + <td><code>E:focus</code></td> + <td>Qualquer elemento E que tenha um foco no teclado</td> + </tr> + <tr> + <td><code>E:active</code></td> + <td>O elemento E que é envolvido na corrente ação do usuário</td> + </tr> + <tr> + <td><code>E:link</code></td> + <td>Qualquer elemento E que seja um hiperlink para uma URL que o usuário <em>não visitou</em> recentemente</td> + </tr> + <tr> + <td><code>E:visited</code></td> + <td>Qualquer elemento E que seja um hiperlink para uma URL que o usuário <em>visitou</em> recentemente</td> + </tr> + </tbody> +</table> + +<p>A propriedade <code>cursor</code> especifica a forma do ponteiro: Algumas das formas comuns são como segue. Coloque seu mouse sobre os itens nesta lista para ver as formas comuns dos ponteiros no seu navegador:</p> + +<table style="margin-left: 2em;"> + <tbody> + <tr> + <td style="width: 10em;"><strong>Seletor</strong></td> + <td><strong>Seleciona</strong></td> + </tr> + <tr style="cursor: pointer;"> + <td><code>pointer</code></td> + <td>Indica um link</td> + </tr> + <tr style="cursor: wait;"> + <td><code>wait</code></td> + <td>Indica que o programa não pode aceitar a entrada</td> + </tr> + <tr style="cursor: progress;"> + <td><code>progress</code></td> + <td>Indica que o programa está trabalhando, mas ainda pode aceitar a entrada</td> + </tr> + <tr style="cursor: default;"> + <td><code>default</code></td> + <td>O padrão (usualmente uma flecha)</td> + </tr> + </tbody> +</table> + +<p><br> + Uma propriedade <code>outline</code> cria um contorno que é normalmente usado para indicar foco do teclado. Estes valores são similares aos da propriedade <code>border</code>, exceto que você não pode especificar lados individuais.</p> + +<p>Algumas outras características das interfaces de usuário são implementadas usando atributos, de uma maneira normal. Por exemplo, um elemento que está desabilitado ou somente leitura tem o atributo <code>disabled</code> ou o atributo <code>readonly</code>. Seletores podem especificar estes atributos como qualquer outros atributos, usando colchetes: <code>{{ mediawiki.external('disabled') }}</code> ou <code>{{ mediawiki.external('readonly') }}</code>.</p> + +<table style="background-color: #fffff4; border: 1px solid #3366bb; padding: 1em; width: 100%;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Estas regras especificam estilos para um botão que muda dinamicamente como a interação do usuário com isso: + <div style="width: 30em;"> + <pre> +.green-button { + background-color:#cec; + color:#black; + border:2px outset #cec; + } + +.green-button[disabled] { + background-color:#cdc; + color:#777; + } + +.green-button:active { + border-style: inset; + } +</pre> + </div> + + <p>Este wiki não suporta uma interface de usuário na página, então estes botões não são "clicáveis". Aqui estão algumas imagens estáticas para ilustrar a idéia:</p> + + <table style="background-color: #ffffff; border: 2px outset #3366bb; padding: 1em;"> + <tbody> + <tr> + <td> + <table> + <tbody> + <tr> + <td><span style="background-color: #ccddcc; border: 2px outset #cceecc; color: #777777; cursor: default; height: 2em; margin-right: 1em; padding: .5em 1em; width: 8em;">Clique Aqui</span></td> + <td><span style="background-color: #cceecc; border: 2px outset #cceecc; cursor: move; height: 2em; margin-right: 1em; padding: .5em 1em; width: 8em;">Clique Aqui</span></td> + <td><span style="background-color: #cceecc; border: 2px inset #cceecc; cursor: move; height: 2em; margin-right: 1em; padding: .5em 1em; width: 8em;">Clique Aqui</span></td> + </tr> + <tr style="line-height: 25%;"> + <td> </td> + </tr> + <tr style="font-style: italic;"> + <td>desativado</td> + <td>normal</td> + <td>ativo</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + + <p>Um botão plenamente funcional também tem um contorno escuro em toda a sua volta quando isto é o padrão, e um contorno pontilhado na face do botão quando ele é focado pelo teclado. Isto pode também ter um efeito quando o ponteiro está sobre ele.</p> + </td> + </tr> + </tbody> +</table> + +<table style="background-color: #f4f4f4; border: 1px solid #3366bb; margin-bottom: 1em; padding: 1em; width: 100%;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Para mais informações sobre interfaces de usuário em CSS, veja <a class="external" href="http://www.w3.org/TR/CSS21/ui.html">User interface</a> em CSS Specification. + <p>Existe um exemplo da linguagem de marcação Mozilla para interfaces de usuário, XUL, na segunda parte deste tutorial.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Imprimindo_um_documento" name="A.C3.A7.C3.A3o:_Imprimindo_um_documento">Ação: Imprimir um documento</h2> + +<p>Crie um novo documento HTML, <code>doc4.html</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela para pegar tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<HTML> + +<HEAD> +<TITLE>Impressão de amostra</TITLE> +<LINK rel="stylesheet" type="text/css" href="style4.css"></strong> +</HEAD> + +<BODY> +<H1>Seção A</H1> +<P>Esta é a primeira seção...</P> + +<H1>Seção B</H1> +<P>Esta é a segunda seção...</P> + +<DIV id="print-head"> +Dirigir para mídias paginadas +</DIV> + +<DIV id="print-foot"> +Página: +</DIV> + +</BODY> +</HTML> +</pre> +</div> + +<p>Crie uma nova folha de estilo, <code>style4.css</code>. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela para pegar tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre>/*** Impressão de amostra ***/ + +/* Padrão para a tela */ +#print-head, +#print-foot { + display: none; + } + +/* Somente impressão */ +@media print { + +h1 { + page-break-before: always; + padding-top: 2em; + } + +h1:first-child { + page-break-before: avoid; + counter-reset: page; + } + +#print-head { + display: block; + position: fixed; + top: 0pt; + left:0pt; + right: 0pt; + + font-size: 200%; + text-align: center; + } + +#print-foot { + display: block; + position: fixed; + bottom: 0pt; + right: 0pt; + + font-size: 200%; + } + +#print-foot:after { + content: counter(page); + counter-increment: page; + } + +} /* Fim de somente impressão */ +</pre> +</div> + +<p>Quando você exibe este documento em seu navegador, ele usa o estilo padrão do navegador.</p> + +<p>Quando você imprime (ou prevê a impressão) do documento, a folha de estilo coloca cada seção em uma página separada, e adiciona um cabeçalho e um rodapé para cada página. Se o seu navegador suportar contadores, isto adiciona um número na página no seu rodapé.</p> + +<table> + <tbody> + <tr> + <td> + <table style="border: 2px outset #3366bb; padding: 1em;"> + <tbody> + <tr> + <td> + <table style="margin-right: 2em; width: 15em;"> + <tbody> + <tr> + <td> + <div style="font-size: 150%; text-align: center; margin-bottom: .5em;">Cabeçalho</div> + + <div style="font-size: 150%; font-weight: bold;">Secção A</div> + + <div style="font-size: 75%;">Esta é a primeira secção...</div> + + <div style="font-size: 150%; text-align: right; margin-top: 12em;">Página: 1</div> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + <td> + <table style="border: 2px outset #3366bb; padding: 1em;"> + <tbody> + <tr> + <td> + <table style="margin-right: 2em; width: 15em;"> + <tbody> + <tr> + <td> + <div style="font-size: 150%; text-align: center; margin-bottom: .5em;">Cabeçalho</div> + + <div style="font-size: 150%; font-weight: bold;">Secção B</div> + + <div style="font-size: 75%;">Esta é a segunda secção...</div> + + <div style="font-size: 150%; text-align: right; margin-top: 12em;">Página: 2</div> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<table style="background-color: #fffff4; border: 1px solid #3366bb; padding: 1em; width: 100%;"> + <caption>Desafios</caption> + <tbody> + <tr> + <td>Mova o estilo específico de impressão para um arquivo CSS separado. + <p>Use as ligações nesta página para ler a CSS Specification. Ache detalhes de como importar o novo arquivo CSS específico para impressão em sua folha de estilo.</p> + + <p>Faça os cabeçalhos serem azuis quando o ponteiro do mouse estiver sobre eles.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/M%C3%ADdia" title="Talk:pt/CSS/Como_começar/Mídia">Discussão</a>.</p> + +<p>Até agora, todas as regras de estilo neste tutorial foram especificadas em arquivos. As regras e seus volumes são fixos. A próxima página descreve como você muda as regras dinamicamente usando uma linguagem de programação: <strong><a href="/pt/CSS/Como_come%C3%A7ar/JavaScript" title="pt/CSS/Como_começar/JavaScript">JavaScript</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Tabelas", "CSS:Como começar:JavaScript") }}</p> diff --git a/files/pt-pt/web/css/como_começar/o_que_é_css/index.html b/files/pt-pt/web/css/como_começar/o_que_é_css/index.html new file mode 100644 index 0000000000..a87487b3a3 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/o_que_é_css/index.html @@ -0,0 +1,134 @@ +--- +title: O que é CSS +slug: Web/CSS/Como_começar/O_que_é_CSS +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +<p>{{Next("CSS:Como começar:Porque usar CSS")}}</p> + +<p>Esta página explica o que é CSS. Você cria um documento de amostra para que possa trabalhar com as páginas seguintes.</p> + +<h3 id="Informa.C3.A7.C3.B5es:_O_que_.C3.A9_CSS.3F" name="Informa.C3.A7.C3.B5es:_O_que_.C3.A9_CSS.3F">Informações: O que é CSS?</h3> + +<p>CSS é uma linguagem que especifica como os documentos são apresentados aos usuários.</p> + +<p>Um <em>documento</em> é uma coleção de informações estruturadas utilizando uma <em>linguagem de marcação</em>.</p> + +<table style="background-color: #fffff4; border: 1px solid #36b; margin-bottom: 1em; padding: 1em;"> + <caption>Exemplos</caption> + <tbody> + <tr> + <td> + <ul> + <li>Uma página da Web como esta é um documento.<br> + As informações que você vê em uma página da Web, geralmente, é estruturada utilizando a linguagem de marcação HTML (HyperText Markup Language - Linguagem de Marcação de Hiper Texto).</li> + </ul> + + <ul> + <li>Uma caixa de diálogo em um aplicativo Mozilla é um documento.<br> + A interface com o usuário controla o que aparece em uma caixa de diálogo Mozilla, que é estruturada utilizando a linguagem de marcação XUL (XML User-interface Language - Linguagem de Interface do Usuário XML).</li> + </ul> + </td> + </tr> + </tbody> +</table> + +<p>Neste tutorial, os quadros entitulados <strong>Mais detalhes</strong> como este logo abaixo, contêm informações opcionais. Se você está com pressa para progredir no tutorial, você pode ignorar esses quadros, retornando para lê-los posteriormente. Caso contrário, leia-os ao encontrá-los, e talvez siga os links para aprender mais.</p> + +<table style="background-color: #f4f4f4; border: 1px solid #36b; margin-bottom: 1em; padding: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td> + <p>Um documento não é igual a um arquivo. Ele pode ou não ser armazenado em um arquivo.</p> + + <p>Por exemplo, o documento que você está lendo agora não está armazendo em um arquivo. Quando seu navegador da Web solicita esta página, o servidor consulta um banco de dados e gera o documento, reunindo partes do documento a partir de muitos arquivos. Entretanto, neste tutorial você vai trabalhar com documentos que estão armazenados em arquivos.</p> + + <p>Para mais informações sobre documentos e linguagens de marcação, consulte outras partes deste Web site — por exemplo:</p> + + <table style="background-color: inherit; margin-left: 2em;"> + <tbody> + <tr> + <td><a href="/pt/HTML" title="pt/HTML">HTML</a></td> + <td>para páginas da Web</td> + </tr> + <tr> + <td><a href="/pt/XML" title="pt/XML">XML</a></td> + <td>para documentos estruturados em geral</td> + </tr> + <tr> + <td><a href="/pt/SVG" title="pt/SVG">SVG</a></td> + <td>para gráficos</td> + </tr> + <tr> + <td><a href="/pt/XUL" title="pt/XUL">XUL</a></td> + <td>para interfaces com o usuário no Mozilla</td> + </tr> + </tbody> + </table> + + <p>Na Parte II deste tutorial você verá exemplos dessas linguagens de marcação.</p> + </td> + </tr> + </tbody> +</table> + +<p><em>Apresentar</em> um documento a um usuário significa convertê-lo para uma forma que humanos possam usá-lo. O Mozilla é projetado para apresentar documentos visualmente — por exemplo, em uma tela de computador, projetor ou impressora.</p> + +<table style="background-color: #f4f4f4; border: 1px solid #36b; margin-bottom: 1em; padding: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>CSS não serve apenas para navegadores e apresentação visual. Em uma terminologia formal de CSS, o programa que apresenta um documento ao usuário é chamado de <em>agente usuário</em> (UA - User Agent). Um navegador é apenas um tipo de UA. Entretanto, na Parte I deste tutorial você irá trabalhar apenas com CSS em um navegador. + <p>Para mais definições formais de terminologia sobre CSS, consulte <a class="external" href="http://www.w3.org/TR/CSS21/conform.html#q1">Definitions</a> na CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="A.C3.A7.C3.A3o:_Criando_um_documento" name="A.C3.A7.C3.A3o:_Criando_um_documento">Ação: Criando um documento</h3> + +<p>Utilize seu computador para criar um novo diretório e um novo arquivo de texto dentro dele. O arquivo irá conter seu documento.</p> + +<p>Copie e cole o código HTML mostrado abaixo. Salve o arquivo utilizando o nome <code>doc1.html</code></p> + +<div style="width: 40em;"> +<pre><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<html> + <head> + <title>Documento de amostra</title> + </head> + + <body> + <p> + <strong>C</strong>ascading + <strong>S</strong>tyle + <strong>S</strong>heets + </p> + </body> +</html> +</pre> +</div> + +<p>Em seu navegador, abra uma aba ou uma nova janela, e abra o arquivo do diretório.</p> + +<p>Você deve ver o texto com as iniciais em negrito, conforme abaixo:</p> + +<table style="border: 2px outset #36b; padding: 1em;"> + <tbody> + <tr> + <td><strong>C</strong>ascading <strong>S</strong>tyle <strong>S</strong>heets</td> + </tr> + </tbody> +</table> + +<p>O que você vê em seu navegador pode não ser exatamente como o exibido aqui, por causa das configurações de seu navegador e deste wiki. Se houver diferenças na fonte, espaçamento ou cor, não há importância.</p> + +<h4 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h4> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/O_que_%C3%A9_CSS" title="Talk:pt/CSS/Como_começar/O_que_é_CSS">Discussão</a>.</p> + +<p>Seu documento ainda não utiliza CSS. Na página a seguir você utilizará CSS para especificar o estilo: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Porque_usar_CSS" title="pt/CSS/Como_começar/Porque_usar_CSS">Porque usar CSS</a></strong></p> + +<p>{{Next("CSS:Como começar:Porque usar CSS")}}</p> diff --git a/files/pt-pt/web/css/como_começar/o_que_é_css_question_/index.html b/files/pt-pt/web/css/como_começar/o_que_é_css_question_/index.html new file mode 100644 index 0000000000..d386670557 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/o_que_é_css_question_/index.html @@ -0,0 +1,94 @@ +--- +title: O que é CSS? +slug: Web/CSS/Como_começar/O_que_é_CSS? +tags: + - 'CSS:Como_começar' +--- +<p> +</p><p>This page explains what CSS is. +You create a simple document that you will work with on the following pages. +</p> +<h3 id="Information:_What_is_CSS.3F" name="Information:_What_is_CSS.3F"> Information: What is CSS? </h3> +<p>CSS is a language for specifying how documents are presented to users. +</p><p>A <i>document</i> is a collection of information that is structured using a <i>markup language</i>. +</p> +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> +<caption>Examples +</caption><tbody><tr> +<td> +<ul><li>A web page like this one is a document.<br>The information that you see in a web page is usually structured using the markup language HTML (HyperText Markup Language). +</li></ul> +<ul><li>A dialog in a Mozilla application is a document.<br>The user interface controls that you see in a Mozilla dialog are structured using the markup language XUL (XML User-interface Language). +</li></ul> +</td></tr></tbody></table> +<p>In this tutorial, boxes captioned <b>More details</b> like the one below contain optional information. +If you are in a hurry to progress with the tutorial then you could skip these boxes, perhaps returning to read them later. Otherwise read them when you come to them, and perhaps follow the links to learn more. +</p> +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> +<caption>More details +</caption><tbody><tr> +<td> +<p>A document is not the same as a file. It might or might not be stored in a file. +</p><p>For example, the document that you are reading now is not stored in a file. When your web browser requests this page, the server queries a database and generates the document, gathering parts of the document from many files. However, in this tutorial you will work with documents that are stored in files. +</p><p>For more information about documents and markup languages, see other parts of this web site—for example: +</p> +<table style="background-color: inherit; margin-left: 2em;"> +<tbody><tr> +<td><a href="pt/HTML">HTML</a></td><td>for web pages +</td></tr> +<tr> +<td><a href="pt/XML">XML</a></td><td>for structured documents in general +</td></tr> +<tr> +<td><a href="pt/SVG">SVG</a></td><td>for graphics +</td></tr> +<tr> +<td><a href="pt/XUL">XUL</a></td><td>for user interfaces in Mozilla +</td></tr></tbody></table> +<p>In Part II of this tutorial you will see examples of these markup languages. +</p> +</td></tr></tbody></table> +<p><i>Presenting</i> a document to a user means converting it into a form that humans can make use of. Mozilla is designed to present documents visually—for example, on a computer screen, projector or printer. +</p> +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> +<caption>More details +</caption><tbody><tr> +<td> CSS is not just for browsers, and not just for visual presentation. In formal CSS terminology, the program that presents a document to a user is called a <i>user agent</i> (UA). A browser is just one kind of UA. However, in Part I of this tutorial you will only work with CSS in a browser. +<p>For some formal definitions of terminology relating to CSS, see <a class="external" href="http://www.w3.org/TR/CSS21/conform.html#q1">Definitions</a> in the CSS Specification. +</p> +</td></tr></tbody></table> +<h3 id="Action:_Creating_a_document" name="Action:_Creating_a_document"> Action: Creating a document </h3> +<p>Use your computer to create a new directory and a new text file there. +The file will contain your document. +</p><p>Copy and paste the HTML shown below. Save the file using the name <code>doc1.html</code> +</p> +<div style="width: 40em;"><pre><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<html> + <head> + <title>Sample document</title> + </head> + + <body> + <p> + <strong>C</strong>ascading + <strong>S</strong>tyle + <strong>S</strong>heets + </p> + </body> +</html> +</pre></div> +<p>In your browser, open a new tab or a new window, and open the file there. +</p><p>You should see the text with the initial letters bold, like this: +</p> +<table style="border: 2px outset #36b; padding: 1em;"> +<tbody><tr> +<td> <strong>C</strong>ascading <strong>S</strong>tyle <strong>S</strong>heets +</td></tr></tbody></table> +<p>What you see in your browser might not look exactly the same as this, because of settings in your browser and in this wiki. If there are some differences in the font, spacing and colors that you see, they are not important. +</p> +<h4 id="What_next.3F" name="What_next.3F"> What next? </h4> +<p>If you had difficulty understanding this page, or if you have other comments about it, please contribute to its <a>Discussion</a> page. +</p><p>Your document does not yet use CSS. +On the next page you use CSS to specify its style: +<b><a href="pt/CSS/Getting_Started/Why_use_CSS%3f">Why use CSS?</a></b> +</p>{{ languages( { "en": "en/CSS/Getting_Started/What_is_CSS", "fr": "fr/CSS/Premiers_pas/Pr\u00e9sentation_des_CSS", "it": "it/Conoscere_i_CSS/Che_cosa_sono_i_CSS", "ja": "ja/CSS/Getting_Started/What_is_CSS", "pl": "pl/CSS/Na_pocz\u0105tek/Czym_jest_CSS", "zh-cn": "cn/CSS/Getting_Started/What_is_CSS" } ) }} diff --git a/files/pt-pt/web/css/como_começar/porque_usar_css/index.html b/files/pt-pt/web/css/como_começar/porque_usar_css/index.html new file mode 100644 index 0000000000..fad0fc8ea8 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/porque_usar_css/index.html @@ -0,0 +1,110 @@ +--- +title: Porque usar CSS +slug: Web/CSS/Como_começar/Porque_usar_CSS +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +<p>{{ PreviousNext("CSS:Como começar:O que é CSS", "CSS:Como começar:Como o CSS trabalha") }}</p> + +<p>Esta página explica porque os documentos usam CSS. Você usa CSS para adicionar uma folha de estilo ao seu documento de amostra.</p> + +<h2 id="Informa.C3.A7.C3.B5es:_Por_que_usar_CSS.3F" name="Informa.C3.A7.C3.B5es:_Por_que_usar_CSS.3F">Informações: Por que usar CSS?</h2> + +<p>CSS ajuda a manter o conteúdo das informações de um documento separado dos detalhes de como exibí-lo. Os detalhes de como exibir o documento são conhecidos como <em>estilo</em>. Você mantém o estilo separado do conteúdo, de modo que você pode:</p> + +<ul> + <li>Evitar duplicação</li> + <li>Tornar a manutenção mais fácil</li> + <li>Utilizar o conteúdo com diferentes estilos para diferentes propósitos</li> +</ul> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Seu Web site pode ter milhares de páginas similares. Utilizando CSS, você armazena as informações em arquivos comuns que todas as páginas compartilham. + <p>Quando um usuário exibe uma página da Web, o navegador do usuário carrega as informações de estilo junto com o conteúdo da página.</p> + + <p>Quando um usuário imprime uma página da Web, você fornece informações de estilo diferentes que tornam a página impressa mais fácil de ler.</p> + </td> + </tr> + </tbody> +</table> + +<p>Geralmente, com CSS, você utiliza a linguagem de marcação para descrever o conteúdo das informações do documento, não seu estilo. Você utiliza CSS para especificar o estilo, não o conteúdo. (Posteriormente neste tutorial, você verá algumas exceções deste método.)</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Uma linguagem de marcação, como o HTML, também fornece alguns modos de especificar o estilo. + <p>Por exemplo, em HTML, você pode usar uma tag <code><b></code> para tornar o texto negrito, e você pode especificar a cor do segundo plano de uma página na tag <code><body></code>.</p> + + <p>Ao utilizar CSS, você normalmente evita utilizar esses recursos da linguagem de marcação para que todas as informações de estilo de seu documento estejam em um só lugar.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Criando_uma_folha_de_estilo" name="A.C3.A7.C3.A3o:_Criando_uma_folha_de_estilo">Ação: Criando uma folha de estilo</h2> + +<p>Crie outro arquivo de texto no mesmo diretório do anterior. Este arquivo será sua folha de estilo. Nomeie-o como: <code>style1.css</code></p> + +<p>Em seu arquivo CSS, copie e cole esta única linha, então salve o arquivo:</p> + +<div style="width: 40em;"> +<pre class="eval">strong {color: red;} +</pre> +</div> + +<h4 id="Ligando_seu_documento_.C3.A0_sua_folha_de_estilo" name="Ligando_seu_documento_.C3.A0_sua_folha_de_estilo">Ligando seu documento à sua folha de estilo</h4> + +<p>Para ligar seu documento com sua folha de estilo, edite seu aquivo HTML. Adicione a linha mostrada aqui em negrito:</p> + +<div style="width: 40em; color: gray;"> +<pre class="eval"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<HTML> + <HEAD> + <TITLE>Documento de amostra</TITLE> + <strong style="color: black;"><LINK rel="stylesheet" type="text/css" href="style1.css"></strong> + </HEAD> + <BODY> + <P> + <STRONG>C</STRONG>ascading + <STRONG>S</STRONG>tyle + <STRONG>S</STRONG>heets + </P> + </BODY> +</HTML> +</pre> +</div> + +<p>Salve o arquivo e atualize a tela do seu navegador. A folha de estilo fez as letras iniciais aparecerem em vermelha, como isto:</p> + +<table style="border: 2px outset #36b; padding: 1em;"> + <tbody> + <tr> + <td><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4;"> + <caption>Desafio</caption> + <tbody> + <tr> + <td>Além do vermelho, CSS permite algumas outras cores com nomes. + <p>Sem olhar um referência, ache mais cinco nomes de cores que trabalham em sua folha de estilo.</p> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Porque_usar_CSS" title="Talk:pt/CSS/Como_começar/Porque_usar_CSS">Discussão</a>.</p> + +<p>Agora você tem um documento de amostra ligado a uma folha de estilo separada, você está pronto para ler mais sobre como seu navegador combina-os quando exibe o documento na tela: <strong><a href="/pt/CSS/Como_come%C3%A7ar/Como_o_CSS_trabalha" title="pt/CSS/Como_começar/Como_o_CSS_trabalha">Como o CSS trabalha</a></strong>.</p> + +<p>{{ PreviousNext("CSS:Como começar:O que é CSS", "CSS:Como começar:Como o CSS trabalha") }}</p> diff --git a/files/pt-pt/web/css/como_começar/seletores/index.html b/files/pt-pt/web/css/como_começar/seletores/index.html new file mode 100644 index 0000000000..250eb58d3f --- /dev/null +++ b/files/pt-pt/web/css/como_começar/seletores/index.html @@ -0,0 +1,207 @@ +--- +title: Seletores +slug: Web/CSS/Como_começar/Seletores +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Selectors +--- +<p>{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}</p> + +<p>Esta página explica como você pode aplicar estilos seletivamente, e como diferentes tipos de seletor têm propriedades diferentes.</p> + +<p>Você adiciona alguns atributos às tags do seu documento de amostra, e usa estes atributos em sua folha de estilo de amostra.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Seletores" name="Informa.C3.A7.C3.A3o:_Seletores">Informação: Seletores</h2> + +<p>CSS tem sua própria terminologia para descrever a linguagem CSS. Anteriormente neste tutorial, você criou uma linha em sua folha de estilo com esta:</p> + +<div style="width: 30em;"> +<pre>strong {color: red;} +</pre> +</div> + +<p>Na terminologia das CSS, esta linha inteira é uma <em>regra</em>. Esta regra começa com <code>STRONG</code>, que é um <em>seletor</em>. Isto seleciona que elementos no DOM a regra se aplicará.</p> + +<table style="border: 1px solid #36b; background-color: #f4f4f4; padding: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>A parte interior das chaves é a <em>declaração</em>. + <p>A palavra-chave <code>color</code> é uma <em>propriedade</em>, e <code>red</code> é um <em>valor</em>.</p> + + <p>O ponto-e-vírgula depois do par propriedade-valor separa isto de outros pares propriedade-valor na mesma descrição.</p> + + <p>Este tutorial refere-se a um seletor <code>STRONG</code>, como um seletor de <em>tag</em>. A Especificação das CSS refere-se a isto como um seletor de <em>tipo</em>.</p> + </td> + </tr> + </tbody> +</table> + +<p>Esta página do tutorial explica mais sobre os seletores que você pode usar nas regras das CSS.</p> + +<p>Em adição aos nomes de tags, você pode usar valores de atributo nos seletores. Isto permite a você que as regras tornem-se mais específicas.</p> + +<p>Dois atributos tem estado especial para as CSS. Eles são <code>class</code> e <code>id</code>.</p> + +<p>Use o atributo <code>class</code> em uma tag para nomear a tag com um nome de classe. Isto é, o nome que você escolher para a classe.</p> + +<p>Na sua folha de estilo, digite um registro completo (período) antes do nome de classe quando você usá-lo em um seletor.</p> + +<p>Use o atributo <code>id</code> em uma tag para nomear a tag com um nome de id. Isto é, o nome que você escolher para o id. O nome do id deve ser único no documento.</p> + +<p>Na sua folha de estilo, digite um sinal de número (#) antes do id quando você usá-lo em um seletor.</p> + +<table style="border: 1px solid #36b; background-color: #ffe; padding: 1em;"> + <caption>Exemplos</caption> + <tbody> + <tr> + <td>Este tag HTML tem ambos os atributos <code>class</code> e <code>id</code>. + <div style="width: 30em;"> + <pre> +<P class="key" id="principal"> +</pre> + </div> + + <p>O id, <code>principal</code>, deve ser o único no documento, mas outras tags no documento podem ter o mesmo nome de classe, <code>key</code>.</p> + + <p>Em uma folha de estilo CSS, esta regra faz todos os elementos da classe <code>key</code> verdes. (Eles podem não ser todos elementos <small>P</small>.)</p> + + <div style="width: 30em;"> + <pre> +.key {color: green;} +</pre> + </div> + + <p>Esta regra faz um elemento com o id <code>principal</code> negrito:</p> + + <div style="width: 30em;"> + <pre> +#principal {font-weight: bolder;} +</pre> + </div> + </td> + </tr> + </tbody> +</table> + +<p>Se mais de uma regra se aplicar a um elemento e especificar a mesma propriedade, então CSS dará prioridade para a regra que tiver o seletor mais específico. Um seletor id é mais específíco que um seletor classe, que por sua vez é mais específico que um seletor tag.</p> + +<table style="border: 1px solid #36b; background-color: #f4f4f4; padding: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Você pode combinar seletores para fazer um seletor mais específico. + <p>Por exemplo, o seletor <code>.key</code> seleciona todos os elementos que tem o nome de classe <code>key</code>. O seletor <code>p.key</code> seleciona somente os elementos P que tiverem o nome de classe <code>key</code>.</p> + + <p>Você não está restrito aos dois atributos especiais, <code>class</code> e <code>id</code>. Você pode especificar outros atributos igualando entre colchetes. Por exemplo, o seletor <code>{{ mediawiki.external('type=button') }}</code> seleciona todos os elementos que tiverem um atributo <code>type</code> com o valor <code>button</code>.</p> + + <p>Uma página posterior deste tutorial (<a href="/pt/CSS/Como_come%C3%A7ar/Tabelas" title="pt/CSS/Como_começar/Tabelas">Tabelas</a>) tem informações sobre seletores complexos baseados em parentescos.</p> + + <p>Para um informação completa sobre seletores, veja <a class="external" href="http://www.w3.org/TR/CSS21/selector.html">Selectors</a> na CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<p>Se sua folha de estilo tiver regras conflitantes e elas estiverem igualmente especificadas, então CSS dará prioridade para a regra que foi especificada por último na folha de estilo.</p> + +<p>Quando você tiver um problema com regras conflitantes, tente resolvê-lo fazendo uma das regras mais especificada, então ela terá prioridade. Se você não puder fazer isto, tente mover uma das regras para mais perto do fim da folha de estilo, então esta terá prioridade.</p> + +<h3 id="A.C3.A7.C3.A3o:_Usando_seletores_de_classe_e_id" name="A.C3.A7.C3.A3o:_Usando_seletores_de_classe_e_id">Ação: Usando seletores de classe e id</h3> + +<p>Edite seu arquivo HTML, e duplique o paragrafo copiando e colando-o. Então adicione os atributos de id e classe na primeira cópia, e um id na segunda cópia como mostrado abaixo. Um alternativa é copiar e colar o arquivo inteiro novamente:</p> + +<div style="width: 48em; color: gray;"> +<pre class="eval"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<HTML> + <HEAD> + <TITLE>Documento de amostra</TITLE> + <LINK rel="stylesheet" type="text/css" href="style1.css"> + </HEAD> + <BODY> + <P <strong style="color: black;">id="first"</strong>> + <STRONG <strong style="color: black;">class="carrot"</strong>>C</STRONG>ascading + <STRONG <strong style="color: black;">class="spinach"</strong>>S</STRONG>tyle + <STRONG <strong style="color: black;">class="spinach"</strong>>S</STRONG>heets + </P> + <strong style="color: black;"><P id="second"> + <STRONG>C</STRONG>ascading + <STRONG>S</STRONG>tyle + <STRONG>S</STRONG>heets + </P></strong> + </BODY> +</HTML> +</pre> +</div> + +<p>Agora edite seu arquivo CSS. Substitua os componentes inteiros com:</p> + +<div style="width: 40em;"> +<pre>strong {color: red;} +.carrot {color: orange;} +.spinach {color: green;} +#first {font-style: italic;} +</pre> +</div> + +<p><br> + Atualize seu navegador para ver o resultado:</p> + +<table style="border: 2px outset #36b; padding: 1em;"> + <tbody> + <tr> + <td style="font-style: italic;"><strong style="color: orange;">C</strong>ascading <strong style="color: green;">S</strong>tyle <strong style="color: green;">S</strong>heets</td> + </tr> + <tr> + <td><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> +</table> + +<p><br> + Você pode tentar re-dispor as linhas no seu arquivo CSS para mostrar que a ordem não muda o efeito.</p> + +<p>Os seletores de classe <code>.carrot</code> e <code>.spinach</code> tem prioridade sobre o seletor de tag <code>STRONG</code>.</p> + +<p>O seletor id <code>#first</code> tem prioridade sobre a classe o os seletores de tag.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4;"> + <caption>Desafios</caption> + <tbody> + <tr> + <td>Sem mudar seu arquivo HTML, adicione uma única regra para seu arquivo CSS deixando todas as letras iniciais da mesma cor que estão agora, mas fazendo todo o segundo parágrafo aparecer em azul: + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td style="font-style: italic;"><strong style="color: orange;">C</strong>ascading <strong style="color: green;">S</strong>tyle <strong style="color: green;">S</strong>heets</td> + </tr> + <tr> + <td style="color: blue;"><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> + </table> + + <p>Agora mude a regra que você acabou de adicionar (sem mudar mais nenhuma coisa), para fazer o primeiro parágrafo em azul também:</p> + + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td style="font-style: italic; color: blue;"><strong style="color: orange;">C</strong>ascading <strong style="color: green;">S</strong>tyle <strong style="color: green;">S</strong>heets</td> + </tr> + <tr> + <td style="color: blue;"><strong style="color: red;">C</strong>ascading <strong style="color: red;">S</strong>tyle <strong style="color: red;">S</strong>heets</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Seletores" title="Talk:pt/CSS/Como_começar/Seletores">Discussão</a>.</p> + +<p>Sua folha de estilo de amostra está começando a parecer densa e complicada. A próxima página descreve caminhos para fazer o CSS mais fácil de ler: <strong><a href="/pt/CSS/Como_come%C3%A7ar/CSS_leg%C3%ADvel" title="pt/CSS/Como_começar/CSS_legível">CSS legível</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}</p> diff --git a/files/pt-pt/web/css/como_começar/tabelas/index.html b/files/pt-pt/web/css/como_começar/tabelas/index.html new file mode 100644 index 0000000000..c8daefb048 --- /dev/null +++ b/files/pt-pt/web/css/como_começar/tabelas/index.html @@ -0,0 +1,654 @@ +--- +title: Tabelas +slug: Web/CSS/Como_começar/Tabelas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Styling_tables +--- +<p>{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}</p> + +<p>Esta página descreve seletores mais avançados, e algumas maneiras específicas para estilizar tabelas.</p> + +<p>Você cria um novo documento de amostra contendo uma tabela, e uma folha de estilo para isto.</p> + +<h2 id="Informa.C3.A7.C3.A3o:_Mais_seletores" name="Informa.C3.A7.C3.A3o:_Mais_seletores">Informação: Mais seletores</h2> + +<p>CSS possui algumas maneiras para selecionar elementos baseadas nas relações entre eles. Você pode usá-las para fazer seletores que sejam mais específicos.</p> + +<p>Aqui está um sumário de seletores baseados em relações:</p> + +<table style="margin-left: 2em;"> + <tbody> + <tr> + <td style="width: 10em;"><strong>Seletor</strong></td> + <td><strong>Seleciona</strong></td> + </tr> + <tr> + <td><code>A E</code></td> + <td>Qualquer elemento E que seja <em>descendente</em> de um elemento A (isso é: um subitem, ou um subitem de um sub item, <em>etc</em>.)</td> + </tr> + <tr> + <td><code>A > E</code></td> + <td>Qualquer elemento E que seja subitem de um elemento A</td> + </tr> + <tr> + <td><code>E:first-child</code></td> + <td>Qualque elemento E que seja o primeiro subitem do seu principal</td> + </tr> + <tr> + <td><code>B + E</code></td> + <td>Qualquer elemento E que seja o próximo <em>irmão</em> de um elemento B (isso é: o próximo subitem do mesmo principal)</td> + </tr> + </tbody> +</table> + +<p>Você pode combinar isto para expressar relações complexas.</p> + +<p>Você pode também usar o símbolo <code>*</code> (asterisco) para dizer "qualquer elemento".</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; margin-bottom: 1em;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Uma tabela HTML tem um atributo <code>id</code>, mas suas linhas e células não tem identificadores individuais: + <div style="width: 30em;"> + <pre class="eval"> +<TABLE id="data-table-1"> +... +<TR> +<TD>Prefix</TD> +<TD>0001</TD> +<TD>default</TD> +</TR> +... +</pre> + </div> + + <p>Estas regras fazem a primeira célula em cada linha em negrito, e a segunda célula em cada linha monoespaçada. Elas afetam somente uma tabela específica no documento:</p> + + <div style="width: 45em;"> + <ol> + <li>data-table-1 td:first-child {font-weight: bolder;}</li> + <li>data-table-1 td:first-child + td {font-family: monospace;}</li> + </ol> + </div> + + <p>O resultado é algo como isto:</p> + + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td> + <table style="width: 18em; margin-right: 2em;"> + <tbody> + <tr> + <td><strong>Prefix</strong></td> + <td><code>0001</code></td> + <td>default</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>De maneira usual, se você faz um seletor mais específico então você aumenta sua prioridade. + <p>Usando estas técnicas, você evita precisar especificar atributos <code>class</code> ou <code>id</code> em muitas tags no seu documento. Em vez disso, CSS faz o trabalho.</p> + + <p>Em grandes projetos onde a velocidade é importante, você pode fazer suas folhas de estilo mais eficientes evitando regras complexas que dependem da relação entre elementos.</p> + + <p>Para detalhes completos sobre seletores, veja <a class="external" href="http://www.w3.org/TR/CSS21/selector.html">Selectors</a> em CSS Specification.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="Informa.C3.A7.C3.A3o:_Tabelas" name="Informa.C3.A7.C3.A3o:_Tabelas">Informação: Tabelas</h2> + +<p>Uma tabela é um arranjo de informação em uma grade retangular. Algumas tabelas podem ser complexas, e para tabelas complexas diferentes navegadores podem exibir diferentes resultados.</p> + +<p>Quando você desenha seu documento, use e a tabela para expressar as relações entre as peças da informação. Então não importará se os diferentes navegadores apresentarem a informação de maneiras levemente diferentes, pois o significado ainda pode ser compreendido.</p> + +<p>Não use tabelas de maneiras não usuais para produzir disposições visuais particulares. As técnicas na página anterior deste tutorial (<a href="/pt/CSS/Como_come%C3%A7ar/Disposi%C3%A7%C3%A3o" title="pt/CSS/Como_começar/Disposição">Disposição</a>) são melhores para isto.</p> + +<h4 id="Estrutura_da_tabela" name="Estrutura_da_tabela">Estrutura da tabela</h4> + +<p>Em uma tabela, cada peça de informação é exibida em uma <em>célula</em>.</p> + +<p>As células em uma linha horizontal na página compõem uma <em>linha</em>.</p> + +<p>Em algumas tabelas, as linhas podem ser agrupadas. Um grupo especial de linhas no começo da tabela é o <em>cabeçalho</em>. Um grupo especial de linhas no final da tabela é o <em>rodapé</em>. As linhas principais na tabela são o <em>corpo</em>, e elas podem também estar em grupos.</p> + +<p>As células em uma linha vertical na página compõem uma <em>coluna</em>, mas as colunas têm usos limitados nas tabelas das CSS.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; width: 100%;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>A tabela de seletores próxima ao topo desta página tem dez células em cinco linhas. + <p>A primeira linha é o cabeçalho. As outras quatro linhas são o corpo. Não há um rodapé.</p> + + <p>Ela tem duas colunas.</p> + </td> + </tr> + </tbody> +</table> + +<p>Este tutorial somente cobre tabelas simples, onde os resultados são razoavelmente previsíveis. Em uma tabela simples, toda célula ocupa somente uma linha e coluna. Você pode usar CSS para tabelas complexas onde células <em>expandam</em> (extendam-se sobre) mais do que uma linha ou coluna, mas tabelas como estas estão fora do escopo deste tutorial básico.</p> + +<h3 id="Bordas" name="Bordas">Bordas</h3> + +<p>Células não têm margens.</p> + +<p>Células têm bordas e enchimento. Por padrão, as bordas são separadas pelo valor da propriedade <code>border-spacing</code> da tabela. Você pode também remover o espaçamento completamente configurando a propriedade <code>border-collapse</code> da tabela para <code>collapse</code>.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; width: 100%;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Aqui estão três tabelas. + <p>A tabela da esquerda tem espaçamento de borda 0.5 em. A tabela do centro tem espaçamento da borda zero. A tabela da direita tem bordas unidas:</p> + + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td style="padding-right: 2em;"> + <table style=""> + <tbody> + <tr> + <td style="border: 1px solid #c00; text-align: center;">Paus</td> + <td style="border: 1px solid #c00; text-align: center;">Copas</td> + </tr> + <tr> + <td style="border: 1px solid #c00; text-align: center;">Ouros</td> + <td style="border: 1px solid #c00; text-align: center;">Espadas</td> + </tr> + </tbody> + </table> + </td> + <td style="padding-right: 2em;"> + <table style=""> + <tbody> + <tr> + <td style="border: 1px solid #c00; text-align: center;">Paus</td> + <td style="border: 1px solid #c00; text-align: center;">Copas</td> + </tr> + <tr> + <td style="border: 1px solid #c00; text-align: center;">Ouros</td> + <td style="border: 1px solid #c00; text-align: center;">Espadas</td> + </tr> + </tbody> + </table> + </td> + <td style="padding-right: 6em;"> + <table style="border-collapse: collapse;"> + <tbody> + <tr> + <td style="border: 1px solid #c00; text-align: center;">Paus</td> + <td style="border: 1px solid #c00; text-align: center;">Copas</td> + </tr> + <tr> + <td style="border: 1px solid #c00; text-align: center;">Ouros</td> + <td style="border: 1px solid #c00; text-align: center;">Espadas</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="Subt.C3.ADtulos" name="Subt.C3.ADtulos">Subtítulos</h3> + +<p>Um <em>subtítulo</em> é uma etiqueta que se aplica à tabela inteira. Por padrão, isto é mostrado no topo da tabela.</p> + +<p>Para mover isto para o fim, configure a propriedade <code>caption-side</code> para <code>bottom</code>. A propriedade é herdada, então alternativamente você pode configurar isto na tabela em outro elemento ascendente.</p> + +<p>Para estilizar o texto do subtítulo, use qualquer das propriedades usuais para texto.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; width: 100%;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Esta tabela tem um subtítulo no fim: + <div style="width: 30em;"> + <pre class="eval"> +#demo-table > caption { + caption-side: bottom; + font-style: italic; + text-align: right; + } +</pre> + </div> + + <table style="border: 2px outset #36b; padding: 1em 6em 1em 1em; background-color: white;"> + <tbody> + <tr> + <td> + <table> + <caption>Naipes</caption> + <tbody> + <tr> + <td> + <table style="border-collapse: collapse;"> + <tbody> + <tr> + <td style="border: 1px solid gray; text-align: center;">Paus</td> + <td style="border: 1px solid gray; text-align: center;">Copas</td> + </tr> + <tr> + <td style="border: 1px solid gray; text-align: center;">Ouros</td> + <td style="border: 1px solid gray; text-align: center;">Espadas</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="C.C3.A9lulas_vazias" name="C.C3.A9lulas_vazias">Células vazias</h3> + +<p>Você pode exibir células vazias (isto é, suas bordas e fundos) especificando <code>empty-cells: show;</code> para o elemento da tabela.</p> + +<p>Você pode escondê-los especificando <code>empty-cells:hide;</code>. Então, se um elemento principal tem um fundo e o chama, isto mostra através da célula vazia.</p> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; width: 100%;"> + <caption>Exemplo</caption> + <tbody> + <tr> + <td>Estas tabelas tem um fundo de verde pálido. Suas células tem um fundo de cinza pálido e bordas de cinza escuro. + <p>Na esquerda da tabela, a célula vazia é mostrada. Na direita, é escondida:</p> + + <table style="border: 2px outset #36b; padding: 1em; background-color: white;"> + <tbody> + <tr> + <td style="padding-right: 2em;"> + <table style="background-color: #dfd;"> + <tbody> + <tr> + <td style="border: 1px solid #555; background-color: #eee;"> </td> + <td style="border: 1px solid #555; background-color: #eee; text-align: center;">Copas</td> + </tr> + <tr> + <td style="border: 1px solid #555; background-color: #eee; text-align: center;">Ouros</td> + <td style="border: 1px solid #555; background-color: #eee; text-align: center;">Espadas</td> + </tr> + </tbody> + </table> + </td> + <td style="padding-right: 6em;"> + <table style="background-color: #dfd;"> + <tbody> + <tr> + <td> </td> + <td style="border: 1px solid #555; background-color: #eee; text-align: center;">Copas</td> + </tr> + <tr> + <td style="border: 1px solid #555; background-color: #eee; text-align: center;">Ouros</td> + <td style="border: 1px solid #555; background-color: #eee; text-align: center;">Espadas</td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #f4f4f4; margin-bottom: 1em;"> + <caption>Mais detalhes</caption> + <tbody> + <tr> + <td>Para informações detalhasdas sobre tabelas, veja <a class="external" href="http://www.w3.org/TR/CSS21/tables.html">Tables</a> em CSS Specification. + <p>A informação lá vai além do que há neste tutorial, mas não cobre as diferenças entre os navegadores que podem afetar tabelas complexas.</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="A.C3.A7.C3.A3o:_Estilizando_uma_tabela" name="A.C3.A7.C3.A3o:_Estilizando_uma_tabela">Ação: Estilizando uma tabela</h2> + +<p>Faça um novo documento HTML, <code>doc3.html</code>. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre><DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> +<HTML> +<HEAD> +<TITLE>Documento de amostra 3</TITLE> +<LINK rel="stylesheet" type="text/css" href="style3.css"> +</HEAD> +<BODY> + +<TABLE id="demo-table"> +<CAPTION>Oceanos</CAPTION> + +<THEAD> +<TR> +<TH></TH> +<TH>Área</TH> +<TH>Profundidade Média</TH> +</TR> +<TR> +<TH></TH> +<TH>milhões de km<SUP>2</SUP></TH> +<TH>m</TH> +</TR> +</THEAD> + +<TBODY> +<TR> +<TH>Ártico</TH> +<TD>13,000</TD> +<TD>1,200</TD> +</TR> +<TR> +<TH>Atlântico</TH> +<TD>87,000</TD> +<TD>3,900</TD> +</TR> +<TR> +<TH>Pacífico</TH> +<TD>180,000</TD> +<TD>4,000</TD> +</TR> +<TR> +<TH>Índico</TH> +<TD>75,000</TD> +<TD>3,900</TD> +</TR> +<TR> +<TH>Antártico</TH> +<TD>20,000</TD> +<TD>4,500</TD> +</TR> +</TBODY> + +<TFOOT> +<TR> +<TH>Total</TH> +<TD>361,000</TD> +<TD></TD> +</TR> +<TR> +<TH>Média</TH> +<TD>72,000</TD> +<TD>3,800</TD> +</TR> +</TFOOT> + +</TABLE> + +</BODY> +</HTML> +</pre> +</div> + +<p>Crie uma nova folha de estilo, <code>style3.css</code>. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:</p> + +<div style="width: 48em; height: 12em; overflow: auto;"> +<pre>/*** Estilo para doc3.html (Tabelas) ***/ + +#demo-table { + font: 100% sans-serif; + background-color: #efe; + border-collapse: collapse; + empty-cells: show; + border: 1px solid #7a7; + } + +#demo-table > caption { + text-align: left; + font-weight: bold; + font-size: 200%; + border-bottom: .2em solid #4ca; + margin-bottom: .5em; + } + + +/* basic shared rules */ +#demo-table th, +#demo-table td { + text-align: right; + padding-right: .5em; + } + +#demo-table th { + font-weight: bold; + padding-left: .5em; + } + + +/* header */ +#demo-table > thead > tr:first-child > th { + text-align: center; + color: blue; + } + +#demo-table > thead > tr + tr > th { + font-style: italic; + color: gray; + } + +/* fix size of superscript */ +#demo-table sup { + font-size: 75%; + } + +/* body */ +#demo-table td { + background-color: #cef; + padding:.5em .5em .5em 3em; + } + +#demo-table tbody th:after { + content: ":"; + } + + +/* footer */ +#demo-table tfoot { + font-weight: bold; + } + +#demo-table tfoot th { + color: blue; + } + +#demo-table tfoot th:after { + content: ":"; + } + +#demo-table > tfoot td { + background-color: #cee; + } + +#demo-table > tfoot > tr:first-child td { + border-top: .2em solid #7a7; + } +</pre> +</div> + +<p>Abra o documento no seu navegador. Deve ser muito similar a este:</p> + +<table style="border: 2px outset #36b; padding: 1em 6em 1em 1em; background-color: white;"> + <tbody> + <tr> + <td> + <div> + <p style="font: bold 200% sans-serif; text-align: left; border-bottom: .2em solid #4ca; margin: 0px 0px .5em 0px;">Oceanos</p> + + <div style="border: 1px solid #7a7; background-color: #efe;"> + <table style="font: 100% sens-serif; background-color: #efe; border-collapse: collapse; text-align: right; padding-right: .5em;"> + <tbody> + <tr style="text-align: center; color: blue;"> + <th> </th> + <th>Área</th> + <th style="padding-left: .5em; padding-right: .5em;">Profundidade média</th> + </tr> + <tr style="font-style: italic; color: gray;"> + <th> </th> + <th style="padding-left: .5em; padding-right: .5em;">milhões de km<sup>2</sup></th> + <th style="padding-left: .5em; padding-right: .5em;">m</th> + </tr> + <tr> + <th style="padding-right: .5em;">Ártico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">13,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">1,200</td> + </tr> + <tr> + <th style="padding-right: .5em;">Atlântico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">87,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">3,900</td> + </tr> + <tr> + <th style="padding-right: .5em;">Pacífico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">180,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">4,000</td> + </tr> + <tr> + <th style="padding-right: .5em;">Índico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">75,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">3,900</td> + </tr> + <tr> + <th style="padding-left: .5em; padding-right: .5em;">Antártico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">20,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em;">4,500</td> + </tr> + <tr> + <th style="padding-right: .5em; color: blue;">Total:</th> + <td style="background-color: #cee; padding: .5em .5em .5em 3em; border-top: .2em solid #7a7;">361,000</td> + <td style="background-color: #cee; padding: .5em .5em .5em 3em; border-top: .2em solid #7a7;"> </td> + </tr> + <tr> + <th style="padding-right: .5em; color: blue;">Média:</th> + <td style="background-color: #cee; padding: .5em .5em .5em 3em;">72,000</td> + <td style="background-color: #cee; padding: .5em .5em .5em 3em;">3,800</td> + </tr> + </tbody> + </table> + </div> + </div> + </td> + </tr> + </tbody> +</table> + +<p>Compare estas regras em sua folha de estilo com a tabela exibida, para se assegurar de que entende o efeito de cada regra. Se você achou uma regra com a qual não está seguro sobre, descomente-a e atualize o navegador para ver o que acontece.</p> + +<p>Aqui estão algumas notas sobre esta tabela:</p> + +<ul> + <li>O subtítulo encontra-se fora da borda da tabela.</li> + <li>Se você tiver um tamanho mínimo do ponto ajustado nas Opções, isto pode afetar o sobre-escrito no km<sup>2</sup>.</li> + <li>Existem três células vazias. Duas delas permitem que o fundo da tabela apareça através. A terceira tem um fundo e uma borda no topo.</li> + <li>As colunas são adicionadas pela folha de estilos.</li> +</ul> + +<table style="border: 1px solid #36b; padding: 1em; background-color: #fffff4; width: 100%;"> + <caption>Desafios</caption> + <tbody> + <tr> + <td>Mude a folha de estilo para fazer a tabela parecer com isto: + <table style="border: 2px outset #36b; padding: 1em 6em 1em 1em; background-color: white;"> + <tbody> + <tr> + <td> + <div> + <div style="border: 1px solid #7a7; background-color: #efe;"> + <table style="font: 100% sens-serif; background-color: #efe; border-collapse: collapse; text-align: right; padding-right: .5em;"> + <tbody> + <tr style="text-align: center; color: blue;"> + <th> </th> + <th>Área</th> + <th style="padding-left: .5em; padding-right: .5em;">Profundidade média</th> + </tr> + <tr style="font-style: italic; color: gray;"> + <th> </th> + <th style="padding-left: .5em; padding-right: .5em;">milhões de km<sup>2</sup></th> + <th style="padding-left: .5em; padding-right: .5em;">m</th> + </tr> + <tr> + <th style="padding-right: .5em;">Ártico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7;">13,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7; border-right: 0px;">1,200</td> + </tr> + <tr> + <th style="padding-right: .5em;">Atlântico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7;">87,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7; border-right: 0px;">3,900</td> + </tr> + <tr> + <th style="padding-right: .5em;">Pacífico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7;">180,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7; border-right: 0px;">4,000</td> + </tr> + <tr> + <th style="padding-right: .5em;">Índico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7;">75,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7; border-right: 0px;">3,900</td> + </tr> + <tr> + <th style="padding-left: .5em; padding-right: .5em;">Antártico:</th> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7;">20,000</td> + <td style="background-color: #cef; padding: .5em .5em .5em 3em; border: 1px solid #7a7; border-right: 0px;">4,500</td> + </tr> + <tr> + <th style="padding-right: .5em; color: blue;">Total:</th> + <td style="background-color: #cee; padding: .5em .5em .5em 3em; border-top: .2em solid #7a7;">361,000</td> + <td style="background-color: #cee; padding: .5em .5em .5em 3em; border-top: .2em solid #7a7;"> </td> + </tr> + <tr> + <th style="padding-right: .5em; color: blue;">Média:</th> + <td style="background-color: #cee; padding: .5em .5em .5em 3em;">72,000</td> + <td style="background-color: #cee; padding: .5em .5em .5em 3em;">3,800</td> + </tr> + </tbody> + </table> + </div> + + <p style="font: italic 100% sans-serif; text-align: right; border-top: .4em solid #4ca; margin: 1em 0px 0px 0px;">Oceanos</p> + </div> + </td> + </tr> + </tbody> + </table> + </td> + </tr> + </tbody> +</table> + +<h3 id="O_que_vem_depois.3F" name="O_que_vem_depois.3F">O que vem depois?</h3> + +<p>Se você teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor combribua nesta página de <a href="/Talk:pt/CSS/Como_come%C3%A7ar/Tabelas" title="Talk:pt/CSS/Como_começar/Tabelas">Discussão</a>.</p> + +<p>Esta é a última página deste tutorial que foca as propriedades e valores das CSS. Para um sumário completo de propriedades e valores, veja <a class="external" href="http://www.w3.org/TR/CSS21/propidx.html">Full property table</a> em CSS Specification.</p> + +<p>A próxima página mostra novamente o propósito e a estrutura das folhas de estilo CSS: <strong><a href="/pt/CSS/Como_come%C3%A7ar/M%C3%ADdia" title="pt/CSS/Como_começar/Mídia">Mídia</a></strong></p> + +<p>{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}</p> diff --git a/files/pt-pt/web/css/consulta_de_mídia/index.html b/files/pt-pt/web/css/consulta_de_mídia/index.html new file mode 100644 index 0000000000..2bf4f5470c --- /dev/null +++ b/files/pt-pt/web/css/consulta_de_mídia/index.html @@ -0,0 +1,436 @@ +--- +title: Utilizar consultas de média +slug: Web/CSS/Consulta_de_mídia +tags: + - Avançado + - CSS + - Desenho Adaptável + - Guía + - Media +translation_of: Web/CSS/Media_Queries/Using_media_queries +--- +<p>{{ gecko_minversion_header("1.9.1") }}</p> + +<p>As <strong>consultas de média </strong>permitem modificar um site ou aplicação de acordo com o tipo de dispositivo (ecrã ou impressora, por exemplo) ou características e parâmetros específicos (como a resolução de ecrã ou largura do {{glossary("viewport")}} do navegador). Podem utilizar-se para:</p> + +<ul> + <li>Aplicar estilos condicionalmente numa folha CSS, com recurso às regras {{cssxref("@media")}} e {{cssxref("@import")}};</li> + <li>Desenhar para um tipo de média específico com os elementos HTML {{HTMLElement("link")}}, {{HTMLElement("source")}}, e outros;</li> + <li>Testar e monitorizar estados de média utilizando os métodos de JavaScript {{domxref("Window.matchMedia()")}} and {{domxref("MediaQueryList.addListener()")}}.</li> +</ul> + +<h2 id="Sintaxe">Sintaxe</h2> + +<p>Consultas de média consistem num <a class="internal" href="/pt-PT/docs/Web/CSS/@media" title="En/CSS/@media">tipo de média</a> e uma ou mais expressões envolvendo recursos de média. Note que estas consultas não são sensíveis a maiúsculas. Pode-se combinar várias consultas com <em>operadores lógicos</em>.</p> + +<p>O resultado da consulta é verdadeiro se o tipo de média especificado na consulta de média encaixa com o tipo de dispositivo no qual o documento está a ser exibido <strong>e</strong> se todas as expressões na consulta de média forem verdadeiras.</p> + +<p>Quando uma consulta de média é verdadeira, a folha de estilos correspondente é aplicada seguinto as regras normais de cascata.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> Considere a etiqueta {{HTMLElement("link")}} com uma consulta de média. O ficheiro CSS que ela refere é descarregado mesmo que a consulta de média seja falsa; o conteúdo da folha não será aplicado até a consulta se tornar verdadeira.</p> +</div> + +<h3 id="Operadores_lógicos">Operadores lógicos</h3> + +<p>Você pode compor consultas de média complexas usando operadores lógicos, incluindo <code>not</code>, <code>and</code>, e <code>only</code> ; assim como combinar consultas de média numa lista separada por vírgulas, o que é equivalente a um operador "ou".</p> + +<h4 id="and"><font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);"><strong>and</strong></span></font></h4> + +<p>O operador <code>and</code> indica que a consulta é verdadeira se cada subconsulta que a compõe for verdadeira. Também pode juntar os tipos de média às funcionalidades de média. Tem maior precedência que a vírgula ("ou") e o <code>not</code>.</p> + +<h4 id="not"><strong><code>not</code></strong></h4> + +<p>A palavra-chave <code>not</code>, nega o resultado de toda a consulta; por exemplo, "<code><span style="font-family: monospace;">all</span> and (not color)</code>" é verdadeiro para dispositivos monocromáticos independentemente do tipo de média. É o operador com menor precedência depois da vírgula.</p> + +<h4 id="only"><strong><code>only</code></strong></h4> + +<p>A palavra-chave <code>only</code> indica que só deve ser aplicado o estilo se a consulta inteira for verdadeira. Quando se utiliza este operador, é obrigatório especificar um tipo de média.</p> + +<p>É útil para esconder folhas de estilo de navegadores antigos que não suportam consultas de média. Por exemplo, se não for utilizado <code>only</code>, navegadores antigos interpretam a consulta <code>screen and (max-width: 500px)</code> apenas como <code>screen</code> - ignoram o resto e aplicam o estilo em todos os ecrãs. </p> + +<p>Este operador não pode ser utilizado em conjunto com o <code>not</code>, e ambos têm a mesma precedência.</p> + +<h4 id="(vírgula)"><code>,</code> (vírgula)</h4> + +<p>Cada subconsulta numa lista separada por vírgulas é avaliada isoladamente e e alguma for verdadeira, a consulta composta é verdadeira. Por outras palavras, as vírgulas são equivalentes a um "ou-lógico".</p> + +<h4 id="Precedência_dos_operadores">Precedência dos operadores</h4> + +<ul> + <li>As vírgulas têm a menor precedência;</li> + <li><code>only</code> e <code>not</code> têm a mesma precedência;</li> + <li><code>and</code> tem a maior precedência.</li> +</ul> + +<p>Os parênteses <strong>não </strong>podem ser utilizados para mudar esta precedência.</p> + +<p> </p> + +<h3 id="Pseudo_BNF_(para_aqueles_que_gostam_desde_tipo_de_coisa)">Pseudo BNF (para aqueles que gostam desde tipo de coisa)</h3> + +<pre>media_query_list: <media_query> [, <media_query> ]* +media_query: [[only | not]? <media_type> [ and <expression> ]*] + | <expression> [ and <expression> ]* +expression: ( <media_feature> [: <value>]? ) +media_type: all | aural | braille | handheld | print | + projection | screen | tty | tv | embossed +media_feature: width | min-width | max-width + | height | min-height | max-height + | device-width | min-device-width | max-device-width + | device-height | min-device-height | max-device-height + | device-aspect-ratio | min-device-aspect-ratio | max-device-aspect-ratio + | color | min-color | max-color + | color-index | min-color-index | max-color-index + | monochrome | min-monochrome | max-monochrome + | resolution | min-resolution | max-resolution + | scan | grid</pre> + +<p>Consultas de média não diferenciam maiúsculas de minúsculas. Consultas de média que envolvem tipos de média desconhecidos são sempre falsas.</p> + +<div class="note"><strong>Nota:</strong> Os parênteses são requisitados a volta de expressões; esquecer de usá-los é um erro.</div> + +<h2 id="Recursos_de_média">Recursos de média</h2> + +<p>A maioria dos recursos de média pode ser prefixado com "min-" ou "max-" para expressar "maior ou igual a" ou "menor ou igual a". Isto evita usar os símbolos "<" e ">", que poderiam entrar em conflito com HTML e XML. Se você usar um recurso de média sem especificar um valor, a expressão é definida como verdadeira se o valor do recurso for diferente de zero.</p> + +<div class="note"><strong>Nota:</strong> Se um recurso de média não se aplica ao dispositivo no qual o navegador está sendo rodado, expressões envolvendo este recurso de média serão sempre falsas. Por exemplo, consultando a relação de aspecto de um dispositivo auditivo sempre resultará em falso.</div> + +<h3 id="color">color</h3> + +<p><strong>Valor:</strong> {{cssxref("<color>")}}<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> sim</p> + +<p>Indica o número de bits por componente de cor do dispositivo de saída. Se o dispositivo não é colorido, este valor é zero.</p> + +<div class="note"><strong>Nota:</strong> Se os componentes de cor tiverem diferentes de números de bits por componente de cor, o menor número é usado. Por exemplo, se uma tela usa 5 bits para azul e vermelho e 6 bits para verde, então o dispositivo é considerado para usar 5 bits por componente de cor. Se o dispositivo usa cores indexadas, o número mínimo de bits por componente de cor na tabela de cores é usado.</div> + +<h4 id="Exemplos">Exemplos</h4> + +<p>Para aplicar uma folha de estilos a todos os dispositivos coloridos:</p> + +<pre>@media all and (color) { ... } +</pre> + +<p>Para aplicar uma folha de estilos a dispositivos com no mínimo 4 bits por componente de cor:</p> + +<pre>@media all and (min-color: 4) { ... } +</pre> + +<h3 id="color-index">color-index</h3> + +<p><strong>Valor:</strong> integer<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> sim</p> + +<p>Indica o número de entradas na tabela de cor para o dispositivo de saída.</p> + +<h4 id="Exemplos_2">Exemplos</h4> + +<p>Para indicar que uma folha de estilos deve ser aplicada a todos os dispositivos usando cores indexadas, você pode fazer:</p> + +<pre>@media all and (color-index) { ... } +</pre> + +<p>Para aplicar uma folha de estilos a dispositivos de cores indexadas com no mínimo 256 cores:</p> + +<pre><link rel="stylesheet" media="all and (min-color-index: 256)" href="http://foo.bar.com/stylesheet.css" /> +</pre> + +<h3 id="device-aspect-ratio">device-aspect-ratio</h3> + +<p><strong>Valor:</strong> integer / integer<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}<br> + <strong>Aceita os prefixos min/max:</strong> sim</p> + +<p>Descreve a relação de aspecto do dispositivo de saída. Este valor consiste em dois positivos inteiros (integer) separados por um caractére barra ("/"). Isto representa o número de pixels horizontais sobre o número de pixels verticais.</p> + +<h4 id="Exemplo">Exemplo</h4> + +<p>O que vem a seguir selecionar uma folha de estilos especial para uso em dispositivos de tela comprida (widescreen):</p> + +<pre>@media screen and (device-aspect-ratio: 16/9), screen and (device-aspect-ratio: 16/10) { ... }</pre> + +<p>Isto seleciona o estilo quando a relação de aspecto for 16:9 ou 16:10.</p> + +<h3 id="device-height">device-height</h3> + +<p><strong>Valor:</strong> {{cssxref("<length>")}}<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}<br> + <strong>Aceita os prefixos min/max: </strong>sim</p> + +<p>Descreve a altura do dispositivo de saída (sendo a tela ou página inteira, ao invés de somente a área de renderização, como a janela do documento).</p> + +<h4 id="Exemplo_2">Exemplo</h4> + +<p>Para aplicar uma folha de estilos a um documento quando exibido em uma tela que for mais fina do que 800 pixels, você pode usar isto:</p> + +<pre><link rel="stylesheet" media="screen and (max-device-width: 799px)" /> +</pre> + +<h3 id="device-width">device-width</h3> + +<p><strong>Valor:</strong> {{cssxref("<length>")}}<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}<br> + <strong>Aceita os prefixos min/max:</strong> sim</p> + +<p>Descreve a largura do dispositivo de saída (sendo a tela ou a página inteira, ao invés de somente a área de renderização, como a janela do documento).</p> + +<h3 id="grid">grid</h3> + +<p><strong>Valor:</strong> integer<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> all<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p>Determina Determines se o dispositivo de saída é um dispositivo <em>grid</em> ou um dispositivo bitmap. Se o dispositivo for baseado em <em>grid</em> (tal como um terminal tty ou uma tela de celular com somente uma fonte), o valor é 1. Caso contrário é zero.</p> + +<div class="note"><strong>Nota:</strong> Gecko (e consequentemente o Firefox) não suporta dispositivos <em>grid</em> atualmente, então este recurso de média não é suportado.</div> + +<h4 id="Exemplo_3">Exemplo</h4> + +<p>Para aplicar um estilo a dispositivos de mão com uma tela de 15 caracteres ou mais estreito:</p> + +<pre>@media handheld and (grid) and (max-width: 15em) { ... } +</pre> + +<div class="note"><strong>Nota:</strong> A unidade "em" tem um uso especial em dispositivos <em>grid</em>; desde que a largura exata de um "em" não pôde ser determinada, 1em é assumido como a largura de uma célula <em>grid</em> horizontal, e a altura de uma célula vertical.</div> + +<h3 id="height">height</h3> + +<p><strong>Valor:</strong> {{cssxref("<length>")}}<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}<br> + <strong>Aceita os prefixos min/max:</strong> sim</p> + +<p>O recurso de média <code>height</code> descreve a altura da superfície de renderização do dispositivo de saída (tal como a altura da <em>viewport</em> ou da caixa de páginas em uma impressora).</p> + +<div class="note"><strong>Nota:</strong> Quando o usuário redimenciona a janela, o Firefox substituirá as folhas de estilos como for apropriado, baseado em consultas de média usando os recursos de média <code>width</code> e <code>height</code>.</div> + +<h3 id="monochrome">monochrome</h3> + +<p><strong>Valor:</strong> integer<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> sim</p> + +<p>Indica o número de bits por pixel em um dispositivo monocromático (escala de cinza). Se o dispositivo não for monocromático, o valor do dispositivo é 0.</p> + +<h4 id="Exemplos_3">Exemplos</h4> + +<p>Para aplicar uma folha de estilos para todos os dispositivos monocromáticos:</p> + +<pre>@media all and (monochrome) { ... } +</pre> + +<p>Para aplicar uma folha de estilos para dispositivos monocromáticos com no mínimo 8 bits por pixel:</p> + +<pre>@media all and (min-monochrome: 8) { ... } +</pre> + +<h3 id="orientation">orientation</h3> + +<p><strong>Valor:</strong> <code>landscape</code> | <code>portrait</code><br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p>Indica se o dispositivo está em modo paisagem (a exibição é mais larga do que alta) ou retrato (a exibição é mais alta do que larga).</p> + +<h4 id="Exemplo_4">Exemplo</h4> + +<p>Para aplicar uma folha de estilos somente na orientação retrato:</p> + +<pre>@media all and (orientation: portrait) { ... }</pre> + +<h3 id="resolution">resolution</h3> + +<p><strong>Valor:</strong> {{cssxref("<resolution>")}}<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Bitmap", "bitmap")}}<br> + <strong>Aceita os prefixos min/max:</strong> sim</p> + +<p>Indica a resolução (densidade de pixels) do dispositivo de saída. A resolução pode ser especificada tanto em pontos por polegada (dpi) quanto pontos por centímetro (dpcm).</p> + +<h4 id="Exemplo_5">Exemplo</h4> + +<p>Para aplicar uma folha de estilos a dispositivos com no mínimo 300 pontos por polegada de resolução:</p> + +<pre>@media print and (min-resolution: 300dpi) { ... } +</pre> + +<h3 id="scan">scan</h3> + +<p><strong>Valor:</strong> <code>progressive</code> | <code>interlace</code><br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/TV", "tv")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p>Descreve o processo de escaneamento de dispositivos de saída de televisão.</p> + +<div class="note"><strong>Nota: </strong>Gecko (e consequentemente o Firefox) não suportam o tipo de média <code>tv</code> atualmente, então este recurso de média não é suportado.</div> + +<h4 id="Exemplo_6">Exemplo</h4> + +<p>Para aplicar uma folha de estilos somente para televisões com escaneamento progressivo:</p> + +<pre>@media tv and (scan: progressive) { ... } +</pre> + +<h3 id="width">width</h3> + +<p><strong>Valor:</strong> {{cssxref("<length>")}}<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}<br> + <strong>Aceita os prefixos min/max:</strong> sim</p> + +<p>O recurso de média <code>width</code> descreve a largura da superfície de renderização do dispositivo de saída (tal como a largura da janela do documento, ou a largura da caixa de páginas em uma impressora).</p> + +<div class="note"><strong>Nota: </strong>Quando o usuário redimensiona a janela, o Firefox substituirá a folha de estilo como apropriado, baseado nas consultas de média usando os recursos de média <code>width</code> e <code>height</code>.</div> + +<h4 id="Exemplos_4">Exemplos</h4> + +<p>Se você desejar espeficar uma folha de estilos para dispositivos de mão, ou dispositivos de tela com uma largura maior do que 20em, você pode usar esta folha de estilos:</p> + +<pre>@media handheld and (min-width: 20em), screen and (min-width: 20em) { ... } +</pre> + +<p>Este recurso de média especifica uma folha de estilos que deve ser aplicada a médias impressas mais largas do que 8.5 polegadas:</p> + +<pre><link rel="stylesheet" media="print and (min-width: 8.5in)" + href="http://foo.com/mystyle.css" /> +</pre> + +<p>Este recurso especifica uma folha de estilos que é usável quando a <em>viewport</em> estiver entre 500 e 800 pixels de largura:</p> + +<pre>@media screen and (min-width: 500px) and (max-width: 800px) { ... } +</pre> + +<h2 id="Características_de_média_específicas_da_Mozilla">Características de média específicas da Mozilla</h2> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">{{ gecko_minversion_header("1.9.2") }}</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">A Mozilla oferece várias características de média específicas para o Gecko. Algumas delas podem ser propostas como características oficiais de média.</p> + +<h3 id="-moz-images-in-menus">-moz-images-in-menus</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se o dispositivo permitir às imagens, aparecer nos menus, recebe 1; caso contrário, o valor é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(images-in-menus)") }} do CSS.</p> + +<h3 id="-moz-mac-graphite-theme">-moz-mac-graphite-theme</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se o usuário configurou o dispositivo para usar a aparência "Graphite" no Mac OS X, o valor é 1. Se o usuário está usando a aparência azul padrão, ou não for no Mac OS X, o valor é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(mac-graphite-theme)") }} do CSS.</p> + +<h3 id="-moz-maemo-classic">-moz-maemo-classic</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se o usuário está usando o Maemo com o tema original, o valor é 1; se estiver usando o novo tema "Fremantle", o valor é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(maemo-classic)") }} do CSS.</p> + +<h3 id="-moz-scrollbar-end-backward">-moz-scrollbar-end-backward</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se a interface do dispositivo do usuário exibe um botão de seta para trás ao fim da barra de rolagem, o valor é 1. Caso contrário é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-end-backward)") }} do CSS.</p> + +<h3 id="-moz-scrollbar-end-forward">-moz-scrollbar-end-forward</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se a interface do dispositivo do usuário exibe um botão de seta para frente ao fim da barra de rolagem, o valor é 1. Caso contrário é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-end-forward)") }} do CSS.</p> + +<h3 id="-moz-scrollbar-start-backward">-moz-scrollbar-start-backward</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se a interface do dispositivo do usuário exibe uma seta para trás no início da barra de rolagem, o valor é 1. Caso contrário é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-start-backward)") }} do CSS.</p> + +<h3 id="-moz-scrollbar-start-forward">-moz-scrollbar-start-forward</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se a interface do dispositivo do usuário exibe uma seta para frente no início da barra de rolagem, o valor é 1. Caso contrário é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-start-forward)") }} do CSS.</p> + +<h3 id="-moz-scrollbar-thumb-proportional">-moz-scrollbar-thumb-proportional</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se a interface do dispositivo do usuário exibe a barra de rolagem proporcionalmente (isto é, tamanho baseado na porcentagem do documento que está visível), o valor é 1. Caso contrário é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-thumb-proportional)") }} do CSS.</p> + +<h3 id="-moz-touch-enabled">-moz-touch-enabled</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se o dispositivo suporta eventos de toque (para um tela sensível ao toque), o valor é 1. Caso contrário é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(touch-enabled)") }} do CSS.</p> + +<h4 id="Exemplo_7">Exemplo</h4> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Você pode usar isso para renderizar seus botões ligeiramente maiores, por exemplo, se o usuário estiver em um dispositivo com tela sensível ao toque, para torná-lo mais amigável aos dedos.</p> + +<h3 id="-moz-windows-classic">-moz-windows-classic</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se o usuário estiver usando o Windows, sem tema (no modo clássico ao invés de usar "uxtheme"), o valor é 1; caso contrário é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(windows-classic)") }} do CSS.</p> + +<h3 id="-moz-windows-compositor">-moz-windows-compositor</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se o usuário estiver usando o Windows com o compositor DWM, o valor é 1; caso contrário é 0.</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(windows-compositor)") }} do CSS.</p> + +<h3 id="-moz-windows-default-theme">-moz-windows-default-theme</h3> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;"><strong>Valor:</strong> inteiro<br> + <strong style="font-weight: bold;">média</strong><strong>:</strong> {{cssxref("Media/Visual", "visual")}}<br> + <strong>Aceita os prefixos min/max:</strong> não</p> + +<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1.7em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px;">Se o usuário está correntemente usando um dos temas do Windows (Luna, Royale, Zune ou Aero (incluindo o Vista Basic, Vista Advanced e o Aero Glass), o valor 1. Caso contrário é 0.</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/css3-mediaqueries/" title="http://www.w3.org/TR/css3-mediaqueries/">CSS 3 media query specification</a> (en)</li> + <li><a class="internal" href="/en/CSS/@media" title="En/CSS/@media">Media types</a> (en)</li> +</ul> diff --git a/files/pt-pt/web/css/consultas_de_media/index.html b/files/pt-pt/web/css/consultas_de_media/index.html new file mode 100644 index 0000000000..f9bbd7b94e --- /dev/null +++ b/files/pt-pt/web/css/consultas_de_media/index.html @@ -0,0 +1,110 @@ +--- +title: Consultas de média +slug: Web/CSS/Consultas_de_media +tags: + - CSS + - Consultas de Média + - Consultas de média CSS3 + - Desenho Adaptável + - Referencia + - Visão Geral +translation_of: Web/CSS/Media_Queries +--- +<div>{{CSSRef}}</div> + +<p><strong>Consultas de média</strong> permitem adaptar o seu site ou aplicação de acordo com diferentes características ou parâmetros dos dispositivos utilizados.</p> + +<p>São um elemento chave de <a href="/en-US/docs/Web/Apps/Progressive/Responsive">desenho adaptável </a>. Por exemplo, uma consulta de média pode reduzir o tamanho do texto em dispositivos pequenos, aumentar o espaço entre parágrafos quando a página é visualizada em modo de paisagem, ou ampliar os botões nos ecrãs táteis.</p> + +<p>Em <a href="/en-US/docs/Web/CSS">CSS</a>, utiliza-se a <a href="/en-US/docs/Web/CSS/At-rule">regra "at"</a> {{cssxref("@media")}} para aplicar, condicionalmente, parte de uma folha de estilos com base no resultado de uma consulta de média. E utiliza-se {{cssxref("@import")}} para aplicar, condicionalmente, uma folha de estilos inteira.</p> + +<h3 id="Consultas_de_média_em_HTML">Consultas de média em HTML</h3> + +<p>Em <a href="/en-US/docs/Web/HTML">HTML</a>, as consultas de média podem-se aplicar a vários elementos:</p> + +<ul> + <li>No atributo {{htmlattrxref("media", "link")}} do elemento {{HTMLElement("link")}}. O valor deste atributo define os média a que se deve aplicar o recurso ligado (tipicamente, este recurso é um documento CSS).</li> + <li>No atributo {{htmlattrxref("media", "source")}} do elemento {{HTMLElement("source")}} (apenas é válido quando este elemento está aninhado dentro de um elemento {{HTMLElement("picture")}}.). O valor deste atributo define quais os média que podem utilizar a imagem associada ao elemento.</li> + <li>No atributo {{htmlattrxref("media", "style")}} do elemento {{HTMLElement("style")}}. O valor deste atributo define os média a que são aplicados os estilos.</li> +</ul> + +<h3 id="Consultas_de_média_em_JavaScript">Consultas de média em JavaScript</h3> + +<p>Em <a href="/en-US/docs/Web/JavaScript">JavaScript</a>, pode-se usar o método {{domxref("Window.matchMedia()")}} para verificar se a janela possui as características definidas na consulta de média. Também se pode utilizar {{domxref("MediaQueryList.addListener()")}} para gerar eventos sempre que houver mudanças no resultado da consulta de média. Com estas funcionalidades, o seu site ou aplicação pode responder a mudanças na configuração, orientação ou estado do dispositivo.</p> + +<p>Pode aprender mais sobre utilização programática das consultas de média no artigo <a href="/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries">Testar consultas de média</a>.</p> + +<h2 id="Referências">Referências</h2> + +<h3 id="Regras_at">Regras "at"</h3> + +<div class="index"> +<ul> + <li>{{cssxref("@import")}}</li> + <li>{{cssxref("@media")}}</li> +</ul> +</div> + +<h2 id="Guias">Guias</h2> + +<dl> + <dt><a href="/en-US/docs/Web/CSS/Media_Queries/Using_media_queries">Utilizar consultas de média</a></dt> + <dd>Introdução às consultas de média, a sua sintaxe, os operadores e funcionalidades utilizadas para construir as expressões das consultas de média.</dd> + <dt><a href="/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries">Testar consultas de média programaticamente</a></dt> + <dd>Descrição de como utilizar consultas de média no código JavaScript code para determinar o estado do dispositivo, e como instalar <em>listeners</em> que notificam o código quando o resultado das consultas muda (por exemplo, quando o utilizador roda o ecrã ou redimensiona a janela do navegador).</dd> + <dt><a href="/en-US/docs/Web/CSS/Media_Queries/Using_Media_Queries_for_Accessibility">Utilizar Consultas de média para Acessibilidade</a></dt> + <dd>Este artigo explica de que forma as consultas de média podem ajudar os utilizadores a compreender melhor o seu site.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS5 Media Queries')}}</td> + <td>{{Spec2('CSS5 Media Queries')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('CSS3 Conditional')}}</td> + <td>{{Spec2('CSS3 Conditional')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('CSS4 Media Queries')}}</td> + <td>{{Spec2('CSS4 Media Queries')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('CSS3 Media Queries')}}</td> + <td>{{Spec2('CSS3 Media Queries')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'media.html')}}</td> + <td>{{Spec2('CSS2.1')}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h2> + +<h3 id="media_rule">@media rule</h3> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se gostaria de contribuir para estes dados, visite o repositório <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um <em>pull request</em>.</div> + +<p>{{Compat("css.at-rules.media")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>A regra {{cssxref("@supports")}} permite aplicar estilos em função da compatibilidade do navegador com diversas tecnologias CSS.</li> +</ul> diff --git a/files/pt-pt/web/css/content/index.html b/files/pt-pt/web/css/content/index.html new file mode 100644 index 0000000000..cc627821d8 --- /dev/null +++ b/files/pt-pt/web/css/content/index.html @@ -0,0 +1,18 @@ +--- +title: content +slug: Web/CSS/content +translation_of: Web/CSS/content +--- +<p><span class="lang lang-pt">« <a href="/pt/Refer%c3%aancia_CSS" title="https://developer.mozilla.org/pt/Referência_CSS">Referência CSS</a></span></p> +<h3 id="Resumo">Resumo</h3> +<p>A propriedade <code>content</code> é usada com os pseudo-elementos <a href="/pt/CSS/%3abefore" title="pt/CSS/:before"><code>:before</code></a> e <a href="/pt/CSS/:after" title="pt/CSS/:after"><code>:after</code></a> para gerar conteúdo com o elemento.</p> +<ul> <li>Valor inicial: <code>normal</code></li> <li>Aplica-se a: Pseudo-elementos <code>:before</code> e <code>:after</code></li> <li>Herdado: não</li> <li>Mídia: todas</li> <li>Valor computado: <ul> <li>Em <code>:before</code> e <code>:after</code>, <code>normal</code> é computado como <code>none</code></li> <li>Para elementos sempre é computado como <code>normal</code></li> <li>Endereços são convertidos para absolutos</li> <li>Quando for <code>attr()</code>, o valor será o mesmo do atributo escolhido</li> <li>Para outras, fica como o especificado</li> </ul> </li> +</ul> +<h3 id="Sintáxe">Sintáxe</h3> +<pre>content: normal | none | + [ <string> | <uri> | <counter> | attr() | + open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit +</pre> +<h3 id="Valores">Valores</h3> +<dl> <dt>none</dt> <dd>O pseudo-elemento não é gerado.</dd> <dt>normal</dt> <dd>Computado como<code> none </code>para os pseudo-elementos <code>:before</code> e <code>:after</code>.</dd> <dt><string></dt> <dd>Conteúdo de texto.</dd> <dt><uri><code> url()</code></dt> <dd>O valor especifica um recurso externo (como uma imagem). Se o recurso não puder ser exibido, ele é ignorado ou um marcador aparece em seu lugar.</dd> <dt><counter></dt> <dd>Contadores podem ser especificados como duas funções: 'counter()' ou 'counters()'. O primeiro tem duas formas: 'counter(<var>name</var>)' ou 'counter(<var>name</var>, <var>style</var>)'. <span class="long_text" id="result_box"><span style="background-color: rgb(255, 255, 255);" title="The generated text is the value of the innermost counter of the given name in scope at this pseudo-element; it is formatted in the indicated style ('decimal' by default).">O texto gerado é o valor do contador de intimidades de o nome dado no âmbito deste pseudo-elemento, que é formatado no estilo indicado</span></span> ('decimal' por padrão).A segunda também tem duas formas: 'counters(<var>name</var>, <var>string</var>)' ou 'counters(<var>name</var>, <var>string</var>, <var>style</var>)'. <span class="long_text" id="result_box"><span style="background-color: rgb(255, 255, 255);" title="The generated text is the value of all counters with the given name in scope at this pseudo-element, from outermost to innermost separated by the specified string.">O texto gerado é o valor de todos os contadores com o nome dado no âmbito deste pseudo-elemento, a partir ultraperiféricas intimidades separadas pela seqüência especificada</span></span>. Os contadores são testados da maneira indicada ('decimal' por padrão). Veja a seção contadores automáticos e numeração para mais informação. O nome não pode ser 'none', 'inherit' ou 'initial'. Isso faz com que a função seja ignorada.</dd> <dt>attr(X)</dt> <dd>Retorna o valor da propriedade X do elemento. Se não existir a propriedade X, será retornado um texto vazio. A diferenciação entre maiúsculas e minúsculas depende do idioma do documento.</dd> <dt>open-quote | close-quote</dt> <dd>Esses valores são trocadas pelo texto apropriado da propriedade <code><a href="/pt/CSS/quotes" rel="custom nofollow" title="pt/CSS/quotes">quotes</a></code>.</dd> <dt>no-open-quote | no-close-quote</dt> <dd>Não introduz conteúdo, previne a inserção em um elemento de um <code>open-quote</code> ou <code>close quote</code>.</dd> +</dl> diff --git a/files/pt-pt/web/css/counter-increment/index.html b/files/pt-pt/web/css/counter-increment/index.html new file mode 100644 index 0000000000..43197dba12 --- /dev/null +++ b/files/pt-pt/web/css/counter-increment/index.html @@ -0,0 +1,66 @@ +--- +title: counter-increment +slug: Web/CSS/counter-increment +tags: + - CSS + - CSS List + - CSS Property + - Reference +translation_of: Web/CSS/counter-increment +--- +<p>{{ CSSRef() }}</p> + +<h2 id="Resumo" name="Resumo">Resumo</h2> + +<p><code>counter-increment</code> é usado para aumentar o valor de <a href="pt/CSS_Counters">CSS Counters</a> com um valor dado.</p> + +<p>{{cssinfo}}</p> + +<h2 id="Sintaxe" name="Sintaxe">Sintaxe</h2> + +<pre class="eval">counter-increment: [<identifier> <integer>?]+ | inherit | none +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>identifier </dt> + <dd>O nome do contador para incrementar.</dd> + <dt>integer </dt> + <dd>O valor para adicionar ao contador. O padrão é 1 se nada for dado.</dd> +</dl> + +<p>Você pode especificar como muitos contadores para incrementar como você quiser, cada um separado por um espaço.</p> + +<h2 id="Propriedades_relacionadas" name="Propriedades_relacionadas">Propriedades relacionadas</h2> + +<ul> + <li><a href="pt/CSS/counter-reset">counter-reset</a> reinicia os <a href="pt/CSS_Counters">CSS Counters</a> especificados a uma quantidade dada.</li> +</ul> + +<h2 id="Exemplos" name="Exemplos">Exemplos</h2> + +<pre>h1 { + counter-increment: chapter section 2 page; + /* Aumenta o valor dos contadores de capítulo e página em 1 + e o contador da seção em 2. */ +} +</pre> + +<p><span class="comment">== Notas ==</span></p> + +<h2 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS21/generate.html#propdef-counter-increment">CSS 2.1</a></li> +</ul> + +<p><span class="comment">== Compatibilidade com navegadores ==</span></p> + +<h2 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h2> + +<p><a href="pt/CSS_Counters">CSS Counters</a>, {{ Cssxref("counter-increment") }}, {{ Cssxref("counter-reset") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> diff --git a/files/pt-pt/web/css/counter-reset/index.html b/files/pt-pt/web/css/counter-reset/index.html new file mode 100644 index 0000000000..709c4f8112 --- /dev/null +++ b/files/pt-pt/web/css/counter-reset/index.html @@ -0,0 +1,69 @@ +--- +title: counter-reset +slug: Web/CSS/counter-reset +tags: + - CSS + - CSS List + - CSS Property + - CSS Reference +translation_of: Web/CSS/counter-reset +--- +<p>{{ CSSRef() }}</p> + +<h2 id="Resumo" name="Resumo">Resumo</h2> + +<p><code>counter-reset</code> é usado para reiniciar os <a href="pt/CSS_Counters">CSS Counters</a> a um valor dado.</p> + +<ul> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: não</li> +</ul> + +<h2 id="Sintaxe" name="Sintaxe">Sintaxe</h2> + +<pre class="eval">counter-reset: [<identifier> <integer>?]+ | inherit | none +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>identifier </dt> + <dd>O nome do contador para reiniciar.</dd> + <dt>integer </dt> + <dd>O valor para reiniciar o contador para cada ocorrência do elemento. O padrão é 0 se nada for dado.</dd> +</dl> + +<p>Você pode especificar como muitos contadores para reiniciar quando você quiser, cada um separado por um espaço.</p> + +<h2 id="Propriedades_relacionadas" name="Propriedades_relacionadas">Propriedades relacionadas</h2> + +<ul> + <li><a href="pt/CSS/counter-increment">counter-increment</a> aumenta o valor dos <a href="pt/CSS_Counters">CSS Counters</a> especificados a uma quantidade dada.</li> +</ul> + +<h2 id="Exemplos" name="Exemplos">Exemplos</h2> + +<pre>h1 { + counter-reset: chapter section 1 page; + /* Configura os contadores de capítulo e página em 0 + e o contador da seção em 1. */ +} +</pre> + +<p><span class="comment">== Notas ==</span></p> + +<h2 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS21/generate.html#propdef-counter-reset">CSS 2.1</a></li> +</ul> + +<p><span class="comment">== Browser compatibility ==</span></p> + +<h2 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h2> + +<p><a href="pt/CSS_Counters">CSS Counters</a>, {{ Cssxref("counter-increment") }}, {{ Cssxref("counter-reset") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> diff --git a/files/pt-pt/web/css/css_background_and_borders/index.html b/files/pt-pt/web/css/css_background_and_borders/index.html new file mode 100644 index 0000000000..87b26bd607 --- /dev/null +++ b/files/pt-pt/web/css/css_background_and_borders/index.html @@ -0,0 +1,154 @@ +--- +title: CSS Background and Borders +slug: Web/CSS/CSS_Background_and_Borders +tags: + - CSS + - CSS Backgrounds and Borders + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Backgrounds_and_Borders +--- +<p>{{CSSRef}}</p> + +<p><strong>CSS Background and Borders</strong> is a module of CSS that defines how background and borders of elements are described. Borders can be lines or images, boxes can have one or multiple backgrounds, have rounded corners, and shadows.</p> + +<h2 id="Reference">Reference</h2> + +<h3 id="CSS_Properties">CSS Properties</h3> + +<div class="index"> +<ul> + <li>{{cssxref("background")}}</li> + <li>{{cssxref("background-attachment")}}</li> + <li>{{cssxref("background-clip")}}</li> + <li>{{cssxref("background-color")}}</li> + <li>{{cssxref("background-image")}}</li> + <li>{{cssxref("background-origin")}}</li> + <li>{{cssxref("background-position")}}</li> + <li>{{cssxref("background-repeat")}}</li> + <li>{{cssxref("background-size")}}</li> + <li>{{cssxref("box-shadow")}}</li> + <li>{{cssxref("border")}}</li> + <li>{{cssxref("border-bottom")}}</li> + <li>{{cssxref("border-bottom-color")}}</li> + <li>{{cssxref("border-bottom-left-radius")}}</li> + <li>{{cssxref("border-bottom-right-radius")}}</li> + <li>{{cssxref("border-bottom-style")}}</li> + <li>{{cssxref("border-bottom-width")}}</li> + <li>{{cssxref("border-collapse")}}</li> + <li>{{cssxref("border-color")}}</li> + <li>{{cssxref("border-image")}}</li> + <li>{{cssxref("border-image-outset")}}</li> + <li>{{cssxref("border-image-repeat")}}</li> + <li>{{cssxref("border-image-slice")}}</li> + <li>{{cssxref("border-image-source")}}</li> + <li>{{cssxref("border-image-width")}}</li> + <li>{{cssxref("border-left")}}</li> + <li>{{cssxref("border-left-color")}}</li> + <li>{{cssxref("border-left-style")}}</li> + <li>{{cssxref("border-left-width")}}</li> + <li>{{cssxref("border-radius")}}</li> + <li>{{cssxref("border-right")}}</li> + <li>{{cssxref("border-right-color")}}</li> + <li>{{cssxref("border-right-style")}}</li> + <li>{{cssxref("border-right-width")}}</li> + <li>{{cssxref("border-style")}}</li> + <li>{{cssxref("border-top")}}</li> + <li>{{cssxref("border-top-color")}}</li> + <li>{{cssxref("border-top-left-radius")}}</li> + <li>{{cssxref("border-top-right-radius")}}</li> + <li>{{cssxref("border-top-style")}}</li> + <li>{{cssxref("border-top-width")}}</li> + <li>{{cssxref("border-width")}}</li> +</ul> +</div> + +<h2 id="Guides">Guides</h2> + +<dl> + <dt><a href="/en-US/docs/Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds">Using CSS multiple backgrounds</a></dt> + <dd>Explains how to set backgrounds on elements and how they will interact with it.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Background_and_Borders/Scaling_background_images">Scaling background images</a></dt> + <dd>Describes how to change the appearance of the background images, by stretching them or repeating them, to cover the whole background of the element, or not.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSS3 Backgrounds') }}</td> + <td>{{ Spec2('CSS3 Backgrounds') }}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'box.html')}}</td> + <td>{{Spec2('CSS2.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('CSS1', '#border')}}</td> + <td>{{Spec2('CSS1')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable()}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>4.0</td> + <td>3.5</td> + <td>1.0 (85)</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatGeckoMobile("1.9.2")}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>{{CompatVersionUnknown()}}</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/pt-pt/web/css/css_background_and_borders/múltiplos_planos_de_fundo/index.html b/files/pt-pt/web/css/css_background_and_borders/múltiplos_planos_de_fundo/index.html new file mode 100644 index 0000000000..dbd858e82c --- /dev/null +++ b/files/pt-pt/web/css/css_background_and_borders/múltiplos_planos_de_fundo/index.html @@ -0,0 +1,57 @@ +--- +title: Utilização de múltiplos fundos em CSS +slug: Web/CSS/CSS_Background_and_Borders/Múltiplos_planos_de_fundo +tags: + - CSS + - CSS Background + - Example + - Guide + - Intermediate +translation_of: Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds +--- +<p>{{CSSRef}}</p> + +<p>Com <span class="seoSummary"><a href="https://developer.mozilla.org/en/CSS/CSS3" title="CSS3">CSS3 </a></span>pode aplicar <strong>múltiplos fundos</strong> aos elementos. Estes são colocados um sobre o outro, com o primeiro fundo fornecido no topo e o último fundo listado por trás. Só o último fundo pode incluir uma cor de fundo:</p> + +<p>É fácil especificar múltiplos fundos:</p> + +<pre class="brush: css">.myclass { + background: background1, background 2, ..., backgroundN; +} +</pre> + +<p>Você pode fazer isto com o apanhado da propriedade {{ cssxref("background") }} e das sub-propriedades desta: {{ cssxref("background") }}, {{ cssxref("background-attachment") }}, {{ cssxref("background-clip") }},<code> </code>{{ cssxref("background-image") }}, {{ cssxref("background-origin") }}, {{ cssxref("background-position") }}, {{ cssxref("background-repeat") }}, {{ cssxref("background-size") }}.</p> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Neste exemplo, três fundos são empilhados: a logo do Firefox, um <a href="/en/CSS/-moz-linear-gradient" title="en/CSS/-moz-linear-gradient">gradiente linear</a> (en) e uma imagem com flores:</p> + +<pre class="brush: css">.multi_bg_example { + background: url(http://demos.hacks.mozilla.org/openweb/resources/images/logos/firefox-48.png), + -moz-linear-gradient(left, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1)), + url(http://demos.hacks.mozilla.org/openweb/resources/images/patterns/flowers-pattern.jpg); + background-repeat: no-repeat, no-repeat, repeat; + background-position: bottom right, left, right; +} +</pre> + +<table class="standard-table" style="width: 450px;"> + <tbody> + <tr> + <td class="header">Foto</td> + <td class="header">Demonstração ao vivo</td> + </tr> + <tr> + <td><img alt="css_multibg.png" class="default internal" src="/@api/deki/files/4028/=css_multibg.png"></td> + <td> </td> + </tr> + </tbody> +</table> + +<p>Como pode ver aqui, o logótipo do Firefox (listado primeiro) está no topo, seguida pelo gradiente, que está uma camada acima do fundo florido. Cada sub-propriedade ({{ cssxref("background-repeat") }} e {{ cssxref("background-position") }}) subsequentes aplicam-se aos fundos correspondentes. Dessa forma, o primeiro valor listado para {{ cssxref("background-repeat") }} aplica-se ao primeiro fundo (mais a frente), e assim por diante.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/en/Using_gradients" title="en/Using gradients">Utilizar gradients de CSS</a></li> +</ul> diff --git a/files/pt-pt/web/css/css_box_model/index.html b/files/pt-pt/web/css/css_box_model/index.html new file mode 100644 index 0000000000..cb4dd91343 --- /dev/null +++ b/files/pt-pt/web/css/css_box_model/index.html @@ -0,0 +1,167 @@ +--- +title: CSS Box Model +slug: Web/CSS/CSS_Box_Model +tags: + - CSS + - CSS Box Model + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Box_Model +--- +<div>{{CSSRef}}</div> + +<p><strong>CSS Box Model</strong> is a CSS module that defines the rectangular boxes, including their padding and margin, that are generated for elements and laid out according to the visual formatting model.</p> + +<h2 id="Reference">Reference</h2> + +<h3 id="Properties">Properties</h3> + +<h4 id="Properties_controlling_the_flow_of_content_in_a_box">Properties controlling the flow of content in a box</h4> + +<div class="index"> +<ul> + <li>{{cssxref("box-decoration-break")}}</li> + <li>{{cssxref("box-sizing")}}</li> + <li>{{cssxref("overflow")}}</li> + <li>{{cssxref("overflow-x")}}</li> + <li>{{cssxref("overflow-y")}}</li> +</ul> +</div> + +<h4 id="Properties_controlling_the_size_of_a_box">Properties controlling the size of a box</h4> + +<div class="index"> +<ul> + <li>{{cssxref("height")}}</li> + <li>{{cssxref("width")}}</li> + <li>{{cssxref("max-height")}}</li> + <li>{{cssxref("max-width")}}</li> + <li>{{cssxref("min-height")}}</li> + <li>{{cssxref("min-width")}}</li> +</ul> +</div> + +<h4 id="Properties_controlling_the_margins_of_a_box">Properties controlling the margins of a box</h4> + +<div class="index"> +<ul> + <li>{{cssxref("margin")}}</li> + <li>{{cssxref("margin-bottom")}}</li> + <li>{{cssxref("margin-left")}}</li> + <li>{{cssxref("margin-right")}}</li> + <li>{{cssxref("margin-top")}}</li> +</ul> +</div> + +<h4 id="Properties_controlling_the_paddings_of_a_box">Properties controlling the paddings of a box</h4> + +<div class="index"> +<ul> + <li>{{cssxref("padding")}}</li> + <li>{{cssxref("padding-bottom")}}</li> + <li>{{cssxref("padding-left")}}</li> + <li>{{cssxref("padding-right")}}</li> + <li>{{cssxref("padding-top")}}</li> +</ul> +</div> + +<h4 id="Other_properties">Other properties</h4> + +<div class="index"> +<ul> + <li>{{cssxref("box-shadow")}}</li> + <li>{{cssxref("visibility")}}</li> +</ul> +</div> + +<h2 id="Guides_and_tools">Guides and tools</h2> + +<dl> + <dt><a href="/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model">Introduction to the CSS box model</a></dt> + <dd>Explains one of the fundamental concept of CSS, the box model: describes the meaning of the margin, padding, as well as the different areas of a box.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing">Mastering margin collapsing</a></dt> + <dd>In several cases, two adjacent margins are collapsed into one. This article describes when this is happening and how to control it.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Box_Model/Box-shadow_generator">Box-shadow generator</a></dt> + <dd>An interactive tool that allows to visually create shadows and to generate the needed syntax for the {{cssxref("box-shadow")}} property.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSS3 Box")}}</td> + <td>{{Spec2("CSS3 Box")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS2.1", "box.html")}}</td> + <td>{{Spec2("CSS2.1")}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName("CSS1")}}</td> + <td>{{Spec2("CSS1")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{CompatGeckoDesktop("1")}}</td> + <td>3.0</td> + <td>3.5</td> + <td>1.0 (85)</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>1.0</td> + <td>{{CompatGeckoMobile("1")}}</td> + <td>6.0</td> + <td>6.0</td> + <td>1.0</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/pt-pt/web/css/css_box_model/introducao_modelo_caixa_css/index.html b/files/pt-pt/web/css/css_box_model/introducao_modelo_caixa_css/index.html new file mode 100644 index 0000000000..388a72ab39 --- /dev/null +++ b/files/pt-pt/web/css/css_box_model/introducao_modelo_caixa_css/index.html @@ -0,0 +1,69 @@ +--- +title: Introdução ao modelo de Caixa de CSS +slug: Web/CSS/CSS_Box_Model/Introducao_modelo_caixa_CSS +tags: + - CSS + - Modelo de Caixa de CSS + - Principiante + - Referencia +translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model +--- +<p>{{CSSRef}}</p> + +<h2 id="Resumo">Resumo</h2> + +<p>In a document, each element is represented as a rectangular box. Determining the size, properties — like its color, background, borders aspect — and the position of these boxes is the goal of the rendering engine.</p> + +<p>In CSS, each of these rectangular boxes is described using the standard <em>box model</em>. This model describes the space of the content taken by an element. Each box has four edges: the <strong>margin edge</strong>, <strong>border edge</strong>, <strong>padding edge</strong>, and <strong>content edge</strong>.</p> + +<p><img alt="CSS Box model" src="https://mdn.mozillademos.org/files/8685/boxmodel-(3).png" style="height: 384px; width: 548px;"></p> + +<p><a name="content-area"></a>The <strong>content area</strong> is the area containing the real content of the element. It often has a background, a color or an image (in that order, an opaque image hiding the background color) and is located inside the <em>content edge</em>; its dimensions are the <em>content width</em>, or <em>content-box width</em>, and the <em>content height</em>, or <em>content-box height</em>.</p> + +<p>If the CSS {{ cssxref("box-sizing") }} property is set to default, the CSS properties {{ cssxref("width") }}, {{ cssxref("min-width") }}, {{ cssxref("max-width") }}, {{ cssxref("height") }}, {{ cssxref("min-height") }} and {{ cssxref("max-height") }} control the content size.</p> + +<p><a name="padding-area"></a>The <strong>padding area</strong> extends to the border surrounding the padding. When the content area has a background, color, or image set on it, this will extend into the padding, which is why you can think of the padding as extending the content. The padding is located inside the <em>padding edge</em>, and its dimensions are the <em>padding-box width</em> and the <em>padding-box height</em>.</p> + +<p>The space between the padding and the content edge can be controlled using the {{ cssxref("padding-top") }}, {{ cssxref("padding-right") }}, {{ cssxref("padding-bottom") }}, {{ cssxref("padding-left") }} and the shorthand {{ cssxref("padding") }} CSS properties.</p> + +<p><a name="border-area"></a>The <strong>border area</strong> extends the padding area to the area containing the borders. It is the area inside the <em>border edge</em>, and its dimensions are the <em>border-box width</em> and the <em>border-box height</em>. This area depends on the size of the border that is defined by the {{ cssxref("border-width") }} property or the shorthand {{ cssxref("border") }}.</p> + +<p><a name="margin-area"></a>The <strong>margin area</strong> extends the border area with an empty area used to separate the element from its neighbors. It is the area inside the <em>margin edge</em>, and its dimensions are the <em>margin-box width </em>and the <em>margin-box height</em>.</p> + +<p>The size of the margin area is controlled using the {{ cssxref("margin-top") }}, {{ cssxref("margin-right") }}, {{ cssxref("margin-bottom") }}, {{ cssxref("margin-left") }} and the shorthand {{ cssxref("margin") }} CSS properties.</p> + +<p>When <a href="/en/CSS/margin_collapsing" title="en/CSS/margin_collapsing">margin collapsing</a> happens, the margin area is not clearly defined since margins are shared between boxes.</p> + +<p>Finally, note that, for non-replaced inline elements, the amount of space taken up (the contribution to the height of the line) is determined by the {{ cssxref('line-height') }} property, even though the border and padding appear visually around the content.</p> + +<h2 id="Especificação">Especificação</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName("CSS2.1","box.html#box-dimensions")}}</td> + <td>{{ Spec2('CSS2.1') }}</td> + <td>Though more precisely worded, there is no practical change</td> + </tr> + <tr> + <td>{{ SpecName("CSS1","#formatting-model")}}</td> + <td>{{ Spec2('CSS1') }}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/CSS/Refer%C3%AAncia_CSS" title="CSS Reference">Referência CSS</a></li> + <li>{{ CSS_key_concepts() }}</li> + <li>Related CSS properties: {{ cssxref("box-sizing") }}, {{ cssxref("background-clip") }}, {{ cssxref("height") }}, {{ cssxref("max-height") }}, {{ cssxref("min-height") }}, {{ cssxref("width") }}, {{ cssxref("max-height") }}, {{ cssxref("min-height") }}, {{ cssxref("padding") }}, {{ cssxref("padding-top") }}, {{ cssxref("padding-right") }}, {{ cssxref("padding-bottom") }}, {{ cssxref("padding-left") }}, {{ cssxref("border") }}, {{ cssxref("border-top") }}, {{ cssxref("border-right") }}, {{ cssxref("border-bottom") }}, {{ cssxref("border-left") }}, {{ cssxref("border-width") }}, {{ cssxref("border-top-width") }}, {{ cssxref("border-right-width") }}, {{ cssxref("border-bottom-width") }}, {{ cssxref("border-left-width") }}, {{ cssxref("margin") }}, {{ cssxref("margin-top") }}, {{ cssxref("margin-right") }}, {{ cssxref("margin-bottom") }}, {{ cssxref("margin-left") }}</li> +</ul> diff --git a/files/pt-pt/web/css/css_colors/ferramenta_selecao_cor/index.html b/files/pt-pt/web/css/css_colors/ferramenta_selecao_cor/index.html new file mode 100644 index 0000000000..696f2afd11 --- /dev/null +++ b/files/pt-pt/web/css/css_colors/ferramenta_selecao_cor/index.html @@ -0,0 +1,3243 @@ +--- +title: Ferramenta de seleção de cor +slug: Web/CSS/CSS_Colors/Ferramenta_selecao_cor +tags: + - CSS + - Ferramentas + - Seleção de cor + - cor +translation_of: Web/CSS/CSS_Colors/Color_picker_tool +--- +<div style="display: none;"> +<h2 id="ColorPicker_Tool" name="ColorPicker_Tool">ColorPicker tool</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"> <div id="container"> + <div id="palette" class="block"> + <div id="color-palette"></div> + <div id="color-info"> + <div class="title"> CSS Color </div> + </div> + </div> + + <div id="picker" class="block"> + <div class="ui-color-picker" data-topic="picker" data-mode="HSL"></div> + <div id="picker-samples" sample-id="master"></div> + <div id="controls"> + <div id="delete"> + <div id="trash-can"></div> + </div> + <div id="void-sample" class="icon"></div> + </div> + </div> + + <div id="canvas" data-tutorial="drop"> + <div id="zindex" class="ui-input-slider" data-topic="z-index" data-info="z-index" + data-max="20" data-sensivity="10"></div> + </div> + </div> + +</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">/* + * COLOR PICKER TOOL + */ + +.ui-color-picker { + width: 420px; + margin: 0; + border: 1px solid #DDD; + background-color: #FFF; + display: table; + + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.ui-color-picker .picking-area { + width: 198px; + height: 198px; + margin: 5px; + border: 1px solid #DDD; + position: relative; + float: left; + display: table; +} + +.ui-color-picker .picking-area:hover { + cursor: default; +} + +/* HSV format - Hue-Saturation-Value(Brightness) */ +.ui-color-picker .picking-area { + background: url('https://mdn.mozillademos.org/files/5707/picker_mask_200.png') center center; + + background: -moz-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%), + -moz-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%); + background: -webkit-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%), + -webkit-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%); + background: -ms-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%), + -ms-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%); + background: -o-linear-gradient(bottom, #000 0%, rgba(0, 0, 0, 0) 100%), + -o-linear-gradient(left, #FFF 0%, rgba(255, 255, 255, 0) 100%); + + background-color: #F00; +} + +/* HSL format - Hue-Saturation-Lightness */ +.ui-color-picker[data-mode='HSL'] .picking-area { + background: -moz-linear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%, + hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%), + -moz-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%); + background: -webkit-linear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%, + hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%), + -webkit-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%); + background: -ms-linear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%, + hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%), + -ms-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%); + background: -o-linear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%, + hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%), + -o-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%); + background-color: #F00; +} + +.ui-color-picker .picker { + width: 10px; + height: 10px; + border-radius: 50%; + border: 1px solid #FFF; + position: absolute; + top: 45%; + left: 45%; +} + +.ui-color-picker .picker:before { + width: 8px; + height: 8px; + content: ""; + position: absolute; + border: 1px solid #999; + border-radius: 50%; +} + +.ui-color-picker .hue, +.ui-color-picker .alpha { + width: 198px; + height: 28px; + margin: 5px; + border: 1px solid #FFF; + float: left; +} + +.ui-color-picker .hue { + background: url("https://mdn.mozillademos.org/files/5701/hue.png") center; + background: -moz-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%, + #00F 66.66%, #F0F 83.33%, #F00 100%); + background: -webkit-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%, + #00F 66.66%, #F0F 83.33%, #F00 100%); + background: -ms-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%, + #00F 66.66%, #F0F 83.33%, #F00 100%); + background: -o-linear-gradient(left, #F00 0%, #FF0 16.66%, #0F0 33.33%, #0FF 50%, + #00F 66.66%, #F0F 83.33%, #F00 100%); +} + +.ui-color-picker .alpha { + border: 1px solid #CCC; + background: url("https://mdn.mozillademos.org/files/5705/alpha.png"); +} + +.ui-color-picker .alpha-mask { + width: 100%; + height: 100%; + background: url("https://mdn.mozillademos.org/files/6089/alpha_mask.png"); +} + +.ui-color-picker .slider-picker { + width: 2px; + height: 100%; + border: 1px solid #777; + background-color: #FFF; + position: relative; + top: -1px; +} + +/* input HSV and RGB */ + +.ui-color-picker .info { + width: 200px; + margin: 5px; + float: left; +} + +.ui-color-picker .info * { + float: left; +} + +.ui-color-picker .input { + width: 64px; + margin: 5px 2px; + float: left; +} + +.ui-color-picker .input .name { + height: 20px; + width: 30px; + text-align: center; + font-size: 14px; + line-height: 18px; + float: left; +} + +.ui-color-picker .input input { + width: 30px; + height: 18px; + margin: 0; + padding: 0; + border: 1px solid #DDD; + text-align: center; + float: right; + + -moz-user-select: text; + -webkit-user-select: text; + -ms-user-select: text; +} + +.ui-color-picker .input[data-topic="lightness"] { + display: none; +} + +.ui-color-picker[data-mode='HSL'] .input[data-topic="value"] { + display: none; +} + +.ui-color-picker[data-mode='HSL'] .input[data-topic="lightness"] { + display: block; +} + +.ui-color-picker .input[data-topic="alpha"] { + margin-top: 10px; + width: 93px; +} + +.ui-color-picker .input[data-topic="alpha"] > .name { + width: 60px; +} + +.ui-color-picker .input[data-topic="alpha"] > input { + float: right; +} + +.ui-color-picker .input[data-topic="hexa"] { + width: auto; + float: right; + margin: 6px 8px 0 0; +} + +.ui-color-picker .input[data-topic="hexa"] > .name { + display: none; +} + +.ui-color-picker .input[data-topic="hexa"] > input { + width: 90px; + height: 24px; + padding: 2px 0; + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +/* Preview color */ +.ui-color-picker .preview { + width: 95px; + height: 53px; + margin: 5px; + margin-top: 10px; + border: 1px solid #DDD; + background-image: url("https://mdn.mozillademos.org/files/5705/alpha.png"); + float: left; + position: relative; +} + +.ui-color-picker .preview:before { + height: 100%; + width: 50%; + left: 50%; + top: 0; + content: ""; + background: #FFF; + position: absolute; + z-index: 1; +} + +.ui-color-picker .preview-color { + width: 100%; + height: 100%; + background-color: rgba(255, 0, 0, 0.5); + position: absolute; + z-index: 1; +} + +.ui-color-picker .switch_mode { + width: 10px; + height: 20px; + position: relative; + border-radius: 5px 0 0 5px; + border: 1px solid #DDD; + background-color: #EEE; + left: -12px; + top: -1px; + z-index: 1; + transition: all 0.5s; +} + +.ui-color-picker .switch_mode:hover { + background-color: #CCC; + cursor: pointer; +} + +/* + * UI Component + */ + +.ui-input-slider { + height: 20px; + font-family: "Segoe UI", Arial, Helvetica, sans-serif; + -moz-user-select: none; + user-select: none; +} + +.ui-input-slider * { + float: left; + height: 100%; + line-height: 100%; +} + +/* Input Slider */ + +.ui-input-slider > input { + margin: 0; + padding: 0; + width: 50px; + text-align: center; + + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +.ui-input-slider-info { + width: 90px; + padding: 0px 10px 0px 0px; + text-align: right; + text-transform: lowercase; +} + +.ui-input-slider-left, .ui-input-slider-right { + width: 16px; + cursor: pointer; + background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center left no-repeat; +} + +.ui-input-slider-right { + background: url("https://mdn.mozillademos.org/files/5679/arrows.png") center right no-repeat; +} + +.ui-input-slider-name { + width: 90px; + padding: 0 10px 0 0; + text-align: right; + text-transform: lowercase; +} + +.ui-input-slider-btn-set { + width: 25px; + background-color: #2C9FC9; + border-radius: 5px; + color: #FFF; + font-weight: bold; + line-height: 14px; + text-align: center; +} + +.ui-input-slider-btn-set:hover { + background-color: #379B4A; + cursor: pointer; +} + +/* + * COLOR PICKER TOOL + */ + +body { + max-width: 1000px; + margin: 0 auto; + + font-family: "Segoe UI", Arial, Helvetica, sans-serif; + + box-shadow: 0 0 5px 0 #999; + + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + + -moz-user-select: none; + -webkit-user-select: none; + -ms-user-select: none; + user-select: none; + +} + +/** + * Resize Handle + */ +.resize-handle { + width: 10px; + height: 10px; + background: url('https://mdn.mozillademos.org/files/6083/resize.png') center center no-repeat; + position: absolute; + bottom: 0; + right: 0; +} + +[data-resize='both']:hover { + cursor: nw-resize !important; +} + +[data-resize='width']:hover { + cursor: w-resize !important; +} + +[data-resize='height']:hover { + cursor: n-resize !important; +} + +[data-hidden='true'] { + display: none; +} + +[data-collapsed='true'] { + height: 0 !important; +} + +.block { + display: table; +} + + +/** + * Container + */ +#container { + width: 100%; + + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + + display: table; +} + +/** + * Picker Zone + */ + +#picker { + padding: 10px; + width: 980px; +} + +.ui-color-picker { + padding: 3px 5px; + float: left; + border-color: #FFF; +} + +.ui-color-picker .switch_mode { + display: none; +} + +.ui-color-picker .preview-color:hover { + cursor: move; +} + +/** + * Picker Container + */ + +#picker-samples { + width: 375px; + height: 114px; + max-height: 218px; + margin: 0 10px 0 30px; + overflow: hidden; + position: relative; + float: left; + + transition: all 0.2s; +} + +#picker-samples .sample { + width: 40px; + height: 40px; + margin: 5px; + border: 1px solid #DDD; + position: absolute; + float: left; + transition: all 0.2s; +} + +#picker-samples .sample:hover { + cursor: pointer; + border-color: #BBB; + transform: scale(1.15); + border-radius: 3px; +} + +#picker-samples .sample[data-active='true'] { + border-color: #999; +} + +#picker-samples .sample[data-active='true']:after { + content: ""; + position: absolute; + background: url('https://mdn.mozillademos.org/files/6065/arrow.png') center no-repeat; + width: 100%; + height: 12px; + top: -12px; + z-index: 2; +} + +#picker-samples #add-icon { + width: 100%; + height: 100%; + position: relative; + box-shadow: inset 0px 0px 2px 0px #DDD; +} + +#picker-samples #add-icon:hover { + cursor: pointer; + border-color: #DDD; + box-shadow: inset 0px 0px 5px 0px #CCC; +} + +#picker-samples #add-icon:before, +#picker-samples #add-icon:after { + content: ""; + position: absolute; + background-color: #EEE; + box-shadow: 0 0 1px 0 #EEE; +} + +#picker-samples #add-icon:before { + width: 70%; + height: 16%; + top: 42%; + left: 15%; +} + +#picker-samples #add-icon:after { + width: 16%; + height: 70%; + top: 15%; + left: 42%; +} + +#picker-samples #add-icon:hover:before, +#picker-samples #add-icon:hover:after { + background-color: #DDD; + box-shadow: 0 0 1px 0 #DDD; +} + +/** + * Controls + */ + +#controls { + width: 110px; + padding: 10px; + float: right; +} + +#controls #picker-switch { + text-align: center; + float: left; +} + +#controls .icon { + width: 48px; + height: 48px; + margin: 10px 0; + background-repeat: no-repeat; + background-position: center; + border: 1px solid #DDD; + display: table; + float: left; +} + +#controls .icon:hover { + cursor: pointer; +} + +#controls .picker-icon { + background-image: url('https://mdn.mozillademos.org/files/6081/picker.png'); +} + +#controls #void-sample { + margin-right: 10px; + background-image: url('https://mdn.mozillademos.org/files/6087/void.png'); + background-position: center left; +} + +#controls #void-sample[data-active='true'] { + border-color: #CCC; + background-position: center right; +} + +#controls .switch { + width: 106px; + padding: 1px; + border: 1px solid #CCC; + font-size: 14px; + text-align: center; + line-height: 24px; + overflow: hidden; + float: left; +} + +#controls .switch:hover { + cursor: pointer; +} + +#controls .switch > * { + width: 50%; + padding: 2px 0; + background-color: #EEE; + float: left; +} + +#controls .switch [data-active='true'] { + color: #FFF; + background-image: url('https://mdn.mozillademos.org/files/6025/grain.png'); + background-color: #777; +} + +/** + * Trash Can + */ + +#delete { + width: 100%; + height: 94px; + background-color: #DDD; + background-image: url('https://mdn.mozillademos.org/files/6025/grain.png'); + background-repeat: repeat; + + text-align: center; + color: #777; + + position: relative; + float: right; +} + +#delete #trash-can { + width: 80%; + height: 80%; + border: 2px dashed #FFF; + border-radius: 5px; + background: url('https://mdn.mozillademos.org/files/6085/trash-can.png') no-repeat center; + + position: absolute; + top: 10%; + left: 10%; + + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; + + transition: all 0.2s; +} + +#delete[drag-state='enter'] { + background-color: #999; +} + +/** + * Color Theme + */ + +#color-theme { + margin: 0 8px 0 0; + border: 1px solid #EEE; + display: inline-block; + float: right; +} + +#color-theme .box { + width: 80px; + height: 92px; + float: left; +} + +/** + * Color info box + */ +#color-info { + width: 360px; + float: left; +} + +#color-info .title { + width: 100%; + padding: 15px; + font-size: 18px; + text-align: center; + background-image: url('https://mdn.mozillademos.org/files/6071/color-wheel.png'); + background-repeat:no-repeat; + background-position: center left 30%; +} + +#color-info .copy-container { + position: absolute; + top: -100%; +} + +#color-info .property { + min-width: 280px; + height: 30px; + margin: 10px 0; + text-align: center; + line-height: 30px; +} + +#color-info .property > * { + float: left; +} + +#color-info .property .type { + width: 60px; + height: 100%; + padding: 0 16px 0 0; + text-align: right; +} + +#color-info .property .value { + width: 200px; + height: 100%; + padding: 0 10px; + font-family: "Segoe UI", Arial, Helvetica, sans-serif; + font-size: 16px; + color: #777; + text-align: center; + background-color: #FFF; + border: none; +} + +#color-info .property .value:hover { + color: #37994A; +} + +#color-info .property .value:hover + .copy { + background-position: center right; +} + +#color-info .property .copy { + width: 24px; + height: 100%; + padding: 0 5px; + background-color: #FFF; + background-image: url('https://mdn.mozillademos.org/files/6073/copy.png'); + background-repeat: no-repeat; + background-position: center left; + border-left: 1px solid #EEE; + text-align: right; + float: left; +} + +#color-info .property .copy:hover { + background-position: center right; +} + + +/** + * Color Palette + */ + +#palette { + width: 1000px; + padding: 10px 0; + background-image: url('https://mdn.mozillademos.org/files/6025/grain.png'); + background-repeat: repeat; + background-color: #EEE; + color: #777; + + -moz-box-sizing: border-box; + -webkit-box-sizing: border-box; + box-sizing: border-box; +} + +#color-palette { + width: 640px; + font-family: Arial, Helvetica, sans-serif; + color: #777; + float: left; +} + +#color-palette .container { + width: 100%; + height: 50px; + line-height: 50px; + overflow: hidden; + float: left; + transition: all 0.5s; +} + +#color-palette .container > * { + float: left; +} + +#color-palette .title { + width: 100px; + padding: 0 10px; + text-align: right; + line-height: inherit; +} + +#color-palette .palette { + width: 456px; + height: 38px; + margin: 3px; + padding: 3px; + display: table; + background-color: #FFF; +} + +#color-palette .palette .sample { + width: 30px; + height: 30px; + margin: 3px; + position: relative; + border: 1px solid #DDD; + float: left; + transition: all 0.2s; +} + +#color-palette .palette .sample:hover { + cursor: pointer; + border-color: #BBB; + transform: scale(1.15); + border-radius: 3px; +} + +#color-palette .controls { +} + +#color-palette .controls > * { + float: left; +} + +#color-palette .controls > *:hover { + cursor: pointer; +} + +#color-palette .controls .lock { + width: 24px; + height: 24px; + margin: 10px; + padding: 3px; + background-image: url('https://mdn.mozillademos.org/files/6077/lock.png'); + background-repeat: no-repeat; + background-position: bottom right; +} + +#color-palette .controls .lock:hover { + /*background-image: url('images/unlocked-hover.png');*/ + background-position: bottom left; +} + +#color-palette .controls .lock[locked-state='true'] { + /*background-image: url('images/locked.png');*/ + background-position: top left ; +} + +#color-palette .controls .lock[locked-state='true']:hover { + /*background-image: url('images/lock-hover.png');*/ + background-position: top right; +} + +/** + * Canvas + */ + +#canvas { + width: 100%; + height: 300px; + min-height: 250px; + border-top: 1px solid #DDD; + background-image: url('https://mdn.mozillademos.org/files/6025/grain.png'); + background-repeat: repeat; + position: relative; + float: left; +} + +#canvas[data-tutorial='drop'] { + text-align: center; + font-size: 30px; + color: #777; +} + +#canvas[data-tutorial='drop']:before { + content: "Drop colors here to compare"; + width: 40%; + padding: 30px 9% 70px 11%; + + background-image: url('https://mdn.mozillademos.org/files/6075/drop.png'); + background-repeat: no-repeat; + background-position: left 35px top 60%; + + text-align: right; + + border: 3px dashed rgb(221, 221, 221); + border-radius: 15px; + + position: absolute; + top: 50px; + left: 20%; +} + +#canvas[data-tutorial='drop']:after { + content: "adjust, change or modify"; + width: 40%; + font-size: 24px; + position: absolute; + top: 130px; + left: 32%; + z-index: 2; +} + +#canvas [data-tutorial='dblclick'] { + background-color: #999 !important; +} + +#canvas [data-tutorial='dblclick']:before { + content: "double click to activate"; + width: 80px; + color: #FFF; + position: absolute; + top: 10%; + left: 20%; + z-index: 2; +} + +#canvas .sample { + width: 100px; + height: 100px; + min-width: 20px; + min-height: 20px; + position: absolute; + border: 1px solid rgba(255, 255, 255, 0.3); +} + +#canvas .sample:hover { + cursor: move; +} + +#canvas .sample[data-active='true']:after { + content: ""; + position: absolute; + background: url('https://mdn.mozillademos.org/files/6065/arrow.png') center no-repeat; + width: 100%; + height: 12px; + top: -12px; + z-index: 2; +} + +#canvas .sample:hover > * { + cursor: pointer; + display: block !important; +} + +#canvas .sample .resize-handle { + display: none; +} + +#canvas .sample .pick { + width: 10px; + height: 10px; + margin: 5px; + background: url('https://mdn.mozillademos.org/files/6079/pick.png') center no-repeat; + position: absolute; + top: 0; + left: 0; + display: none; +} + +#canvas .sample .delete { + width: 10px; + height: 10px; + margin: 5px; + background: url('https://mdn.mozillademos.org/files/6069/close.png') center no-repeat; + position: absolute; + top: 0; + right: 0; + display: none; +} + + +/** + * Canvas controls + */ + +#canvas .toggle-bg { + width: 16px; + height: 16px; + margin: 5px; + background: url("images/canvas-controls.png") center left no-repeat; + position: absolute; + top: 0; + right: 0; +} + +#canvas .toggle-bg:hover { + cursor: pointer; +} + +#canvas[data-bg='true'] { + background: none; +} + +#canvas[data-bg='true'] .toggle-bg { + background: url('https://mdn.mozillademos.org/files/6067/canvas-controls.png') center right no-repeat; +} + +#zindex { + height: 20px; + margin: 5px; + font-size: 16px; + position: absolute; + opacity: 0; + top: -10000px; + left: 0; + color: #777; + float: left; + transition: opacity 1s; +} + +#zindex input { + border: 1px solid #DDD; + font-size: 16px; + color: #777; +} + +#zindex .ui-input-slider-info { + width: 60px; +} + +#zindex[data-active='true'] { + top: 0; + opacity: 1; +} + +</pre> + +<h3 id="JavaScript_Content">JavaScript Content</h3> + +<pre class="brush: js">'use strict'; + +var UIColorPicker = (function UIColorPicker() { + + function getElemById(id) { + return document.getElementById(id); + } + + var subscribers = []; + var pickers = []; + + /** + * RGBA Color class + * + * HSV/HSB and HSL (hue, saturation, value / brightness, lightness) + * @param hue 0-360 + * @param saturation 0-100 + * @param value 0-100 + * @param lightness 0-100 + */ + + function Color(color) { + + if(color instanceof Color === true) { + this.copy(color); + return; + } + + this.r = 0; + this.g = 0; + this.b = 0; + this.a = 1; + this.hue = 0; + this.saturation = 0; + this.value = 0; + this.lightness = 0; + this.format = 'HSV'; + } + + function RGBColor(r, g, b) { + var color = new Color(); + color.setRGBA(r, g, b, 1); + return color; + } + + function RGBAColor(r, g, b, a) { + var color = new Color(); + color.setRGBA(r, g, b, a); + return color; + } + + function HSVColor(h, s, v) { + var color = new Color(); + color.setHSV(h, s, v); + return color; + } + + function HSVAColor(h, s, v, a) { + var color = new Color(); + color.setHSV(h, s, v); + color.a = a; + return color; + } + + function HSLColor(h, s, l) { + var color = new Color(); + color.setHSL(h, s, l); + return color; + } + + function HSLAColor(h, s, l, a) { + var color = new Color(); + color.setHSL(h, s, l); + color.a = a; + return color; + } + + Color.prototype.copy = function copy(obj) { + if(obj instanceof Color !== true) { + console.log('Typeof parameter not Color'); + return; + } + + this.r = obj.r; + this.g = obj.g; + this.b = obj.b; + this.a = obj.a; + this.hue = obj.hue; + this.saturation = obj.saturation; + this.value = obj.value; + this.format = '' + obj.format; + this.lightness = obj.lightness; + }; + + Color.prototype.setFormat = function setFormat(format) { + if (format === 'HSV') + this.format = 'HSV'; + if (format === 'HSL') + this.format = 'HSL'; + }; + + /*========== Methods to set Color Properties ==========*/ + + Color.prototype.isValidRGBValue = function isValidRGBValue(value) { + return (typeof(value) === 'number' && isNaN(value) === false && + value >= 0 && value <= 255); + }; + + Color.prototype.setRGBA = function setRGBA(red, green, blue, alpha) { + if (this.isValidRGBValue(red) === false || + this.isValidRGBValue(green) === false || + this.isValidRGBValue(blue) === false) + return; + + this.r = red | 0; + this.g = green | 0; + this.b = blue | 0; + + if (this.isValidRGBValue(alpha) === true) + this.a = alpha | 0; + }; + + Color.prototype.setByName = function setByName(name, value) { + if (name === 'r' || name === 'g' || name === 'b') { + if(this.isValidRGBValue(value) === false) + return; + + this[name] = value; + this.updateHSX(); + } + }; + + Color.prototype.setHSV = function setHSV(hue, saturation, value) { + this.hue = hue; + this.saturation = saturation; + this.value = value; + this.HSVtoRGB(); + }; + + Color.prototype.setHSL = function setHSL(hue, saturation, lightness) { + this.hue = hue; + this.saturation = saturation; + this.lightness = lightness; + this.HSLtoRGB(); + }; + + Color.prototype.setHue = function setHue(value) { + if (typeof(value) !== 'number' || isNaN(value) === true || + value < 0 || value > 359) + return; + this.hue = value; + this.updateRGB(); + }; + + Color.prototype.setSaturation = function setSaturation(value) { + if (typeof(value) !== 'number' || isNaN(value) === true || + value < 0 || value > 100) + return; + this.saturation = value; + this.updateRGB(); + }; + + Color.prototype.setValue = function setValue(value) { + if (typeof(value) !== 'number' || isNaN(value) === true || + value < 0 || value > 100) + return; + this.value = value; + this.HSVtoRGB(); + }; + + Color.prototype.setLightness = function setLightness(value) { + if (typeof(value) !== 'number' || isNaN(value) === true || + value < 0 || value > 100) + return; + this.lightness = value; + this.HSLtoRGB(); + }; + + Color.prototype.setHexa = function setHexa(value) { + var valid = /(^#{0,1}[0-9A-F]{6}$)|(^#{0,1}[0-9A-F]{3}$)/i.test(value); + + if (valid !== true) + return; + + if (value[0] === '#') + value = value.slice(1, value.length); + + if (value.length === 3) + value = value.replace(/([0-9A-F])([0-9A-F])([0-9A-F])/i,'$1$1$2$2$3$3'); + + this.r = parseInt(value.substr(0, 2), 16); + this.g = parseInt(value.substr(2, 2), 16); + this.b = parseInt(value.substr(4, 2), 16); + + this.alpha = 1; + this.RGBtoHSV(); + }; + + /*========== Conversion Methods ==========*/ + + Color.prototype.convertToHSL = function convertToHSL() { + if (this.format === 'HSL') + return; + + this.setFormat('HSL'); + this.RGBtoHSL(); + }; + + Color.prototype.convertToHSV = function convertToHSV() { + if (this.format === 'HSV') + return; + + this.setFormat('HSV'); + this.RGBtoHSV(); + }; + + /*========== Update Methods ==========*/ + + Color.prototype.updateRGB = function updateRGB() { + if (this.format === 'HSV') { + this.HSVtoRGB(); + return; + } + + if (this.format === 'HSL') { + this.HSLtoRGB(); + return; + } + }; + + Color.prototype.updateHSX = function updateHSX() { + if (this.format === 'HSV') { + this.RGBtoHSV(); + return; + } + + if (this.format === 'HSL') { + this.RGBtoHSL(); + return; + } + }; + + Color.prototype.HSVtoRGB = function HSVtoRGB() { + var sat = this.saturation / 100; + var value = this.value / 100; + var C = sat * value; + var H = this.hue / 60; + var X = C * (1 - Math.abs(H % 2 - 1)); + var m = value - C; + var precision = 255; + + C = (C + m) * precision | 0; + X = (X + m) * precision | 0; + m = m * precision | 0; + + if (H >= 0 && H < 1) { this.setRGBA(C, X, m); return; } + if (H >= 1 && H < 2) { this.setRGBA(X, C, m); return; } + if (H >= 2 && H < 3) { this.setRGBA(m, C, X); return; } + if (H >= 3 && H < 4) { this.setRGBA(m, X, C); return; } + if (H >= 4 && H < 5) { this.setRGBA(X, m, C); return; } + if (H >= 5 && H < 6) { this.setRGBA(C, m, X); return; } + }; + + Color.prototype.HSLtoRGB = function HSLtoRGB() { + var sat = this.saturation / 100; + var light = this.lightness / 100; + var C = sat * (1 - Math.abs(2 * light - 1)); + var H = this.hue / 60; + var X = C * (1 - Math.abs(H % 2 - 1)); + var m = light - C/2; + var precision = 255; + + C = (C + m) * precision | 0; + X = (X + m) * precision | 0; + m = m * precision | 0; + + if (H >= 0 && H < 1) { this.setRGBA(C, X, m); return; } + if (H >= 1 && H < 2) { this.setRGBA(X, C, m); return; } + if (H >= 2 && H < 3) { this.setRGBA(m, C, X); return; } + if (H >= 3 && H < 4) { this.setRGBA(m, X, C); return; } + if (H >= 4 && H < 5) { this.setRGBA(X, m, C); return; } + if (H >= 5 && H < 6) { this.setRGBA(C, m, X); return; } + }; + + Color.prototype.RGBtoHSV = function RGBtoHSV() { + var red = this.r / 255; + var green = this.g / 255; + var blue = this.b / 255; + + var cmax = Math.max(red, green, blue); + var cmin = Math.min(red, green, blue); + var delta = cmax - cmin; + var hue = 0; + var saturation = 0; + + if (delta) { + if (cmax === red ) { hue = ((green - blue) / delta); } + if (cmax === green ) { hue = 2 + (blue - red) / delta; } + if (cmax === blue ) { hue = 4 + (red - green) / delta; } + if (cmax) saturation = delta / cmax; + } + + this.hue = 60 * hue | 0; + if (this.hue < 0) this.hue += 360; + this.saturation = (saturation * 100) | 0; + this.value = (cmax * 100) | 0; + }; + + Color.prototype.RGBtoHSL = function RGBtoHSL() { + var red = this.r / 255; + var green = this.g / 255; + var blue = this.b / 255; + + var cmax = Math.max(red, green, blue); + var cmin = Math.min(red, green, blue); + var delta = cmax - cmin; + var hue = 0; + var saturation = 0; + var lightness = (cmax + cmin) / 2; + var X = (1 - Math.abs(2 * lightness - 1)); + + if (delta) { + if (cmax === red ) { hue = ((green - blue) / delta); } + if (cmax === green ) { hue = 2 + (blue - red) / delta; } + if (cmax === blue ) { hue = 4 + (red - green) / delta; } + if (cmax) saturation = delta / X; + } + + this.hue = 60 * hue | 0; + if (this.hue < 0) this.hue += 360; + this.saturation = (saturation * 100) | 0; + this.lightness = (lightness * 100) | 0; + }; + + /*========== Get Methods ==========*/ + + Color.prototype.getHexa = function getHexa() { + var r = this.r.toString(16); + var g = this.g.toString(16); + var b = this.b.toString(16); + if (this.r < 16) r = '0' + r; + if (this.g < 16) g = '0' + g; + if (this.b < 16) b = '0' + b; + var value = '#' + r + g + b; + return value.toUpperCase(); + }; + + Color.prototype.getRGBA = function getRGBA() { + + var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; + var a = ''; + var v = ''; + var x = parseFloat(this.a); + if (x !== 1) { + a = 'a'; + v = ', ' + x; + } + + var value = 'rgb' + a + rgb + v + ')'; + return value; + }; + + Color.prototype.getHSLA = function getHSLA() { + if (this.format === 'HSV') { + var color = new Color(this); + color.setFormat('HSL'); + color.updateHSX(); + return color.getHSLA(); + } + + var a = ''; + var v = ''; + var hsl = '(' + this.hue + ', ' + this.saturation + '%, ' + this.lightness +'%'; + var x = parseFloat(this.a); + if (x !== 1) { + a = 'a'; + v = ', ' + x; + } + + var value = 'hsl' + a + hsl + v + ')'; + return value; + }; + + Color.prototype.getColor = function getColor() { + if (this.a | 0 === 1) + return this.getHexa(); + return this.getRGBA(); + }; + + /*=======================================================================*/ + /*=======================================================================*/ + + /*========== Capture Mouse Movement ==========*/ + + var setMouseTracking = function setMouseTracking(elem, callback) { + elem.addEventListener('mousedown', function(e) { + callback(e); + document.addEventListener('mousemove', callback); + }); + + document.addEventListener('mouseup', function(e) { + document.removeEventListener('mousemove', callback); + }); + }; + + /*====================*/ + // Color Picker Class + /*====================*/ + + function ColorPicker(node) { + this.color = new Color(); + this.node = node; + this.subscribers = []; + + var type = this.node.getAttribute('data-mode'); + var topic = this.node.getAttribute('data-topic'); + + this.topic = topic; + this.picker_mode = (type === 'HSL') ? 'HSL' : 'HSV'; + this.color.setFormat(this.picker_mode); + + this.createPickingArea(); + this.createHueArea(); + + this.newInputComponent('H', 'hue', this.inputChangeHue.bind(this)); + this.newInputComponent('S', 'saturation', this.inputChangeSaturation.bind(this)); + this.newInputComponent('V', 'value', this.inputChangeValue.bind(this)); + this.newInputComponent('L', 'lightness', this.inputChangeLightness.bind(this)); + + this.createAlphaArea(); + + this.newInputComponent('R', 'red', this.inputChangeRed.bind(this)); + this.newInputComponent('G', 'green', this.inputChangeGreen.bind(this)); + this.newInputComponent('B', 'blue', this.inputChangeBlue.bind(this)); + + this.createPreviewBox(); + this.createChangeModeButton(); + + this.newInputComponent('alpha', 'alpha', this.inputChangeAlpha.bind(this)); + this.newInputComponent('hexa', 'hexa', this.inputChangeHexa.bind(this)); + + this.setColor(this.color); + pickers[topic] = this; + } + + /*************************************************************************/ + // Function for generating the color-picker + /*************************************************************************/ + + ColorPicker.prototype.createPickingArea = function createPickingArea() { + var area = document.createElement('div'); + var picker = document.createElement('div'); + + area.className = 'picking-area'; + picker.className = 'picker'; + + this.picking_area = area; + this.color_picker = picker; + setMouseTracking(area, this.updateColor.bind(this)); + + area.appendChild(picker); + this.node.appendChild(area); + }; + + ColorPicker.prototype.createHueArea = function createHueArea() { + var area = document.createElement('div'); + var picker = document.createElement('div'); + + area.className = 'hue'; + picker.className ='slider-picker'; + + this.hue_area = area; + this.hue_picker = picker; + setMouseTracking(area, this.updateHueSlider.bind(this)); + + area.appendChild(picker); + this.node.appendChild(area); + }; + + ColorPicker.prototype.createAlphaArea = function createAlphaArea() { + var area = document.createElement('div'); + var mask = document.createElement('div'); + var picker = document.createElement('div'); + + area.className = 'alpha'; + mask.className = 'alpha-mask'; + picker.className = 'slider-picker'; + + this.alpha_area = area; + this.alpha_mask = mask; + this.alpha_picker = picker; + setMouseTracking(area, this.updateAlphaSlider.bind(this)); + + area.appendChild(mask); + mask.appendChild(picker); + this.node.appendChild(area); + }; + + ColorPicker.prototype.createPreviewBox = function createPreviewBox(e) { + var preview_box = document.createElement('div'); + var preview_color = document.createElement('div'); + + preview_box.className = 'preview'; + preview_color.className = 'preview-color'; + + this.preview_color = preview_color; + + preview_box.appendChild(preview_color); + this.node.appendChild(preview_box); + }; + + ColorPicker.prototype.newInputComponent = function newInputComponent(title, topic, onChangeFunc) { + var wrapper = document.createElement('div'); + var input = document.createElement('input'); + var info = document.createElement('span'); + + wrapper.className = 'input'; + wrapper.setAttribute('data-topic', topic); + info.textContent = title; + info.className = 'name'; + input.setAttribute('type', 'text'); + + wrapper.appendChild(info); + wrapper.appendChild(input); + this.node.appendChild(wrapper); + + input.addEventListener('change', onChangeFunc); + input.addEventListener('click', function() { + this.select(); + }); + + this.subscribe(topic, function(value) { + input.value = value; + }); + }; + + ColorPicker.prototype.createChangeModeButton = function createChangeModeButton() { + + var button = document.createElement('div'); + button.className = 'switch_mode'; + button.addEventListener('click', function() { + if (this.picker_mode === 'HSV') + this.setPickerMode('HSL'); + else + this.setPickerMode('HSV'); + + }.bind(this)); + + this.node.appendChild(button); + }; + + /*************************************************************************/ + // Updates properties of UI elements + /*************************************************************************/ + + ColorPicker.prototype.updateColor = function updateColor(e) { + var x = e.pageX - this.picking_area.offsetLeft; + var y = e.pageY - this.picking_area.offsetTop; + var picker_offset = 5; + + // width and height should be the same + var size = this.picking_area.clientWidth; + + if (x > size) x = size; + if (y > size) y = size; + if (x < 0) x = 0; + if (y < 0) y = 0; + + var value = 100 - (y * 100 / size) | 0; + var saturation = x * 100 / size | 0; + + if (this.picker_mode === 'HSV') + this.color.setHSV(this.color.hue, saturation, value); + if (this.picker_mode === 'HSL') + this.color.setHSL(this.color.hue, saturation, value); + + this.color_picker.style.left = x - picker_offset + 'px'; + this.color_picker.style.top = y - picker_offset + 'px'; + + this.updateAlphaGradient(); + this.updatePreviewColor(); + + this.notify('value', value); + this.notify('lightness', value); + this.notify('saturation', saturation); + + this.notify('red', this.color.r); + this.notify('green', this.color.g); + this.notify('blue', this.color.b); + this.notify('hexa', this.color.getHexa()); + + notify(this.topic, this.color); + }; + + ColorPicker.prototype.updateHueSlider = function updateHueSlider(e) { + var x = e.pageX - this.hue_area.offsetLeft; + var width = this.hue_area.clientWidth; + + if (x < 0) x = 0; + if (x > width) x = width; + + // TODO 360 => 359 + var hue = ((359 * x) / width) | 0; + // if (hue === 360) hue = 359; + + this.updateSliderPosition(this.hue_picker, x); + this.setHue(hue); + }; + + ColorPicker.prototype.updateAlphaSlider = function updateAlphaSlider(e) { + var x = e.pageX - this.alpha_area.offsetLeft; + var width = this.alpha_area.clientWidth; + + if (x < 0) x = 0; + if (x > width) x = width; + + this.color.a = (x / width).toFixed(2); + + this.updateSliderPosition(this.alpha_picker, x); + this.updatePreviewColor(); + + this.notify('alpha', this.color.a); + notify(this.topic, this.color); + }; + + ColorPicker.prototype.setHue = function setHue(value) { + this.color.setHue(value); + + this.updatePickerBackground(); + this.updateAlphaGradient(); + this.updatePreviewColor(); + + this.notify('red', this.color.r); + this.notify('green', this.color.g); + this.notify('blue', this.color.b); + this.notify('hexa', this.color.getHexa()); + this.notify('hue', this.color.hue); + + notify(this.topic, this.color); + }; + + // Updates when one of Saturation/Value/Lightness changes + ColorPicker.prototype.updateSLV = function updateSLV() { + this.updatePickerPosition(); + this.updateAlphaGradient(); + this.updatePreviewColor(); + + this.notify('red', this.color.r); + this.notify('green', this.color.g); + this.notify('blue', this.color.b); + this.notify('hexa', this.color.getHexa()); + + notify(this.topic, this.color); + }; + + /*************************************************************************/ + // Update positions of various UI elements + /*************************************************************************/ + + ColorPicker.prototype.updatePickerPosition = function updatePickerPosition() { + var size = this.picking_area.clientWidth; + var value = 0; + var offset = 5; + + if (this.picker_mode === 'HSV') + value = this.color.value; + if (this.picker_mode === 'HSL') + value = this.color.lightness; + + var x = (this.color.saturation * size / 100) | 0; + var y = size - (value * size / 100) | 0; + + this.color_picker.style.left = x - offset + 'px'; + this.color_picker.style.top = y - offset + 'px'; + }; + + ColorPicker.prototype.updateSliderPosition = function updateSliderPosition(elem, pos) { + elem.style.left = Math.max(pos - 3, -2) + 'px'; + }; + + ColorPicker.prototype.updateHuePicker = function updateHuePicker() { + var size = this.hue_area.clientWidth; + var offset = 1; + var pos = (this.color.hue * size / 360 ) | 0; + this.hue_picker.style.left = pos - offset + 'px'; + }; + + ColorPicker.prototype.updateAlphaPicker = function updateAlphaPicker() { + var size = this.alpha_area.clientWidth; + var offset = 1; + var pos = (this.color.a * size) | 0; + this.alpha_picker.style.left = pos - offset + 'px'; + }; + + /*************************************************************************/ + // Update background colors + /*************************************************************************/ + + ColorPicker.prototype.updatePickerBackground = function updatePickerBackground() { + var nc = new Color(this.color); + nc.setHSV(nc.hue, 100, 100); + this.picking_area.style.backgroundColor = nc.getHexa(); + }; + + ColorPicker.prototype.updateAlphaGradient = function updateAlphaGradient() { + this.alpha_mask.style.backgroundColor = this.color.getHexa(); + }; + + ColorPicker.prototype.updatePreviewColor = function updatePreviewColor() { + this.preview_color.style.backgroundColor = this.color.getColor(); + }; + + /*************************************************************************/ + // Update input elements + /*************************************************************************/ + + ColorPicker.prototype.inputChangeHue = function inputChangeHue(e) { + var value = parseInt(e.target.value); + this.setHue(value); + this.updateHuePicker(); + }; + + ColorPicker.prototype.inputChangeSaturation = function inputChangeSaturation(e) { + var value = parseInt(e.target.value); + this.color.setSaturation(value); + e.target.value = this.color.saturation; + this.updateSLV(); + }; + + ColorPicker.prototype.inputChangeValue = function inputChangeValue(e) { + var value = parseInt(e.target.value); + this.color.setValue(value); + e.target.value = this.color.value; + this.updateSLV(); + }; + + ColorPicker.prototype.inputChangeLightness = function inputChangeLightness(e) { + var value = parseInt(e.target.value); + this.color.setLightness(value); + e.target.value = this.color.lightness; + this.updateSLV(); + }; + + ColorPicker.prototype.inputChangeRed = function inputChangeRed(e) { + var value = parseInt(e.target.value); + this.color.setByName('r', value); + e.target.value = this.color.r; + this.setColor(this.color); + }; + + ColorPicker.prototype.inputChangeGreen = function inputChangeGreen(e) { + var value = parseInt(e.target.value); + this.color.setByName('g', value); + e.target.value = this.color.g; + this.setColor(this.color); + }; + + ColorPicker.prototype.inputChangeBlue = function inputChangeBlue(e) { + var value = parseInt(e.target.value); + this.color.setByName('b', value); + e.target.value = this.color.b; + this.setColor(this.color); + }; + + ColorPicker.prototype.inputChangeAlpha = function inputChangeAlpha(e) { + var value = parseFloat(e.target.value); + + if (typeof value === 'number' && isNaN(value) === false && + value >= 0 && value <= 1) + this.color.a = value.toFixed(2); + + e.target.value = this.color.a; + this.updateAlphaPicker(); + }; + + ColorPicker.prototype.inputChangeHexa = function inputChangeHexa(e) { + var value = e.target.value; + this.color.setHexa(value); + this.setColor(this.color); + }; + + /*************************************************************************/ + // Internal Pub/Sub + /*************************************************************************/ + + ColorPicker.prototype.subscribe = function subscribe(topic, callback) { + this.subscribers[topic] = callback; + }; + + ColorPicker.prototype.notify = function notify(topic, value) { + if (this.subscribers[topic]) + this.subscribers[topic](value); + }; + + /*************************************************************************/ + // Set Picker Properties + /*************************************************************************/ + + ColorPicker.prototype.setColor = function setColor(color) { + if(color instanceof Color !== true) { + console.log('Typeof parameter not Color'); + return; + } + + if (color.format !== this.picker_mode) { + color.setFormat(this.picker_mode); + color.updateHSX(); + } + + this.color.copy(color); + this.updateHuePicker(); + this.updatePickerPosition(); + this.updatePickerBackground(); + this.updateAlphaPicker(); + this.updateAlphaGradient(); + this.updatePreviewColor(); + + this.notify('red', this.color.r); + this.notify('green', this.color.g); + this.notify('blue', this.color.b); + + this.notify('hue', this.color.hue); + this.notify('saturation', this.color.saturation); + this.notify('value', this.color.value); + this.notify('lightness', this.color.lightness); + + this.notify('alpha', this.color.a); + this.notify('hexa', this.color.getHexa()); + notify(this.topic, this.color); + }; + + ColorPicker.prototype.setPickerMode = function setPickerMode(mode) { + if (mode !== 'HSV' && mode !== 'HSL') + return; + + this.picker_mode = mode; + this.node.setAttribute('data-mode', this.picker_mode); + this.setColor(this.color); + }; + + /*************************************************************************/ + // UNUSED + /*************************************************************************/ + + var setPickerMode = function setPickerMode(topic, mode) { + if (pickers[topic]) + pickers[topic].setPickerMode(mode); + }; + + var setColor = function setColor(topic, color) { + if (pickers[topic]) + pickers[topic].setColor(color); + }; + + var getColor = function getColor(topic) { + if (pickers[topic]) + return new Color(pickers[topic].color); + }; + + var subscribe = function subscribe(topic, callback) { + if (subscribers[topic] === undefined) + subscribers[topic] = []; + + subscribers[topic].push(callback); + }; + + var unsubscribe = function unsubscribe(callback) { + subscribers.indexOf(callback); + subscribers.splice(index, 1); + }; + + var notify = function notify(topic, value) { + if (subscribers[topic] === undefined || subscribers[topic].length === 0) + return; + + var color = new Color(value); + for (var i in subscribers[topic]) + subscribers[topic][i](color); + }; + + var init = function init() { + var elem = document.querySelectorAll('.ui-color-picker'); + var size = elem.length; + for (var i = 0; i < size; i++) + new ColorPicker(elem[i]); + }; + + return { + init : init, + Color : Color, + RGBColor : RGBColor, + RGBAColor : RGBAColor, + HSVColor : HSVColor, + HSVAColor : HSVAColor, + HSLColor : HSLColor, + HSLAColor : HSLAColor, + setColor : setColor, + getColor : getColor, + subscribe : subscribe, + unsubscribe : unsubscribe, + setPickerMode : setPickerMode + }; + +})(); + + + +/** + * UI-SlidersManager + */ + +var InputSliderManager = (function InputSliderManager() { + + var subscribers = {}; + var sliders = []; + + var InputComponent = function InputComponent(obj) { + var input = document.createElement('input'); + input.setAttribute('type', 'text'); + input.style.width = 50 + obj.precision * 10 + 'px'; + + input.addEventListener('click', function(e) { + this.select(); + }); + + input.addEventListener('change', function(e) { + var value = parseFloat(e.target.value); + + if (isNaN(value) === true) + setValue(obj.topic, obj.value); + else + setValue(obj.topic, value); + }); + + return input; + }; + + var SliderComponent = function SliderComponent(obj, sign) { + var slider = document.createElement('div'); + var startX = null; + var start_value = 0; + + slider.addEventListener("click", function(e) { + document.removeEventListener("mousemove", sliderMotion); + setValue(obj.topic, obj.value + obj.step * sign); + }); + + slider.addEventListener("mousedown", function(e) { + startX = e.clientX; + start_value = obj.value; + document.body.style.cursor = "e-resize"; + + document.addEventListener("mouseup", slideEnd); + document.addEventListener("mousemove", sliderMotion); + }); + + var slideEnd = function slideEnd(e) { + document.removeEventListener("mousemove", sliderMotion); + document.body.style.cursor = "auto"; + slider.style.cursor = "pointer"; + }; + + var sliderMotion = function sliderMotion(e) { + slider.style.cursor = "e-resize"; + var delta = (e.clientX - startX) / obj.sensivity | 0; + var value = delta * obj.step + start_value; + setValue(obj.topic, value); + }; + + return slider; + }; + + var InputSlider = function(node) { + var min = parseFloat(node.getAttribute('data-min')); + var max = parseFloat(node.getAttribute('data-max')); + var step = parseFloat(node.getAttribute('data-step')); + var value = parseFloat(node.getAttribute('data-value')); + var topic = node.getAttribute('data-topic'); + var unit = node.getAttribute('data-unit'); + var name = node.getAttribute('data-info'); + var sensivity = node.getAttribute('data-sensivity') | 0; + var precision = node.getAttribute('data-precision') | 0; + + this.min = isNaN(min) ? 0 : min; + this.max = isNaN(max) ? 100 : max; + this.precision = precision >= 0 ? precision : 0; + this.step = step < 0 || isNaN(step) ? 1 : step.toFixed(precision); + this.topic = topic; + this.node = node; + this.unit = unit === null ? '' : unit; + this.sensivity = sensivity > 0 ? sensivity : 5; + value = isNaN(value) ? this.min : value; + + var input = new InputComponent(this); + var slider_left = new SliderComponent(this, -1); + var slider_right = new SliderComponent(this, 1); + + slider_left.className = 'ui-input-slider-left'; + slider_right.className = 'ui-input-slider-right'; + + if (name) { + var info = document.createElement('span'); + info.className = 'ui-input-slider-info'; + info.textContent = name; + node.appendChild(info); + } + + node.appendChild(slider_left); + node.appendChild(input); + node.appendChild(slider_right); + + this.input = input; + sliders[topic] = this; + setValue(topic, value); + }; + + InputSlider.prototype.setInputValue = function setInputValue() { + this.input.value = this.value.toFixed(this.precision) + this.unit; + }; + + var setValue = function setValue(topic, value, send_notify) { + var slider = sliders[topic]; + if (slider === undefined) + return; + + value = parseFloat(value.toFixed(slider.precision)); + + if (value > slider.max) value = slider.max; + if (value < slider.min) value = slider.min; + + slider.value = value; + slider.node.setAttribute('data-value', value); + + slider.setInputValue(); + + if (send_notify === false) + return; + + notify.call(slider); + }; + + var setMax = function setMax(topic, value) { + var slider = sliders[topic]; + if (slider === undefined) + return; + + slider.max = value; + setValue(topic, slider.value); + }; + + var setMin = function setMin(topic, value) { + var slider = sliders[topic]; + if (slider === undefined) + return; + + slider.min = value; + setValue(topic, slider.value); + }; + + var setUnit = function setUnit(topic, unit) { + var slider = sliders[topic]; + if (slider === undefined) + return; + + slider.unit = unit; + setValue(topic, slider.value); + }; + + var setStep = function setStep(topic, value) { + var slider = sliders[topic]; + if (slider === undefined) + return; + + slider.step = parseFloat(value); + setValue(topic, slider.value); + }; + + var setPrecision = function setPrecision(topic, value) { + var slider = sliders[topic]; + if (slider === undefined) + return; + + value = value | 0; + slider.precision = value; + + var step = parseFloat(slider.step.toFixed(value)); + if (step === 0) + slider.step = 1 / Math.pow(10, value); + + setValue(topic, slider.value); + }; + + var setSensivity = function setSensivity(topic, value) { + var slider = sliders[topic]; + if (slider === undefined) + return; + + value = value | 0; + + slider.sensivity = value > 0 ? value : 5; + }; + + var getNode = function getNode(topic) { + return sliders[topic].node; + }; + + var getPrecision = function getPrecision(topic) { + return sliders[topic].precision; + }; + + var getStep = function getStep(topic) { + return sliders[topic].step; + }; + + var subscribe = function subscribe(topic, callback) { + if (subscribers[topic] === undefined) + subscribers[topic] = []; + subscribers[topic].push(callback); + }; + + var unsubscribe = function unsubscribe(topic, callback) { + subscribers[topic].indexOf(callback); + subscribers[topic].splice(index, 1); + }; + + var notify = function notify() { + if (subscribers[this.topic] === undefined) + return; + for (var i = 0; i < subscribers[this.topic].length; i++) + subscribers[this.topic][i](this.value); + }; + + var createSlider = function createSlider(topic, label) { + var slider = document.createElement('div'); + slider.className = 'ui-input-slider'; + slider.setAttribute('data-topic', topic); + + if (label !== undefined) + slider.setAttribute('data-info', label); + + new InputSlider(slider); + return slider; + }; + + var init = function init() { + var elem = document.querySelectorAll('.ui-input-slider'); + var size = elem.length; + for (var i = 0; i < size; i++) + new InputSlider(elem[i]); + }; + + return { + init : init, + setMax : setMax, + setMin : setMin, + setUnit : setUnit, + setStep : setStep, + getNode : getNode, + getStep : getStep, + setValue : setValue, + subscribe : subscribe, + unsubscribe : unsubscribe, + setPrecision : setPrecision, + setSensivity : setSensivity, + getPrecision : getPrecision, + createSlider : createSlider, + }; + +})(); + + +'use strict'; + +window.addEventListener("load", function() { + ColorPickerTool.init(); +}); + +var ColorPickerTool = (function ColorPickerTool() { + + /*========== Get DOM Element By ID ==========*/ + + function getElemById(id) { + return document.getElementById(id); + } + + function allowDropEvent(e) { + e.preventDefault(); + } + + /*========== Make an element resizable relative to it's parent ==========*/ + + var UIComponent = (function UIComponent() { + + function makeResizable(elem, axis) { + var valueX = 0; + var valueY = 0; + var action = 0; + + var resizeStart = function resizeStart(e) { + e.stopPropagation(); + e.preventDefault(); + if (e.button !== 0) + return; + + valueX = e.clientX - elem.clientWidth; + valueY = e.clientY - elem.clientHeight; + + document.body.setAttribute('data-resize', axis); + document.addEventListener('mousemove', mouseMove); + document.addEventListener('mouseup', resizeEnd); + }; + + var mouseMove = function mouseMove(e) { + if (action >= 0) + elem.style.width = e.clientX - valueX + 'px'; + if (action <= 0) + elem.style.height = e.clientY - valueY + 'px'; + }; + + var resizeEnd = function resizeEnd(e) { + if (e.button !== 0) + return; + + document.body.removeAttribute('data-resize', axis); + document.removeEventListener('mousemove', mouseMove); + document.removeEventListener('mouseup', resizeEnd); + }; + + var handle = document.createElement('div'); + handle.className = 'resize-handle'; + + if (axis === 'width') action = 1; + else if (axis === 'height') action = -1; + else axis = 'both'; + + handle.className = 'resize-handle'; + handle.setAttribute('data-resize', axis); + handle.addEventListener('mousedown', resizeStart); + elem.appendChild(handle); + }; + + /*========== Make an element draggable relative to it's parent ==========*/ + + var makeDraggable = function makeDraggable(elem, endFunction) { + + var offsetTop; + var offsetLeft; + + elem.setAttribute('data-draggable', 'true'); + + var dragStart = function dragStart(e) { + e.preventDefault(); + e.stopPropagation(); + + if (e.target.getAttribute('data-draggable') !== 'true' || + e.target !== elem || e.button !== 0) + return; + + offsetLeft = e.clientX - elem.offsetLeft; + offsetTop = e.clientY - elem.offsetTop; + + document.addEventListener('mousemove', mouseDrag); + document.addEventListener('mouseup', dragEnd); + }; + + var dragEnd = function dragEnd(e) { + if (e.button !== 0) + return; + + document.removeEventListener('mousemove', mouseDrag); + document.removeEventListener('mouseup', dragEnd); + }; + + var mouseDrag = function mouseDrag(e) { + elem.style.left = e.clientX - offsetLeft + 'px'; + elem.style.top = e.clientY - offsetTop + 'px'; + }; + + elem.addEventListener('mousedown', dragStart, false); + }; + + return { + makeResizable : makeResizable, + makeDraggable : makeDraggable + }; + + })(); + + /*========== Color Class ==========*/ + + var Color = UIColorPicker.Color; + var HSLColor = UIColorPicker.HSLColor; + + /** + * ColorPalette + */ + var ColorPalette = (function ColorPalette() { + + var samples = []; + var color_palette; + var complementary; + + var hideNode = function(node) { + node.setAttribute('data-hidden', 'true'); + }; + + var ColorSample = function ColorSample(id) { + var node = document.createElement('div'); + node.className = 'sample'; + + this.uid = samples.length; + this.node = node; + this.color = new Color(); + + node.setAttribute('sample-id', this.uid); + node.setAttribute('draggable', 'true'); + node.addEventListener('dragstart', this.dragStart.bind(this)); + node.addEventListener('click', this.pickColor.bind(this)); + + samples.push(this); + }; + + ColorSample.prototype.updateBgColor = function updateBgColor() { + this.node.style.backgroundColor = this.color.getColor(); + }; + + ColorSample.prototype.updateColor = function updateColor(color) { + this.color.copy(color); + this.updateBgColor(); + }; + + ColorSample.prototype.updateHue = function updateHue(color, degree, steps) { + this.color.copy(color); + var hue = (steps * degree + this.color.hue) % 360; + if (hue < 0) hue += 360; + this.color.setHue(hue); + this.updateBgColor(); + }; + + ColorSample.prototype.updateSaturation = function updateSaturation(color, value, steps) { + var saturation = color.saturation + value * steps; + if (saturation <= 0) { + this.node.setAttribute('data-hidden', 'true'); + return; + } + + this.node.removeAttribute('data-hidden'); + this.color.copy(color); + this.color.setSaturation(saturation); + this.updateBgColor(); + }; + + ColorSample.prototype.updateLightness = function updateLightness(color, value, steps) { + var lightness = color.lightness + value * steps; + if (lightness <= 0) { + this.node.setAttribute('data-hidden', 'true'); + return; + } + this.node.removeAttribute('data-hidden'); + this.color.copy(color); + this.color.setLightness(lightness); + this.updateBgColor(); + }; + + ColorSample.prototype.updateBrightness = function updateBrightness(color, value, steps) { + var brightness = color.value + value * steps; + if (brightness <= 0) { + this.node.setAttribute('data-hidden', 'true'); + return; + } + this.node.removeAttribute('data-hidden'); + this.color.copy(color); + this.color.setValue(brightness); + this.updateBgColor(); + }; + + ColorSample.prototype.updateAlpha = function updateAlpha(color, value, steps) { + var alpha = parseFloat(color.a) + value * steps; + if (alpha <= 0) { + this.node.setAttribute('data-hidden', 'true'); + return; + } + this.node.removeAttribute('data-hidden'); + this.color.copy(color); + this.color.a = parseFloat(alpha.toFixed(2)); + this.updateBgColor(); + }; + + ColorSample.prototype.pickColor = function pickColor() { + UIColorPicker.setColor('picker', this.color); + }; + + ColorSample.prototype.dragStart = function dragStart(e) { + e.dataTransfer.setData('sampleID', this.uid); + e.dataTransfer.setData('location', 'palette-samples'); + }; + + var Palette = function Palette(text, size) { + this.samples = []; + this.locked = false; + + var palette = document.createElement('div'); + var title = document.createElement('div'); + var controls = document.createElement('div'); + var container = document.createElement('div'); + var lock = document.createElement('div'); + + container.className = 'container'; + title.className = 'title'; + palette.className = 'palette'; + controls.className = 'controls'; + lock.className = 'lock'; + title.textContent = text; + + controls.appendChild(lock); + container.appendChild(title); + container.appendChild(controls); + container.appendChild(palette); + + lock.addEventListener('click', function () { + this.locked = !this.locked; + lock.setAttribute('locked-state', this.locked); + }.bind(this)); + + for(var i = 0; i < size; i++) { + var sample = new ColorSample(); + this.samples.push(sample); + palette.appendChild(sample.node); + } + + this.container = container; + this.title = title; + }; + + var createHuePalette = function createHuePalette() { + var palette = new Palette('Hue', 12); + + UIColorPicker.subscribe('picker', function(color) { + if (palette.locked === true) + return; + + for(var i = 0; i < 12; i++) { + palette.samples[i].updateHue(color, 30, i); + } + }); + + color_palette.appendChild(palette.container); + }; + + var createSaturationPalette = function createSaturationPalette() { + var palette = new Palette('Saturation', 11); + + UIColorPicker.subscribe('picker', function(color) { + if (palette.locked === true) + return; + + for(var i = 0; i < 11; i++) { + palette.samples[i].updateSaturation(color, -10, i); + } + }); + + color_palette.appendChild(palette.container); + }; + + /* Brightness or Lightness - depends on the picker mode */ + var createVLPalette = function createSaturationPalette() { + var palette = new Palette('Lightness', 11); + + UIColorPicker.subscribe('picker', function(color) { + if (palette.locked === true) + return; + + if(color.format === 'HSL') { + palette.title.textContent = 'Lightness'; + for(var i = 0; i < 11; i++) + palette.samples[i].updateLightness(color, -10, i); + } + else { + palette.title.textContent = 'Value'; + for(var i = 0; i < 11; i++) + palette.samples[i].updateBrightness(color, -10, i); + } + }); + + color_palette.appendChild(palette.container); + }; + + var isBlankPalette = function isBlankPalette(container, value) { + if (value === 0) { + container.setAttribute('data-collapsed', 'true'); + return true; + } + + container.removeAttribute('data-collapsed'); + return false; + }; + + var createAlphaPalette = function createAlphaPalette() { + var palette = new Palette('Alpha', 10); + + UIColorPicker.subscribe('picker', function(color) { + if (palette.locked === true) + return; + + for(var i = 0; i < 10; i++) { + palette.samples[i].updateAlpha(color, -0.1, i); + } + }); + + color_palette.appendChild(palette.container); + }; + + var getSampleColor = function getSampleColor(id) { + if (samples[id] !== undefined && samples[id]!== null) + return new Color(samples[id].color); + }; + + var init = function init() { + color_palette = getElemById('color-palette'); + + createHuePalette(); + createSaturationPalette(); + createVLPalette(); + createAlphaPalette(); + + }; + + return { + init : init, + getSampleColor : getSampleColor + }; + + })(); + + /** + * ColorInfo + */ + var ColorInfo = (function ColorInfo() { + + var info_box; + var select; + var RGBA; + var HEXA; + var HSLA; + + var updateInfo = function updateInfo(color) { + if (color.a | 0 === 1) { + RGBA.info.textContent = 'RGB'; + HSLA.info.textContent = 'HSL'; + } + else { + RGBA.info.textContent = 'RGBA'; + HSLA.info.textContent = 'HSLA'; + } + + RGBA.value.value = color.getRGBA(); + HSLA.value.value = color.getHSLA(); + HEXA.value.value = color.getHexa(); + }; + + var InfoProperty = function InfoProperty(info) { + + var node = document.createElement('div'); + var title = document.createElement('div'); + var value = document.createElement('input'); + var copy = document.createElement('div'); + + node.className = 'property'; + title.className = 'type'; + value.className = 'value'; + copy.className = 'copy'; + + title.textContent = info; + value.setAttribute('type', 'text'); + + copy.addEventListener('click', function() { + value.select(); + }); + + node.appendChild(title); + node.appendChild(value); + node.appendChild(copy); + + this.node = node; + this.value = value; + this.info = title; + + info_box.appendChild(node); + }; + + var init = function init() { + + info_box = getElemById('color-info'); + + RGBA = new InfoProperty('RGBA'); + HSLA = new InfoProperty('HSLA'); + HEXA = new InfoProperty('HEXA'); + + UIColorPicker.subscribe('picker', updateInfo); + + }; + + return { + init: init + }; + + })(); + + /** + * ColorPicker Samples + */ + var ColorPickerSamples = (function ColorPickerSamples() { + + var samples = []; + var nr_samples = 0; + var active = null; + var container = null; + var samples_per_line = 10; + var trash_can = null; + var base_color = new HSLColor(0, 50, 100); + var add_btn; + var add_btn_pos; + + var ColorSample = function ColorSample() { + var node = document.createElement('div'); + node.className = 'sample'; + + this.uid = samples.length; + this.index = nr_samples++; + this.node = node; + this.color = new Color(base_color); + + node.setAttribute('sample-id', this.uid); + node.setAttribute('draggable', 'true'); + + node.addEventListener('dragstart', this.dragStart.bind(this)); + node.addEventListener('dragover' , allowDropEvent); + node.addEventListener('drop' , this.dragDrop.bind(this)); + + this.updatePosition(this.index); + this.updateBgColor(); + samples.push(this); + }; + + ColorSample.prototype.updateBgColor = function updateBgColor() { + this.node.style.backgroundColor = this.color.getColor(); + }; + + ColorSample.prototype.updatePosition = function updatePosition(index) { + this.index = index; + this.posY = 5 + ((index / samples_per_line) | 0) * 52; + this.posX = 5 + ((index % samples_per_line) | 0) * 52; + this.node.style.top = this.posY + 'px'; + this.node.style.left = this.posX + 'px'; + }; + + ColorSample.prototype.updateColor = function updateColor(color) { + this.color.copy(color); + this.updateBgColor(); + }; + + ColorSample.prototype.activate = function activate() { + UIColorPicker.setColor('picker', this.color); + this.node.setAttribute('data-active', 'true'); + }; + + ColorSample.prototype.deactivate = function deactivate() { + this.node.removeAttribute('data-active'); + }; + + ColorSample.prototype.dragStart = function dragStart(e) { + e.dataTransfer.setData('sampleID', this.uid); + e.dataTransfer.setData('location', 'picker-samples'); + }; + + ColorSample.prototype.dragDrop = function dragDrop(e) { + e.stopPropagation(); + this.color = Tool.getSampleColorFrom(e); + this.updateBgColor(); + }; + + ColorSample.prototype.deleteSample = function deleteSample() { + container.removeChild(this.node); + samples[this.uid] = null; + nr_samples--; + }; + + var updateUI = function updateUI() { + updateContainerProp(); + + var index = 0; + var nr = samples.length; + for (var i=0; i < nr; i++) + if (samples[i] !== null) { + samples[i].updatePosition(index); + index++; + } + + AddSampleButton.updatePosition(index); + }; + + var deleteSample = function deleteSample(e) { + trash_can.parentElement.setAttribute('drag-state', 'none'); + + var location = e.dataTransfer.getData('location'); + if (location !== 'picker-samples') + return; + + var sampleID = e.dataTransfer.getData('sampleID'); + samples[sampleID].deleteSample(); + console.log(samples); + + updateUI(); + }; + + var createDropSample = function createDropSample() { + var sample = document.createElement('div'); + sample.id = 'drop-effect-sample'; + sample.className = 'sample'; + container.appendChild(sample); + }; + + var setActivateSample = function setActivateSample(e) { + if (e.target.className !== 'sample') + return; + + unsetActiveSample(active); + Tool.unsetVoidSample(); + CanvasSamples.unsetActiveSample(); + active = samples[e.target.getAttribute('sample-id')]; + active.activate(); + }; + + var unsetActiveSample = function unsetActiveSample() { + if (active) + active.deactivate(); + active = null; + }; + + var getSampleColor = function getSampleColor(id) { + if (samples[id] !== undefined && samples[id]!== null) + return new Color(samples[id].color); + }; + + var updateContainerProp = function updateContainerProp() { + samples_per_line = ((container.clientWidth - 5) / 52) | 0; + var height = 52 * (1 + (nr_samples / samples_per_line) | 0); + container.style.height = height + 10 + 'px'; + }; + + var AddSampleButton = (function AddSampleButton() { + var node; + var _index = 0; + var _posX; + var _posY; + + var updatePosition = function updatePosition(index) { + _index = index; + _posY = 5 + ((index / samples_per_line) | 0) * 52; + _posX = 5 + ((index % samples_per_line) | 0) * 52; + + node.style.top = _posY + 'px'; + node.style.left = _posX + 'px'; + }; + + var addButtonClick = function addButtonClick() { + var sample = new ColorSample(); + container.appendChild(sample.node); + updatePosition(_index + 1); + updateUI(); + }; + + var init = function init() { + node = document.createElement('div'); + var icon = document.createElement('div'); + + node.className = 'sample'; + icon.id = 'add-icon'; + node.appendChild(icon); + node.addEventListener('click', addButtonClick); + + updatePosition(0); + container.appendChild(node); + }; + + return { + init : init, + updatePosition : updatePosition + }; + })(); + + var init = function init() { + container = getElemById('picker-samples'); + trash_can = getElemById('trash-can'); + + AddSampleButton.init(); + + for (var i=0; i<16; i++) { + var sample = new ColorSample(); + container.appendChild(sample.node); + } + + AddSampleButton.updatePosition(samples.length); + updateUI(); + + active = samples[0]; + active.activate(); + + container.addEventListener('click', setActivateSample); + + trash_can.addEventListener('dragover', allowDropEvent); + trash_can.addEventListener('dragenter', function() { + this.parentElement.setAttribute('drag-state', 'enter'); + }); + trash_can.addEventListener('dragleave', function(e) { + this.parentElement.setAttribute('drag-state', 'none'); + }); + trash_can.addEventListener('drop', deleteSample); + + UIColorPicker.subscribe('picker', function(color) { + if (active) + active.updateColor(color); + }); + + }; + + return { + init : init, + getSampleColor : getSampleColor, + unsetActiveSample : unsetActiveSample + }; + + })(); + + /** + * Canvas Samples + */ + var CanvasSamples = (function CanvasSamples() { + + var active = null; + var canvas = null; + var samples = []; + var zindex = null; + var tutorial = true; + + var CanvasSample = function CanvasSample(color, posX, posY) { + + var node = document.createElement('div'); + var pick = document.createElement('div'); + var delete_btn = document.createElement('div'); + node.className = 'sample'; + pick.className = 'pick'; + delete_btn.className = 'delete'; + + this.uid = samples.length; + this.node = node; + this.color = color; + this.updateBgColor(); + this.zIndex = 1; + + node.style.top = posY - 50 + 'px'; + node.style.left = posX - 50 + 'px'; + node.setAttribute('sample-id', this.uid); + + node.appendChild(pick); + node.appendChild(delete_btn); + + var activate = function activate() { + setActiveSample(this); + }.bind(this); + + node.addEventListener('dblclick', activate); + pick.addEventListener('click', activate); + delete_btn.addEventListener('click', this.deleteSample.bind(this)); + + UIComponent.makeDraggable(node); + UIComponent.makeResizable(node); + + samples.push(this); + canvas.appendChild(node); + return this; + }; + + CanvasSample.prototype.updateBgColor = function updateBgColor() { + this.node.style.backgroundColor = this.color.getColor(); + }; + + CanvasSample.prototype.updateColor = function updateColor(color) { + this.color.copy(color); + this.updateBgColor(); + }; + + CanvasSample.prototype.updateZIndex = function updateZIndex(value) { + this.zIndex = value; + this.node.style.zIndex = value; + }; + + CanvasSample.prototype.activate = function activate() { + this.node.setAttribute('data-active', 'true'); + zindex.setAttribute('data-active', 'true'); + + UIColorPicker.setColor('picker', this.color); + InputSliderManager.setValue('z-index', this.zIndex); + }; + + CanvasSample.prototype.deactivate = function deactivate() { + this.node.removeAttribute('data-active'); + zindex.removeAttribute('data-active'); + }; + + CanvasSample.prototype.deleteSample = function deleteSample() { + if (active === this) + unsetActiveSample(); + canvas.removeChild(this.node); + samples[this.uid] = null; + }; + + CanvasSample.prototype.updatePosition = function updatePosition(posX, posY) { + this.node.style.top = posY - this.startY + 'px'; + this.node.style.left = posX - this.startX + 'px'; + }; + + var canvasDropEvent = function canvasDropEvent(e) { + var color = Tool.getSampleColorFrom(e); + + if (color) { + var offsetX = e.pageX - canvas.offsetLeft; + var offsetY = e.pageY - canvas.offsetTop; + var sample = new CanvasSample(color, offsetX, offsetY); + if (tutorial) { + tutorial = false; + canvas.removeAttribute('data-tutorial'); + var info = new CanvasSample(new Color(), 100, 100); + info.node.setAttribute('data-tutorial', 'dblclick'); + } + } + + }; + + var setActiveSample = function setActiveSample(sample) { + ColorPickerSamples.unsetActiveSample(); + Tool.unsetVoidSample(); + unsetActiveSample(); + active = sample; + active.activate(); + }; + + var unsetActiveSample = function unsetActiveSample() { + if (active) + active.deactivate(); + active = null; + }; + + var createToggleBgButton = function createToggleBgButton() { + var button = document.createElement('div'); + var state = false; + button.className = 'toggle-bg'; + canvas.appendChild(button); + + button.addEventListener('click', function() { + console.log(state); + state = !state; + canvas.setAttribute('data-bg', state); + }); + }; + + var init = function init() { + canvas = getElemById('canvas'); + zindex = getElemById('zindex'); + + canvas.addEventListener('dragover', allowDropEvent); + canvas.addEventListener('drop', canvasDropEvent); + + createToggleBgButton(); + + UIColorPicker.subscribe('picker', function(color) { + if (active) active.updateColor(color); + }); + + InputSliderManager.subscribe('z-index', function (value) { + if (active) active.updateZIndex(value); + }); + + UIComponent.makeResizable(canvas, 'height'); + }; + + return { + init : init, + unsetActiveSample : unsetActiveSample + }; + + })(); + + var StateButton = function StateButton(node, state) { + this.state = false; + this.callback = null; + + node.addEventListener('click', function() { + this.state = !this.state; + if (typeof this.callback === "function") + this.callback(this.state); + }.bind(this)); + }; + + StateButton.prototype.set = function set() { + this.state = true; + if (typeof this.callback === "function") + this.callback(this.state); + }; + + StateButton.prototype.unset = function unset() { + this.state = false; + if (typeof this.callback === "function") + this.callback(this.state); + }; + + StateButton.prototype.subscribe = function subscribe(func) { + this.callback = func; + }; + + + /** + * Tool + */ + var Tool = (function Tool() { + + var samples = []; + var controls = null; + var void_sw; + + var createPickerModeSwitch = function createPickerModeSwitch() { + var parent = getElemById('controls'); + var icon = document.createElement('div'); + var button = document.createElement('div'); + var hsv = document.createElement('div'); + var hsl = document.createElement('div'); + var active = null; + + icon.className = 'icon picker-icon'; + button.className = 'switch'; + button.appendChild(hsv); + button.appendChild(hsl); + + hsv.textContent = 'HSV'; + hsl.textContent = 'HSL'; + + active = hsl; + active.setAttribute('data-active', 'true'); + + function switchPickingModeTo(elem) { + active.removeAttribute('data-active'); + active = elem; + active.setAttribute('data-active', 'true'); + UIColorPicker.setPickerMode('picker', active.textContent); + }; + + var picker_sw = new StateButton(icon); + picker_sw.subscribe(function() { + if (active === hsv) + switchPickingModeTo(hsl); + else + switchPickingModeTo(hsv); + }); + + hsv.addEventListener('click', function() { + switchPickingModeTo(hsv); + }); + hsl.addEventListener('click', function() { + switchPickingModeTo(hsl); + }); + + parent.appendChild(icon); + parent.appendChild(button); + }; + + var setPickerDragAndDrop = function setPickerDragAndDrop() { + var preview = document.querySelector('#picker .preview-color'); + var picking_area = document.querySelector('#picker .picking-area'); + + preview.setAttribute('draggable', 'true'); + preview.addEventListener('drop', drop); + preview.addEventListener('dragstart', dragStart); + preview.addEventListener('dragover', allowDropEvent); + + picking_area.addEventListener('drop', drop); + picking_area.addEventListener('dragover', allowDropEvent); + + function drop(e) { + var color = getSampleColorFrom(e); + UIColorPicker.setColor('picker', color); + }; + + function dragStart(e) { + e.dataTransfer.setData('sampleID', 'picker'); + e.dataTransfer.setData('location', 'picker'); + }; + }; + + var getSampleColorFrom = function getSampleColorFrom(e) { + var sampleID = e.dataTransfer.getData('sampleID'); + var location = e.dataTransfer.getData('location'); + + if (location === 'picker') + return UIColorPicker.getColor(sampleID); + if (location === 'picker-samples') + return ColorPickerSamples.getSampleColor(sampleID); + if (location === 'palette-samples') + return ColorPalette.getSampleColor(sampleID); + }; + + var setVoidSwitch = function setVoidSwitch() { + var void_sample = getElemById('void-sample'); + void_sw = new StateButton(void_sample); + void_sw.subscribe( function (state) { + void_sample.setAttribute('data-active', state); + if (state === true) { + ColorPickerSamples.unsetActiveSample(); + CanvasSamples.unsetActiveSample(); + } + }); + }; + + var unsetVoidSample = function unsetVoidSample() { + void_sw.unset(); + }; + + var init = function init() { + controls = getElemById('controls'); + + var color = new Color(); + color.setHSL(0, 51, 51); + UIColorPicker.setColor('picker', color); + + setPickerDragAndDrop(); + createPickerModeSwitch(); + setVoidSwitch(); + }; + + return { + init : init, + unsetVoidSample : unsetVoidSample, + getSampleColorFrom : getSampleColorFrom + }; + + })(); + + var init = function init() { + UIColorPicker.init(); + InputSliderManager.init(); + ColorInfo.init(); + ColorPalette.init(); + ColorPickerSamples.init(); + CanvasSamples.init(); + Tool.init(); + }; + + return { + init : init + }; + +})(); +</pre> +</div> + +<p> </p> + +<p>{{CSSRef}}</p> + +<p>Esta ferramenta facilita a criação, ajuste, e experimentação de cores personalizadas na internet. Também facilita conversão entre vários <a href="/en-US/docs/Web/CSS/color_value">formatos de cor</a> disponíveis em <a href="/pt-PT/docs/Web/CSS">CSS</a>, incluindo: HEXA colors, RGB (Red/Green/Blue) e HSL (Hue/Saturation/Lightness). Também é possível controlar o canal alfa nos formatos RGB (rgba) and HSL (hsla).</p> + +<p>Ao ajustar os parâmetros que definem a cor, a mesma é mostrada nos três formatos padrão de CSS na internet. Além disso, com base na cor atualmente selecionada, é gerada uma paleta para HSL e HSV, assim como alfa. A caixa de seleção de cores no estilo "conta-gotas" pode mudar entre HSL e HSV. Também pode testar as cores e ver como se intersetam arrastando-as para a caixa por baixo da ferramenta e deslocando-as para o mesmo ponto. Ajuste o valor do índice-Z relativo para as mover para a frente e para trás umas das outras.</p> + +<p>Esta ferramenta vai ajudá-lo a identificar as cores perfeitas para o CSS do seu <a href="/pt-PT/docs/Web/HTML">HTML</a>.</p> + +<p>{{ EmbedLiveSample('ColorPicker_Tool', '100%', '900') }}</p> + +<p>As cores que gerou em cima podem ser usadas em qualquer sítio que estaria uma cor em CSS e/ou HTML, salvo indicação em contrário.</p> + +<h2 id="See_also">See also</h2> + +<p>Para mais informações sobre cores, consulte estes artigos:</p> + +<ul> + <li><a href="/pt-PT/docs/Web/HTML/Aplicar_cor_elementos_HTML_utilizando_CSS">Aplicar cor aos elementos HTML com CSS</a></li> + <li><a href="/en-US/docs/Learn/CSS/Styling_text/Fundamentals">Fundamentos de estilização de texto e tipos de letra</a></li> + <li><a href="/en-US/docs/Learn/CSS/Styling_boxes/Borders">Estilizar contornos com CSS</a></li> + <li><a href="/en-US/docs/Learn/CSS/Styling_boxes/Backgrounds">Mudar estilo do fundo com CSS</a></li> + <li><a href="/en-US/docs/Learn/Accessibility/CSS_and_JavaScript#Color_and_color_contrast">Cor e contraste</a></li> +</ul> + +<p> </p> + +<ul> + <li> </li> +</ul> diff --git a/files/pt-pt/web/css/css_columns/index.html b/files/pt-pt/web/css/css_columns/index.html new file mode 100644 index 0000000000..6a356077b5 --- /dev/null +++ b/files/pt-pt/web/css/css_columns/index.html @@ -0,0 +1,240 @@ +--- +title: CSS Multi-column Layout +slug: Web/CSS/CSS_Columns +tags: + - CSS + - CSS Multi-column Layout + - Layout + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Columns +--- +<div>{{CSSRef("CSS3 Multicol")}}</div> + +<p>The <strong>CSS Multi-column Layout</strong> standard is a CSS module that adds support for multi-column layouts to CSS. This module makes it easier and more reliable than ever to produce columnar layouts without having to hand-code complicated and fragile structures. Support is included for establishing the number of columns in a layout, as well as how content should flow from column to column, gap sizes, column dividing lines (known as column rules), and so forth.</p> + +<h2 id="Multi-column_layout_basics">Multi-column layout basics</h2> + +<p>The three key properties used to produce the layout of columns in CSS are {{cssxref("column-count")}}, {{cssxref("column-width")}}, and {{cssxref("column-gap")}}. Other properties provide ways to fine-tune details of how things are organized and rendered within the layout structure built using those properties, but the job of figuring out what goes where is generally handled by these four.</p> + +<h3 id="Suggesting_the_number_of_columns_and_their_widths">Suggesting the number of columns and their widths</h3> + +<p>The first two properties, <code>column-count</code> and <code>column-width</code>, are both the most important and the most potentially misleading. It's important to understand that:</p> + +<ul> + <li>The {{cssxref("column-count")}} property specifies a <em>maximum</em> number of columns to use to render the text. The browser will consider the amount of horizontal space available, the value of <code>column-width</code>, and the value of <code>column-gap</code>, then draw the largest number of columns across that it can fit into the available space.</li> + <li>The {{cssxref("column-width")}} property specifies a <em>minimum</em> column width, given a {{cssxref("length")}} value. Each column the browser creates will be at least this wide, but may be wider. After determining the number of columns that it will draw, any remaining horizontal space may be divided up by the browser among the columns and added to their widths.</li> +</ul> + +<p>In a way, then, they're more like recommendations than hard and fast rules. And this makes sense once you consider the logic of it; this allows multi-column layouts to be responsive and adaptive to the screen width, while also supporting the overall layout of the page and the intent of the author. As the width of the containing space (or the screen) shrinks, the browser will reduce the number of columns it creates, adjusting the remaining columns' widths to ensure that the overall width is as expected.</p> + +<p>The other thing you can control is the distance between the columns, known as the column gap. The column gap can be controlled using the {{cssxref("column-gap")}} property. By convention, the default gap is <code>1em</code>, but this may or may not be the case in any given browser, so if it matters to you, explicitly set it. The column gap, unlike the column count and width, doesn't get adjusted by the browser as it tries to fit the content into the available space.</p> + +<p>Take a look at the example below, in which you can use the range control at the top to adjust the width of the columns' containing element.</p> + +<div class="hidden"> +<h4 id="HTML">HTML</h4> + +<pre class="brush: html"><p> + Use the slider to change the container width: +</p> +<div class="controls"> + <input type="range" id="widthSlider" min="350" max="625"> + <span id="widthDisplay"></span> +</div> +<div class="columnbox"> +<p> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Praesent dignissim feugiat tellus, vitae vehicula nunc + fermentum at. Nulla ut leo tincidunt turpis tincidunt + facilisis vel sit amet nisl. Duis odio mauris, ornare vitae + est eget, molestie aliquet quam. Quisque sed lacus sodales + nulla dignissim semper. Mauris finibus erat ut molestie + sagittis. Maecenas eget augue dapibus eros mollis + consectetur quis a mauris. Ut quis ipsum egestas, molestie + augue id, lobortis neque. Sed malesuada id justo nec + accumsan. Curabitur non tempus ligula, ut congue libero. + Morbi mattis, neque at feugiat rutrum, ipsum massa iaculis + risus, ut rutrum justo purus et urna. Aenean semper ornare + enim, maximus tincidunt ante tincidunt sed. Fusce imperdiet + id tellus molestie laoreet. +</p> +<p> + Sed non fringilla turpis, ac fermentum neque. Nunc tortor + sapien, convallis in odio dictum, maximus hendrerit metus. + Phasellus vitae molestie lacus, sed imperdiet enim. Praesent + tempus ligula eget orci interdum, et tempus nunc rutrum. + Cras vel arcu non ipsum sodales faucibus vestibulum eu mi. + Fusce sed laoreet turpis, eu rutrum leo. Vestibulum sit amet + porta mauris. Curabitur in nisi a neque ultricies iaculis + sit amet vel felis. Suspendisse lobortis iaculis gravida. Ut + bibendum vestibulum lacus eget dignissim. +</p> +</div></pre> + +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">let widthSlider = document.getElementById("widthSlider"); +let widthDisplay = document.getElementById("widthDisplay"); +let columnBox = document.querySelector(".columnbox"); + +widthSlider.value = columnBox.offsetWidth; +widthDisplay.innerText = widthSlider.value; + +widthSlider.addEventListener("input", function(event) { + columnBox.style.width = widthSlider.value.toString() + "px"; + widthDisplay.innerText = widthSlider.value; +}, false);</pre> + +<h4 id="CSS">CSS</h4> + +<pre class="brush: css">body { + font: 16px "Open Sans", "Arial", "sans-serif"; +} + +.columnbox { + width: 400px; + column-count: 3; + column-width: 12em; + border: 1px dotted black; +} + +.columnbox p:first-child { + margin-top: 0; +} + +.controls { + font: 16px "Open Sans", "Arial", sans-serif; +}</pre> + +<h4 id="Result">Result</h4> +</div> + +<p>{{EmbedLiveSample("Suggesting_the_number_of_columns_and_their_widths", 650, 800)}}</p> + +<h3 id="Text_wrapping_in_multi-column_layouts">Text wrapping in multi-column layouts</h3> + +<p>The {{cssxref("column-fill")}} property also affects layout. By default, the browser will create as many appropriately-sized columns as it can, then balance the contents across them so that each column is approximately the same length. If, however, you prefer to have the browser fill the first column to its maximum height before moving on to the next column, you can set <code>column-fill</code> to <code>auto</code> (instead of the default, <code>balance</code>).</p> + +<p>If there is no constraint on the column height, however, there will only be one column created, as it will never reach its maximum height to trigger wrapping to the second column, so be sure to either place your columns inside a container which constrains their height, either by using {{cssxref("height")}} or {{cssxref("max-height")}}.</p> + +<div class="note"> +<p>While the CSS specification defines the {{cssxref("break-before")}}, {{cssxref("break-after")}}, and {{cssxref("break-inside")}} properties to help control wrapping of elements across region, column, or page boundaries, these properties are generally not implemented widely enough to use in real-world code at this time.</p> +</div> + +<h3 id="Column_appearance">Column appearance</h3> + +<p>You can specify that a column rule—a dividing line drawn in the center of each column gap—be drawn between each column in the rendered output of your layout by using the {{cssxref("column-rule-style")}}, {{cssxref("column-rule-width")}}, and {{cssxref("column-rule-color")}} properties, or the shorthand property {{cssxref("column-rule")}}.</p> + +<h2 id="Reference">Reference</h2> + +<h3 id="CSS_properties">CSS properties</h3> + +<div class="index"> +<ul> + <li>{{cssxref("break-after")}}</li> + <li>{{cssxref("break-before")}}</li> + <li>{{cssxref("break-inside")}}</li> + <li>{{cssxref("column-count")}}</li> + <li>{{cssxref("column-fill")}}</li> + <li>{{cssxref("column-gap")}}</li> + <li>{{cssxref("column-rule")}}</li> + <li>{{cssxref("column-rule-color")}}</li> + <li>{{cssxref("column-rule-style")}}</li> + <li>{{cssxref("column-rule-width")}}</li> + <li>{{cssxref("column-span")}}</li> + <li>{{cssxref("column-width")}}</li> + <li>{{cssxref("columns")}}</li> +</ul> +</div> + +<h2 id="Guides">Guides</h2> + +<dl> + <dt><a href="/en-US/docs/Web/CSS/CSS_Columns/Using_multi-column_layouts">Using CSS multi-column layouts</a></dt> + <dd>Step-by-step tutorial about how to build layouts using several columns.</dd> +</dl> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Multicol')}}</td> + <td>{{Spec2('CSS3 Multicol')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}} {{property_prefix('-webkit')}}</td> + <td>{{CompatGeckoDesktop(9)}}{{property_prefix('-moz')}}<br> + {{CompatGeckoDesktop(52)}}</td> + <td>10</td> + <td>11.10<br> + 15{{property_prefix('-webkit')}}</td> + <td>3.0 (522){{property_prefix('-webkit')}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>2.1{{property_prefix('-webkit')}}</td> + <td>{{compatGeckoMobile(22)}}{{property_prefix('-moz')}}<br> + {{CompatGeckoMobile(52)}}</td> + <td>10</td> + <td>11.5<br> + 32{{property_prefix('-webkit')}}</td> + <td>3.2{{property_prefix('-webkit')}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<p>Other CSS layout technologies include:</p> + +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout">CSS Flexible box layout</a> (CSS flexbox)</li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid layout</a></li> +</ul> diff --git a/files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html b/files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html new file mode 100644 index 0000000000..4e1d10f5de --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html @@ -0,0 +1,215 @@ +--- +title: Alinhamento de Itens num Recipiente Flex +slug: Web/CSS/CSS_Flexible_Box_Layout/alinhamento_de_itens_num_recipiente_flex +tags: + - Alinhar + - CSS + - Flex + - Guía + - align-content + - align-items + - align-self + - alinhamento + - flexbox + - justificar + - justify-content +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container +--- +<p>{{CSSRef}}</p> + +<p class="summary">Uma das razões pelas quais o flexbox atraiu rapidamente o interesse dos programadores da Web é que este trouxe os melhores recursos de alinhamento para a Web, pela primeira vez. Este permitiu o alinhamento vertical adequado, e assim nós podemos finalmente, centrar uma caixa facilmente. Neste guia, Nós iremos analisar detalhadamente como as propriedades de alinhamento e justificação funcionam no Flexbox.</p> + +<p>Para centrar a nossa caixa, nós utilizamos a propriedade <code>align-items</code> para alinhar o nosso item no eixo transversal, que neste caso é o eixo do bloco na vertical. Nós utilizamos o <code>justify-content</code> para alinhar o item no eixo principal, que neste caso é o eixo horizontal.</p> + +<p><img alt="A containing element with another box centered inside it." src="https://mdn.mozillademos.org/files/15627/align1.png" style="display: block; height: 357px; margin: 0px auto; width: 616px;"></p> + +<p> </p> + +<p>Podem ver o código do exemplo abaixo. Muda o tamanho do <em>container</em> ou do elemento aninhado e o elemento aninhado permanecerá centrado.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/intro.html", '100%', 700)}}</p> + +<h2 id="Propriedades_que_controlam_o_alinhamento">Propriedades que controlam o alinhamento</h2> + +<p>As propriedades que nós iremos ver neste guia são as seguintes:</p> + +<ul> + <li>{{cssxref("justify-content")}} — controla o alinhamento de todos os itens no eixo principal.</li> + <li>{{cssxref("align-items")}} — controla o alinhamento de todos os itens no eixo transversal.</li> + <li>{{cssxref("align-self")}} — controla o alinhamento de um item <em>flex </em>individual no eixo transversal.</li> + <li>{{cssxref("align-content")}} — descrito na especificação como para “empacotar linhas do <em>flex</em>”; controla o espaço entre as linhas do <em>flex</em> no eixo das coordenadas.</li> +</ul> + +<p>Vamos também descobrir como as margens automáticas podem ser utilizadas para alinhamento em <em>flexbox</em>.</p> + +<div class="note"> +<p><strong>Nota</strong>: As propriedades de alinhamento em <em>Flexbox</em> foram colocadas na sua própria especificação — <a href="https://www.w3.org/TR/css-align-3/">CSS Box Alignment Level 3</a>. É expectável que esta especificação irá enfim substituir as propriedades definidas em <em>Flexbox Level One</em>.</p> +</div> + +<h2 id="O_Eixo_Transversal">O Eixo Transversal</h2> + +<p>As propriedades <code>align-items</code> e <code>align-self</code> controlam o alinhamento dos nossos itens da <em>flex</em> no eixo transversal, pelas colunas se a <code>flex-direction</code> for <code>row</code> e ao longo da linha se a <code>flex-direction</code> for <code>column</code>.</p> + +<p>Estamos a dar uso do alinhamento no eixo transversalno exemplo mais fácil do <em>flex</em>. Se adicionarmos <code>display: flex</code> a um <em>container</em>, os sub-elementos tornarão-se todos itens da <em>flex</em> numa linha. Irão esticar-se para serem tão altos quanto o item mais alto, já que esse item está a definir a altura dos itens do eixo transversal. Se o teu <em>flex container</em> tiver uma altura definida, então os itens irão esticar até essa altura, independentemente de quanto conteúdo estiver no item.</p> + +<p><img alt="Three items, one with additional text causing it to be taller than the others." src="https://mdn.mozillademos.org/files/15628/align2.png" style="display: block; height: 131px; margin: 0px auto; width: 509px;"></p> + +<p><img alt="Three items stretched to 200 pixels tall" src="https://mdn.mozillademos.org/files/15629/align3.png" style="display: block; height: 207px; margin: 0px auto; width: 637px;"></p> + +<p>A razão pela qual os items ficam da mesma altura é porque o valor inicial do <code>align-items</code>, a propriedade que controla o alinhamento no eixo transversal, está definida para <code>stretch</code>.</p> + +<p>Podemos utilizar outros valores para controlar de que forma os itens se alinham:</p> + +<ul> + <li><code>align-items: flex-start</code></li> + <li><code>align-items: flex-end</code></li> + <li><code>align-items: center</code></li> + <li><code>align-items: stretch</code></li> + <li><code>align-items: baseline</code></li> +</ul> + +<p>No exemplo de baixo, o valor do <code>align-items</code> é <code>stretch</code>. Experimenta os outros valores e observa como todos os itens se alinham em relação aos outros no <em>flex container</em>.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-items.html", '100%', 520)}} </p> + +<h3 id="Alinhar_um_item_com_align-self">Alinhar um item com <em><code>align-self</code></em></h3> + +<p>A propriedade <code>align-items</code> define a propriedade <code>align-self</code> em todos os itens da <em>flex </em>como um grupo. Isto significa que tu podes explicitamente declarar a propriedade <code>align-self</code> para visar um único item. A propriedade <code>align-self</code> aceita todos os valores da <code>align-items</code> , mais o valor <code>auto</code>, que irá dar <em>reset</em> ao valor definido na <em>flex container</em>.</p> + +<p>Neste próximo exemplo, o <em>flex container</em> tem <code>align-items: flex-start</code>, o que significa que os itens estão todos alinhados com o início do eixo transversal. Eu visei o primeiro item utilizado um <code>first-child</code> e defini esse item para <code>align-items: stretch</code>; outro item foi selecionado utilizando a sua classe de <code>selected</code> e foi-lhe dado <code>align-items: </code><code>center</code>. Podes alterar o valor do <code>align-items</code> ou os valores do <code>align-self</code> em itens individuais para veres como funciona.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self.html", '100%', 650)}} </p> + +<h3 id="Alteração_do_eixo_principal">Alteração do eixo principal</h3> + +<p>Até agora observámos o comportamento quando o nosso <code>flex-direction</code> é <code>row</code>, enquanto trabalhamos numa linguagem escrita de cima a baixo. Isto significa que o eixo principal "corre" horizontalmente, e o alinhamento do nosso eixo transversal muda os itens para cima e para baixo.</p> + +<p><img alt="Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the vertical axis." src="https://mdn.mozillademos.org/files/15630/align4.png" style="display: block; height: 204px; margin: 0px auto; width: 671px;"></p> + +<p>Se nós mudarmos o nosso <code>flex-direction</code> para <code>column</code>, o <code>align-items</code> e o <code>align-self</code> irão alinhar os itens para a esquerda e para a direita.</p> + +<p><img alt="Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the horizontal axis." src="https://mdn.mozillademos.org/files/15631/align5.png" style="display: block; height: 239px; margin: 0px auto; width: 687px;"></p> + +<p>Podes testar isto no exemplo abaixo, que tem um <em>flex container</em> com <code>flex-direction: column</code> mas de resto, é exatamente igual ao exemplo anterior.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self-column.html", '100%', 730)}} </p> + +<h2 id="Alinhar_conteúdo_no_eixo_transversal_—_a_propriedade_align-content">Alinhar conteúdo no eixo transversal — a propriedade <em>align-content</em></h2> + +<p>Até agora temos estado a alinhar os itens, ou um item individual, dentro da área definida pelo <em>flex-container</em>. Se tu tiveres um <em>wrapped multiple-line flex container</em> então também poderás querer utilizar a propriedade <code>align-content</code> para controlar a distribuição do espaço entrelinhas. Na especificação isto é descrito como <a href="https://drafts.csswg.org/css-flexbox/#align-content-property">empacotar as linhas do <em>flex</em></a>.</p> + +<p>Para o <code>align-content</code> funcionar, precisarás de mais altura no teu <em>flex container</em> do que é necessário para mostrar os itens. Irá então afetar todos os itens como um conjunto, e ditará o que irá acontecer com esse espaço livre, e o alinhamento do conjunto inteiro de itens dentro dele.</p> + +<p>A propriedade <code>align-content</code> aceita os seguintes valores:</p> + +<ul> + <li><code>align-content: flex-start</code></li> + <li><code>align-content: flex-end</code></li> + <li><code>align-content: center</code></li> + <li><code>align-content: space-between</code></li> + <li><code>align-content: space-around</code></li> + <li><code>align-content: stretch</code></li> + <li><code>align-content: space-evenly</code> (não definido na especificação da <em>Flexbox</em>)</li> +</ul> + +<p>No exemplo abaixo, o <em>flex container</em> tem uma altura de 400 pixels, o que é mais do que necessário para mostrar os nossos itens. O valor do <code>align-content</code> é <code>space-between</code>, o que significa que o espaço disponível é partilhado entre as linhas da <em>flex</em>, que está posicionada nívelado com o início e o fim do <em>container</em> no eixo transversal.</p> + +<p>Experimenta os outros valores para veres como a propriedade <code>align-content</code> funciona.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content.html", '100%', 850)}} </p> + +<p>Mais uma vez podemos alterar o nosso <code>flex-direction</code> para <code>column</code> de forma a observar como esta propriedade se comporta quando estamos a trabalhar por coluna. Tal como anteriormente, precisamos de espaço suficiente no eixo transversal para ter algum espaço livre depois de mostrar todos os itens.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content-column.html", '100%', 860)}} </p> + +<div class="note"> +<p><strong>Nota</strong>: o valor <code>space-evenly</code> não está definido na especificação da <em>flexbox</em> e será uma adição posterior à especificação do Alinhamento da Caixa. O suporte dos navegadores para este valor não é tão bom quanto o suporte para os valore definidos na especificação da <em>flexbox</em>.</p> +</div> + +<p>Lê a <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content">documentação para o <code>justify-content</code> no MDN</a> para mais detalhes sobre todos estes valores, e o seu suporte em navegadores.</p> + +<h2 id="Alinhar_conteúdo_no_eixo_principal">Alinhar conteúdo no eixo principal</h2> + +<p>Agora que já vimos como o alinhamento funciona no eixo transversal, podemos dar uma olhada no eixo principal. Aqui temos apenas uma propriedade disponível — <code>justify-content</code>. Isto é porque apenas estaremos a lidar como itens como se fossem um grupo no eixo principal. Com o <code>justify-content</code> we control what happens with available space, should there be more space than is needed to display the items.</p> + +<p>In our initial example with <code>display: flex</code> on the container, the items display as a row and all line up at the start of the container. This is due to the initial value of <code>justify-content</code> being <code>flex-start</code>. Any available space is placed at the end of the items.</p> + +<p><img alt="Three items, each 100 pixels wide in a 500 pixel container. The available space is at the end of the items." src="https://mdn.mozillademos.org/files/15632/align6.png" style="display: block; height: 198px; margin: 0px auto; width: 528px;"></p> + +<p>The <code>justify-content</code> property accepts the same values as <code>align-content</code>.</p> + +<ul> + <li><code>align-content: flex-start</code></li> + <li><code>align-content: flex-end</code></li> + <li><code>align-content: center</code></li> + <li><code>align-content: space-between</code></li> + <li><code>align-content: space-around</code></li> + <li><code>align-content: stretch</code></li> + <li><code>align-content: space-evenly</code> (not defined in the Flexbox specification)</li> +</ul> + +<p>In the example below, the value of <code>justify-content</code> is <code>space-between</code>. The available space after displaying the items is distributed between the items. The left and right item line up flush with the start and end.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content.html", '100%', 480)}} </p> + +<p>If the main axis is in the block direction because <code>flex-direction</code> is set to <code>column</code>, then <code>justify-content</code> will distribute space between items in that dimension as long as there is space in the flex container to distribute.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-column.html", '100%', 880)}} </p> + +<h3 id="Modos_de_Alinhamento_e_Gravação">Modos de Alinhamento e Gravação</h3> + +<p>Remember that with all of these alignment methods, the values of <code>flex-start</code> and <code>flex-end</code> are writing mode-aware. If the value of <code>justify-content</code> is <code>start</code> and the writing mode is left-to-right as in English, the items will line up starting at the left side of the container.</p> + +<p><img alt="Three items lined up on the left" src="https://mdn.mozillademos.org/files/15638/Basics5.png" style="display: block; height: 152px; margin: 0px auto; width: 631px;"></p> + +<p>However if the writing mode is right-to-left as in Arabic, the items will line up starting at the right side of the container.</p> + +<p><img alt="Three items lined up from the right" src="https://mdn.mozillademos.org/files/15639/Basics6.png" style="display: block; height: 152px; margin: 0px auto; width: 634px;"></p> + +<p>The live example below has the <code>direction</code> property set to <code>rtl</code> to force a right-to-left flow for our items. You can remove this, or change the values of <code>justify-content</code> to see how flexbox behaves when the start of the inline direction is on the right.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-writing-mode.html", '100%', 440)}} </p> + +<h2 id="Alinhamento_e_flex-direction">Alinhamento e <em>flex-direction</em></h2> + +<p>The start line will also change if you change the <code>flex-direction</code> property — for example using <code>row-reverse</code> instead of <code>row</code>.</p> + +<p>In this next example I have items laid out with <code>flex-direction: row-reverse</code> and <code>justify-content: flex-end</code>. In a left to right language the items all line up on the left. Try changing <code>flex-direction: row-reverse</code> to <code>flex-direction: row</code>. You will see that the items now move to the right hand side.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-reverse.html", '100%', 440)}} </p> + +<p>While this may all seem a little confusing, the rule to remember is that unless you do something to change it, flex items lay themselves out in the direction that words are laid out in the language of your document along the inline, row axis. <code>flex-start</code> will be where the start of a sentence of text would begin.</p> + +<p><img alt="Diagram showing start on the left and end on the right." src="https://mdn.mozillademos.org/files/15634/align8.png" style="display: block; height: 152px; margin: 0px auto; width: 631px;"></p> + +<p>You can switch them to display in the block direction for the language of your document by selecting <code>flex-direction: column</code>. Then <code>flex-start</code> will then be where the top of your first paragraph of text would start.</p> + +<p><img alt="Diagram showing start and the top and end at the bottom." src="https://mdn.mozillademos.org/files/15636/align10.png" style="display: block; height: 273px; margin: 0px auto; width: 709px;"></p> + +<p>If you change flex-direction to one of the reverse values, then they will lay themselves out from the end axis and in the reverse order to the way words are written in the language of your document. <code>flex-start</code> will then change to the end of that axis — so to the location where your lines would wrap if working in rows, or at the end of your last paragraph of text in the block direction.</p> + +<p><img alt="Diagram showing start on the right and end on the left." src="https://mdn.mozillademos.org/files/15635/align9.png" style="display: block; height: 152px; margin: 0px auto; width: 631px;"></p> + +<p><img alt="Diagram showing end at the top and start at the bottom" src="https://mdn.mozillademos.org/files/15637/align11.png" style="display: block; height: 273px; margin: 0px auto; width: 709px;"></p> + +<h2 id="Utilização_de_margen_automáticas_para_o_alinhamento_do_eixo_principal">Utilização de margen automáticas para o alinhamento do eixo principal</h2> + +<p>We don’t have a <code>justify-items</code> or <code>justify-self</code> property available to us on the main axis as our items are treated as a group on that axis. However it is possible to do some individual alignment in order to separate an item or a group of items from others by using auto margins along with flexbox.</p> + +<p>A common pattern is a navigation bar where some key items are aligned to the right, with the main group on the left. You might think that this should be a use case for a <code>justify-self</code> property, however consider the image below. I have three items on one side and two on the other. If I were able to use <code>justify-self</code> on item <em>d</em>, it would also change the alignment of item <em>e</em> that follows, which may or may not be my intention.</p> + +<p><img alt="Five items, in two groups. Three on the left and two on the right." src="https://mdn.mozillademos.org/files/15633/align7.png" style="display: block; height: 84px; margin: 0px auto; width: 645px;"></p> + +<p>Instead we can target item 4 and separate it from the first three items by giving it a <code>margin-left</code> value of <code>auto</code>. Auto margins will take up all of the space that they can in their axis — it is how entering a block with margin auto left and right works. Each side tries to take as much space as it can, and so the block is pushed into the middle.</p> + +<p>In this live example, I have flex items arranged simply into a row with the basic flex values, and the class <code>push</code> has <code>margin-left: auto</code>. You can try removing this, or adding the class to another item to see how it works.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/alignment/auto-margins.html", '100%', 470)}} </p> + +<h2 id="Funcionalidades_de_alinhamento_futuras_para_o_Flexbox">Funcionalidades de alinhamento futuras para o Flexbox</h2> + +<p>At the beginning of this article I explained that the alignment properties currently contained in the Level 1 flexbox specification are also included in Box Alignment Level 3, which may well extend these properties and values in the future. We have already seen one place where this has happened, with the introduction of the <code>space-evenly</code> value for <code>align-content</code> and <code>justify-content</code> properties.</p> + +<p>The Box Alignment module also includes other methods of creating space between items, such as the <code>column-gap</code> and <code>row-gap</code> feature as seen in <a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid Layout</a>. The inclusion of these properties in Box Alignment means that in future we should be able to use <code>column-gap</code> and <code>row-gap</code> in flex layouts too. This will mean you won’t need to use margins to space out flex items.</p> + +<p>My suggestion when exploring flexbox alignment in depth is to do so alongside looking at alignment in Grid Layout. Both specifications use the alignment properties as detailed in the Box Alignment specification. You can see how these properties behave when working with a grid in the MDN article <a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout">Box Alignment in Grid Layout</a>, and I have also compared how alignment works in these specifications in my <a href="https://rachelandrew.co.uk/css/cheatsheets/box-alignment">Box Alignment Cheatsheet</a>.</p> diff --git a/files/pt-pt/web/css/css_flexible_box_layout/casos_de_utilizacao_tipicos_do_flexbox/index.html b/files/pt-pt/web/css/css_flexible_box_layout/casos_de_utilizacao_tipicos_do_flexbox/index.html new file mode 100644 index 0000000000..cd89209634 --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/casos_de_utilizacao_tipicos_do_flexbox/index.html @@ -0,0 +1,143 @@ +--- +title: Casos de utilização típicos do Flexbox +slug: Web/CSS/CSS_Flexible_Box_Layout/casos_de_utilizacao_tipicos_do_flexbox +tags: + - CSS + - Caixa Flexível + - Flexible Box + - Guía + - flexbox + - padrões + - utilizações comuns +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox +--- +<p>{{CSSRef}}</p> + +<p class="summary">Neste guia, nós vamos dar uma vista de olhos em alguns dos casos de utilização comuns para o flexbox - esses lugares onde faz mais sentido do que outro método de layout .</p> + +<h2 id="Porque_escolher_flexbox">Porque escolher flexbox?</h2> + +<p>In a perfect world of browser support, the reason you'd choose to use flexbox is because you want to lay a collection of items out in one direction or another. As you lay out your items you want to control the dimensions of the items in that one dimension, or control the spacing between items. These are the uses that flexbox was designed for. You can read more about the difference between flexbox and CSS Grid Layout in <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Relationship_of_Flexbox_to_Other_Layout_Methods">Relationship of Flexbox to other layout methods</a>, where we discuss how flexbox fits into the overall picture of CSS Layout.</p> + +<p>In reality we also often use Flexbox for jobs that might be better done by Grid Layout, as a fallback for Grid, and also in order to get alignment capabilities. This is something that may well change once Box Alignment is implemented in Block Layout. In this guide I look at some of the typical things you might use flexbox for today.</p> + +<h2 id="Navegação">Navegação</h2> + +<p>A common pattern for navigation is to have a list of items displayed as a horizontal bar. This pattern, as basic as it seems, was difficult to achieve before flexbox. It forms the most simple of flexbox examples, and could be considered the ideal flexbox use case.</p> + +<p>When we have a set of items that we want to display horizontally, we may well end up with additional space. We need to decide what to do with that space, and have a couple of options. We either display the space outside of the items — therefore spacing them out with white space between or around them — or we absorb the extra space inside the items and therefore need a method of allowing the items to grow and take up this space.</p> + +<h3 id="Espaço_distribuído_fora_dos_itens">Espaço distribuído fora dos itens</h3> + +<p>To distribute the space between or around the items we use the alignment properties in flexbox, and the {{cssxref("justify-content")}} property. You can read more about this property in <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container">Aligning Items in a flex container</a>, which deals with aligning items on the main axis.</p> + +<p>In the below live example we display the items at their natural size and by using <code>justify-content: space-between</code> make equal amounts of space between the items. You can change how the space is distributed using the <code>space-around</code> value, or where supported, <code>space-evenly</code>. You could also use <code>flex-start</code> to place the space at the end of the items, <code>flex-end</code> to place it before them, or <code>center</code> to centre the navigation items.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation.html", '100%', 550)}}</p> + +<h3 id="Espaço_distribuído_dentro_dos_itens">Espaço distribuído dentro dos itens</h3> + +<p>A different pattern for navigation would be to distribute the available space within the items themselves, rather than create space between them. In this case we would use the {{cssxref("flex")}} properties to allow items to grow and shrink in proportion to one another as described in <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Controlling_Ratios_of_Flex_Items_Along_the_Main_Ax">Controlling ratios of flex items along the main axis</a>.</p> + +<p>If I wanted all of my navigation items to have equal width, then I might use <code>flex: auto</code>, which is the shorthand for <code>flex: 1 1 auto</code> — all items grow and shrink from a flex-basis of auto. This would mean that the longer item would have more space.</p> + +<p>In the live example below try changing <code>flex: auto</code> to <code>flex: 1</code>. This is the shorthand for <code>flex: 1 1 0</code> and causes all of the items become the same width, as they are working from a flex-basis of 0 allowing all of the space to be distributed evenly.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation-flex.html", '100%', 550)}}</p> + +<h2 id="Dividir_navegação">Dividir navegação</h2> + +<p>Another way to align items on the main axis is to use auto margins. This enables the design pattern of a navigation bar where one group of items are aligned left and another group aligned right.</p> + +<p>Here we are using the auto margins technique described in <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container#Using_auto_margins_for_main_axis_alignment">Using auto margins for main axis alignment</a>. The items are aligned on the main axis with <code>flex-start</code> as this is the initial behaviour of flexbox, and we are aligning the item on the right by giving it a left margin of auto. You can move the class from one item to another to change where the split happens.</p> + +<p>Also in this example we are using margins on the flex items to create a gap between items, and a negative margin on the container in order that the items still remain flush with the right and left edges. Until the <code>gap</code> properties from the Box Alignment specification are implemented in flexbox, we have to use margins in this way if we want to create a gutter between items.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/split-navigation.html", '100%', 550)}}</p> + +<h2 id="Centrar_item">Centrar item</h2> + +<p>Before flexbox, developers would joke that the hardest problem in web design was vertical centering. This has now been made straightforward using the alignment properties in flexbox, as the following live example shows.</p> + +<p>You can play with the alignment, aligning the item to the start with <code>flex-start</code> or end with <code>flex-end</code>.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/center.html", '100%', 700)}}</p> + +<p>In the future we may not need to make a container a flex container just to centre a single item, as the Box Alignment properties will ultimately be implemented in Block layout. For now however, if you need to properly centre one thing inside another, flexbox is the way to do it. As in the above example, make a container into a flex container, and then use either <code>align-items</code> on the parent element or target the flex item itself with <code>align-self</code>.</p> + +<h2 id="Card_layout_pushing_footer_down">Card layout pushing footer down</h2> + +<p>Whether you use flexbox or CSS Grid to lay out a list of card components, these layout methods only work on direct children of the flex or grid component. This means that if you have variable amounts of content, the card will stretch to the height of the grid area or flex container. Any content inside uses regular block layout, meaning that on a card with less content the footer will rise up to the bottom of the content rather than stick to the bottom of the card.</p> + +<p><img alt="Two card components showing that the internals of the component do not stretch with the wrapper." src="https://mdn.mozillademos.org/files/15669/flex-cards.png" style="height: 626px; width: 964px;"></p> + +<p>Flexbox can solve this. We make the card a flex container, with {{cssxref("flex-direction")}}<code>: column</code>. We then set the content area to <code>flex: 1</code>, which is the shorthand for <code>flex: 1 1 auto</code> — the item can grow and shrink from a flex basis of <code>auto</code>. As this is the only item that can grow, it takes up all available space in the flex container and pushes the footer to the bottom. If you remove the <code>flex</code> property from the live example you will see how the footer then moves up to sit directly under the content.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/cards.html", '100%', 800)}}</p> + +<h2 id="Objetos_de_multimédia">Objetos de multimédia</h2> + +<p>The media object is a common pattern in web design — this pattern has an image or other element to one side and text to the right. Ideally a media object should be able to be flipped — moving the image from left to right.</p> + +<p>We see this pattern everywhere, used for comments, and anywhere we need to display images and descriptions. With flexbox we can allow the part of the media object containing the image to take its sizing information from the image, and then the body of the media object flexes to take up the remaining space.</p> + +<p>In the live example below you can see our media object. I have used the alignment properties to align the items on the cross axis to <code>flex-start</code>, and then set the <code>.content</code> flex item to <code>flex: 1</code>. As with our column layout card pattern above, using <code>flex: 1</code> means this part of the card can grow.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media.html", '100%', 600)}}</p> + +<p>Some things that you might want to try in this live example relate to the different ways you might want to constrain the media object in your design.</p> + +<p>To prevent the image growing too large, add a {{cssxref("max-width")}} to the image. As that side of the media object is using the initial values of flexbox it can shrink but not grow, and uses a <code>flex-basis</code> of auto. Any {{cssxref("width")}} or max-width applied to the image will become the <code>flex-basis</code>.</p> + +<pre class="brush: css">.image img { + max-width: 100px; +} +</pre> + +<p>You could also allow both sides to grow and shrink in proportion. If you set both sides to <code>flex: 1</code>, they will grow and shrink from a {{cssxref("flex-basis")}} of 0, so you will end up with two equal-sized columns. You could either take the content as a guide and set both to <code>flex: auto</code>, in which case they would grow and shrink from the size of the content or any size applied directly to the flex items such as a width on the image.</p> + +<pre class="brush: css">.media .content { + flex: 1; + padding: 10px; +} + +.image { + flex: 1; +}</pre> + +<p>You could also give each side different {{cssxref("flex-grow")}} factors, for example setting the side with the image to <code>flex: 1</code> and the content side to <code>flex: 3</code>. This will mean they use a <code>flex-basis</code> of <code>auto</code> but distribute that space at different rates according to the <code>flex-grow</code> factor you have assigned. The flex properties we use to do this are described in detail in the guide <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Controlling_Ratios_of_Flex_Items_Along_the_Main_Ax">Controlling ratios of flex items along the main axis</a>.</p> + +<pre class="brush: css">.media .content { + flex: 3; + padding: 10px; +} + +.image { + flex: 1; +}</pre> + +<h3 id="Flipping_the_media_object">Flipping the media object</h3> + +<p>To switch the display of the media object so that the image is on the right and the content is on the left we can use the <code>flex-direction</code> property set to <code>row-reverse</code>. The media object now displays the other way around. I have achieved this in the live example by adding a class of <code>flipped</code> alongside the existing <code>.media</code> class. This means you can see how the display changes by removing that class from the html.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media-flipped.html", '100%', 650)}}</p> + +<h2 id="Controlos_de_formulário">Controlos de formulário</h2> + +<p>Flexbox is particularly useful when it comes to styling form controls. Forms have lots of markup and lots of small elements that we typically want to align with each other. A common pattern is to have an {{htmlelement("input")}} element paired with a {{htmlelement("button")}}, perhaps for a search form or where you simply want your visitor to enter an email address.</p> + +<p>Flexbox makes this type of layout easy to achieve. I have contained my <code><button></code> and <code><input></code> field in a wrapper which I have given a border and set to <code>display: flex</code>. I have then set the <code>align-items</code> property to <code>center</code> so that the fields stay aligned with each other. I then use the flex properties to allow the <code><input></code> field to grow, while the button does not grow. This means we have a pair of fields, with the text field growing and shrinking as the available space changes.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/input-button.html", '100%', 550)}}</p> + +<p>You could add a label or icon to the left as easily as we popped the button onto the right. I have added a label, and other than some styling for background colour I didn’t need to change the layout. The stretchy input field now has a little less space to play with but it uses the space left after the two items are accounted for.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/use-cases/label-input-button.html", '100%', 550)}}</p> + +<p>Patterns like this can make it much easier to create a library of form elements for your design, which easily accommodate additional elements being added. You are taking advantage of the flexibility of flexbox by mixing items that do not grow with those that do.</p> + +<h2 id="Conclusão">Conclusão</h2> + +<p>While exploring the above patterns you have hopefully started to see how you can think through the best way to use flexbox to achieve the result that you want. Quite often you have more than one choice. Mix items that cannot stretch with those that can, use the content to inform the size, or allow flexbox to share out space in proportion. It’s up to you. </p> + +<p>Think about the best way to present the content that you have and then see how flexbox or other layout methods can help you achieve it.</p> diff --git a/files/pt-pt/web/css/css_flexible_box_layout/index.html b/files/pt-pt/web/css/css_flexible_box_layout/index.html new file mode 100644 index 0000000000..ec5c17b62e --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/index.html @@ -0,0 +1,155 @@ +--- +title: CSS Flexible Box Layout +slug: Web/CSS/CSS_Flexible_Box_Layout +tags: + - CSS + - CSS Flexible Boxes + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Flexible_Box_Layout +--- +<div>{{CSSRef}}</div> + +<p class="summary"><strong>CSS Flexible Box Layout</strong> is a module of <a href="/en-US/docs/Web/CSS">CSS</a> that defines a CSS box model optimized for user interface design, and the layout of items in one dimension. In the flex layout model, the children of a flex container can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated.</p> + +<h2 id="Basic_Example">Basic Example</h2> + +<p>In the following example a container has been set to <code>display: flex</code>, which means that the three child items become flex items. The value of <code>justify-content</code> has been set to <code>space-between</code> in order to space the items out evenly on the main axis. An equal amount of space is placed between each item with the left and right items being flush with the edges of the flex container. You can also see that the items are stretching on the cross axis, due to the default value of <code>align-items </code>being <code>stretch</code>. The items stretch to the height of the flex container, making them each appear as tall as the tallest item.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/basics/simple-example.html", '100%', 500)}}</p> + +<h2 id="Reference">Reference</h2> + +<h3 id="CSS_Properties">CSS Properties</h3> + +<div class="index"> +<ul> + <li>{{cssxref("align-content")}}</li> + <li>{{cssxref("align-items")}}</li> + <li>{{cssxref("align-self")}}</li> + <li>{{cssxref("flex")}}</li> + <li>{{cssxref("flex-basis")}}</li> + <li>{{cssxref("flex-direction")}}</li> + <li>{{cssxref("flex-flow")}}</li> + <li>{{cssxref("flex-grow")}}</li> + <li>{{cssxref("flex-shrink")}}</li> + <li>{{cssxref("flex-wrap")}}</li> + <li>{{cssxref("justify-content")}}</li> + <li>{{cssxref("order")}}</li> +</ul> +</div> + +<h3 id="Glossary_entries">Glossary entries</h3> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Glossary/Flexbox">Flexbox</a></li> + <li><a href="/en-US/docs/Glossary/Flex_Container">Flex Container</a></li> + <li><a href="/en-US/docs/Glossary/Flex_Item">Flex Item</a></li> + <li><a href="/en-US/docs/Glossary/Main_Axis">Main Axis</a></li> + <li><a href="/en-US/docs/Glossary/Cross_Axis">Cross Axis</a></li> + <li><a href="/en-US/docs/Glossary/Flex">Flex</a></li> +</ul> +</div> + +<h2 id="Guides">Guides</h2> + +<dl> + <dt><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox">Basic Concepts of Flexbox</a></dt> + <dd>An overview of the features of flexbox</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Relationship_of_Flexbox_to_Other_Layout_Methods">Relationship of flexbox to other layout methods</a></dt> + <dd>How flexbox relates to other layout methods, and other CSS specifications</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container">Aligning items in a flex container</a></dt> + <dd>How the Box Alignment properties work with flexbox.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items">Ordering flex items</a></dt> + <dd>Explaining the different ways to change the order and direction of items, and covering the potential issues in doing so.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Controlling_Ratios_of_Flex_Items_Along_the_Main_Ax">Controlling Ratios of flex items along the main axis</a></dt> + <dd>This article explains the flex-grow, flex-shrink and flex-basis properties.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Mastering_Wrapping_of_Flex_Items">Mastering wrapping of flex items</a></dt> + <dd>How to create flex containers with multiple lines and control the display of the items in those lines.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox">Typical use cases of flexbox</a></dt> + <dd>Common design patterns that are typical flexbox use cases.</dd> + <dt><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Backwards_Compatibility_of_Flexbox">Backwards compatibility of Flexbox</a></dt> + <dd>Browser status of flexbox, interoperability issues and supporting older browsers and versions of the spec</dd> +</dl> + +<h2 id="External_resources">External resources</h2> + +<ul> + <li><a href="https://github.com/philipwalton/flexbugs">Flexbugs — a community curated list of flexbox browser bugs and workarounds</a></li> +</ul> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSS3 Flexbox') }}</td> + <td>{{ Spec2('CSS3 Flexbox') }}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable()}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoDesktop("20.0")}}</td> + <td>21.0{{property_prefix("-webkit")}}<br> + 29.0</td> + <td>10.0{{property_prefix("-ms")}}<br> + 11.0</td> + <td>12.10</td> + <td>6.1{{property_prefix("-webkit")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox Mobile (Gecko)</th> + <th>Android</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown()}}</td> + <td>4.4</td> + <td>11</td> + <td>12.10</td> + <td><span style="font-size: 12px; line-height: 18px;">7.1{{property_prefix("-webkit")}}</span></td> + </tr> + </tbody> +</table> +</div> + +<p> </p> diff --git a/files/pt-pt/web/css/css_flexible_box_layout/ordenacao_dos_itens_flex/index.html b/files/pt-pt/web/css/css_flexible_box_layout/ordenacao_dos_itens_flex/index.html new file mode 100644 index 0000000000..b2bc22df09 --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/ordenacao_dos_itens_flex/index.html @@ -0,0 +1,140 @@ +--- +title: Ordenação do itens Flex +slug: Web/CSS/CSS_Flexible_Box_Layout/ordenacao_dos_itens_flex +tags: + - Acessibilidade + - CSS + - Flex + - Guía + - direção + - flexbox + - ordem + - reverter +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items +--- +<p>{{CSSRef}}</p> + +<p class="summary">Os novos métodos de layout, tais como Flexbox e Grielha trazem com eles a possibilidade de controlar a ordem do conteúdo. Neste artigo, nós iremos analisar as maneiras pelas quais pode alterar a ordem visual do seu conteúdo quando utilizar o Flexbox. Nós também iremos considerar as implicações de reordenar itens de um ponto de vista de acessibilidade. </p> + +<h2 id="Reverter_a_exibição_dos_itens">Reverter a exibição dos itens</h2> + +<p>The {{cssxref("flex-direction")}} property can take one of four values:</p> + +<ul> + <li><code>row</code></li> + <li><code>column</code></li> + <li><code>row-reverse</code></li> + <li><code>column-reverse</code></li> +</ul> + +<p>The first two values keep the items in the same order that they appear in the document source order and display them sequentially from the start line.</p> + +<p><img alt="The items are displayed in a row starting on the left." src="https://mdn.mozillademos.org/files/15649/Basics1.png" style="display: flex; height: 152px; margin: 0px auto; width: 522px;"></p> + +<p><img alt="The items are displayed as a column starting from the top " src="https://mdn.mozillademos.org/files/15650/align10.png" style="display: flex; height: 273px; margin: 0px auto; width: 709px;"></p> + +<p>The second two values reverse the items by switching the start and end lines.</p> + +<p><img alt="The items are displayed in reverse order starting on the right-hand line." src="https://mdn.mozillademos.org/files/15651/align9.png" style="display: flex; height: 152px; margin: 0px auto; width: 631px;"></p> + +<p><img alt="The items are displayed in a column in reverse order starting at the bottom line." src="https://mdn.mozillademos.org/files/15652/align11.png" style="display: flex; height: 273px; margin: 0px auto; width: 709px;"></p> + +<p>Remember that the start line relates to writing modes. The row-related examples above demonstrate how <code>row</code> and <code>row-reverse</code> work in a left-to-right language such as English. If you were working in a right-to-left language like Arabic then <code>row</code> would start on the right, <code>row-reverse</code> on the left.</p> + +<p><img alt="Flex containers with Arabic letters showing how row starts from the right hand side and row-reverse from the left." src="https://mdn.mozillademos.org/files/15647/order-rtl.png" style="display: flex; height: 302px; margin: 0px auto; width: 528px;"></p> + +<p>This can seem like a neat way to display things in reverse order however you should be mindful that the items are only <em>visually</em> displayed in reverse order. The specification says the following on this matter:</p> + +<blockquote> +<p>“Nota: The reordering capabilities of flex layout intentionally affect only the visual rendering, leaving speech order and navigation based on the source order. This allows authors to manipulate the visual presentation while leaving the source order intact for non-CSS UAs and for linear models such as speech and sequential navigation.” - <a href="https://www.w3.org/TR/css-flexbox-1/#flow-order">Ordering and Orientation</a></p> +</blockquote> + +<p>If your items were links or some other element that the user could tab to, then the tabbing order would be the order that these items appear in the document source — not your visual order.</p> + +<p>If you are using a reverse value, or otherwise reordering your items, you should consider whether you actually need to change the logical order in the source. The specification continues with a warning not to use reordering to fix issues in your source:</p> + +<blockquote> +<p>“Authors must not use order or the <em>-reverse values of flex-flow/flex-direction as a substitute for correct source ordering, as that can ruin the accessibility of the document.” </em></p> +</blockquote> + +<div class="note"> +<p><strong>Nota</strong>: For some years Firefox had a bug whereby it would attempt to follow the visual order and not the source order, making it behave differently to other browsers. This has now been fixed. You should always take the source order as the logical order of the document as all up-to-date user agents will be following the specification and doing so.</p> +</div> + +<p>In the live example below I have added a focus style in order that as you tab from link to link you can see which is highlighted. If you change the order using <code>flex-direction</code> you can see how the tab order continues to follow the order that the items are listed in the source.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/order/order.html", '100%', 500)}}</p> + +<p>In the same way that changing the value of <code>flex-direction</code> does not change the order in which items are navigated to, changing this value does not change paint order. It is a visual reversal of the items only.</p> + +<h2 id="A_propriedade_order">A propriedade <em><code>order</code></em></h2> + +<p>In addition to reversing the order in which flex items are visually displayed, you can target individual items and change where they appear in the visual order with the {{cssxref("order")}} property.</p> + +<p>The <code>order</code> property is designed to lay the items out in <em>ordinal groups</em>. What this means is that items are assigned an integer that represents their group. The items are then placed in the visual order according to that integer, lowest values first. If more than one item has the same integer value, then within that group the items are laid out as per source order.</p> + +<p>As an example, I have 5 flex items, and assign <code>order</code> values as follows:</p> + +<ul> + <li>Source item 1: <code>order: 2</code></li> + <li>Source item 2: <code>order: 3</code></li> + <li>Source item 3: <code>order: 1</code></li> + <li>Source item 4: <code>order: 3</code></li> + <li>Source item 5: <code>order: 1</code></li> +</ul> + +<p>These items would be displayed on the page in the following order:</p> + +<ul> + <li>Source item 3: <code>order: 1</code></li> + <li>Source item 5: <code>order: 1</code></li> + <li>Source item 1: <code>order: 2</code></li> + <li>Source item 2: <code>order: 3</code></li> + <li>Source item 4: <code>order: 3</code></li> +</ul> + +<p><img alt="Items have a number showing their source order which has been rearranged." src="https://mdn.mozillademos.org/files/15653/order-property.png" style="display: flex; height: 100px; margin: 0px auto; width: 634px;"></p> + +<p>You can play around with the values in this live example below and see how that changes the order. Also, try changing <code>flex-direction</code> to <code>row-reverse</code> and see what happens — the start line is switched so the ordering begins from the opposite side.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/order/flex-direction.html", '100%', 440)}}</p> + +<p>Flex items have a default <code>order</code> value of <code>0</code>, therefore items with an integer value greater than 0 will be displayed after any items that have not been given an explicit <code>order</code> value.</p> + +<p>You can also use negative values with order, which can be quite useful. If you want to make one item display first, and leave the order of all other items unchanged, you can give that item an order of <code>-1</code>. As this is lower than 0 the item will always be displayed first.</p> + +<p>In the live code example below I have items laid out using Flexbox. By changing which item has the class <code>active</code> assigned to it in the HTML, you can change which item displays first and therefore becomes full width at the top of the layout, with the other items displaying below it.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/order/negative-order.html", '100%', 520)}}</p> + +<p>The items are displayed in what is described in the specification as <em>order-modified document order</em>. The value of the order property is taken into account before the items are displayed.</p> + +<p>Order also changes the paint order of the items; items with a lower value for <code>order</code> will be painted first and those with a higher value for <code>order</code> painted afterwards.</p> + +<h2 id="A_propriedade_order_e_acessibilidade">A propriedade <em>order</em> e acessibilidade</h2> + +<p>Use of the <code>order</code> property has exactly the same implications for accessibility as changing the direction with <code>flex-direction</code>. Using <code>order</code> changes the order in which items are painted, and the order in which they appear visually. It does not change the sequential navigation order of the items. Therefore if a user is tabbing between the items, they could find themselves jumping around your layout in a very confusing way.</p> + +<p>By tabbing around any of the live examples on this page, you can see how order is potentially creating a strange experience for anyone not using a pointing device of some kind. To read more about this disconnect of visual order and logical order and some of the potential problems it raises for accessibility, see the following resources.</p> + +<ul> + <li><a href="https://tink.uk/flexbox-the-keyboard-navigation-disconnect/">Flexbox and the keyboard navigation disconnect</a></li> + <li><a href="http://adrianroselli.com/2015/10/html-source-order-vs-css-display-order.html">HTML Source Order vs CSS Display Order</a></li> + <li><a href="https://alastairc.ac/2017/06/the-responsive-order-conflict">The Responsive Order Conflict for Keyboard Focus</a></li> +</ul> + +<h2 id="Casos_de_utilização_para_order">Casos de utilização para <em>order</em></h2> + +<p>There are sometimes places where the fact that the logical and therefore reading order of flex items is separate from the visual order, is helpful. Used carefully the <code>order</code> property can allow for some useful common patterns to be easily implemented.</p> + +<p>You might have a design, perhaps a card that will display a news item. The heading of the news item is the key thing to highlight and would be the element that a user might jump to if they were tabbing between headings to find content they wanted to read. The card also has a date; the finished design we want to create is something like this.</p> + +<p><img alt="A design component with a date, then heading and then content." src="https://mdn.mozillademos.org/files/15648/order-card.png" style="height: 400px; width: 618px;"></p> + +<p>Visually the date appears above the heading, in the source. However, if the card was read out by a screen reader I would prefer that the title was announced first and then the publication date. We can make this so using the <code>order</code> property.</p> + +<p>The card is going to be our flex container, with <code>flex-direction</code> set to column. I then give the date an <code>order</code> of <code>-1</code>. This pulls it up above the heading.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/order/usecase-order.html", '100%', 730)}}</p> + +<p>These small tweaks are the sort of cases where the <code>order</code> property makes sense. Keep the logical order as the reading and tab order of the document, and maintain that in the most accessible and structured fashion. Then use <code>order</code> for purely visual design tweaks. When doing so take care that you are not reordering items that could be accessed by the keyboard as a user is tabbing around. Especially when using newer layout methods you should ensure that your browser testing includes testing the site using keyboard only, rather than a mouse or touchscreen. You will quickly see if your development choices make getting around the content difficult.</p> diff --git a/files/pt-pt/web/css/css_flexible_box_layout/relação_do_flexbox_com_outros_métodos_de_layout/index.html b/files/pt-pt/web/css/css_flexible_box_layout/relação_do_flexbox_com_outros_métodos_de_layout/index.html new file mode 100644 index 0000000000..83c570f33e --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/relação_do_flexbox_com_outros_métodos_de_layout/index.html @@ -0,0 +1,125 @@ +--- +title: Relação do flexbox com outros métodos de layout +slug: >- + Web/CSS/CSS_Flexible_Box_Layout/relação_do_flexbox_com_outros_métodos_de_layout +tags: + - CSS + - Guía + - Modo de Gravação + - alinhamento de caixa + - conteúdos + - exibição + - flexbox + - grelha +translation_of: >- + Web/CSS/CSS_Flexible_Box_Layout/Relationship_of_Flexbox_to_Other_Layout_Methods +--- +<div>{{CSSRef}}</div> + +<p class="summary">Neste artigo, nós iremos ver como o Flexbox se encaixa com todos os outros módulos de CSS. Nós iremos saber quais as especificações que também precisa de ter em consideração se quiser aprender flexboxm, e saber por que o flexbox é diferente de alguns outros módulos.</p> + +<div class="note"> +<p><strong>Nota</strong>: CSS versions 1 and 2 were a single monolithic specification where all of CSS was defined in one large document. As CSS became a more feature rich language, maintaining one huge specification became problematic, with different parts of CSS moving on at different speeds. CSS was therefore modularised, and the various CSS Specifications are different modules that make up CSS today. These modules relate to each other, and are at different stages of development.</p> +</div> + +<h2 id="O_módulo_de_alinhamento_de_caixa">O módulo de alinhamento de caixa</h2> + +<p>For many people the first reason they start to look at flexbox is because of the ability to properly align flex items inside a flex container. Flexbox provides access to properties that allow the alignment of items on their cross axis and justification of items on the main axis.</p> + +<p>These properties started life in the flexbox specification, but are now also part of the <a href="https://www.w3.org/TR/css-align-3/">Especificação de Alinhamento de Caixa</a> (inglês). This specification details how alignment works in all layout — not just flexbox. Box alignment deals with alignment and justification, and also distribution of space along an axis.</p> + +<p>The reason that the Box alignment properties remain detailed in the flexbox specification as well as being in box alignment is to ensure that completion of the flexbox spec is not held up by box alignment, which has to detail these methods for all layout types. There is a note in the flexbox spec stating that in future, once it is completed, the definitions in Box Alignment Level 3 will supercede those of flexbox:</p> + +<blockquote> +<p>"Note: While the alignment properties are defined in CSS Box Alignment <a href="">CSS-ALIGN-3</a>, Flexible Box Layout reproduces the definitions of the relevant ones here so as to not create a normative dependency that may slow down advancement of the spec. These properties apply only to flex layout until CSS Box Alignment Level 3 is finished and defines their effect for other layout modes. Additionally, any new values defined in the Box Alignment module will apply to Flexible Box Layout; in otherwords, the Box Alignment module, once completed, will supercede the definitions here."</p> +</blockquote> + +<p>In a later article in this series — Aligning items in a flex container — we will take a thorough look at how the Box Alignment properties apply to flex items.</p> + +<h3 id="As_propriedades_de_gap">As propriedades de <em>gap</em></h3> + +<p>A recent addition to the Box Alignment specification has been the {{cssxref("row-gap")}} and {{cssxref("column-gap")}} properties, long with the shorthand {{cssxref("gap")}}. These properties were initially defined in the CSS Grid specification and named <code>grid-row-gap</code>, <code>grid-column-gap</code> and <code>grid-gap</code>. They have been renamed and moved to Box Alignment in order that they can be used in all layout methods — this will ultimately include flexbox. Until browsers implement the <code>gap</code> properties for flexbox, {{cssxref("margin")}}s have to be used to create gaps between items.</p> + +<h2 id="Modos_de_Gravação">Modos de Gravação</h2> + +<p>In the <a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox">Basic concepts of flexbox</a> article, I explained that flexbox is <strong>writing mode aware</strong>. Writing modes are fully detailed in the CSS <a href="https://www.w3.org/TR/css-writing-modes-3/">Writing Modes specification</a>, which details how CSS supports the various different writing modes that exist internationally. We need to be aware of how this will impact our flex layouts as writing mode changes the direction that blocks are laid out in our document. Understanding <strong>block</strong> and <strong>inline</strong> directions is key to new layout methods.</p> + +<p>It is worth noting that we might want to change the writing mode of our document for reasons other than publishing content in a language that uses a different writing mode. See <a href="https://24ways.org/2016/css-writing-modes/">this article</a> for a full description of writing modes and ways to use them, both for content in other languages and for creative reasons. </p> + +<h3 id="Os_modes_de_gravação">Os modes de gravação</h3> + +<p>The writing modes specification defines the following values of the {{cssxref("writing-mode")}} property, which serve to change the direction that blocks are laid out on the page, to match the direction that blocks lay out when content is formatted in that particular writing mode. You can change the live example below to these modes in order to see what happens to the flex layout.</p> + +<ul> + <li><code>horizontal-tb</code></li> + <li><code>vertical-rl</code></li> + <li><code>vertical-lr</code></li> + <li><code>sideways-rl</code></li> + <li><code>sideways-lr</code></li> +</ul> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/relationship/writing-modes.html", '100%', 360)}} </p> + +<p>Note that <code>sideways-rl</code> and <code>sideways-lr</code> have support only in Firefox currently. There are also some known issues with regard to <code>writing-mode</code> and flexbox. You can see more information on browser support in the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode">MDN documentation for writing-mode</a>. However if you are planning on using writing modes in your layout, carefully testing the results is advisable — not least because it would be easy to make things hard to read!</p> + +<p>Note that you would not normally use CSS and the <code>writing-mode</code> property to change an entire document to another writing mode. This would be done via HTML, by add a <code>dir</code> and <code>lang</code> attribute to the <code>html</code> element to indicate the document language and default text direction. This would mean that the document would display correctly even if CSS did not load.</p> + +<h2 id="Flexbox_e_outros_métodos_de_layout">Flexbox e outros métodos de <em>layout</em></h2> + +<p>The flexbox specification contains a <a href="https://www.w3.org/TR/css-flexbox-1/#flex-containers">definition of what happens</a> if an item uses another layout method and then becomes a flex item. For example, if an item is floated and then its parent becomes a flex container. Or, how a flex container behaves as part of layout.</p> + +<p>An element set to <code>display: flex</code> behaves in most ways like any other block level container that establishes a containing block. Floats will not intrude, and the containers' margins will not collapse.</p> + +<p>With regard to flex items, if an item was floated or cleared and then becomes a flex item due to the parent having <code>display: flex</code> applied, the floating and clearing will no longer happen, and the item will not be taken out of normal flow in the way that floats are. If you have used the {{cssxref("vertical-align")}} property, as used with <code>inline-block</code> or table layout for alignment, this will no longer affect the item and you can use the alignment properties of flexbox instead.</p> + +<p>In this next live example the child elements have been floated, and then their container has had <code>display: flex</code> added. If you remove <code>display: flex</code>, you should see that the <code>.box</code> element collapses as we have no clearing applied. This demonstrates that the float is happening. Re-apply <code>display: flex</code> and the collapsing does not happen. This is because the items no longer have a float applied, as they have been transformed into flex items.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/relationship/floats.html", '100%', 430)}}</p> + +<h2 id="Flexbox_e_Layout_de_Grelha">Flexbox e <em>Layout</em> de Grelha</h2> + +<p><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid Layout</a> and Flexbox generally act in the same way with regards to overwriting other methods. You might however want to use flexbox as a fallback for grid layout, as there is better support for flexbox in older browsers. This approach works very well. If a flex item becomes a grid item, then the <code>flex</code> properties that may have been assigned to the child elements will be ignored.</p> + +<p>You can use the Box Alignment properties across both layout methods, so using flexbox as a fallback for grid layout can work very well.</p> + +<h3 id="Flex_e_grelha_—_qual_é_a_diferença">Flex e grelha — qual é a diferença?</h3> + +<p>A common question is to ask what the difference is between Flexbox and CSS Grid Layout — why do we have two specifications that sometimes appear to be doing the same thing as each other?</p> + +<p>The most straightforward answer to this question is defined in the specifications themselves. Flexbox is a one-dimensional layout method whereas Grid Layout is a two-dimensional layout method. In the below example I have a flex layout. As already described in the Basic concepts article, flex items can be allowed to wrap but, once they do so, each line becomes a flex container of its own. When space is distributed flexbox does not look at the placement of items in other rows and tries to line things up with each other.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/relationship/flex-layout.html", '100%', 750)}}</p> + +<p>If we create a very similar layout using Grid, we can control the layout in both rows and columns.</p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/relationship/grid-layout.html", '100%', 700)}}</p> + +<p>These examples point to another key differences between these layout methods. In Grid Layout you do the majority of sizing specification on the container, setting up tracks and then placing items into them. In flexbox, while you create a flex container and set the direction at that level, any control over item sizing needs to happen on the items themselves.</p> + +<p>In some cases you could happily use either layout method, but as you become confident with both you will find each one suiting different layout needs, and you will end up with both methods in your CSS. There is rarely a right or wrong answer.</p> + +<p>As a rule of thumb, if you are adding widths to flex items in order to make items in one row of a wrapped flex container line up with the items above them you really want two-dimensional layout. In this case it is likely that the component would be better laid out using CSS Grid Layout. It isn't the case that you should use flexbox for small components and grid layout for larger ones; a tiny component can be two dimensional, and a large layout can be represented better with layout in one dimension. Try things out — we have a choice in layout method for the first time, so take advantage of it.</p> + +<p>For more comparisons of grid and flexbox see the article <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship of Grid Layout to other layout methods</a>. This article details many of the ways that Grid Layout differs from flex layout, and demonstrates some of the extra functionality you get when using Grid Layout such as layering of items on the grid. This may also help in your decision as to which layout method to use.</p> + +<h2 id="Flexbox_e_exibição_conteúdos">Flexbox e exibição: conteúdos</h2> + +<p>The <code>contents</code> value of the {{cssxref("display")}} property is a new value that is described in the spec as follows:</p> + +<blockquote> +<p>“The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been replaced with its children and pseudo-elements in the document tree.”</p> +</blockquote> + +<p>This value of <code>display</code> controls box generation, and whether the element should generate a box that we can style and see on the page, or whether instead the box it would normally create should be removed and the child elements essentially moved up to participate in whatever layout method the parent would have been part of. This is much easier to see with an example.</p> + +<p>In the following live example I have a flex container with three child elements. One of these flex items has two elements nested inside it, which would not ordinarily participate in flex layout. Flex layout only applies to the direct children of a flex container.</p> + +<p>By adding <code>display: contents</code> to the wrapper around the nested elements, you can see that that item has disappeared from the layout, allowing the two sub-children to be laid out as if they were direct children of the flex container. You can try removing the <code>display: contents</code> line to see it return.</p> + +<p>Note that this only removes the box from the layout; the sub-children don’t become direct children in any other way. You can see that as I have used a direct child selector to add the background and borders to the flex items, this has not been applied to our nested children. They have been laid out as flex items, but as they are not direct children they do not get the other styling.</p> + +<p>Also, having removed the box you cannot then use it to — for example — add a background colour behind the nested sub children. If you remove <code>display: contents</code> in this live example you will see that the direct child we are removing has an orange background colour. This also disappears when the box disappears. </p> + +<p>{{EmbedGHLiveSample("css-examples/flexbox/relationship/display-contents.html", '100%', 650)}}</p> + +<p>Browser support for <code>display:contents</code> is limited and required for this demo to work. Firefox supports <code>display: contents</code> already, and the value is being implemented in Chrome. Once there is better browser support this feature will be very useful in circumstances where you need the markup for semantic reasons but do not want to display the box that it would generate by default.</p> diff --git a/files/pt-pt/web/css/css_tipos/index.html b/files/pt-pt/web/css/css_tipos/index.html new file mode 100644 index 0000000000..ea7049f5a4 --- /dev/null +++ b/files/pt-pt/web/css/css_tipos/index.html @@ -0,0 +1,65 @@ +--- +title: CSS - Tipos de datos básicos +slug: Web/CSS/CSS_Tipos +tags: + - CSS + - Referencia + - Resumo + - Sinopse + - Tipos de Dados de CSS +translation_of: Web/CSS/CSS_Types +--- +<div>{{CssRef}}</div> + +<p><strong>CSS - tipos de dados básicos</strong> define typical values (including keywords and units) accepted by CSS properties and functions. They are a special kind of <a href="https://www.w3.org/TR/css3-values/#component-types">component value type</a>.</p> + +<p>In formal syntax, data types are denoted by a keyword placed between the inequality signs "<" and ">".</p> + +<h2 id="Referência">Referência</h2> + +<div class="index"> +<ul> + <li>{{cssxref("<angle>")}}</li> + <li>{{cssxref("<basic-shape>")}}</li> + <li>{{cssxref("<blend-mode>")}}</li> + <li>{{cssxref("<color>")}}</li> + <li>{{cssxref("<custom-ident>")}}</li> + <li>{{cssxref("<filter-function>")}}</li> + <li>{{cssxref("<flex>")}}</li> + <li>{{cssxref("<frequency>")}}</li> + <li>{{cssxref("<gradient>")}}</li> + <li>{{cssxref("<image>")}}</li> + <li>{{cssxref("<integer>")}}</li> + <li>{{cssxref("<length>")}}</li> + <li>{{cssxref("<number>")}}</li> + <li>{{cssxref("<percentage>")}}</li> + <li>{{cssxref("<position>")}}</li> + <li>{{cssxref("<ratio>")}}</li> + <li>{{cssxref("<resolution>")}}</li> + <li>{{cssxref("<shape-box>")}}</li> + <li>{{cssxref("<single-transition-timing-function>")}}</li> + <li>{{cssxref("<string>")}}</li> + <li>{{cssxref("<time>")}}</li> + <li>{{cssxref("<transform-function>")}}</li> + <li>{{cssxref("<url>")}}</li> +</ul> +</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSS3 Values') }}</td> + <td>{{ Spec2('CSS3 Values') }}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> diff --git a/files/pt-pt/web/css/cursor/index.html b/files/pt-pt/web/css/cursor/index.html new file mode 100644 index 0000000000..152fe3b344 --- /dev/null +++ b/files/pt-pt/web/css/cursor/index.html @@ -0,0 +1,159 @@ +--- +title: cursor +slug: Web/CSS/cursor +tags: + - Referencia_CSS +translation_of: Web/CSS/cursor +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade {{ Cssxref("cursor") }} especifica o estilo do ponteiro do mouse quando estiver sobre o elemento.</p> + +<ul> + <li>Valor inicial: <code>auto</code></li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: sim</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="/pt/CSS/Media/Visual" title="pt/CSS/Media/Visual">Visual</a>, <a href="/pt/CSS/Media/Interactive" title="pt/CSS/Media/Interactive">Interactive</a></li> + <li><a href="/pt/CSS/computed_value" title="pt/CSS/computed_value">Valor computado</a>: como especificado (endereços relativos são convertidos como absolutos)</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<p><code>cursor:</code> [ {{ mediawiki.external(' ,') }}* {{ mediawiki.external(' <code>auto</code> | <code>crosshair</code> | <code>default</code> | <code>pointer</code> | <code>move</code> | <code>e-resize</code> | <code>ne-resize</code> | <code>nw-resize</code> | <code>n-resize</code> | <code>se-resize</code> | <code>sw-resize</code> | <code>s-resize</code> | <code>w-resize</code> | <code>text</code> | <code>wait</code> | <code>help</code> | <code>progress</code> | <code>copy</code> | <code>alias</code> | <code>context-menu</code> | <code>cell</code> | <code>not-allowed</code> | <code>col-resize</code> | <code>row-resize</code> | <code>no-drop</code> | <code>vertical-text</code> | <code>all-scroll</code> | <code>nesw-resize</code> | <code>nwse-resize</code> | <code>ns-resize</code> | <code>ew-resize</code> ') }} ] | {{ Cssxref("inherit") }}</p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt><url> </dt> + <dd>URL of custom cursor. More than one URL may be provided as fallback, in case some cursor image types are not supported. A non-URL fallback (one of the other values) must be at the end of the fallback list. See <a href="pt/Using_URL_values_for_the_cursor_property">Using URL values for the cursor property</a> for more details.</dd> + <dt><code>default</code> </dt> + <dd>default cursor (typically an arrow)</dd> + <dt><code>auto</code> </dt> + <dd>equivalent to <code>text</code> when over text and <code>default</code> otherwise</dd> + <dt><code>crosshair</code> </dt> + <dd>cross cursor, often used to indicate selection in a bitmap</dd> + <dt><code>pointer</code> </dt> + <dd>cursor used when over links (typically a hand)</dd> + <dt><code>move</code> </dt> + <dd>move cursor</dd> + <dt><code>e-resize</code> </dt> + <dd>cursor for resizing the right edge of a box</dd> + <dt><code>ne-resize</code> </dt> + <dd>cursor for resizing the top right corner of a box</dd> + <dt><code>nw-resize</code> </dt> + <dd>cursor for resizing the top left corner of a box</dd> + <dt><code>n-resize</code> </dt> + <dd>cursor for resizing the top edge of a box</dd> + <dt><code>se-resize</code> </dt> + <dd>cursor for resizing the bottom right corner of a box</dd> + <dt><code>sw-resize</code> </dt> + <dd>cursor for resizing the bottom left corner of a box</dd> + <dt><code>s-resize</code> </dt> + <dd>cursor for resizing the bottom edge of a box</dd> + <dt><code>w-resize</code> </dt> + <dd>cursor for resizing the left edge of a box</dd> + <dt><code>text</code> </dt> + <dd>cursor indicating text can be selected (typically an I-beam)</dd> + <dt><code>wait</code> </dt> + <dd>cursor indicating the program is busy (sometimes an hourglass or a watch)</dd> + <dt><code>help</code> </dt> + <dd>cursor indicating help is available</dd> + <dt><code>progress</code> </dt> + <dd>cursor indicating that the program is busy but the user can still interact with it (unlike for <code>busy</code>)</dd> + <dt><code>copy</code> </dt> + <dd>cursor showing something that can be copied</dd> + <dt><code>alias</code> </dt> + <dd>cursor indicating an alias or shortcut is to be created</dd> + <dt><code>context-menu</code> </dt> + <dd>cursor indicating that a context menu is available under the cursor</dd> + <dt><code>cell</code> </dt> + <dd>cursor indicating that cells can be selected</dd> + <dt><code>not-allowed</code> </dt> + <dd>cursor showing that something cannot be done</dd> + <dt><code>col-resize</code> </dt> + <dd>cursor for resizing columns horizontally</dd> + <dt><code>row-resize</code> </dt> + <dd>cursor for resizing rows vertically</dd> + <dt><code>no-drop</code> </dt> + <dd>cursor showing that a drop is not allowed at the current location</dd> + <dt><code>vertical-text</code> </dt> + <dd>cursor indicating that vertical text can be selected (typically a sideways I-beam)</dd> + <dt><code>all-scroll</code> </dt> + <dd>cursor showing that something can be scrolled in any direction (panned)</dd> + <dt><code>nesw-resize</code> </dt> + <dd>cursor for resizing in the top-right or bottom-left directions</dd> + <dt><code>nwse-resize</code> </dt> + <dd>cursor for resizing in the top-left or bottom-right directions</dd> + <dt><code>ns-resize</code> </dt> + <dd>cursor for resizing up or down</dd> + <dt><code>ew-resize</code> </dt> + <dd>cursor for resizing left or right</dd> +</dl> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/cursor.html">View Live Examples</a></p> + +<pre>Inline: + +<span style="cursor: crosshair">Some Text</span> + +External: + +.pointer { + cursor: pointer; +} +.move { + cursor: move; +} + +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>While this property works on older browsers, not all values are fully supported.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS21/ui.html#propdef-cursor">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-ui/#cursor">css3-ui</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga/th></th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Firefox</td> + <td>1.5</td> + </tr> + <tr> + <td>Netscape</td> + <td>6</td> + </tr> + <tr> + <td>Opera</td> + <td>7</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/cursor", "fr": "fr/CSS/cursor", "pl": "pl/CSS/cursor" } ) }}</p> diff --git a/files/pt-pt/web/css/direction/index.html b/files/pt-pt/web/css/direction/index.html new file mode 100644 index 0000000000..a89e7a1b6c --- /dev/null +++ b/files/pt-pt/web/css/direction/index.html @@ -0,0 +1,46 @@ +--- +title: direction +slug: Web/CSS/direction +tags: + - Referencia_CSS +translation_of: Web/CSS/direction +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p>The <code>direction</code> property should be set to match the direction of the text: <code>rtl</code> for Hebrew or Arabic text and <code>ltr</code> for other scripts. This should normally be done as part of the document (e.g., using the <code>dir</code> attribute in HTML) rather than through direct use of CSS. +</p><p>The property sets the base text direction of block-level elements and the direction of embeddings created by the {{ Cssxref("unicode-bidi") }} property. It also sets the default alignment of text and block-level elements and the direction that cells flow within a table row. +</p> +<ul><li> Valor inicial: <code>ltr</code> +</li><li> Aplica-se a: todos os elementos +</li><li> Herdado: sim +</li><li> Porcentagens: N/A +</li><li> Mídia: <a href="pt/CSS/Media/Visual">visual</a> +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<pre class="eval">direction: [ 'ltr' | 'rtl' | inherit ] ; +</pre> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> ltr </dt><dd> The default value of <code>direction</code>. Text and other elements go from left to right +</dd><dt> rtl </dt><dd> Text and other elements go from right to left +</dd></dl> +<p>For the <code>direction</code> property to have any effect on inline-level elements, the {{ Cssxref("unicode-bidi") }} property's value must be 'embed' or 'override'. +</p> +<h3 id="Exemplos" name="Exemplos"> Exemplos </h3> +<pre class="eval">blockquote { + direction : rtl ; +} +</pre> +<h3 id="Notas" name="Notas"> Notas </h3> +<p>Unlike the <code>dir</code> attribute in HTML, the <code>direction</code> property is not inherited from table columns into table cells, since CSS inheritance follows the document tree, and table cells are inside of the rows but not inside of the columns. +</p> +<h3 id="Especifica.C3.A7.C3.A3o" name="Especifica.C3.A7.C3.A3o"> Especificação </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS21/visuren.html#direction">CSS 2.1</a> +</li><li> <a class="external" href="http://www.w3.org/TR/2003/CR-css3-text-20030514/#direction">CSS 3 Text Module</a> +</li></ul> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m"> Veja também </h3> +<p>{{ Cssxref("unicode-bidi") }} +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/direction", "fr": "fr/CSS/direction", "pl": "pl/CSS/direction" } ) }} diff --git a/files/pt-pt/web/css/display/index.html b/files/pt-pt/web/css/display/index.html new file mode 100644 index 0000000000..43db53135e --- /dev/null +++ b/files/pt-pt/web/css/display/index.html @@ -0,0 +1,707 @@ +--- +title: display +slug: Web/CSS/display +tags: + - CSS + - CSS Display + - Propriedade de CSS +translation_of: Web/CSS/display +--- +<div>{{CSSRef}}</div> + +<p>Esta propriedade <strong><code>display</code></strong> de CSS especifica o tipo de caixa de renderização utilizado para um elemento. Em HTML, os valores da propriedade <code>display</code> predefinidos têm o seu comportamento descrito nas especificações de HTML ou de uma folha de estilo predefinida do navegador ou do utilizador. O valor predefinido no XML é <code>inline</code>, incluindo os elementos de <a href="/pt-PT/docs/Web/SVG">SVG</a> .</p> + +<p>Em adição aos diferentes tipos de caixa de exibição, o valor <code>none</code> deixa-o desativar a exibição de um elemento; quando utiliza <code>none</code>, todos os elementos descendentes também têm as suas exibições desativadas. O documento é renderizado como se o elemento não existisse na árvore do documento.</p> + +<pre class="brush:css no-line-numbers">/* <display-outside> values */ +display: block; +display: inline; +display: run-in; + +/* <display-inside> values */ +display: flow; +display: flow-root; +display: table; +display: flex; +display: grid; +display: ruby; +display: subgrid; + +/* <display-outside> plus <display-inside> values */ +display: block flow; +display: inline table; +display: flex run-in; + +/* <display-listitem> values */ +display: list-item; +display: list-item block; +display: list-item inline; +display: list-item flow; +display: list-item flow-root; +display: list-item block flow; +display: list-item block flow-root; +display: flow list-item block; + +/* <display-internal> values */ +display: table-row-group; +display: table-header-group; +display: table-footer-group; +display: table-row; +display: table-cell; +display: table-column-group; +display: table-column; +display: table-caption; +display: ruby-base; +display: ruby-text; +display: ruby-base-container; +display: ruby-text-container; + +/* <display-box> values */ +display: contents; +display: none; + +/* <display-legacy> values */ +display: inline-block; +display: inline-table; +display: inline-flex; +display: inline-grid; + +/* Global values */ +display: inherit; +display: initial; +display: unset; +</pre> + +<p>{{cssinfo}}</p> + +<h2 id="Sintaxe" name="Sintaxe">Sintaxe</h2> + +<p>A propriedade <code>display</code> é especificada utilizando os valores chave. Os valores chave são agrupados em seis categorias:</p> + +<ul> + <li><code><a href="#display-outside"><display-outside></a></code></li> + <li><code><a href="#display-inside"><display-inside></a></code></li> + <li><code><a href="#display-listitem"><display-listitem></a></code></li> + <li><code><a href="#display-internal"><display-internal></a></code></li> + <li><code><a href="#display-box"><display-box></a></code></li> + <li><code><a href="#display-legacy"><display-legacy></a></code></li> +</ul> + +<p>Currently it's best to specify <code>display</code> using a single keyword; although the latest specifications allow you to combine some keywords, this is not yet well supported by browsers.</p> + +<h3 id="Valores">Valores</h3> + +<dl> + <dt><a id="display-outside" name="display-outside"><code><display-outside></code></a></dt> + <dd>These keywords specify the element’s outer display type, which is essentially its role in flow layout. They are defined as follows: + <table class="standard-table"> + <thead> + <tr> + <td class="header">Valor</td> + <td class="header">Descrição</td> + </tr> + </thead> + <tbody> + <tr> + <td><code>block</code></td> + <td>The element generates a block element box.</td> + </tr> + <tr> + <td><code>inline</code></td> + <td>The element generates one or more inline element boxes.</td> + </tr> + <tr> + <td><code>run-in</code> {{experimental_inline}}</td> + <td>The element generates a run-in box. Run-in elements act like inlines or blocks, depending on the surrounding elements. That is: + <ul> + <li>If the run-in box contains a block box, same as block.</li> + <li>If a block box follows the run-in box, the run-in box becomes the first inline box of the block box.</li> + <li>If an inline box follows, the run-in box becomes a block box.</li> + </ul> + </td> + </tr> + </tbody> + </table> + </dd> + <dt><a id="display-inside" name="display-inside"><code><display-inside></code></a></dt> + <dd>These keywords specify the element’s inner display type, which defines the type of formatting context that lays out its contents (assuming it is a non-replaced element). They are defined as follows: + <table class="standard-table"> + <thead> + <tr> + <td class="header">Value</td> + <td class="header">Description</td> + </tr> + </thead> + <tbody> + <tr> + <td><code>flow</code> {{experimental_inline}}</td> + <td>The element lays out its contents using flow layout (block-and-inline layout). + <p>If its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box. Otherwise it generates a block container box.</p> + + <p>Depending on the value of other properties (such as {{cssxref("position")}}, {{cssxref("float")}}, or {{cssxref("overflow")}}) and whether it is itself participating in a block or inline formatting context, it either establishes a new <a href="/en-US/docs/Web/Guide/CSS/Block_formatting_context">block formatting context</a> for its contents or integrates its contents into its parent formatting context.</p> + </td> + </tr> + <tr> + <td><code>flow-root</code> {{experimental_inline}}</td> + <td>The element generates a block element box that establishes a new <a href="/en-US/docs/Web/Guide/CSS/Block_formatting_context">block formatting context</a>.</td> + </tr> + <tr> + <td><code>table</code></td> + <td>These elements behave like {{HTMLElement("table")}} HTML elements. It defines a block-level box.</td> + </tr> + <tr> + <td><code>flex</code></td> + <td>The element behaves like a block element and lays out its content according to the <a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout">flexbox model</a>.</td> + </tr> + <tr> + <td><code>grid</code></td> + <td>The element behaves like a block element and lays out its content according to the grid model.</td> + </tr> + <tr> + <td><code>subgrid</code> {{experimental_inline}}</td> + <td>If the parent element has <code>display:grid</code>, the element itself and its content are laid out according to the grid model.</td> + </tr> + <tr> + <td><code>ruby</code> {{experimental_inline}}</td> + <td>The element behaves like an inline element and lays out its content according to the ruby formatting model. It behaves like the corresponding {{HTMLElement("ruby")}} HTML elements.</td> + </tr> + </tbody> + </table> + </dd> + <dt><a id="display-listitem" name="display-listitem"><code><display-listitem></code></a></dt> + <dd> + <p>The element generates a block box for the content and a separate list-item inline box.</p> + + <p>If no <code><display-inside></code> value is specified, the principal box’s inner display type defaults to <code>flow</code>. If no <code><display-outside></code> value is specified, the principal box’s outer display type defaults to <code>block</code>.</p> + </dd> + <dt><a id="display-internal" name="display-internal"><code><display-internal></code></a></dt> + <dd> + <p>Some layout models, such as <span class="css">table</span> and ruby, have a complex internal structure, with several different roles that their children and descendants can fill. This section defines those "internal" display values, which only have meaning within that particular layout mode.</p> + + <p>Unless otherwise specified, both the inner display type and the outer display type of elements using these display values are set to the given keyword.</p> + + <table class="standard-table"> + <thead> + <tr> + <td class="header">Valor</td> + <td class="header">Descrição</td> + </tr> + </thead> + <tbody> + <tr> + <td><code>table-row-group</code></td> + <td>These elements behave like {{HTMLElement("tbody")}} HTML elements</td> + </tr> + <tr> + <td><code>table-header-group</code></td> + <td>These elements behave like {{HTMLElement("thead")}} HTML elements.</td> + </tr> + <tr> + <td><code>table-footer-group</code></td> + <td>These elements behave like {{HTMLElement("tfoot")}} HTML elements.</td> + </tr> + <tr> + <td><code>table-row</code></td> + <td>These elements behave like {{HTMLElement("tr")}} HTML elements.</td> + </tr> + <tr> + <td><code>table-cell</code></td> + <td>These elements behave like {{HTMLElement("td")}} HTML elements.</td> + </tr> + <tr> + <td><code>table-column-group</code></td> + <td>These elements behave like {{HTMLElement("colgroup")}} HTML elements.</td> + </tr> + <tr> + <td><code>table-column</code></td> + <td>These elements behave like {{HTMLElement("col")}} HTML elements.</td> + </tr> + <tr> + <td><code>table-caption</code></td> + <td>These elements behave like {{HTMLElement("caption")}} HTML elements.</td> + </tr> + <tr> + <td><code>ruby-base</code> {{experimental_inline}}</td> + <td>These elements behave like {{HTMLElement("rb")}} elements.</td> + </tr> + <tr> + <td><code>ruby-text</code> {{experimental_inline}}</td> + <td>These elements behave like {{HTMLElement("rt")}} elements.</td> + </tr> + <tr> + <td><code>ruby-base-container</code> {{experimental_inline}}</td> + <td>These elements behave like {{HTMLElement("rbc")}} elements generated as anonymous boxes.</td> + </tr> + <tr> + <td><code>ruby-text-container</code> {{experimental_inline}}</td> + <td>These elements behave like {{HTMLElement("rtc")}} elements.</td> + </tr> + </tbody> + </table> + </dd> + <dt><a id="display-box" name="display-box"><code><display-box></code></a></dt> + <dd>These values define whether an element generates display boxes at all. + <table class="standard-table"> + <thead> + <tr> + <td class="header">Valor</td> + <td class="header">Descrição</td> + </tr> + </thead> + <tbody> + <tr> + <td><code>contents</code> {{experimental_inline}}</td> + <td>These elements don't produce a specific box by themselves. They are replaced by their pseudo-box and their child boxes.</td> + </tr> + <tr> + <td><code>none</code></td> + <td> + <p>Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off.</p> + + <p>To have an element take up the space that it would normally take, but without actually rendering anything, use the {{cssxref("visibility")}} property instead.</p> + </td> + </tr> + </tbody> + </table> + </dd> + <dt><a id="display-legacy" name="display-legacy"><code><display-legacy></code></a></dt> + <dd>CSS 2 used a single-keyword syntax for the <code>display</code> property, requiring separate keywords for block-level and inline-level variants of the same layout mode. They are defined as follows: + <table class="standard-table"> + <thead> + <tr> + <td class="header">Valor</td> + <td class="header">Descrição</td> + </tr> + </thead> + <tbody> + <tr> + <td><code>inline-block</code></td> + <td> + <p>The element generates a block element box that will be flowed with surrounding content as if it were a single inline box (behaving much like a replaced element would)</p> + + <p>It is equivalent to <code>inline flow-root</code>.</p> + </td> + </tr> + <tr> + <td><code>inline-table</code></td> + <td> + <p>The <code>inline-table</code> value does not have a direct mapping in HTML. It behaves like a {{HTMLElement("table")}} HTML element, but as an inline box, rather than a block-level box. Inside the table box is a block-level context.</p> + + <p>It is equivalent to <code>inline table</code>.</p> + </td> + </tr> + <tr> + <td><code>inline-flex</code></td> + <td> + <p>The element behaves like an inline element and lays out its content according to the flexbox model.</p> + + <p>It is equivalent to <code>inline flex</code>.</p> + </td> + </tr> + <tr> + <td><code>inline-grid</code></td> + <td>The element behaves like an inline element and lays out its content according to the grid model.</td> + </tr> + </tbody> + </table> + </dd> +</dl> + +<h3 id="Sintaxe_formal">Sintaxe formal</h3> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Hide_element" name="Hide_element">Elementos <em>Hide</em></h3> + +<h4 id="Conteúdo_de_HTML">Conteúdo de HTML</h4> + +<pre class="brush: html"><p>Visible text</p> +<p class="secret">Invisible text</p></pre> + +<h4 id="Conteúdo_de_CSS">Conteúdo de CSS</h4> + +<pre class="brush: css">p.secret { + display: none; +}</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{EmbedLiveSample("Hide_element", 300, 60)}}</p> + +<p><a href="/samples/cssref/display.html">View Live Examples</a></p> + +<h2 id="Specifications" name="Specifications">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Display', '#the-display-properties', 'display')}}</td> + <td>{{Spec2('CSS3 Display')}}</td> + <td>Added <code>run-in</code>, <code>flow</code>, <code>flow-root</code>, <code>contents</code>, and multi-keyword values.</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Ruby', '#ruby-display', 'display')}}</td> + <td>{{Spec2('CSS3 Ruby')}}</td> + <td>Added <code>ruby</code>, <code>ruby-base</code>, <code>ruby-text</code>, <code>ruby-base-container</code>, and <code>ruby-text-container</code>.</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Grid', '#grid-containers', 'display')}}</td> + <td>{{Spec2('CSS3 Grid')}}</td> + <td>Added the grid box model values.</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Flexbox', '#flex-containers', 'display')}}</td> + <td>{{Spec2('CSS3 Flexbox')}}</td> + <td>Added the flexible box model values.</td> + </tr> + <tr> + <td>{{SpecName('CSS2.1', 'visuren.html#display-prop', 'display')}}</td> + <td>{{Spec2('CSS2.1')}}</td> + <td>Added the table model values and <code>inline-block<em>.</em></code></td> + </tr> + <tr> + <td>{{SpecName('CSS1', '#display', 'display')}}</td> + <td>{{Spec2('CSS1')}}</td> + <td>Initial definition. Basic values: <code>none</code>, <code>block</code>, <code>inline</code>, and <code>list-item</code>.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td><code>none</code>, <code>inline</code> and <code>block</code></td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>4.0</td> + <td>7.0</td> + <td>1.0 (85)</td> + </tr> + <tr> + <td><code>inline-block</code></td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>5.5<sup>[4]</sup></td> + <td>7.0</td> + <td>1.0 (85)</td> + </tr> + <tr> + <td><code>list-item</code></td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>6.0</td> + <td>7.0</td> + <td>1.0 (85)</td> + </tr> + <tr> + <td rowspan="2"><code>run-in</code> {{experimental_inline}}</td> + <td>1.0 [5]</td> + <td rowspan="2">{{CompatNo}}</td> + <td rowspan="2">{{CompatNo}}</td> + <td rowspan="2">8.0</td> + <td>7.0</td> + <td>1.0 (85)<sup>[5]</sup></td> + </tr> + <tr> + <td>4.0 Removed in 32</td> + <td>Not Blink versions (15 upwards)</td> + <td>5.0 (532.5) Removed in 8.0</td> + </tr> + <tr> + <td><code>inline-table</code></td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>8.0</td> + <td>7.0</td> + <td>1.0 (85)</td> + </tr> + <tr> + <td><code>table</code>, <code>table-cell</code>, <code>table-column</code>, <code>table-column-group</code>, <code>table-header-group</code>, <code>table-row-group</code>, <code>table-footer-group</code>, <code>table-row</code>, and <code>table-caption</code></td> + <td>1.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>8.0</td> + <td> + <p>7.0</p> + </td> + <td>1.0 (85)</td> + </tr> + <tr> + <td><code>flex</code></td> + <td> + <p>21.0{{property_prefix("-webkit")}}</p> + + <p>29.0</p> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("18.0")}}<sup>[1]</sup><br> + {{CompatGeckoDesktop("20.0")}}</td> + <td> + <p>10{{property_prefix("-ms")}}<sup><font size="2">[8]</font></sup><br> + 11</p> + </td> + <td>12.50</td> + <td> + <p>6.1{{property_prefix("-webkit")}}</p> + + <p>9.0</p> + </td> + </tr> + <tr> + <td><code>inline-flex</code></td> + <td>21.0{{property_prefix("-webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("18.0")}}<sup>[1]</sup><br> + {{CompatGeckoDesktop("20.0")}}</td> + <td>10{{property_prefix("-ms")}}<sup><font size="2">[8]</font></sup><br> + 11</td> + <td>12.50</td> + <td>6.1{{property_prefix("-webkit")}}</td> + </tr> + <tr> + <td><code>grid</code> {{experimental_inline}}</td> + <td>{{CompatChrome(57)}}</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-ms")}}</td> + <td>{{CompatGeckoDesktop("45.0")}}<sup>[6]</sup></td> + <td>10.0{{property_prefix("-ms")}}</td> + <td>{{CompatOpera(44)}}</td> + <td>TP</td> + </tr> + <tr> + <td><code>inline-grid</code> {{experimental_inline}}</td> + <td>{{CompatChrome(57)}}</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-ms")}}</td> + <td>{{CompatGeckoDesktop("45.0")}}<sup>[6]</sup></td> + <td>10.0{{property_prefix("-ms")}}</td> + <td>{{CompatOpera(44)}}</td> + <td>TP</td> + </tr> + <tr> + <td><code>subgrid</code> {{experimental_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ruby</code>, <code>ruby-base</code>, <code>ruby-text</code>, <code>ruby-base-container</code>, <code>ruby-text-container</code> {{experimental_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("34.0")}}<sup>[3]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>contents</code> {{experimental_inline}}</td> + <td>{{CompatChrome(58)}}<sup>[7]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop("37")}}<sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>flow-root</code></td> + <td>{{CompatChrome(58)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("53.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(45)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>7.0{{property_prefix("-webkit")}}</td> + </tr> + <tr> + <td><code>grid</code> {{experimental_inline}}</td> + <td>{{CompatChrome(57)}}</td> + <td>{{CompatChrome(57)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile(44)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>inline-grid</code> {{experimental_inline}}</td> + <td>{{CompatChrome(57)}}</td> + <td>{{CompatChrome(57)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile(44)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>flow-root</code></td> + <td>{{CompatChrome(58)}}</td> + <td>{{CompatChrome(58)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOperaMobile(45)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] To activate flexbox support, for Firefox 18 and 19, the user has to change the about:config preference "layout.css.flexbox.enabled" to <code>true</code>. Multi-line flexbox are supported since Firefox 28.</p> + +<p>[2] Before Firefox 37, the <code>contents</code> value was disabled by default, and could be enabled by setting the <code>layout.css.display-contents.enabled</code> pref to <code>true</code>. In Firefox 37, it was enabled by default, and in Firefox 53 the pref was removed altogether.</p> + +<p>[3] CSS Ruby support is behind pref "layout.css.ruby.enabled". The user has to change this pref to true to activate this.</p> + +<p>[4] In IE < 8, natural inline elements only.</p> + +<p>[5] Not before inline-elements.</p> + +<p>[6] CSS Grid support is unprefixed in Nightly/Alpha builds and behind pref "layout.css.grid.enabled" in Beta/release builds.</p> + +<p>[7] In Chrome, the <code>contents</code> value is currently disabled by default, but can be enabled with the "Experimental Web Platform features" flag.</p> + +<p>[8] In IE 10, only special prefixed values, <code>-ms-flexbox</code> and <code>-ms-inline-flexbox</code>, are recognized.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{Cssxref("visibility")}}, {{Cssxref("float")}}, {{Cssxref("position")}}</li> + <li>{{Cssxref("flex")}}</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: block; opacity: 0; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/css/float/index.html b/files/pt-pt/web/css/float/index.html new file mode 100644 index 0000000000..62f8ddf017 --- /dev/null +++ b/files/pt-pt/web/css/float/index.html @@ -0,0 +1,111 @@ +--- +title: float +slug: Web/CSS/float +tags: + - Referencia_CSS +translation_of: Web/CSS/float +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade <code>float</code> especifica se um elemento deve flutuar pelo lado direito, pelo esquerdo ou não flutuar, onde os elementos <code>inline</code> envolverão ao redor dele.</p> + +<ul> + <li>Valor inicial: none;</li> + <li>Aplica-se a: todos elementos;</li> + <li>Herdado: não;</li> + <li>Valor computado: como especificado.</li> +</ul> + +<p>Um <strong>elemento flutuante</strong> é um elemento onde o valor computado é diferente de <code>none</code>.</p> + +<p>Note que se você estiver referenciando a esta propriedade do JavaScript como um membro do objeto <a href="pt/DOM/element.style">element.style</a>, você precisa escrever isto em <strong>cssFloat</strong> (veja a lista do <a href="pt/DOM/CSS">DOM:CSS</a>). Note também que para o IE você precisa escrever <strong>styleFloat</strong>.</p> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<p>float: left | right | none | <a href="pt/CSS/inherit">inherit</a></p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<ul> + <li><strong>left</strong> : O elemento flutua pelo lado esquerdo de um bloco;</li> + <li><strong>right</strong> : O elemento flutua pelo lado direito de um bloco;</li> + <li><strong>none</strong> : O elemento não flutua.</li> +</ul> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/float.html">View Live Examples</a></p> + +<pre><html> + <head> + <style type="text/css"> + b + { + font-size: 25px; + float:right; + } + </style> + </head> + <body> + + <p> + <b>HELLO!</b> + Isto é algum texto. Isto é algum texto. Isto é algum texto. + Isto é algum texto. Isto é algum texto. Isto é algum texto. + Isto é algum texto. Isto é algum texto. Isto é algum texto. + Isto é algum texto. Isto é algum texto. Isto é algum texto. + Isto é algum texto. Isto é algum texto. Isto é algum texto. + Isto é algum texto. Isto é algum texto. Isto é algum texto. + Isto é algum texto. Isto é algum texto. Isto é algum texto. + Isto é algum texto. Isto é algum texto. Isto é algum texto. + </p> + +</body> +</html> +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>TODO: deve explicar como os flutuantes se posicionam. Mencionar o <a href="pt/CSS/block_formatting_context">contexto de formatação de bloco</a>.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#float">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/visuren.html#propdef-float">CSS 2.1</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("clear") }}, {{ Cssxref("display") }}, {{ Cssxref("position") }}, {{ Cssxref("float") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/float", "fr": "fr/CSS/float" } ) }}</p> diff --git a/files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html b/files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html new file mode 100644 index 0000000000..250bb3eef9 --- /dev/null +++ b/files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html @@ -0,0 +1,23 @@ +--- +title: Folhas de estilo alternativas +slug: Web/CSS/Folhas_de_estilo_alternativas +translation_of: Web/CSS/Alternative_style_sheets +--- +<p>O Firefox oferece suporte a folhas de estilo alternativa. AS páginas que disponibilizam folhas de estilo alternativas permitem que o usuário selecione o estilo que a página será mostrada usando o submenu Exibir>Estilos da página. Fornecendo uma maneira de visualizar várias versões de uma mesma página, com base em suas necessidades e preferências.</p> +<p>Um site pode usar a tag link para adicionar as folhas de estilo alternativa.</p> +<p>Por exemplo:</p> +<pre class="eval"><link href="padrao.css" rel="stylesheet" type="text/css" title="Estilo padrao"> +<link href="estilo1.css" rel="alternate stylesheet" type="text/css" title="Estilo 1"> +<link href="estilo2.css" rel="alternate stylesheet" type="text/css" title="Estilo 2"> +</pre> +<p>Oferecendo essas três folhas de estilo, disponibilizaremos ao usuário as opções "Estilo Padrão", "Estilo 1" e "Estilo 2" no submenu. Quando o usuário selecionar um dos estilos, a página imediatamente será recarregada usando o estilo selecionado.</p> +<p>O valor do atributo title na tag link nomeia cada opção de estilo. Quando o valor deste atributo é repetido, entende-se como parte da mesma opção. Caso a tag link não possua o atributo title, a folha correspondente será sempre aplicada.</p> +<p>Use rel="stylesheet" para aplicar as folhas correspondente ao estilo padrão, e rel="alternate stylesheet" para aplicar as folhas correspondente aos estilos alternativos. Isso permite que o Firefox diferencie as folhas de estilo padrão das alternativas e permite que os navegadores que não suportam folhas de estilo alternativa apliquem somente as folhas do estilo padrão.</p> +<p> </p> +<h3 id="Exemplo" name="Exemplo">Exemplo</h3> +<p><a class="external" href="http://developer.mozilla.org/samples/cssref/altstyles/index.html">Clique aqui</a> para ver um exemplo.</p> +<p> </p> +<h3 id="Especifica.C3.A7.C3.A3o" name="Especifica.C3.A7.C3.A3o">Especificação</h3> +<ul> + <li><a class="external" href="http://www.w3.org/TR/html401/present/styles.html#h-14.3">HTML 4.01: Folhas de Estilo Externa</a></li> +</ul> diff --git a/files/pt-pt/web/css/font-size-adjust/index.html b/files/pt-pt/web/css/font-size-adjust/index.html new file mode 100644 index 0000000000..bc7b060a83 --- /dev/null +++ b/files/pt-pt/web/css/font-size-adjust/index.html @@ -0,0 +1,75 @@ +--- +title: font-size-adjust +slug: Web/CSS/font-size-adjust +tags: + - Referencia_CSS +translation_of: Web/CSS/font-size-adjust +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade {{ Cssxref("font-size-adjust") }} especifica que o tamanho da fonte deve ser escolhido baseado na altura das letras minúsculas antes da altura das letras maísculas.</p> + +<p>Isto é útil desde a legibilidade das fontes, especialmente em tamanhos pequenos, é mais determinado pelo tamanho das letras minúsculas do que pelo tamanho das letras maíusculas. Isto pode causar problemas quando a primeira escolha {{ Cssxref("font-family") }} não está disponível e sua substituição tem uma relação de aspecto significativamente diferente (a relação do tamanho das fontes minúsculas para o tamanho da fonte).</p> + +<p>Para fazer isto de forma que seja compatível com os navegadores que não suportam {{ Cssxref("font-size-adjust") }}, é especificado um número que a propriedade {{ Cssxref("font-size") }} é multiplicada por. Isto significa que o valor especificado para a propriedade deve geralmente ser a relação de aspecto da primeira escolha de fonte. Por exemplo, uma folha de estilo que especifica <code><a href="pt/CSS/font-size">font-size</a>: 16px; <a href="pt/CSS/font-size-adjust">font-size-adjust</a>: 0.5</code> está realmente especificando que as letras minúsculas da fonte deverão ter <code>8px</code> de altura (16px vezes 0.5).</p> + +<ul> + <li><a href="pt/CSS/initial_value">Valor inicial</a>: <code>none</code></li> + <li>Aplica-se a: todos os elementos</li> + <li><a href="pt/CSS/inheritance">Herdado</a>: sim</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">visual</a></li> + <li><a href="pt/CSS/computed_value">Valor computado</a>: como especificado</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<p><code>font-size-adjust:</code> <number> | <code>none</code> | {{ Cssxref("inherit") }}</p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt><code>none</code> </dt> + <dd>Escolha o tamanho da fonte baseado somente na propriedade {{ Cssxref("font-size") }}.</dd> + <dt><code><number></code> </dt> + <dd> + <p>Escolha o tamanho da fonte de modo que suas letras minúsculas (como determinado pela métrica x-height da fonte) sejam o número especificado de vezes pelo {{ Cssxref("font-size") }}.</p> + + <p>O número especificado deve geralmente ser a relação de aspecto (relação de x-height para o tamanho da fonte) da primeira escolha de {{ Cssxref("font-family") }}. Isto significará que a primeira escolha de fonte, quando disponível, aparecerá no mesmo tamanho nos navegadores, se não suportarem o {{ Cssxref("font-size-adjust") }}.</p> + </dd> +</dl> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/font-size-adjust.html">View Live Examples</a></p> + +<pre>p{ + font: 12px Verdana, sans-serif; + font-size-adjust: 0.58; +} + +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/1998/REC-CSS2-19980512/fonts.html#propdef-font-size-adjust">CSS 2</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-fonts/#font-size-adjust">css3-fonts</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<p>Suportado em todas as plataformas começando em Gecko 1.9 / Firefox 3, mas suportado no Windows somente signitivamente mais cedo.</p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-family") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/font-size-adjust", "fr": "fr/CSS/font-size-adjust" } ) }}</p> diff --git a/files/pt-pt/web/css/font-size/index.html b/files/pt-pt/web/css/font-size/index.html new file mode 100644 index 0000000000..e3d0ca9fa8 --- /dev/null +++ b/files/pt-pt/web/css/font-size/index.html @@ -0,0 +1,83 @@ +--- +title: font-size +slug: Web/CSS/font-size +tags: + - Referencia_CSS +translation_of: Web/CSS/font-size +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>The font-size property specifies the size of the font. The font size may, in turn, change the size of other things, since it is used to compute the value of <code>em</code> and <code>ex</code> length units.</p> + +<ul> + <li>Valor inicial: <code>medium</code></li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: sim</li> + <li>Percentagens: relativas ao elemento font-size pai</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> + <li>Valor computado: comprimento absoluto</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<p><code>font-size:</code> <code>xx-small</code> | <code>x-small</code> | <code>small</code> | <code>medium</code> | <code>large</code> | <code>x-large</code> | <code>xx-large</code></p> + +<p><code>font-size:</code> <code>smaller</code> | <code>larger</code></p> + +<p><code>font-size:</code> <length> | <percentage> | {{ Cssxref("inherit") }}</p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>xx-small, x-small, small, medium, large, x-large, xx-large </dt> + <dd>A set of absolute size keywords based on the user's default font size (which is <code>medium</code>). Similar to presentational HTML's <code><font size="1"></code> through <code><font size="7"></code> where the user's default font size is <code><font size="3"></code>.</dd> + <dt>larger, smaller </dt> + <dd>Larger or smaller than the parent element's font size, by roughly the ratio used to separate the absolute size keywords above.</dd> + <dt><a href="pt/CSS/length"><length></a> </dt> + <dd>A positive <a href="pt/CSS/length">length</a>.</dd> + <dt><percentage> </dt> + <dd>A positive percentage of the parent element's font size.</dd> +</dl> + +<p>It is best to avoid using values that are not relative to the user's default font size, such as <lengths> with units other than <code>em</code> or <code>ex</code>. However, if such values must be used, <code>px</code> are preferred over other units because their meaning does not vary depending on what the operating system thinks (generally incorrectly) the resolution of the monitor is.</p> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/font-size.html">View Live Examples</a></p> + +<pre>/* Set paragraph text to be very large. */ +p { font-size: xx-large } + +/* Set h1 (level 1 heading) text to be 2.5 times the size + * of the text around it. */ +h1 { font-size: 250% } + +/* Sets text enclosed within span tag to be 16px */ +span { font-size: 16px; } +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p><code>em</code> and <code>ex</code> units on the {{ Cssxref("font-size") }} property are relative to the parent element's font size (unlike all other properties, where they're relative to the font size on the element). This means <code>em</code> units and percentages do the same thing for {{ Cssxref("font-size") }}.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#font-size">CSS 1 </a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/fonts.html#propdef-font-size">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-fonts/#font-size">css3-fonts</a></li> +</ul> + +<p><span class="comment">== Compatibilidade com navegadores ==</span></p> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/font-size", "fr": "fr/CSS/font-size" } ) }}</p> diff --git a/files/pt-pt/web/css/font-smooth/index.html b/files/pt-pt/web/css/font-smooth/index.html new file mode 100644 index 0000000000..2cab7696d8 --- /dev/null +++ b/files/pt-pt/web/css/font-smooth/index.html @@ -0,0 +1,85 @@ +--- +title: font-smooth +slug: Web/CSS/font-smooth +translation_of: Web/CSS/font-smooth +--- +<div>{{ CSSRef }} {{ Non-standard_header }}</div> + +<p>A propriedade <a href="/en/CSS" title="CSS">CSS</a> <strong><code>font-smooth</code></strong> controla a aplicação anti-aliasing quando as fontes são renderizadas.</p> + +<table class="properties"> + <tbody> + <tr> + <td><strong>{{ Xref_cssinitial() }}</strong></td> + <td><code>auto</code></td> + </tr> + <tr> + <td><strong>Applies to</strong></td> + <td>todos os elementos e conteúdos gerados</td> + </tr> + <tr> + <td><strong>{{ Xref_cssinherited() }}</strong></td> + <td>sim</td> + </tr> + <tr> + <td><strong>Percentages</strong></td> + <td>relativo ao tamanho da fonte do elemento pai</td> + </tr> + <tr> + <td><strong>Media</strong></td> + <td>{{ Xref_cssvisual() }}</td> + </tr> + <tr> + <td><strong>{{ Xref_csscomputed() }}</strong></td> + <td>como especificado</td> + </tr> + </tbody> +</table> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="brush:css">/* Keyword values */ +font-smooth: auto; +font-smooth: never; +font-smooth: always; + +/* <length> value */ +font-smooth: 2em; +</pre> + +<div class="note"> +<p><strong>WebKit</strong> implementa uma propriedade similar, mas com valores diferentes: <strong><code>-webkit-font-smoothing</code></strong>. Isto só funciona no Mac OS X/macOS.</p> + +<ul> + <li><code>auto</code> - Deixa o navegador decidir (Usa o subpixel anti-aliasing quando disponível; este é o padrão)</li> + <li><code>none</code> - Desativa a suavização da fonte; exibe o texto com bordas afiadas e irregulares.</li> + <li><code>antialiased</code> - Suaviza a fonte no nível do pixel, ao contrário do subpixel. Muda a renderização de subpixel para o antialiasing para texto claro em fundos escuros e faz com que pareça mais suave.</li> + <li><code>subpixel-antialiased</code> - Na maioria de displays não retina, isso irá deixar o texto mais nítido.</li> +</ul> +</div> + +<div class="note"> +<p><strong>Firefox</strong> implementa uma propriedade similar, mas com valores diferentes: <strong><code>-moz-osx-font-smoothing</code></strong>. Isto só funciona no Mac OS X/macOS.</p> + +<ul> + <li><code>auto</code> - Permite que o navegador selecione uma otimização para suavização de fonte, normalmente <code>grayscale</code>.</li> + <li><code>grayscale</code> - Renderiza o texto com grayscale antialiasing, ao contrário do subpixel. Muda a renderização do subpixel para antialiasing para que texto o claro em fundos escuros pareça mais claro.</li> +</ul> +</div> + +<h2 id="Especificações">Especificações</h2> + +<p>Embora presente no início (2002) rascunhos de <a href="http://www.w3.org/TR/WD-font/#font-smooth">CSS3 Fonts</a>, <code>font-smooth</code> foi removido e esta especificação não está na faixa de padrões.</p> + +<h2 id="Compatibilidade_dos_Navegadores">Compatibilidade dos Navegadores</h2> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se você quiser contribuir com os dados, confira <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pull request.</div> + +<p>{{Compat("css.properties.font-smooth")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="http://usabilitypost.com/2012/11/05/stop-fixing-font-smoothing/">Please Stop "Fixing" Font Smoothing – UsabilityPost</a></li> + <li><a href="https://www.zachleat.com/web/font-smooth/">Laissez-faire font smoothing and anti-aliasing</a></li> +</ul> diff --git a/files/pt-pt/web/css/font-style/index.html b/files/pt-pt/web/css/font-style/index.html new file mode 100644 index 0000000000..55bd8de94f --- /dev/null +++ b/files/pt-pt/web/css/font-style/index.html @@ -0,0 +1,40 @@ +--- +title: font-style +slug: Web/CSS/font-style +tags: + - Referencia_CSS +translation_of: Web/CSS/font-style +--- +<p>{{ CSSRef() }}</p> + +<h2 id="Sum.C3.A1rio" name="Sum.C3.A1rio">Sumário</h2> + +<p>A propriedade <strong>font-style</strong> especifica normal (também conhecido como<em>upright</em> ou<em>roman</em>), itálico, e oblíquo faces dentro do<em>font-family</em>.</p> + +<p>{{cssinfo}}</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<p><code>font-style:</code> <code>normal</code> | <code>italic</code> | <code>oblique</code></p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>normal, oblique, italic </dt> + <dd>Especifica que o<em>user-agent</em> deve escolher a tipografia 'normal', 'oblique' ou 'italic' dentro do {{ Cssxref("font-family") }}.</dd> +</dl> + +<h2 id="Exemplos" name="Exemplos">Exemplos</h2> + +<pre>h1 { font-style: italic } +p { font-style: oblique } + +</pre> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#font-style">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/fonts.html#propdef-font-style">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-fonts/#font-style">css3-fonts</a></li> +</ul> diff --git a/files/pt-pt/web/css/font-weight/index.html b/files/pt-pt/web/css/font-weight/index.html new file mode 100644 index 0000000000..8879e55501 --- /dev/null +++ b/files/pt-pt/web/css/font-weight/index.html @@ -0,0 +1,119 @@ +--- +title: font-weight +slug: Web/CSS/font-weight +tags: + - Referencia_CSS +translation_of: Web/CSS/font-weight +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propeidade {{ Cssxref("font-weight") }} especifica o peso ou o traço da fonte:</p> + +<ul> + <li>Valor inicial: normal</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: sim</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> + <li>Valor computado: Um dos valores numéricos (100, etc.), ou um dos valores numéricos mais um dos valores relativos (mais realçado ou menos realçado)</li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<p><code>font-weight:</code> <code>normal</code> | <code>bold</code> | <code>bolder</code> | <code>lighter</code> | <code>100</code> | <code>200</code> | <code>300</code> | <code>400</code> | <code>500</code> | <code>600</code> | <code>700</code> | <code>800</code> | <code>900</code> | {{ Cssxref("inherit") }}</p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<dl> + <dt>normal </dt> + <dd>O peso normal da fonte. Semelhante ao 400.</dd> + <dt>bold </dt> + <dd>O peso negrito da fonte. Semelhante ao 700.</dd> + <dt>lighter </dt> + <dd><span id="result_box" lang="pt"><span>Um peso de fonte mais leve que o elemento pai (entre os pesos disponíveis da fonte).</span></span></dd> + <dt>bolder </dt> + <dd><span id="result_box" lang="pt"><span>Um peso de fonte duas vezes grosso que o elemento pai (entre os pesos disponíveis da fonte).</span></span></dd> + <dt>100, 200, 300, 400, 500, 600, 700, 800, 900 </dt> + <dd><span id="result_box" lang="pt"><span class="alt-edited">Os pesos numéricos de fontes para fontes que fornecem mais do que apenas normal e negrito. Se o peso exato fornecido não estiver disponível, então 600-900 utiliza o mais próximo e disponível peso mais duas vezes grosso (ou, se não houver, o peso mais leve disponível e mais próximo) e 100-500 utiliza o peso mais leve disponível e mais próximo (ou, se não houver, o peso mais escuro disponível e mais próximo). Significa que para fontes que fornecem apenas normal e negrito, 100-500 são normais e 600-900 são negritos.</span></span></dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><p> +<span id="result_box" lang="pt"><span class="alt-edited">Alice começava a ficar muito cansada de sentar-se junto à irmã no banco e +de não ter nada para fazer: uma ou duas vezes ela espiou o livro que a irmã +estava a ler, mas não tinha fotos nem conversas nele, «e qual é a utilização +de um livro», pensou Alice, «sem fotos ou conversas?»</span></span> +</p> + +<div>Sou quatro vezes grosso<br/> + <span>Sou mais leve</span> +</div> +</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush:css">/* <span class="short_text" id="result_box" lang="pt"><span>Definir o texto do parágrafo como negrito</span></span>. */ +p { + font-weight: bold; +} + +/* <span id="result_box" lang="pt"><span>Defina o texto div para dois passos mais grossos do +que o normal, mas menos que um negrito padrão.</span></span> */ +div { + font-weight: 600; +} + +/* <span id="result_box" lang="pt"><span>Define o texto dentro da tag span para +ser um passo mais leve que o pai.</span></span> */ +span { + font-weight: lighter; +}</pre> + +<h3 id="Resultado">Resultado</h3> + +<p>{{EmbedLiveSample("Exemplos","400","300")}}</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#font-weight">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/fonts.html#propdef-font-weight">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-fonts/#font-weight">css3-fonts</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>3</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/font-weight", "fr": "fr/CSS/font-weight" } ) }}</p> diff --git a/files/pt-pt/web/css/font/index.html b/files/pt-pt/web/css/font/index.html new file mode 100644 index 0000000000..e212941e9f --- /dev/null +++ b/files/pt-pt/web/css/font/index.html @@ -0,0 +1,140 @@ +--- +title: font +slug: Web/CSS/font +tags: + - Referencia_CSS +translation_of: Web/CSS/font +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>The font property is a shorthand property for setting {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("font-size") }}, {{ Cssxref("line-height") }} and {{ Cssxref("font-family") }} at the same place in the style sheet.</p> + +<ul> + <li>Valor inicial: refere-se a propriedades individuais</li> + <li>Aplica-se a: todos os elementos</li> + <li>Herdado: sim</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> +</ul> + +<p> </p> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<p><code>font:</code> [ <<a href="pt/CSS/font-style">font-style</a>> || <<a href="pt/CSS/font-variant">font-variant</a>> || <<a href="pt/CSS/font-weight">font-weight</a>> ]? <<a href="pt/CSS/font-size">font-size</a>> [ / <<a href="pt/CSS/line-height">line-height</a>> ]? <<a href="pt/CSS/font-family">font-family</a>></p> + +<p><code>font:</code> <code>caption</code> | <code>icon</code> | <code>menu</code> | <code>message-box</code> | <code>small-caption</code> | <code>status-bar</code> | <code>-moz-window</code> | <code>-moz-document</code> | <code>-moz-workspace</code> | <code>-moz-desktop</code> | <code>-moz-info</code> | <code>-moz-dialog</code> | <code>-moz-button</code> | <code>-moz-pull-down-menu</code> | <code>-moz-list</code> | <code>-moz-field</code></p> + +<p><code>font:</code> {{ Cssxref("inherit") }}</p> + +<h3 id="Valores" name="Valores">Valores</h3> + +<p>Using the {{ Cssxref("font") }} shorthand property sets the longhand properties as specified, and sets all other font-related properties to their initial values.</p> + +<p>See {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("font-size") }}, and {{ Cssxref("font-family") }} for legal values of each property.</p> + +<p>System fonts can also be specified using the {{ Cssxref("font") }} property,<em>instead of</em> specifying individual longhand properties:</p> + +<dl> + <dt>caption </dt> + <dd>The font used for captioned controls (e.g., buttons, drop-downs, etc.).</dd> + <dt>icon </dt> + <dd>The font used to label icons.</dd> + <dt>menu </dt> + <dd>The font used in menus (e.g., dropdown menus and menu lists).</dd> + <dt>message-box </dt> + <dd>The font used in dialog boxes.</dd> + <dt>small-caption </dt> + <dd>The font used for labeling small controls.</dd> + <dt>status-bar </dt> + <dd>The font used in window status bars.</dd> + <dt>-moz-window </dt> + <dd> </dd> + <dt>-moz-document </dt> + <dd> </dd> + <dt>-moz-workspace </dt> + <dd> </dd> + <dt>-moz-desktop </dt> + <dd> </dd> + <dt>-moz-info </dt> + <dd> </dd> + <dt>-moz-dialog </dt> + <dd> </dd> + <dt>-moz-button </dt> + <dd> </dd> + <dt>-moz-pull-down-menu </dt> + <dd> </dd> + <dt>-moz-list </dt> + <dd> </dd> + <dt>-moz-field </dt> + <dd> </dd> +</dl> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/font.html">View Live Examples</a></p> + +<pre>/* Set the font size to 12pt and the line height to 14pt. Set the font family to sans-serif */ +p { font: 12pt/14pt sans-serif } +</pre> + +<pre>/* Set the font size to 80% of the parent tag or default value (if no parent tag present) +and set the font family to sans-serif */ +p { font: 80% sans-serif } +</pre> + +<pre>/* Set the font weight to bold, the font-style to italic, the font size to large, +and the font family to serif. */ +p { font: bold italic large serif } +</pre> + +<h3 id="Notas" name="Notas">Notas</h3> + +<p>The {{ Cssxref("font-size") }} and {{ Cssxref("font-family") }} parts of the shorthand are mandatory. Omitting them is a syntax error, and causes the entire declaration to be ignored.</p> + +<p>Properties for which no values are given are set to their initial value, which is <code>normal</code> for all properties that can be omitted ({{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, and {{ Cssxref("line-height") }}).</p> + +<p>The {{ Cssxref("font-size-adjust") }} property is also set to its initial value (<code>none</code>) when the {{ Cssxref("font") }} shorthand property is specified.</p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#font">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/1998/REC-CSS2-19980512/fonts.html#propdef-font">CSS 2</a> (for {{ Cssxref("font-size-adjust") }})</li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/fonts.html#propdef-font">CSS 2.1</a></li> + <li><a class="external" href="http://www.w3.org/TR/css3-ui/#font">css3-ui</a> (for new system font values)</li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>3</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p>{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/font", "fr": "fr/CSS/font", "pl": "pl/CSS/font" } ) }}</p> diff --git a/files/pt-pt/web/css/grid-gap/index.html b/files/pt-pt/web/css/grid-gap/index.html new file mode 100644 index 0000000000..fef808f4cb --- /dev/null +++ b/files/pt-pt/web/css/grid-gap/index.html @@ -0,0 +1,177 @@ +--- +title: grid-gap +slug: Web/CSS/grid-gap +translation_of: Web/CSS/gap +--- +<p>A propriedade CSS <strong><code>grid-gap</code></strong> é uma propriedade de <a href="/pt-PT/docs/Web/CSS/Shorthand_properties">taquigrafia</a> para {{cssxref("grid-row-gap")}} e {{cssxref("grid-column-gap")}} especificando os canais entre as linhas de grelha e as colunas.</p> + +<pre class="brush: css no-line-numbers">/* One <length> value */ +grid-gap: 20px; +grid-gap: 1em; +grid-gap: 3vmin; +grid-gap: 0.5cm; + +/* One <percentage> value */ +grid-gap: 16%; +grid-gap: 100%; + +/* Two <length> values */ +grid-gap: 20px 10px; +grid-gap: 1em 0.5em; +grid-gap: 3vmin 2vmax; +grid-gap: 0.5cm 2mm; + +/* One or two <percentage> values */ +grid-gap: 16% 100%; +grid-gap: 21px 82%; + +/* Global values */ +grid-gap: inherit; +grid-gap: initial; +grid-gap: unset; +</pre> + +<p>{{cssinfo}}</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<p>This property is specified as a value for <code><'grid-row-gap'></code> followed optionally by a value for <code><'grid-column-gap'></code>. If <code><'grid-column-gap'></code> is omitted, it’s set to the same value as <code><'grid-row-gap'></code>.</p> + +<p><code><'grid-row-gap'></code> and <code><'grid-column-gap'></code> are each specified as a <code><length></code> or a <code><percentage></code>.</p> + +<h3 id="Valores">Valores</h3> + +<dl> + <dt><code><length></code></dt> + <dd>Is the width of the gutter separating the grid lines.</dd> + <dt><code><percentage></code></dt> + <dd>Is the width of the gutter separating the grid lines, relative to the dimension of the element.</dd> +</dl> + +<h3 id="Sintaxe_formal">Sintaxe formal</h3> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Exemplo">Exemplo</h2> + +<h3 id="Conteúdeo_de_HTML">Conteúdeo de HTML</h3> + +<pre class="brush: html"><div id="grid"> + <div></div> + <div></div> + <div></div> + <div></div> + <div></div> + <div></div> + <div></div> + <div></div> + <div></div> +</div></pre> + +<h3 id="Conteúdo_de_CSS">Conteúdo de CSS</h3> + +<pre class="brush: css; highlight[5]">#grid { + display: grid; + height: 200px; + grid-template: repeat(3, 1fr) / repeat(3, 1fr); + grid-gap: 20px 5px; +} + +#grid > div { + background-color: lime; +} +</pre> + +<p>{{EmbedLiveSample("Example", "100%", "200px")}}</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSS3 Grid", "#propdef-grid-gap", "grid-gap")}}</td> + <td>{{Spec2("CSS3 Grid")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p> </p> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir dos dados estruturados. Se pretender contribuir para os dados, por favor, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pedido de submissão.</div> + +<p>{{Compat("css.properties.grid-gap")}}</p> + +<p> </p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>Propriedade de CSS relacionadas: {{cssxref("grid-row-gap")}}, {{cssxref("grid-column-gap")}}</li> + <li>Guia de layout de grelha: <em><a href="/pt-PT/docs/Web/CSS/layout_de_grelha_css/conceitos_basicos_de_layour_de_grelha#Canais">Conceitos básicos de layout de grelha - Canais</a></em></li> +</ul> + +<section class="Quick_links" id="Quick_Links"> +<ol> + <li><a href="/pt-PT/docs/Web/CSS"><strong>CSS</strong></a></li> + <li><a href="/pt-PT/docs/Web/CSS/Referência_CSS"><strong>Referência CSS</strong></a></li> + <li><a href="/pt-PT/docs/Web/CSS/layout_de_grelha_css">CSS - Layout de Grelha</a></li> + <li data-default-state="open"><a href="#"><strong>Guias</strong></a> + <ol> + <li><a href="/pt-PT/docs/Web/CSS/layout_de_grelha_css/conceitos_basicos_de_layour_de_grelha">Conceitos básicos de layout de grelha</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship to other layout methods</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid">Line-based placement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas">Grid template areas</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Layout_using_Named_Grid_Lines">Layout using named grid lines</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout">Auto-placement in grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout">Box alignment in grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid,_Logical_Values_and_Writing_Modes">Grids, logical values and writing modes</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility">CSS Grid Layout and Accessibility</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_and_Progressive_Enhancement">CSS Grid Layout and Progressive Enhancement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Realizing_common_layouts_using_CSS_Grid_Layout">Realizing common layouts using grids</a></li> + </ol> + </li> + <li data-default-state="open"><a href="#"><strong>Propriedades</strong></a> + <ol> + <li><a href="/en-US/docs/Web/CSS/grid">grid</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-area">grid-area</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-columns">grid-auto-columns</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-flow">grid-auto-flow</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-rows">grid-auto-rows</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column">grid-column</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-end">grid-column-end</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-gap">grid-column-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-start">grid-column-start</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-gap">grid-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row">grid-row</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-end">grid-row-end</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-gap">grid-row-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-start">grid-row-start</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template">grid-template</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-areas">grid-template-areas</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-columns">grid-template-columns</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-rows">grid-template-rows</a></li> + </ol> + </li> + <li data-default-state="open"><a href="#"><strong>Glossário</strong></a> + <ol> + <li><a href="/en-US/docs/Glossary/Grid_lines">Grid lines</a></li> + <li><a href="/en-US/docs/Glossary/Grid_tracks">Grid tracks</a></li> + <li><a href="/en-US/docs/Glossary/Grid_cell">Grid cell</a></li> + <li><a href="/en-US/docs/Glossary/Grid_areas">Grid areas</a></li> + <li><a href="/en-US/docs/Glossary/Gutters">Gutters</a></li> + <li><a href="/en-US/docs/Glossary/Grid_rows">Grid row</a></li> + <li><a href="/en-US/docs/Glossary/Grid_column">Grid column</a></li> + </ol> + </li> +</ol> +</section> diff --git a/files/pt-pt/web/css/height/index.html b/files/pt-pt/web/css/height/index.html new file mode 100644 index 0000000000..e3b2b71c2c --- /dev/null +++ b/files/pt-pt/web/css/height/index.html @@ -0,0 +1,86 @@ +--- +title: height +slug: Web/CSS/height +tags: + - Referencia_CSS +translation_of: Web/CSS/height +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade <code>height</code> é usada para configurar a altura dada a um elemento.</p> + +<ul> + <li>Valor inicial: auto</li> + <li>Aplica-se a: o nível do bloco e elementos substituídos</li> + <li>Herdado: não</li> + <li>Porcentagens: refere-se à altura do bloco que o contém</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval"> height: [ <length> || <percentage> ] auto | inherit +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<ul> + <li><strong>length</strong> : pode ser em px, cm, in, em</li> + <li><strong>percentage</strong> : % especificado como uma porcentagem da altura do elemento pai</li> + <li><strong>auto</strong> : o navegador calculará e selecionará uma altura para o elemento especificado.</li> +</ul> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/height.html">View Live Examples</a></p> + +<pre>table{height: 100%;} + +img{height: 200px;} + +form{height: auto;} +</pre> + +<p><span class="comment">== Notas ==</span></p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#height">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/visudet.html#the-height-property">CSS 2.1</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p><a href="pt/CSS/box_model">box model</a>, {{ Cssxref("width") }}, {{ Cssxref("-moz-box-sizing") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/height", "fr": "fr/CSS/height" } ) }}</p> diff --git a/files/pt-pt/web/css/index.html b/files/pt-pt/web/css/index.html new file mode 100644 index 0000000000..9f7a65ea5f --- /dev/null +++ b/files/pt-pt/web/css/index.html @@ -0,0 +1,105 @@ +--- +title: 'CSS: Folhas de Estilo em Cascata' +slug: Web/CSS +tags: + - Apresentação + - CSS + - Desenho + - Design + - Disposição + - Estilos + - Folhas de Estilo em Cascata + - Folhas de estilo + - Landing + - Referencia + - 'l10n:prioridade' +translation_of: Web/CSS +--- +<div>{{CSSRef}}</div> + +<p class="summary"><span class="seoSummary"><strong>Folhas de Estilo em Cascata (CSS - Cascading Style Sheets</strong>) é uma linguagem de <a href="/pt-PT/docs/Web/API/Folha_de_estilo">folha de estilo</a> utilizada para descrever a apresentação de um documento escrito em <a href="/pt-PT/docs/Web/HTML" title="HyperText Markup Language">HTML</a> or <a href="/pt-PT/docs/Introducao_a_XML">XML</a> (incluindo dialetos de XML, tais como <a href="/pt-PT/docs/Web/SVG">SVG</a>, <a href="/pt-PT/docs/Web/MathML">MathML</a> ou </span> {{Glossary("XHTML", "", 1)}})<span class="seoSummary">. CSS descreve como os elementos deverão ser renderizados no ecrã, no papel, na fala, ou em outra média.</span></p> + +<p>CSS é uma das principais linguagens da Web aberta e está estandardizada nos navegadores de acordo com a <a class="external" href="http://w3.org/Style/CSS/#specs">especificação W3C</a>. Desenvolvida em níveis, CSS1 está agora obsoleta, CSS2.1 é a recomendação, e <a href="/pt-PT/docs/Web/CSS/CSS3" title="CSS3">CSS3</a>, agora divida em pequenos módulos, está a progredir a caminho da estandardização</p> + +<section id="sect1"> +<ul class="card-grid"> + <li><span>Introdução a CSS</span> + + <p>Se é novo no desenvolvimento Web, certifique-se que lê o nosso artigo de <a href="/pt-PT/docs/Learn/Comecar_com_a_Web/CSS_basico">CSS - Essencial</a> para saber o que é CSS e como utilizar.</p> + </li> + <li><span>Tutoriais de CSS</span> + <p>A nossa <a href="/pt-PT/docs/Learn/CSS">área de aprendizagem de CSS</a> contém uma grande quantidade de tutoriais para levá-lo do nível de principiante até à proficiência, abrangendo todos os conteúdos essenciais.</p> + </li> + <li><span>Referência de CSS</span> + <p>A nossa <a href="/pt-PT/docs/Web/CSS/Refer%C3%AAncia_CSS">referência exaustiva de CSS </a>para os programadores da Web que descreve cada propriedade e conceito de CSS.</p> + </li> +</ul> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Tutoriais">Tutoriais</h2> + +<p>A nossa <a href="/pt-PT/docs/Learn/CSS">Área de Aprendizagem de CSS </a>apresenta múltiplos módulos que ensinam CSS desde o início — não é necessário conhecimento prévio.</p> + +<dl> + <dt><a href="/pt-PT/docs/Learn/CSS/Introduction_to_CSS">Introdução ao CSS</a></dt> + <dd>Este módulo permite-lhe começar com os básicos de como o CSS funciona, incluindo selectores e propriedades, escrever regras CSS, aplicar CSS a HTML, como especificar comprimento, cor e outras unidades em CSS, cascata e herança, modelos básicos de caixa e depuração de CSS.</dd> + <dt><a href="/pt-PT/docs/Learn/CSS/Estilo_de_texto">Estilizar texto</a></dt> + <dd>Aqui aprendemos os fundamentos do estilo do texto, incluindo a definição da fonte, negrito e itálico, espaçamento entre linhas e letras, e sombras e outras características do texto. Nós terminamos o módulo, aplicando fontes personalizadas à sua página, e estilizando listas e links.</dd> + <dt><a href="/pt-PT/docs/Learn/CSS/Estilo_de_caixas">Estilizar caixas</a></dt> + <dd>A seguir, focamos em estilizar caixas, um dos passos fundamentais para a criação de uma página web. Neste módulo, recapitulamos o modelo da caixa e depois aprendemos a controlar a disposição das caixas, definindo preenchimentos, bordas e margens, cores de fundo personalizadas, imagens e outras características, bem como características mais avancadas como sombras e filtros nas caixas.</dd> + <dt><a href="/en-US/docs/Learn/CSS/CSS_layout">Disposição de CSS (<em>layout</em>)</a></dt> + <dd>Até agora, já analisámos os fundamentos do CSS, como estilizar os textos, e como estilizar e manipular as caixas que o seu conteúdo contém. Agora é altura de ver como colocar as suas caixas no lugar certo em relação ao <em>{{Glossary("layout viewport", "viewport")}}</em>, e umas às outras. Cobrimos os pré-requisitos necessários para que possa agora mergulhar profundamente no layout do CSS, observando diferentes configurações de visualização, métodos tradicionais de layout envolvendo <em>float </em>e posicionamento, e novas ferramentas de posicionamento como o <em>flexbox</em>.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Tools" id="Referência">Referência</h2> + +<ul> + <li><a href="https://developer.mozilla.org/pt-PT/docs/Web/CSS/Refer%C3%AAncia_CSS">CSS - Referência</a>: This exhaustive reference for seasoned Web developers describes every property and concept of CSS.</li> + <li>CSS key concepts: + <ul> + <li>The <a href="/en-US/docs/Web/CSS/Syntax">syntax and forms of the language</a></li> + <li><a href="/en-US/docs/Web/CSS/Specificity">Specificity</a>, <a href="/en-US/docs/Web/CSS/Inheritance">inheritance</a> and <a href="/en-US/docs/Web/CSS/Cascade">the Cascade</a></li> + <li><a href="/en-US/docs/Web/CSS/box_model">Box model</a> and <a href="/en-US/docs/Web/CSS/margin_collapsing">margin collapse</a></li> + <li>The <a href="/en-US/docs/Web/CSS/All_About_The_Containing_Block">containing block</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context" title="The stacking context">Stacking</a> and <a href="/en-US/docs/Web/CSS/block_formatting_context" title="block formatting context">block-formatting</a> contexts</li> + <li><a href="/en-US/docs/Web/CSS/initial_value">Initial</a>, <a href="/en-US/docs/Web/CSS/computed_value">computed</a>, <a href="/en-US/docs/Web/CSS/used_value">used</a>, and <a href="/en-US/docs/Web/CSS/actual_value">actual</a> values</li> + <li><a href="/en-US/docs/Web/CSS/Shorthand_properties">CSS shorthand properties</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout">CSS Flexible Box Layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid Layout</a></li> + <li><a href="/en-US/docs/Web/CSS/Media_Queries">Media queries</a></li> + </ul> + </li> +</ul> + +<h2 class="Tools" id="Cookbook">Cookbook</h2> + +<p>The <a href="/en-US/docs/Web/CSS/Layout_cookbook">CSS layout cookbook</a> aims to bring together recipes for common layout patterns, things you might need to implement in your own sites. In addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer.</p> + +<h2 class="Tools" id="Ferramentas_para_o_desenvolvimento_de_CSS">Ferramentas para o desenvolvimento de CSS</h2> + +<ul> + <li>You can use the <a class="external" href="https://jigsaw.w3.org/css-validator/">W3C CSS Validation Service</a> to check if your CSS is valid. This is an invaluable debugging tool.</li> + <li><a href="/en-US/docs/Tools">Firefox Developer Tools</a> lets you view and edit a page's live CSS via the <a href="/en-US/docs/Tools/Page_Inspector">Inspector</a> and <a href="/en-US/docs/Tools/Style_Editor">Style Editor</a> tools.</li> + <li>The <a class="link-https" href="https://addons.mozilla.org/en-US/firefox/addon/60">Web Developer extension</a> for Firefox lets you track and edit live CSS on watched sites.</li> + <li>The Web community has created various other <a href="/en-US/docs/Web/CSS/Tools">miscellaneous CSS tools</a> for you to use.</li> +</ul> + +<h2 id="Erros_de_metadados">Erros de metadados</h2> + +<ul> + <li>Firefox: {{bug(1323667)}}</li> +</ul> +</div> +</div> +</section> + +<h2 id="Consultar_também">Consultar também:</h2> + +<ul> + <li><a href="/en-US/docs/Web/Demos_of_open_web_technologies#CSS">CSS demos</a>: Get a creative boost by exploring examples of the latest CSS technologies in action.</li> + <li>Web languages to which CSS is often applied: <a href="/en-US/docs/HTML">HTML</a>, <a href="/en-US/docs/SVG">SVG</a>, <a href="/en-US/docs/XHTML">XHTML</a>, and <a href="/en-US/docs/XML">XML</a>.</li> + <li>Mozilla technologies that make extensive use of CSS: <a href="/en-US/docs/Mozilla/Tech/XUL">XUL</a>, <a href="/en-US/Firefox">Firefox</a>, and <a href="/en-US/docs/Mozilla/Thunderbird">Thunderbird</a> <a href="/en-US/docs/Extensions">extensions</a> and <a href="/en-US/Add-ons/Themes">themes</a>.</li> +</ul> diff --git a/files/pt-pt/web/css/inherit/index.html b/files/pt-pt/web/css/inherit/index.html new file mode 100644 index 0000000000..8bfcd334e5 --- /dev/null +++ b/files/pt-pt/web/css/inherit/index.html @@ -0,0 +1,7 @@ +--- +title: inherit +slug: Web/CSS/inherit +translation_of: Web/CSS/inherit +--- +<p>Herda propriedade do elemento pai. +</p> diff --git a/files/pt-pt/web/css/layout_de_grelha_css/index.html b/files/pt-pt/web/css/layout_de_grelha_css/index.html new file mode 100644 index 0000000000..db142d2dde --- /dev/null +++ b/files/pt-pt/web/css/layout_de_grelha_css/index.html @@ -0,0 +1,250 @@ +--- +title: CSS - Layout de Grade +slug: Web/CSS/layout_de_grelha_css +tags: + - CSS + - Grades + - Layout + - Layout de Grade + - Referencia + - Resumo +translation_of: Web/CSS/CSS_Grid_Layout +--- +<p><strong>CSS - Layout de Grade </strong>destaca-se em dividir uma página em regiões principais, ou definir a relação em termos de tamanho, posição e camada, entre partes de um controle criado a partir de HTML primitivas. <br> + <br> + Tal como as tabelas, o layout de grelha permite que um autor alinhe os elementos em colunas e linhas. No entanto, são possíveis muitos mais layouts ou mais fáceis com a grelha de CSS do que eram com as tabelas. Por exemplo, os elementos filhos de um recipiente de grelha poderão posicionar-se a eles mesmos, e assim eles realmente se sobrepõem e a camada, similar aos elementos posicionados do CSSs..</p> + +<h2 id="Basic_Example" name="Basic_Example">Exemplo básico</h2> + +<p>O exemplo abaixo mostra uma grelha de faixa com três colunas, com novas linhas criadas com um mínimo de 100 píxeis e um máximo de <em>auto</em>. Os itens foram colocados na grelha utilizando o posicionamento baseado em linha .</p> + +<div id="example"> +<div class="hidden"> +<pre class="brush: css">* {box-sizing: border-box;} +.wrapper { + max-width: 940px; + margin: 0 auto; +} + +.wrapper > div { + border: 2px solid rgb(233,171,88); + border-radius: 5px; + background-color: rgba(233,171,88,.5); + padding: 1em; + color: #d9480f; +}</pre> +</div> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><div class="wrapper"> + <div class="one">One</div> + <div class="two">Two</div> + <div class="three">Three</div> + <div class="four">Four</div> + <div class="five">Five</div> + <div class="six">Six</div> +</div></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">.wrapper { + display: grid; + grid-template-columns: repeat(3, 1fr); + grid-gap: 10px; + grid-auto-rows: minmax(100px, auto); +} +.one { + grid-column: 1 / 3; + grid-row: 1; +} +.two { + grid-column: 2 / 4; + grid-row: 1 / 3; +} +.three { + grid-column: 1; + grid-row: 2 / 5; +} +.four { + grid-column: 3; + grid-row: 3; +} +.five { + grid-column: 2; + grid-row: 4; +} +.six { + grid-column: 3; + grid-row: 4; +} +</pre> + +<p>{{ EmbedLiveSample('example', '500', '440') }}</p> +</div> + +<h2 id="Referência">Referência</h2> + +<h3 id="CSS_-_propriedades">CSS - propriedades</h3> + +<div class="index"> +<ul> + <li>{{cssxref("grid-template-columns")}}</li> + <li>{{cssxref("grid-template-rows")}}</li> + <li>{{cssxref("grid-template-areas")}}</li> + <li>{{cssxref("grid-template")}}</li> + <li>{{cssxref("grid-auto-columns")}}</li> + <li>{{cssxref("grid-auto-rows")}}</li> + <li>{{cssxref("grid-auto-flow")}}</li> + <li>{{cssxref("grid")}}</li> + <li>{{cssxref("grid-row-start")}}</li> + <li>{{cssxref("grid-column-start")}}</li> + <li>{{cssxref("grid-row-end")}}</li> + <li>{{cssxref("grid-column-end")}}</li> + <li>{{cssxref("grid-row")}}</li> + <li>{{cssxref("grid-column")}}</li> + <li>{{cssxref("grid-area")}}</li> + <li>{{cssxref("grid-row-gap")}}</li> + <li>{{cssxref("grid-column-gap")}}</li> + <li>{{cssxref("grid-gap")}}</li> +</ul> +</div> + +<h3 id="CSS_-_funções">CSS - funções</h3> + +<div class="index"> +<ul> + <li>{{cssxref("repeat", "repeat()")}}</li> + <li>{{cssxref("minmax", "minmax()")}}</li> + <li>{{cssxref("fit-content", "fit-content()")}}</li> +</ul> +</div> + +<h3 id="CSS_-_tipos_de_dados">CSS - tipos de dados</h3> + +<div class="index"> +<ul> + <li>{{cssxref("<flex>")}}</li> +</ul> +</div> + +<h3 id="Glossário_-_entradas">Glossário - entradas</h3> + +<div class="index"> +<ul> + <li><a href="/pt-PT/docs/Glossário/grelha">Grelha</a></li> + <li><a href="/pt-PT/docs/Glossário/linhas_de_grelha">Linhas de Grelha</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Tracks">Grid Tracks</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Cell">Grid Cell</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Areas">Grid Area</a></li> + <li><a href="/en-US/docs/Glossary/Gutters">Gutters</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Axis">Grid Axis</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Rows">Grid row</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Column">Grid column</a></li> +</ul> +</div> + +<h2 id="Guias">Guias</h2> + +<div class="index"> +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout">Basic concepts of Grid Layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship of Grid Layout to other layout methods</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid">Layout using line-based placement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas">Grid template areas</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Layout_using_Named_Grid_Lines">Layout using named grid lines</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout">Auto-placement in CSS Grid Layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout">Box alignment in CSS Grid Layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid,_Logical_Values_and_Writing_Modes">CSS Grid, Logical Values and Writing Modes</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility">CSS Grid Layout and accessibility</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_and_Progressive_Enhancement">CSS Grid and progressive enhancement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Realising_common_layouts_using_CSS_Grid_">Realising common layouts using CSS Grid</a></li> +</ul> +</div> + +<h2 id="Recursos_externos">Recursos externos</h2> + +<ul> + <li><a href="http://labs.jensimmons.com/">Examples from Jen Simmons</a></li> + <li><a href="http://gridbyexample.com/">Grid by Example - a collection of usage examples and video tutorials</a></li> + <li><a href="https://tympanus.net/codrops/css_reference/grid/">Codrops Grid Reference</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Tools/Page_Inspector/How_to/Examine_grid_layouts">Firefox DevTools CSS Grid Inspector</a></li> + <li><a href="https://mozilladevelopers.github.io/playground/">CSS Grid Playground</a></li> +</ul> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('CSS3 Grid') }}</td> + <td>{{ Spec2('CSS3 Grid') }}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<section class="Quick_links" id="Quick_Links"> +<ol> + <li><a href="/en-US/docs/Web/CSS"><strong>CSS</strong></a></li> + <li><a href="/en-US/docs/Web/CSS/Reference"><strong>CSS Reference</strong></a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS Grid Layout</a></li> + <li data-default-state="open"><a href="#"><strong>Guides</strong></a> + <ol> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout">Basics concepts of grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout">Relationship to other layout methods</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Line-based_Placement_with_CSS_Grid">Line-based placement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Grid_Template_Areas">Grid template areas</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Layout_using_Named_Grid_Lines">Layout using named grid lines</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Auto-placement_in_CSS_Grid_Layout">Auto-placement in grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout">Box alignment in grid layout</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid,_Logical_Values_and_Writing_Modes">Grids, logical values and writing modes</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_Layout_and_Accessibility">CSS Grid Layout and Accessibility</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/CSS_Grid_and_Progressive_Enhancement">CSS Grid Layout and Progressive Enhancement</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Grid_Layout/Realizing_common_layouts_using_CSS_Grid_Layout">Realizing common layouts using grids</a></li> + </ol> + </li> + <li data-default-state="open"><a href="#"><strong>Properties</strong></a> + <ol> + <li><a href="/en-US/docs/Web/CSS/grid">grid</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-area">grid-area</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-columns">grid-auto-columns</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-flow">grid-auto-flow</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-auto-rows">grid-auto-rows</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column">grid-column</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-end">grid-column-end</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-gap">grid-column-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-column-start">grid-column-start</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-gap">grid-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row">grid-row</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-end">grid-row-end</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-gap">grid-row-gap</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-row-start">grid-row-start</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template">grid-template</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-areas">grid-template-areas</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-columns">grid-template-columns</a></li> + <li><a href="/en-US/docs/Web/CSS/grid-template-rows">grid-template-rows</a></li> + </ol> + </li> + <li data-default-state="open"><a href="#"><strong>Glossary</strong></a> + <ol> + <li><a href="/en-US/docs/Glossary/Grid">Grid</a></li> + <li><a href="/en-US/docs/Glossary/Grid_lines">Grid lines</a></li> + <li><a href="/en-US/docs/Glossary/Grid_tracks">Grid tracks</a></li> + <li><a href="/en-US/docs/Glossary/Grid_cell">Grid cell</a></li> + <li><a href="/en-US/docs/Glossary/Grid_areas">Grid areas</a></li> + <li><a href="/en-US/docs/Glossary/Gutters">Gutters</a></li> + <li><a href="/en-US/docs/Glossary/Grid_Axis">Grid Axis</a></li> + <li><a href="/en-US/docs/Glossary/Grid_rows">Grid row</a></li> + <li><a href="/en-US/docs/Glossary/Grid_column">Grid column</a></li> + </ol> + </li> +</ol> +</section> diff --git a/files/pt-pt/web/css/list-style/index.html b/files/pt-pt/web/css/list-style/index.html new file mode 100644 index 0000000000..3a6cf6d36d --- /dev/null +++ b/files/pt-pt/web/css/list-style/index.html @@ -0,0 +1,79 @@ +--- +title: list-style +slug: Web/CSS/list-style +tags: + - Referencia_CSS +translation_of: Web/CSS/list-style +--- +<p>{{ CSSRef() }}</p> + +<h2 id="Resumo" name="Resumo">Resumo</h2> + +<p>A propriedade <code>list-style</code> é uma propriedade usada para configurar list-style-type, list-style-image, e list-style-position.</p> + +<ul> + <li>Valor inicial: olhar propriedades individuais para detalhes</li> + <li>Aplica-se a: elementos com 'display' com valor 'list-item'</li> + <li>Herdado: sim</li> + <li>Porcentagens: N/A</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> +</ul> + +<h2 id="Sintaxe" name="Sintaxe">Sintaxe</h2> + +<pre class="eval"> list-style: [disc | circle | square | decimal | lower-roman | upper-roman | lower-alpha | upper-alpha | none] || [inside | outside] || [<url> | none] +</pre> + +<h2 id="Valores" name="Valores">Valores</h2> + +<p>disc, circle, square, decimal, lower-roman, upper-roman, lower-alpha, upper-alpha, inside, outside, <url>, none</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html">List 1 +<ul class="one"> + <li>List Item1</li> + <li>List Item2</li> + <li>List Item3</li> +</ul> +List 2 +<ul class="two"> + <li>List Item A</li> + <li>List Item B</li> + <li>List Item C</li> +</ul> +</pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css">.one { + list-style: circle; +} + +.two { + list-style: square inside; +}</pre> + +<h3 id="Result">Result</h3> + +<p>{{EmbedLiveSample('Exemplos')}}</p> + +<h2 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#list-style">CSS 1</a></li> +</ul> + +<p><span class="comment">* {{ mediawiki.external('http://www.w3.org/TR/CSS21/visudet.html#the-height-property CSS 2.1') }} == Compatibilidade com navegadores == <table class="standard-table"> <tr> <th>Navegador</th> <th>Versão mais antiga</th> </tr> <tr> <td>Internet Explorer</td> <td>4</td> </tr> <tr> <td>Netscape</td> <td>4</td> </tr> <tr> <td>Opera</td> <td>3.5</td> </tr> </table></span></p> + +<h2 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h2> + +<p><a href="pt/CSS/box_model">list-style-image</a>, {{ Cssxref("list-style-type") }}, {{ Cssxref("list-style-position") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/list-style", "fr": "fr/CSS/list-style" } ) }}</p> diff --git a/files/pt-pt/web/css/média_paginada/index.html b/files/pt-pt/web/css/média_paginada/index.html new file mode 100644 index 0000000000..49df122031 --- /dev/null +++ b/files/pt-pt/web/css/média_paginada/index.html @@ -0,0 +1,19 @@ +--- +title: Média paginada +slug: Web/CSS/Média_paginada +tags: + - CSS + - CSS3 + - Quebras de Página +translation_of: Web/CSS/Paged_Media +--- +<p>Paged media properties control the presentation of content for print or any other media that splits content into discrete pages. It allows you to set page breaks, control printable area, style left and right pages differently, and control breaks inside elements. Popularly supported properties include</p> + +<ul> + <li>{{ cssxref("page-break-before") }}</li> + <li>{{ cssxref("page-break-after") }}</li> + <li>{{ cssxref("page-break-inside") }}</li> + <li>{{ cssxref("orphans") }}</li> + <li>{{ cssxref("widows") }}</li> + <li>{{ cssxref("@page") }}</li> +</ul> diff --git a/files/pt-pt/web/css/pseudoclasses/index.html b/files/pt-pt/web/css/pseudoclasses/index.html new file mode 100644 index 0000000000..d65bef9e51 --- /dev/null +++ b/files/pt-pt/web/css/pseudoclasses/index.html @@ -0,0 +1,165 @@ +--- +title: Pseudoclasses +slug: Web/CSS/Pseudoclasses +tags: + - CSS + - Pseudoclasse + - Referencia + - Resumo + - Seletores + - Sinopse +translation_of: Web/CSS/Pseudo-classes +--- +<div>{{CSSRef}}</div> + +<p>A <a href="/pt-PT/docs/Web/CSS">CSS</a> <strong><dfn>pseudo-class</dfn></strong> is a keyword added to a selector that specifies a special state of the selected element(s). For example, {{CSSxRef(":hover")}} can be used to change a button's color when the user's pointer hovers over it.</p> + +<pre class="brush: css; no-line-numbers">/* Any button over which the user's pointer is hovering */ +button:hover { + color: blue; +}</pre> + +<p>Pseudo-classes let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator ({{CSSxRef(":visited")}}, for example), the status of its content (like {{CSSxRef(":checked")}} on certain form elements), or the position of the mouse (like {{CSSxRef(":hover")}}, which lets you know if the mouse is over an element or not).</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> In contrast to pseudo-classes, <a href="/en-US/docs/Web/CSS/Pseudo-elements">pseudo-elements</a> can be used to style a <em>specific part</em> of an element.</p> +</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">selector:pseudo-class { + property: value; +} +</pre> + +<p>Like regular classes, you can chain together as many pseudo-classes as you want in a selector.</p> + +<h2 id="Índice_de_pseudoclasses_padrões">Índice de pseudoclasses padrões</h2> + +<div class="index" id="index"> +<ul> + <li>{{CSSxRef(":active")}}</li> + <li>{{CSSxRef(":any-link")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":blank")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":checked")}}</li> + <li>{{CSSxRef(":current")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":default")}}</li> + <li>{{CSSxRef(":defined")}}</li> + <li>{{CSSxRef(":dir", ":dir()")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":disabled")}}</li> + <li>{{CSSxRef(":drop")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":empty")}}</li> + <li>{{CSSxRef(":enabled")}}</li> + <li>{{CSSxRef(":first")}}</li> + <li>{{CSSxRef(":first-child")}}</li> + <li>{{CSSxRef(":first-of-type")}}</li> + <li>{{CSSxRef(":fullscreen")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":future")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":focus")}}</li> + <li>{{CSSxRef(":focus-visible")}}</li> + <li>{{CSSxRef(":focus-within")}}</li> + <li>{{CSSxRef(":has", ":has()")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":host")}}</li> + <li>{{CSSxRef(":host()")}}</li> + <li>{{CSSxRef(":host-context()")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":hover")}}</li> + <li>{{CSSxRef(":indeterminate")}}</li> + <li>{{CSSxRef(":in-range")}}</li> + <li>{{CSSxRef(":invalid")}}</li> + <li>{{CSSxRef(":lang", ":lang()")}}</li> + <li>{{CSSxRef(":last-child")}}</li> + <li>{{CSSxRef(":last-of-type")}}</li> + <li>{{CSSxRef(":left")}}</li> + <li>{{CSSxRef(":link")}}</li> + <li>{{CSSxRef(":local-link")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":matches", ":matches()")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":not", ":not()")}}</li> + <li>{{CSSxRef(":nth-child", ":nth-child()")}}</li> + <li>{{CSSxRef(":nth-col", ":nth-col()")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":nth-last-child", ":nth-last-child()")}}</li> + <li>{{CSSxRef(":nth-last-col", ":nth-last-col()")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":nth-last-of-type", ":nth-last-of-type()")}}</li> + <li>{{CSSxRef(":nth-of-type", ":nth-of-type()")}}</li> + <li>{{CSSxRef(":only-child")}}</li> + <li>{{CSSxRef(":only-of-type")}}</li> + <li>{{CSSxRef(":optional")}}</li> + <li>{{CSSxRef(":out-of-range")}}</li> + <li>{{CSSxRef(":past")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":placeholder-shown")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":read-only")}}</li> + <li>{{CSSxRef(":read-write")}}</li> + <li>{{CSSxRef(":required")}}</li> + <li>{{CSSxRef(":right")}}</li> + <li>{{CSSxRef(":root")}}</li> + <li>{{CSSxRef(":scope")}}</li> + <li>{{CSSxRef(":target")}}</li> + <li>{{CSSxRef(":target-within")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":user-invalid")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef(":valid")}}</li> + <li>{{CSSxRef(":visited")}}</li> +</ul> +</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Fullscreen")}}</td> + <td>{{Spec2("Fullscreen")}}</td> + <td>Defined <code>:fullscreen</code>.</td> + </tr> + <tr> + <td>{{SpecName("HTML WHATWG", "#pseudo-classes")}}</td> + <td>{{Spec2("HTML WHATWG")}}</td> + <td>Defines when particular selectors match HTML elements.</td> + </tr> + <tr> + <td>{{SpecName("CSS4 Selectors")}}</td> + <td>{{Spec2("CSS4 Selectors")}}</td> + <td>Defined <code style="white-space: nowrap;">:any-link</code>, <code>:blank</code>, <code style="white-space: nowrap;">:local-link</code>, <code>:scope</code>, <code>:drop</code>, <code>:current</code>, <code>:past</code>, <code>:future</code>, <code style="white-space: nowrap;">:placeholder-shown</code>, <code style="white-space: nowrap;">:user-invalid</code>, <code style="white-space: nowrap;">:nth-col()</code>, <code style="white-space: nowrap;">:nth-last-col()</code> and <code>:matches()</code>.<br> + No significant change for pseudo-classes defined in {{SpecName("CSS3 Selectors")}} and {{SpecName("HTML5 W3C")}} (though semantic meaning not taken over).</td> + </tr> + <tr> + <td>{{SpecName("HTML5 W3C")}}</td> + <td>{{Spec2("HTML5 W3C")}}</td> + <td>Copies the relevant section from the canonical (WHATWG) HTML spec.</td> + </tr> + <tr> + <td>{{SpecName("CSS3 Basic UI")}}</td> + <td>{{Spec2("CSS3 Basic UI")}}</td> + <td>Defined <code>:default</code>, <code>:valid</code>, <code>:invalid</code>, <code>:in-range</code>, <code>:out-of-range</code>, <code>:required</code>, <code>:optional</code>, <code>:read-only</code> and <code>:read-write</code>, but without the associated semantic meaning.</td> + </tr> + <tr> + <td>{{SpecName("CSS3 Selectors")}}</td> + <td>{{Spec2("CSS3 Selectors")}}</td> + <td>Defined <code>:target</code>, <code>:root</code>, <code>:nth-child()</code>, <code>:nth-last-of-child()</code>, <code>:nth-of-type()</code>, <code>:nth-last-of-type()</code>, <code>:last-child</code>, <code>:first-of-type</code>, <code>:last-of-type</code>, <code>:only-child</code>, <code>:only-of-type</code>, <code>:empty</code> and <code>:not()</code>.<br> + Defined the syntax of <code>:enabled</code>, <code>:disabled</code>, <code>:checked</code>, and <code>:indeterminate</code>, but without the associated semantic meaning.<br> + No significant change for pseudo-classes defined in {{SpecName('CSS2.1')}}.</td> + </tr> + <tr> + <td>{{SpecName("CSS2.1")}}</td> + <td>{{Spec2("CSS2.1")}}</td> + <td>Defined <code>:lang()</code>, <code>:first-child</code>, <code>:hover</code>, and <code>:focus</code>.<br> + No significant change for pseudo-classes defined in {{SpecName('CSS1')}}.</td> + </tr> + <tr> + <td>{{SpecName("CSS1")}}</td> + <td>{{Spec2("CSS1")}}</td> + <td>Defined <code>:link</code>, <code>:visited</code> and <code>:active</code>, but without the associated semantic meaning.</td> + </tr> + </tbody> +</table> + +<h2 id="Consultar_também">Consultar também:</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/CSS/Pseudoelementos">Pseudoelementos</a></li> +</ul> diff --git a/files/pt-pt/web/css/pseudoelementos/index.html b/files/pt-pt/web/css/pseudoelementos/index.html new file mode 100644 index 0000000000..780d17c378 --- /dev/null +++ b/files/pt-pt/web/css/pseudoelementos/index.html @@ -0,0 +1,104 @@ +--- +title: Pseudoelementos +slug: Web/CSS/Pseudoelementos +tags: + - CSS + - Pseudoelemento + - Referencia + - Resumo + - Seletores + - Sinopse +translation_of: Web/CSS/Pseudo-elements +--- +<div>{{CSSRef}}</div> + +<p>Um <strong>pseudoelemento</strong> de CSS é uma palavra-chave adicionada ao seletor que lhe permite estilizar uma parte específica do(s) elemento(s) selecionado(s). Por exemplo, {{CSSxRef("::first-line")}} pode ser utilizado para alterar o tipo de letra da primeira linha de um parágrafo.</p> + +<pre class="brush: css no-line-numbers">/* The first line of every <p> element. */ +p::first-line { + color: blue; + text-transform: uppercase; +}</pre> + +<div class="note"> +<p><strong>Nota:</strong> In contrast to pseudo-elements, {{CSSxRef("pseudo-classes")}} can be used to style an element based on its <em>state</em>.</p> +</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">selector::pseudo-element { + property: value; +}</pre> + +<p>You can use only one pseudo-element in a selector. It must appear after the simple selectors in the statement.</p> + +<div class="note"> +<p><strong>Note:</strong> As a rule, double colons (<code>::</code>) should be used instead of a single colon (<code>:</code>). This distinguishes pseudo-classes from pseudo-elements. However, since this distinction was not present in older versions of the W3C spec, most browsers support both syntaxes for the original pseudo-elements.</p> +</div> + +<h2 id="Índice_de_pseudoelementos_padrões">Índice de pseudoelementos padrões</h2> + +<div class="index" id="index"> +<ul> + <li>{{CSSxRef("::after", "::after (:after)")}}</li> + <li>{{CSSxRef("::backdrop")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef("::before", "::before (:before)")}}</li> + <li>{{CSSxRef("::cue", "::cue (:cue)")}}</li> + <li>{{CSSxRef("::first-letter", "::first-letter (:first-letter)")}}</li> + <li>{{CSSxRef("::first-line", "::first-line (:first-line)")}}</li> + <li>{{CSSxRef("::grammar-error")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef("::marker")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef("::placeholder")}} {{Experimental_Inline}}</li> + <li>{{CSSxRef("::selection")}}</li> + <li>{{CSSxRef("::slotted", "::slotted()")}}</li> + <li>{{CSSxRef("::spelling-error")}} {{Experimental_Inline}}</li> +</ul> +</div> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão Mais Baixa</th> + <th>Suporta</th> + </tr> + <tr> + <td rowspan="2">Internet Explorer</td> + <td>8.0</td> + <td><code>:pseudo-element</code></td> + </tr> + <tr> + <td>9.0</td> + <td><code>:pseudo-element ::pseudo-element</code></td> + </tr> + <tr> + <td rowspan="2">Firefox (Gecko)</td> + <td>1.0 (1.0)</td> + <td><code>:pseudo-element</code></td> + </tr> + <tr> + <td>1.0 (1.5)</td> + <td><code>:pseudo-element ::pseudo-element</code></td> + </tr> + <tr> + <td rowspan="2">Opera</td> + <td>4.0</td> + <td><code>:pseudo-element</code></td> + </tr> + <tr> + <td>7.0</td> + <td><code>:pseudo-element ::pseudo-element</code></td> + </tr> + <tr> + <td>Safari (WebKit)</td> + <td>1.0 (85)</td> + <td><code>:pseudo-element ::pseudo-element</code></td> + </tr> + </tbody> +</table> + +<h2 id="Consultar_também">Consultar também:</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/Pseudo-classes" style="white-space: nowrap;">Pseudoclasses</a></li> +</ul> diff --git a/files/pt-pt/web/css/referência_css/index.html b/files/pt-pt/web/css/referência_css/index.html new file mode 100644 index 0000000000..1be349b1c9 --- /dev/null +++ b/files/pt-pt/web/css/referência_css/index.html @@ -0,0 +1,171 @@ +--- +title: CSS - Referência +slug: Web/CSS/Referência_CSS +tags: + - CSS + - Referencia + - Resumo + - Sinopse + - 'l10n:priority' +translation_of: Web/CSS/Reference +--- +<div>{{CSSRef}}</div> + +<p class="summary">Utilize esta <strong>referência de CSS </strong>para explorar<strong> </strong>um <a href="/pt-PT/docs/Web/CSS/Referência_CSS#Índex_de_palavra-chave">índex alfabético</a> de todas as propriedades de <a href="/pt-PT/docs/Web/CSS">CSS</a> padrão, <a href="/pt-PT/docs/Web/CSS/Pseudoclasses">pseudoclasses, </a><a href="/pt-PT/docs/Web/CSS/Pseudoelementos">pseudoelementos</a>, <a href="/pt-PT/docs/Web/CSS/CSS_Tipos">tipos de dados</a>, e <a href="/pt-PT/docs/Web/CSS/At-rule">regras "at"</a>. Também pode explorar uma lista de todos os <a href="/pt-PT/docs/Web/CSS/Refer%C3%AAncia_CSS">seletores de CSS organizados pelo tipo</a> e uma lista de <a href="/pt-PT/docs/Web/CSS/Refer%C3%AAncia_CSS$edit#Concepts">conceitos de CSS chave</a>. Também incluido nesta breve <a href="/pt-PT/docs/Web/CSS/Refer%C3%AAncia_CSS$edit#DOM-CSS_CSSOM">referência de DOM-CSS / CSSOM</a>.</p> + +<h2 id="Sintaxe_Básica">Sintaxe Básica</h2> + +<h3 id="Estilo_padrão_de_sintaxe">Estilo padrão de sintaxe</h3> + +<pre class="syntaxbox notranslate"><strong><var>selectorlist</var> { + <var>property</var>: <var>value</var>;</strong> + <var>[more property:value; pairs]</var> +<strong>}</strong> + +... where <var>selectorlist</var> is: <var>selector[:pseudo-class] [::pseudo-element] [, more selectorlists]</var> + +See <a href="#Selectors"><em>selector</em></a>, <a href="#pcls"><em>pseudo-class</em></a>, <em><a href="#pelm">pseudo-element</a></em> lists below. +</pre> + +<h4 id="Exemplos_de_regra_de_estilo">Exemplos de regra de estilo</h4> + +<pre class="brush: css notranslate">strong { + color: red; +} + +div.menu-bar li:hover > ul { + display: block; +} +</pre> + +<p>For a beginner-level introduction to the syntax of CSS selectors, please see <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors">this tutorial</a>. Be aware that any <a href="/en-US/docs/Web/CSS/syntax">CSS syntax</a> error in a rule definition invalidates the entire rule. Invalid rules are ignored by the browser. Note that CSS rule definitions are entirely (ASCII) <a href="https://www.w3.org/TR/css-syntax-3/#intro">text-based</a>, whereas DOM-CSS / CSSOM (the rule management system) is <a href="https://www.w3.org/TR/cssom/#introduction">object-based</a>.</p> + +<h3 id="Sintaxe_de_regra_At">Sintaxe de regra "At"</h3> + +<p>As the structure of at-rules varies widely, please see <a href="/en-US/docs/Web/CSS/At-rule">At-rule</a> to find the syntax of the specific one you want.</p> + +<h2 id="Índex_de_palavra-chave">Índex de palavra-chave</h2> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> Os nomes das propriadades neste índex <strong>não</strong> incluem os <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Properties_Reference">nomes de JavaScript </a>onde eles diferem com nomes padrão de CSS.</p> +</div> + +<div>{{CSS_Ref}}</div> + +<h2 id="Seletors"><a href="/en-US/docs/Web/CSS/CSS_Selectors">Seletors</a></h2> + +<div class="hidden"> +<div class="blockIndicator todo"> +<p><strong>TODO:</strong> Consider using the <code><a href="https://github.com/mdn/kumascript/blob/master/macros/page.ejs">\{{Page}}</a></code> macro for this section.</p> +</div> +</div> + +<h3 id="Seletores_básicos"><a href="/en-US/docs/Web/CSS/CSS_Selectors#Basic_selectors">Seletores básicos</a></h3> + +<ul> + <li><a href="/en-US/docs/Web/CSS/Type_selectors">Type selector</a> <code>elementname</code></li> + <li><a href="/en-US/docs/Web/CSS/Class_selectors">Class selector</a> <code>.classname</code></li> + <li><a href="/en-US/docs/Web/CSS/ID_selectors">ID selector</a> <code>#idname</code></li> + <li><a href="/en-US/docs/Web/CSS/Universal_selectors">Universal selector</a> <code>*</code>, <code>ns|*</code>, <code>*|*</code>, <code>|*</code></li> + <li><a href="/en-US/docs/Web/CSS/Attribute_selectors">Attribute selector</a> <code>[attr=value]</code></li> +</ul> + +<h3 id="Combinadores"><a href="/en-US/docs/Web/CSS/CSS_Selectors#Combinators">Combinadores</a></h3> + +<ul> + <li><a href="/en-US/docs/Web/CSS/Adjacent_sibling_selectors">Adjacent sibling combinator</a> <code>A + B</code></li> + <li><a href="/en-US/docs/Web/CSS/General_sibling_selectors">General sibling combinator</a> <code>A ~ B</code></li> + <li><a href="/en-US/docs/Web/CSS/Child_selectors">Child combinator</a> <code>A > B</code></li> + <li><a href="/en-US/docs/Web/CSS/Descendant_selectors">Descendant combinator</a> <code>A B</code></li> + <li><a href="/en-US/docs/Web/CSS/Column_combinator">Column combinator</a> <code>A || B</code> {{Experimental_Inline}}</li> +</ul> + +<h3 id="Pseudoclasses"><a href="/pt-PT/docs/Web/CSS/Pseudoclasses">Pseudoclasses</a></h3> + +<div class="index"> +<ul> + <li class="hidden">{{Page("/en-US/docs/Web/CSS/Pseudo-classes", "index")}}</li> +</ul> +</div> + +<h3 id="Pseudoelementos"><a href="/pt-PT/docs/Web/CSS/Pseudoelementos">Pseudoelementos</a></h3> + +<div class="index"> +<ul> + <li class="hidden">{{Page("/en-US/docs/Web/CSS/Pseudo-elements", "index")}}</li> +</ul> +</div> + +<div class="blockIndicator note"> +<p><strong>Consulte também:</strong> uma <a href="https://www.w3.org/TR/selectors/#selectors">lista de seletores</a> completa na especificação de Seletores Nível 3.</p> +</div> + +<h2 id="Conceitos">Conceitos</h2> + +<h3 id="Sintaxe_e_semântica">Sintaxe e semântica</h3> + +<ul> + <li><a href="/en-US/docs/Web/CSS/Syntax">CSS syntax</a></li> + <li><a href="/en-US/docs/Web/CSS/At-rule">At-rules</a></li> + <li><a href="/en-US/docs/Web/CSS/Cascade">Cascade</a></li> + <li><a href="/en-US/docs/Web/CSS/Comments">Comments</a></li> + <li><a href="/en-US/docs/Glossary/Descriptor_(CSS)">Descriptor</a></li> + <li><a href="/en-US/docs/Web/CSS/inheritance">Inheritance</a></li> + <li><a href="/en-US/docs/Web/CSS/Shorthand_properties">Shorthand properties</a></li> + <li><a href="/en-US/docs/Web/CSS/Specificity">Specificity</a></li> + <li><a href="/en-US/docs/Web/CSS/Value_definition_syntax">Value definition syntax</a></li> +</ul> + +<h3 id="Valores">Valores</h3> + +<ul> + <li><a href="/en-US/docs/Web/CSS/actual_value">Actual value</a></li> + <li><a href="/en-US/docs/Web/CSS/computed_value">Computed value</a></li> + <li><a href="/en-US/docs/Web/CSS/initial_value">Initial value</a></li> + <li><a href="/en-US/docs/Web/CSS/resolved_value">Resolved value</a></li> + <li><a href="/en-US/docs/Web/CSS/specified_value">Specified value</a></li> + <li><a href="/en-US/docs/Web/CSS/used_value">Used value</a></li> +</ul> + +<h3 id="Layout">Layout</h3> + +<ul> + <li><a href="/en-US/docs/Web/Guide/CSS/Block_formatting_context">Block formatting context</a></li> + <li><a href="/en-US/docs/Web/CSS/box_model">Box model</a></li> + <li><a href="/en-US/docs/Web/CSS/All_About_The_Containing_Block">Containing block</a></li> + <li><a href="/en-US/docs/Web/CSS/Layout_mode">Layout mode</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing">Margin collapsing</a></li> + <li><a href="/en-US/docs/Web/CSS/Replaced_element">Replaced elements</a></li> + <li><a href="/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context">Stacking context</a></li> + <li><a href="/en-US/docs/Web/Guide/CSS/Visual_formatting_model">Visual formatting model</a></li> +</ul> + +<h2 id="DOM-CSS_CSSOM">DOM-CSS / CSSOM</h2> + +<h3 id="Major_object_types">Major object types</h3> + +<ul> + <li>document.<a href="/en-US/docs/Web/API/Document/styleSheets">styleSheets</a></li> + <li>styleSheets[i].<a href="/en-US/docs/Web/API/CSSRuleList">cssRules</a></li> + <li>cssRules[i].<a href="/en-US/docs/Web/API/CSSRule/cssText">cssText</a> (selector & style)</li> + <li>cssRules[i].<a href="/en-US/docs/Web/API/CSSStyleRule/selectorText">selectorText</a></li> + <li>elem.<a href="/en-US/docs/Web/API/HTMLElement/style">style</a></li> + <li>elem.style.<a href="/en-US/docs/Web/API/CSSStyleDeclaration/cssText">cssText</a> (just style)</li> + <li>elem.<a href="/en-US/docs/Web/API/Element/className">className</a></li> + <li>elem.<a href="/en-US/docs/Web/API/Element/classList">classList</a></li> +</ul> + +<h3 id="Métodos_importantes">Métodos importantes</h3> + +<ul> + <li>{{domxref("CSSStyleSheet.insertRule")}}</li> + <li>{{domxref("CSSStyleSheet.deleteRule")}}</li> +</ul> + +<h2 id="Consultar_também">Consultar também:</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/Mozilla_Extensions">Mozilla CSS extensions</a> (prefixed with <code>-moz</code>)</li> + <li><a href="/en-US/docs/Web/CSS/Webkit_Extensions">WebKit CSS extensions</a> (mostly prefixed with <code>-webkit</code>)</li> + <li><a href="/en-US/docs/Web/CSS/Microsoft_CSS_extensions">Microsoft CSS extensions</a> (prefixed with <code>-ms</code>)</li> +</ul> diff --git a/files/pt-pt/web/css/replaced_element/index.html b/files/pt-pt/web/css/replaced_element/index.html new file mode 100644 index 0000000000..47f2e968f9 --- /dev/null +++ b/files/pt-pt/web/css/replaced_element/index.html @@ -0,0 +1,23 @@ +--- +title: Elemento substituído +slug: Web/CSS/Replaced_element +tags: + - CSS + - Element +translation_of: Web/CSS/Replaced_element +--- +<div>{{CSSRef()}}</div> + +<h2 id="Resumo">Resumo</h2> + +<p>No CSS, um <strong>elemento substituído </strong>é um elemento cuja representação está fora do âmbito do CSS. <font><font>Estes são um tipo de objecto externo cuja representação é independente do CSS.</font></font> <font><font>Elementos substituídos típicos são</font></font> {{HTMLElement("img")}}, {{HTMLElement("object")}}, {{HTMLElement("video")}} <font><font>ou elementos de formulário como</font></font> {{HTMLElement("textarea")}} e {{HTMLElement("input")}}<font><font>. </font><font>Alguns elementos, como </font></font>{{HTMLElement("audio")}} ou {{HTMLElement("canvas")}} <font><font>são elementos só em casos específicos substituído. </font></font> <font><font>Objetos inseridos usando as propriedades CSS</font></font> {{cssxref("content")}} <font><font>são elementos substituídos anônimos</font></font><font><font>.</font></font></p> + +<p><font><font>CSS manipula elementos substituídos especificamente em alguns casos, como ao calcular margens e alguns valores automáticos.</font></font></p> + +<p><font><font>Note-se que alguns elementos substituído,mas não todos,têm dimensões intrínsecas ou uma linha de base definida (<em>baseline</em>), que é utilizada por algumas propriedades CSS como </font></font>{{cssxref("vertical-align")}}.</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{CSS_key_concepts()}}</li> +</ul> diff --git a/files/pt-pt/web/css/shorthand_properties/index.html b/files/pt-pt/web/css/shorthand_properties/index.html new file mode 100644 index 0000000000..8bfb4a4bbc --- /dev/null +++ b/files/pt-pt/web/css/shorthand_properties/index.html @@ -0,0 +1,143 @@ +--- +title: Propriedades de taquigrafia +slug: Web/CSS/Shorthand_properties +tags: + - CSS + - Guía + - Referencia +translation_of: Web/CSS/Shorthand_properties +--- +<div>{{cssref}}</div> + +<p class="summary"><strong><dfn>Propriedades de taquigrafia </dfn></strong>são propriedades de CSS que lhe permitem definir simultaneamente os valores de várias outras propriedades de CSS. Ao utilizar uma propriedade de taquigrafia, pode escrever folhas de estilo mais concisas (e muitas vezes mais legíveis), poupando tempo e energia .</p> + +<p>The CSS specification defines shorthand properties to group the definition of common properties acting on the same theme. For instance, the CSS {{cssxref("background")}} property is a shorthand property that's able to define the values of {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-repeat")}}, and {{cssxref("background-position")}}. Similarly, the most common font-related properties can be defined using the shorthand {{cssxref("font")}}, and the different margins around a box can be defined using the {{cssxref("margin")}} shorthand.</p> + +<h2 id="Tricky_edge_cases" name="Tricky_edge_cases">Tricky edge cases</h2> + +<p>Even if they are very convenient to use, there are a few edge cases to keep in mind when using them:</p> + +<ol> + <li>A value which is not specified is set to its initial value. That sounds anecdotal, but it really means that it <strong>overrides</strong> previously set values. Therefore: + + <pre class="brush:css">background-color: red; +background: url(images/bg.gif) no-repeat left top; +</pre> + will not set the color of the background to <code>red</code> but to {{cssxref("background-color")}}'s default, <code>transparent</code>, as the second rule has precedence.</li> + <li>Only the individual properties values can inherit. As missing values are replaced by their initial value, it is impossible to allow inheritance of individual properties by omitting them. The keyword <code>inherit</code> can be applied to a property, but only as a whole, not as a keyword for one value or another. That means that the only way to make some specific value to be inherited is to use the longhand property with the keyword <code>inherit</code>.</li> + <li>Shorthand properties try not to force a specific order for the values of the properties they replace. This works well when these properties use values of different types, as the order has no importance, but this does not work as easily when several properties can have identical values. Handling of these cases are grouped in several categories: + <ol> + <li>Shorthands handling properties related to edges of a box, like {{cssxref("border-style")}}, {{cssxref("margin")}} or {{cssxref("padding")}}, always use a consistent 1-to-4-value syntax representing those edges: + <table> + <tbody> + <tr> + <td style="width: 79px;"><img alt="border1.png" src="/files/3646/border1.png"></td> + <td><em>The 1-value syntax</em>: <code>border-width: 1em</code> — The unique value represents all edges</td> + </tr> + <tr> + <td><img alt="border2.png" src="/files/3647/border2.png"></td> + <td><em>The 2-value syntax</em>: <code>border-width: 1em 2em</code> — The first value represents the vertical, that is top and bottom, edges, the second the horizontal ones, that is the left and right ones.</td> + </tr> + <tr> + <td><img alt="border3.png" src="/files/3648/border3.png"></td> + <td><em>The 3-value syntax</em>: <code>border-width: 1em 2em 3em</code> — The first value represents the top edge, the second, the horizontal, that is left and right, ones, and the third value the bottom edge</td> + </tr> + <tr> + <td><img alt="border4.png" src="/files/3649/border4.png"></td> + <td> + <p><em>The 4-value syntax</em>: <code>border-width: 1em 2em 3em 4em</code> — The four values represent the top, right, bottom and left edges respectively, always in that order, that is clock-wise starting at the top (The initial letter of Top-Right-Bottom-Left matches the order of the consonant of the word <em>trouble</em>: TRBL)</p> + </td> + </tr> + </tbody> + </table> + </li> + <li>Similarly, shorthands handling properties related to corners of a box, like {{cssxref("border-radius")}}, always use a consistent 1-to-4-value syntax representing those corners: + <table> + <tbody> + <tr> + <td style="width: 69px;"><img alt="corner1.png" src="/files/3650/corner1.png"></td> + <td><em>The 1-value syntax</em>: <code>border-radius: 1em</code> — The unique value represents all corners</td> + </tr> + <tr> + <td><img alt="corner2.png" src="/files/3651/corner2.png"></td> + <td><em>The 2-value syntax</em>: <code>border-radius: 1em 2em</code> — The first value represents the top left and bottom right corner, the second the top right and bottom left ones.</td> + </tr> + <tr> + <td><img alt="corner3.png" src="/files/3652/corner3.png"></td> + <td><em>The 3-value syntax</em>: <code>border-radius: 1em 2em 3em</code> — The first value represents the top left corner, the second the top right and bottom left ones, and the third value the bottom right corner</td> + </tr> + <tr> + <td><img alt="corner4.png" src="/files/3653/corner4.png"></td> + <td> + <p><em>The 4-value syntax</em>: <code>border-radius: 1em 2em 3em 4em</code> — The four values represent the top left, top right, bottom right and bottom left corners respectively, always in that order, that is clock-wise starting at the top left.</p> + </td> + </tr> + </tbody> + </table> + </li> + </ol> + </li> +</ol> + +<h2 id="Background_Properties" name="Background_Properties">Propriedades de segundo plano</h2> + +<p>A background with the following properties ...</p> + +<pre class="brush:css">background-color: #000; +background-image: url(images/bg.gif); +background-repeat: no-repeat; +background-position: left top;</pre> + +<p>... can be shortened to just one declaration:</p> + +<pre class="brush:css">background: #000 url(images/bg.gif) no-repeat left top;</pre> + +<p>(The shorthand form is actually the equivalent of the longhand properties above plus <code>background-attachment: scroll</code> and, in CSS3, some additional properties.)</p> + +<h2 id="Font_Properties" name="Font_Properties">Propriedades de tipo de letra</h2> + +<p>The following declarations ...</p> + +<pre class="brush:css">font-style: italic; +font-weight: bold; +font-size: .8em; +line-height: 1.2; +font-family: Arial, sans-serif;</pre> + +<p>... can be shortened to the following:</p> + +<pre class="brush:css">font: italic bold .8em/1.2 Arial, sans-serif;</pre> + +<p>This shorthand declaration is actually equivalent to the longhand declarations above plus <code>font-variant: normal</code> and <code>font-size-adjust: none</code> (CSS2.0 / CSS3), <code>font-stretch: normal</code> (CSS3).</p> + +<h2 id="Border_Properties" name="Border_Properties">Propriedades de margem</h2> + +<p>With borders, the width, color, and style can be simplified into one declaration. For example, the following CSS ...</p> + +<pre class="brush:css">border-width: 1px; +border-style: solid; +border-color: #000;</pre> + +<p>... can be simplified as:</p> + +<pre class="brush:css">border: 1px solid #000;</pre> + +<h2 id="Margin_and_Padding_Properties" name="Margin_and_Padding_Properties">Margin and padding properties</h2> + +<p>Shorthand versions of margin and padding values work the same way. The following CSS declarations ...</p> + +<pre class="brush:css">margin-top: 10px; +margin-right: 5px; +margin-bottom: 10px; +margin-left: 5px;</pre> + +<p>... are the same as the following declaration. Note that the values are in clockwise order, beginning at the top: top, right, bottom, then left (TRBL, the consonants in "trouble").</p> + +<pre class="brush:css">margin: 10px 5px 10px 5px;</pre> + +<h2 id="See_also" name="See_also">Consulte também</h2> + +<ul> + <li>{{css_key_concepts}}</li> + <li>Shorthand properties: {{cssxref("animation")}}, {{cssxref("background")}}, {{cssxref("border")}}, {{cssxref("border-bottom")}}, {{cssxref("border-color")}}, {{cssxref("border-left")}}, {{cssxref("border-radius")}}, {{cssxref("border-right")}}, {{cssxref("border-style")}}, {{cssxref("border-top")}}, {{cssxref("border-width")}}, {{cssxref("column-rule")}}, {{cssxref("columns")}}, {{cssxref("flex")}}, {{cssxref("flex-flow")}}, {{cssxref("font")}}, {{cssxref("grid")}}, {{cssxref("grid-area")}}, {{cssxref("grid-column")}}, {{cssxref("grid-row")}}, {{cssxref("grid-template")}}, {{cssxref("list-style")}}, {{cssxref("margin")}}, {{cssxref("offset")}}, {{cssxref("outline")}}, {{cssxref("overflow")}}, {{cssxref("padding")}}, {{cssxref("place-content")}}, {{cssxref("place-items")}}, {{cssxref("place-self")}}, {{cssxref("text-decoration")}}, {{cssxref("transition")}}</li> +</ul> diff --git a/files/pt-pt/web/css/top/index.html b/files/pt-pt/web/css/top/index.html new file mode 100644 index 0000000000..3e2f304073 --- /dev/null +++ b/files/pt-pt/web/css/top/index.html @@ -0,0 +1,54 @@ +--- +title: top +slug: Web/CSS/top +translation_of: Web/CSS/top +--- +<p><span class="lang lang-en">« <a href="/pt/Referência_CSS" title="pt/Referência CSS">Referência CSS</a><br> +</span></p> +<h3 id="Resumo"><span class="lang lang-en">Resumo</span></h3> +<p>A propriedade <code>top</code> especifica o posicionamento vertical do elemento de acordo com o topo.</p> +<p>Para elementos absolutamente posicionados (com a propriedade <code>position</code> ajustada como <code>absolute</code> ou <code>fixed</code>) especifica a distância apartir a margem superior do objeto (até onde vai o <code>background</code>).</p> +<p>Para relativamente posicionados (com a propriedade <code>position</code> ajustada como <code>relative</code>) especifica a distância de acordo com o posicionamento do objeto se a propriedade position fosse qualquer uma que não <code>absolute</code>, <code>relative</code> ou <code>fixed</code>.</p> +<ul> <li>Valor inicial: auto</li> <li>Aplica-se a: <a href="/pt/CSS/position" title="pt/CSS/position">Elementos posicionados</a></li> <li>Herdado: não</li> <li>Porcentagens: Referente a altura do próximo antecedente de posição block</li> <li>Valor computado: distância absoluta, porcentagem ou automático</li> +</ul> +<h3 id="Sintáxe">Sintáxe</h3> +<pre class="eval">top: <length> | <percentage> | auto | inherit +</pre> +<h3 id="Exemplos">Exemplos</h3> +<pre><?xml version="1.0" encoding="utf-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> +<head> +<meta http-equiv="Content-Type" content="application/xhtml+xml" /> +<title>Mozilla.org altura, topo, esquerda, largura e direita - CSS</title> +<style type="text/css"> +/* As medidas de body podem ser mudadas para px para testar o comportamento da div */ +body{ + width: 100%; + height: 100%; +} +/* agora a div pode operar com porcentagem (a altura e a largura do body são a referência) */ +div{ + position: absolute; + left: 15%; + top: 30%; + bottom: 30%; + width: 70%; + height: 40%; + text-align: left; + border: 3px #000 solid; + background: #CCC; +} +</style> +</head> +<body> +<center> + <div>...Qualquer conteúdo...</div> +</center> +</body> +</html> +</pre> +<h3 id="Notas">Notas</h3> +<p><code>top</code> é mais relevante que bottom porque o alinhamento vertical padrão é no topo. Com mais propriedades de posicionamento, top torna-se dispensável.</p> +<h3 id="Veja_mais">Veja mais</h3> +<p><a href="/pt/CSS/position" rel="custom nofollow" title="pt/CSS/position">position</a>, <a href="/pt/CSS/right" rel="custom nofollow" title="pt/CSS/right">right</a>, <a href="/pt/CSS/bottom" rel="custom nofollow" title="pt/CSS/bottom">bottom</a>, <a href="/pt/CSS/left" rel="custom nofollow" title="pt/CSS/left">left</a></p> diff --git a/files/pt-pt/web/css/transform/index.html b/files/pt-pt/web/css/transform/index.html new file mode 100644 index 0000000000..8dc2ee3951 --- /dev/null +++ b/files/pt-pt/web/css/transform/index.html @@ -0,0 +1,238 @@ +--- +title: transform +slug: Web/CSS/transform +tags: + - CSS + - Experimental + - NeedsBrowserCompatibility + - Propriedade + - Propriedade de CSS + - Referencia + - Transforms +translation_of: Web/CSS/transform +--- +<div>{{CSSRef}}{{SeeCompatTable}}</div> + +<p>The CSS <strong><code>transform</code></strong> property lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed.</p> + +<pre class="brush: css no-line-numbers">/* Keyword values */ +transform: none; + +/* Function values */ +transform: matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0); +transform: translate(12px, 50%); +transform: translateX(2em); +transform: translateY(3in); +transform: scale(2, 0.5); +transform: scaleX(2); +transform: scaleY(0.5); +transform: rotate(0.5turn); +transform: skew(30deg, 20deg); +transform: skewX(30deg); +transform: skewY(1.07rad); +transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); +transform: translate3d(12px, 50%, 3em); +transform: translateZ(2px); +transform: scale3d(2.5, 1.2, 0.3); +transform: scaleZ(0.3); +transform: rotate3d(1, 2.0, 3.0, 10deg); +transform: rotateX(10deg); +transform: rotateY(10deg); +transform: rotateZ(10deg); +transform: perspective(17px); + +/* Multiple function values */ +transform: translateX(10px) rotate(10deg) translateY(5px); + +/* Global values */ +transform: inherit; +transform: initial; +transform: unset; +</pre> + +<p>If the property has a value different than <code>none</code>, a <a href="/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context">stacking context</a> will be created. In that case the object will act as a containing block for <code>position</code><code>: fixed</code> elements that it contains.</p> + +<p>{{cssinfo}}</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<p>The <code>transform</code> property may be specified as either the keyword value <code><a href="#none">none</a></code> or as one or more <code><a href="#<transform-function>"><transform-function></a></code> values.</p> + +<h3 id="Valores">Valores</h3> + +<dl> + <dt><a id="<transform-function>" name="<transform-function>"><code><transform-function></code></a></dt> + <dd>One or more of the <a href="/en-US/docs/Web/CSS/transform-function">CSS transform functions</a> to be applied, see below. Composite transforms are effectively applied in order from right to left.</dd> + <dt><a id="none" name="none"><code>none</code></a></dt> + <dd>Specifies that no transform should be applied.</dd> +</dl> + +<h3 id="Formal_syntax">Formal syntax</h3> + +<pre class="syntaxbox">{{csssyntax}}</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<p>See <a href="/en-US/docs/Web/Guide/CSS/Using_CSS_transforms">Using CSS transforms</a>.</p> + +<h2 id="Live_example">Live example</h2> + +<h3 id="HTML_content">HTML content</h3> + +<pre class="brush: html"><p>Transformed element</p></pre> + +<h3 id="CSS_content">CSS content</h3> + +<pre class="brush: css">p { + border: solid red; + + -webkit-transform: translate(100px) rotate(20deg); + -webkit-transform-origin: 0 -250px; + + transform: translate(100px) rotate(20deg); + transform-origin: 0 -250px; +}</pre> + +<p>{{EmbedLiveSample("Live_example", "400", "170")}}</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS Transforms 2', '#transform-functions', 'transform')}}</td> + <td>{{Spec2('CSS Transforms 2')}}</td> + <td>Adds 3D transform functions.</td> + </tr> + <tr> + <td>{{SpecName('CSS3 Transforms', '#transform-property', 'transform')}}</td> + <td>{{Spec2('CSS3 Transforms')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_do_navegador">Compatibilidade do navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funionalidade</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}} {{property_prefix("-webkit")}}<br> + 36</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}{{property_prefix("-moz")}}<sup>[1]</sup><br> + {{CompatGeckoDesktop("16.0")}}<sup>[2]</sup></td> + <td>9.0{{property_prefix("-ms")}}<sup>[3]</sup><br> + 10.0</td> + <td>10.5{{property_prefix("-o")}}<br> + 12.10<br> + 15.0{{property_prefix("-webkit")}}<br> + 23</td> + <td>3.1{{property_prefix("-webkit")}}<br> + 9.0</td> + </tr> + <tr> + <td>Suporte 3D</td> + <td>12.0{{property_prefix("-webkit")}}<br> + 36</td> + <td>{{CompatVersionUnknown}}</td> + <td>10.0{{property_prefix("-moz")}}<br> + {{CompatGeckoDesktop("16.0")}}</td> + <td>10.0</td> + <td>15.0{{property_prefix("-webkit")}}<br> + 23</td> + <td> + <p>4.0{{property_prefix("-webkit")}}<br> + 9.0</p> + </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatAndroid(2.1)}}{{property_prefix("-webkit")}}<sup>[4]</sup></td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}</td> + <td>{{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + {{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<br> + 11.0{{property_prefix("-webkit")}}<sup>[5]</sup></td> + <td>11.5{{property_prefix("-webkit")}}</td> + <td>3.2 {{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + 9.0</td> + </tr> + <tr> + <td>Suporte 3D</td> + <td>{{CompatAndroid(3.0)}}{{property_prefix("-webkit")}}</td> + <td>{{CompatVersionUnknown}}{{ property_prefix("-webkit")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>22{{property_prefix("-webkit")}}</td> + <td>3.2 {{CompatVersionUnknown}}{{property_prefix("-webkit")}}<br> + 9.0</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Gecko 14.0 removed the experimental support for <code>skew()</code>, but it was reintroduced in Gecko 15.0 for compatibility reasons. As it is non-standard and will likely be removed in the future, do not use it.</p> + +<p>[2] Before Firefox 16, the translation values of <code>matrix()</code> and <code>matrix3d()</code> could be {{cssxref("<length>")}}, in addition to the standard {{cssxref("<number>")}}.</p> + +<p>In addition to the unprefixed support, Gecko 44.0 {{geckoRelease("44.0")}} added support for a <code>-webkit</code> prefixed version of the property for web compatibility reasons behind the preference <code>layout.css.prefixes.webkit</code>, defaulting to <code>false</code>. Since Gecko 49.0 {{geckoRelease("49.0")}} the preference defaults to <code>true</code>.</p> + +<p>[3] Internet Explorer 5.5 or later supports a proprietary <a href="https://msdn.microsoft.com/en-us/library/ms533014(VS.85,loband).aspx">Matrix Filter</a> which can be used to achieve a similar effect.</p> + +<p>Internet Explorer 9.0 or earlier has no support for 3D transforms. Mixing 3D and 2D transform functions, such as <code>-ms-transform:rotate(10deg) translateZ(0);</code>, will prevent the entire property from being applied.</p> + +<p>Internet Explorer does not support the global values <code>initial</code> and <code>unset.</code></p> + +<p>[4] Android 2.3 has a bug where input forms will "jump" when typing, if any container element has a <code>-webkit-transform</code>.</p> + +<p>[5] Internet Explorer 11.0 supports the {{property_prefix("-webkit")}} <a href="https://msdn.microsoft.com/library/jj127312#code-snippet-1">prefixed variant as an alias for the default one</a>.</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/en-US/docs/CSS/Using_CSS_transforms">Using CSS Transforms</a></li> + <li><a href="/en-US/docs/Web/CSS/transform-function"><translation-function></a> data type</li> + <li><a href="https://www.paulirish.com/2010/introducing-css3please/#comment-36380">More info</a> on CSS3 Rotation / Matrix Filter issues in the comments on Paul Irish's blog.</li> + <li>A cross-browser 2D <a href="https://louisremi.github.io/jquery.transform.js/">transform plugin for jQuery</a></li> +</ul> diff --git a/files/pt-pt/web/css/usando_transformações_css/index.html b/files/pt-pt/web/css/usando_transformações_css/index.html new file mode 100644 index 0000000000..62190c37dc --- /dev/null +++ b/files/pt-pt/web/css/usando_transformações_css/index.html @@ -0,0 +1,34 @@ +--- +title: CSS/Usando_transformações_CSS +slug: Web/CSS/Usando_transformações_CSS +translation_of: Web/CSS/CSS_Transforms/Using_CSS_transforms +--- +<p>{{ gecko_minversion_header("1.9.1") }}</p> +<p>Firefox 3.5 (Gecko 1.9.1) introduz suporte a transformações CSS; estas são implementadas utilizando um conjunto de propriedades CSS permitindo a você aplicar transformações lineares a elementos HTML. Essas transformações são baseadas sobre o <a class="external" href="http://webkit.org/blog/130/css-transforms/" title="http://webkit.org/blog/130/css-transforms/">design proposto pelo time WebKit</a> e incluem rotar, inclinar, escalar e usar translação. Enquanto isso, é um <a class="external" href="http://www.w3.org/TR/css3-2d-transforms/" title="http://www.w3.org/TR/css3-2d-transforms/">W3C working draft</a>.</p> +<p>Mozilla atualmente suporta as propriedades {{ Cssxref("-moz-transform") }} e {{ Cssxref("-moz-transform-origin") }}. Para detalhes sobre onde funções de transformação são suportadas, veja o artigo <a class="internal" href="/En/CSS/CSS_transform_functions" title="/en/CSS/CSS transform functions">CSS transform functions</a> (en).</p> +<div class="note"> + <strong>Nota:</strong> Até o momento não há suporte ao eixo Z, portanto, perspectiva, rotação 3D, escala 3D, e transformações 3D não são suportadas.</div> +<h2 id="Exemplo_Rotação">Exemplo: Rotação</h2> +<p>Este exemplo cria um <em>iframe</em> que lhe permite utilizar a página inicial do Google, girada 90 graus sobre seu canto inferior esquerdo.</p> +<p><a class="internal" href="/@api/deki/files/2921/=rotated-google-sample.html" title="/@api/deki/files/2921/=rotated-google-sample.html">Visualizar exemplo</a><br> + <a class="internal" href="/@api/deki/files/2920/=google-rotated.png" title="/@api/deki/files/2920/=google-rotated.png">Visualizar <em>screenshot</em> do exemplo</a></p> +<pre class="brush: html"><div style="-moz-transform: rotate(90deg); -moz-transform-origin: bottom left;"> + <iframe src="http://www.google.com/" width="500px" height="600px" /> +</div> +</pre> +<h2 id="Exemplo_Inclinação_e_translação">Exemplo: Inclinação e translação</h2> +<p>Este exemplo cria um iframe que lhe permite utilizar a página inicial do Google, inclinada 10 graus no eicho X.</p> +<p><a class="external" href="/@api/deki/files/2922/=skewed-google-sample.html" title="http://developer.mozilla.org/editor/fckeditor/core/editor/@api/deki/files/2922/=skewed-google-sample.html">Visualizar exemplo</a><br> + <a class="internal" href="/@api/deki/files/2923/=skewed-google.png" title="/@api/deki/files/2923/=skewed-google.png">Visualizar <em>screenshot</em> do exemplo</a></p> +<pre class="brush: html"><div style="-moz-transform: skewx(10deg) translatex(150px); + -moz-transform-origin: bottom left;"> + <iframe src="http://www.google.com/" width="600px" height="500px" /> +</div> +</pre> +<h2 id="Veja_também">Veja também</h2> +<ul> + <li>{{ Cssxref("-moz-transform") }}</li> + <li>{{ Cssxref("-moz-transform-origin") }}</li> + <li><a class="internal" href="/En/CSS/CSS_transform_functions" title="En/CSS/CSS transform functions">CSS transform functions</a> (EN)</li> +</ul> +<p>{{ languages( { "ja": "ja/CSS/Using_CSS_transforms" } ) }}</p> diff --git a/files/pt-pt/web/css/width/index.html b/files/pt-pt/web/css/width/index.html new file mode 100644 index 0000000000..f865e76bed --- /dev/null +++ b/files/pt-pt/web/css/width/index.html @@ -0,0 +1,86 @@ +--- +title: width +slug: Web/CSS/width +tags: + - Referencia_CSS +translation_of: Web/CSS/width +--- +<p>{{ CSSRef() }}</p> + +<h3 id="Resumo" name="Resumo">Resumo</h3> + +<p>A propriedade <code>width</code> é usada para configurar a largura dada a um elemento.</p> + +<ul> + <li>Valor inicial: auto</li> + <li>Aplica-se a: o nível do bloco e elementos substituídos</li> + <li>Herdado: não</li> + <li>Percentagens: refere-se à largura do bloco que o contém</li> + <li>Mídia: <a href="pt/CSS/Media/Visual">Visual</a></li> +</ul> + +<h3 id="Sintaxe" name="Sintaxe">Sintaxe</h3> + +<pre class="eval"> width: [ <length> || <percentage> ] auto | inherit +</pre> + +<h3 id="Valores" name="Valores">Valores</h3> + +<ul> + <li><strong>length</strong> : pode ser em px, cm, in, em</li> + <li><strong>percentage</strong> : % especificado como uma porcentagem da largura do elemento pai</li> + <li><strong>auto</strong> : o navegador calculará e selecionará uma largura para o elemento especificado.</li> +</ul> + +<h3 id="Exemplos" name="Exemplos">Exemplos</h3> + +<p><a href="/samples/cssref/width.html">View Live Examples</a></p> + +<pre>table{width: 100%;} + +img{width: 200px;} + +form{width: auto;} +</pre> + +<p><span class="comment">== Notas ==</span></p> + +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es">Especificações</h3> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/CSS1#width">CSS 1</a></li> + <li><a class="external" href="http://www.w3.org/TR/CSS21/visudet.html#the-width-property">CSS 2.1</a></li> +</ul> + +<h3 id="Compatibilidade_com_navegadores" name="Compatibilidade_com_navegadores">Compatibilidade com navegadores</h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Navegador</th> + <th>Versão mais antiga</th> + </tr> + <tr> + <td>Internet Explorer</td> + <td>4</td> + </tr> + <tr> + <td>Netscape</td> + <td>4</td> + </tr> + <tr> + <td>Opera</td> + <td>3.5</td> + </tr> + </tbody> +</table> + +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m">Veja também</h3> + +<p><a href="pt/CSS/box_model">box model</a>, {{ Cssxref("height") }}, {{ Cssxref("-moz-box-sizing") }}</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<p>{{ languages( { "en": "en/CSS/width", "fr": "fr/CSS/width" } ) }}</p> diff --git a/files/pt-pt/web/css/z-index/index.html b/files/pt-pt/web/css/z-index/index.html new file mode 100644 index 0000000000..0ff1013362 --- /dev/null +++ b/files/pt-pt/web/css/z-index/index.html @@ -0,0 +1,41 @@ +--- +title: z-index +slug: Web/CSS/z-index +tags: + - Referencia_CSS +translation_of: Web/CSS/z-index +--- +<p> +{{ CSSRef() }} +</p> +<h3 id="Resumo" name="Resumo"> Resumo </h3> +<p>A propriedade <code>z-index</code> especifica a ordem-z de um elemento e de seus herdeiros. Quando os elementos sobrepõem, a z-ordem determina qual elemento cobre o outro. +</p> +<ul><li> Valor inicial: auto; +</li><li> Aplica-se a: elementos posicionados; +</li><li> Herdado: não; +</li><li> Mídia: <a href="pt/CSS/Media/Visual">Visual</a>; +</li><li> Valor computado: como especificado. +</li></ul> +<h3 id="Sintaxe" name="Sintaxe"> Sintaxe </h3> +<p>z-index: auto | <integer> | <a href="pt/CSS/inherit">inherit</a> +</p> +<h3 id="Valores" name="Valores"> Valores </h3> +<dl><dt> auto </dt><dd> O elemento é desenhado na mesma ordem-z como um elemento com <code>z-index: 0</code>. Isto <i>não</i> cria uma nova pilha de contexto. +</dd><dt> <integer> </dt><dd> O elemento é desenhado na ordem-z dada. Isto cria também uma nova pilha de contexto, que significa que todos os descendentes também terão o desenho no mesmo z-index. Dessa forma os z-indexes dos descendentes não são comparados aos z-indexes dos elementos do lado de fora deste elemento. +</dd></dl> +<p><span class="comment">== Exemplos ==</span> +</p> +<h3 id="Notas" name="Notas"> Notas </h3> +<p>Valores <code>z-index</code> negativos são suportados corretamente iniciando em <a href="pt/Gecko">Gecko</a> 1.9 / <a href="pt/Firefox_3_para_desenvolvedores">Firefox 3</a>. Versões mais antigas implementaram o comportamento do CSS 2, não o comportamento do CSS 2.1 que é compatível com outros navegadores. +</p> +<h3 id="Especifica.C3.A7.C3.B5es" name="Especifica.C3.A7.C3.B5es"> Especificações </h3> +<ul><li> <a class="external" href="http://www.w3.org/TR/CSS21/visuren.html#propdef-z-index">CSS 2.1</a> +</li></ul> +<p><span class="comment">== Compatibilidade com navegadores ==</span> +</p> +<h3 id="Veja_tamb.C3.A9m" name="Veja_tamb.C3.A9m"> Veja também </h3> +<p>{{ Cssxref("position") }} +</p><p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/CSS/z-index", "fr": "fr/CSS/z-index", "pl": "pl/CSS/z-index" } ) }} diff --git a/files/pt-pt/web/eventos/index.html b/files/pt-pt/web/eventos/index.html new file mode 100644 index 0000000000..e215eccadc --- /dev/null +++ b/files/pt-pt/web/eventos/index.html @@ -0,0 +1,3080 @@ +--- +title: Referência de Eventos +slug: Web/Eventos +tags: + - eventos +translation_of: Web/Events +--- +<p>Eventos DOM são enviados para notificar o código de coisas interessantes que ocorreram. Cada evento é representado por um objeto que é baseado na interface {{domxref ('Evento')}}, e poderá ter campos e/ou funções personalizadas adicionais utilizadas para obter informação adicional sobre o que aconteceu. Os eventos podem representar tudo, desde interações básicas do utilizador até notificações automáticas de coisas a acontecer no modelo de renderização. .</p> + +<p>Este artigo oferece uma lista de eventos que podem ser enviados; alguns são eventos padrão definidos nas especificações oficiais, enquanto outros são eventos utilizadosinternamente pelos navegadores específicos; por exemplo, os eventos específicos da Mozilla são listados para que os <a href="/pt-PT/docs/Mozilla/Add-ons">extras</a> possam utilizá-los para interagir com o navegador.</p> + +<h2 id="Categorias_Mais_Comuns">Categorias Mais Comuns</h2> + +<table class="standard-table"> + <caption>Eventos de Recurso</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("cached")}}</td> + <td>The resources listed in the manifest have been downloaded, and the application is now cached.</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>A resource failed to load.</td> + </tr> + <tr> + <td>{{event("abort")}}</td> + <td>The loading of a resource has been aborted.</td> + </tr> + <tr> + <td>{{event("load")}}</td> + <td>A resource and its dependent resources have finished loading.</td> + </tr> + <tr> + <td>{{event("beforeunload")}}</td> + <td>The window, the document and its resources are about to be unloaded.</td> + </tr> + <tr> + <td>{{event("unload")}}</td> + <td>The document or a dependent resource is being unloaded.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Rede</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("online")}}</td> + <td>The browser has gained access to the network.</td> + </tr> + <tr> + <td>{{event("offline")}}</td> + <td>The browser has lost access to the network.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Foco</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("focus")}}</td> + <td>An element has received focus (does not bubble).</td> + </tr> + <tr> + <td>{{event("blur")}}</td> + <td>An element has lost focus (does not bubble).</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de <em>Websocket</em></caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/open_websocket">open</a></code></td> + <td>A WebSocket connection has been established.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_websocket">message</a></code></td> + <td>A message is received through a WebSocket.</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>A WebSocket connection has been closed with prejudice (some data couldn't be sent for example).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/close_websocket">close</a></code></td> + <td>A WebSocket connection has been closed.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos do Histórico de Sessão</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("pagehide")}}</td> + <td>A session history entry is being traversed from.</td> + </tr> + <tr> + <td>{{event("pageshow")}}</td> + <td>A session history entry is being traversed to.</td> + </tr> + <tr> + <td>{{event("popstate")}}</td> + <td>A session history entry is being navigated to (in certain cases).</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Animação de CSS</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("animationstart")}}</td> + <td>A <a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_animations">CSS animation</a> has started.</td> + </tr> + <tr> + <td>{{event("animationend")}}</td> + <td>A <a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_animations">CSS animation</a> has completed.</td> + </tr> + <tr> + <td>{{event("animationiteration")}}</td> + <td>A <a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_animations">CSS animation</a> is repeated.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Transição de CSS</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("transitionstart")}}</td> + <td>A <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transition</a> has actually started (fired after any delay).</td> + </tr> + <tr> + <td>{{event("transitioncancel")}}</td> + <td>A <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transition</a> has been cancelled.</td> + </tr> + <tr> + <td>{{event("transitionend")}}</td> + <td>A <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transition</a> has completed.</td> + </tr> + <tr> + <td>{{event("transitionrun")}}</td> + <td>A <a href="/en-US/docs/Web/CSS/CSS_Transitions">CSS transition</a> has began running (fired before any delay starts).</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Formulário</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("reset")}}</td> + <td>The reset button is pressed</td> + </tr> + <tr> + <td>{{event("submit")}}</td> + <td>The submit button is pressed</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Impressão</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("beforeprint")}}</td> + <td>The print dialog is opened</td> + </tr> + <tr> + <td>{{event("afterprint")}}</td> + <td>The print dialog is closed</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Composição de Texto</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("compositionstart")}}</td> + <td>The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).</td> + </tr> + <tr> + <td>{{event("compositionupdate")}}</td> + <td>A character is added to a passage of text being composed.</td> + </tr> + <tr> + <td>{{event("compositionend")}}</td> + <td>The composition of a passage of text has been completed or canceled.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Visualização</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("fullscreenchange")}}</td> + <td>An element was turned to fullscreen mode or back to normal mode.</td> + </tr> + <tr> + <td>{{event("fullscreenerror")}}</td> + <td>It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.</td> + </tr> + <tr> + <td>{{event("resize")}}</td> + <td>The document view has been resized.</td> + </tr> + <tr> + <td>{{event("scroll")}}</td> + <td>The document view or an element has been scrolled.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Área de Transferência</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("cut")}}</td> + <td>The selection has been cut and copied to the clipboard</td> + </tr> + <tr> + <td>{{event("copy")}}</td> + <td>The selection has been copied to the clipboard</td> + </tr> + <tr> + <td>{{event("paste")}}</td> + <td>The item from the clipboard has been pasted</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Teclado</caption> + <tbody> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + <tr> + <td>{{event("keydown")}}</td> + <td>ANY key is pressed</td> + </tr> + <tr> + <td>{{event("keypress")}}</td> + <td>ANY key except Shift, Fn, CapsLock is in pressed position. (Fired continously.)</td> + </tr> + <tr> + <td>{{event("keyup")}}</td> + <td>ANY key is released</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Rato</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("mouseenter")}}</td> + <td>A pointing device is moved onto the element that has the listener attached.</td> + </tr> + <tr> + <td>{{event("mouseover")}}</td> + <td>A pointing device is moved onto the element that has the listener attached or onto one of its children.</td> + </tr> + <tr> + <td>{{event("mousemove")}}</td> + <td>A pointing device is moved over an element. (Fired continously as the mouse moves.)</td> + </tr> + <tr> + <td>{{event("mousedown")}}</td> + <td>A pointing device button is pressed on an element.</td> + </tr> + <tr> + <td>{{event("mouseup")}}</td> + <td>A pointing device button is released over an element.</td> + </tr> + <tr> + <td>{{event("auxclick")}}</td> + <td>A pointing device button (ANY non-primary button) has been pressed and released on an element.</td> + </tr> + <tr> + <td>{{event("click")}}</td> + <td>A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.</td> + </tr> + <tr> + <td>{{event("dblclick")}}</td> + <td>A pointing device button is clicked twice on an element.</td> + </tr> + <tr> + <td>{{event("contextmenu")}}</td> + <td>The right button of the mouse is clicked (before the context menu is displayed).</td> + </tr> + <tr> + <td>{{event("wheel")}}</td> + <td>A wheel button of a pointing device is rotated in any direction.</td> + </tr> + <tr> + <td>{{event("mouseleave")}}</td> + <td>A pointing device is moved off the element that has the listener attached.</td> + </tr> + <tr> + <td>{{event("mouseout")}}</td> + <td>A pointing device is moved off the element that has the listener attached or off one of its children.</td> + </tr> + <tr> + <td>{{event("select")}}</td> + <td>Some text is being selected.</td> + </tr> + <tr> + <td>{{event("pointerlockchange")}}</td> + <td>The pointer was locked or released.</td> + </tr> + <tr> + <td>{{event("pointerlockerror")}}</td> + <td>It was impossible to lock the pointer for technical reasons or because the permission was denied.</td> + </tr> + </tbody> +</table> + +<table class="standard-table" style="height: 276px; width: 856px;"> + <caption>Eventos de 'Arrastar e Largar'</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("dragstart")}}</td> + <td>The user starts dragging an element or text selection.</td> + </tr> + <tr> + <td>{{event("drag")}}</td> + <td>An element or text selection is being dragged (Fired continuously every 350ms).</td> + </tr> + <tr> + <td>{{event("dragend")}}</td> + <td>A drag operation is being ended (by releasing a mouse button or hitting the escape key).</td> + </tr> + <tr> + <td>{{event("dragenter")}}</td> + <td>A dragged element or text selection enters a valid drop target.</td> + </tr> + <tr> + <td>{{event("dragover")}}</td> + <td>An element or text selection is being dragged over a valid drop target. (Fired continuously every 350ms.)</td> + </tr> + <tr> + <td>{{event("dragleave")}}</td> + <td>A dragged element or text selection leaves a valid drop target.</td> + </tr> + <tr> + <td>{{event("drop")}}</td> + <td>An element is dropped on a valid drop target.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Média</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("durationchange")}}</td> + <td>The <code>duration</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{event("loadedmetadata")}}</td> + <td>The metadata has been loaded.</td> + </tr> + <tr> + <td>{{event("loadeddata")}}</td> + <td>The first frame of the media has finished loading.</td> + </tr> + <tr> + <td>{{event("canplay")}}</td> + <td>The browser can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.</td> + </tr> + <tr> + <td>{{event("canplaythrough")}}</td> + <td>The browser estimates it can play the media up to its end without stopping for content buffering.</td> + </tr> + <tr> + <td>{{event("ended")}}</td> + <td>Playback has stopped because the end of the media was reached.</td> + </tr> + <tr> + <td>{{event("emptied")}}</td> + <td>The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the <a href="/en-US/docs/XPCOM_Interface_Reference/NsIDOMHTMLMediaElement" rel="internal"><code>load()</code></a> method is called to reload it.</td> + </tr> + <tr> + <td>{{event("stalled")}}</td> + <td>The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.</td> + </tr> + <tr> + <td>{{event("suspend")}}</td> + <td>Media data loading has been suspended.</td> + </tr> + <tr> + <td>{{event("play")}}</td> + <td>Playback has begun.</td> + </tr> + <tr> + <td>{{event("playing")}}</td> + <td>Playback is ready to start after having been paused or delayed due to lack of data.</td> + </tr> + <tr> + <td>{{event("pause")}}</td> + <td>Playback has been paused.</td> + </tr> + <tr> + <td>{{event("waiting")}}</td> + <td>Playback has stopped because of a temporary lack of data.</td> + </tr> + <tr> + <td>{{event("seeking")}}</td> + <td>A <em>seek</em> operation began.</td> + </tr> + <tr> + <td>{{event("seeked")}}</td> + <td>A <em>seek</em> operation completed.</td> + </tr> + <tr> + <td>{{event("ratechange")}}</td> + <td>The playback rate has changed.</td> + </tr> + <tr> + <td>{{event("timeupdate")}}</td> + <td>The time indicated by the <code>currentTime</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{event("volumechange")}}</td> + <td>The volume has changed.</td> + </tr> + <tr> + <td>{{event("complete")}}</td> + <td>The rendering of an {{domxref("OfflineAudioContext")}} is terminated.</td> + </tr> + <tr> + <td>{{event("audioprocess")}}</td> + <td>The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Eventos de Progresso</caption> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("loadstart")}}</td> + <td>Progresso começou.</td> + </tr> + <tr> + <td>{{event("progress")}}</td> + <td>Em progresso.</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>Progresso falhou.</td> + </tr> + <tr> + <td>{{event("timeout")}}</td> + <td>Progression is terminated due to preset time expiring.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/abort_(ProgressEvent)">abort</a></code></td> + <td>Progression has been terminated (not due to an error).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/load_(ProgressEvent)">load</a></code></td> + <td>Progression has been successful.</td> + </tr> + <tr> + <td>{{event("loadend")}}</td> + <td>Progress has stopped (after "error", "abort" or "load" have been dispatched).</td> + </tr> + </tbody> +</table> + +<h3 id="Eventos_de_armazenamento">Eventos de armazenamento</h3> + +<p>{{event("change")}} (see {{anch("Non-standard events")}})<br> + {{event("storage")}}</p> + +<h3 id="Eventos_de_atualização">Eventos de atualização</h3> + +<p>{{event("checking")}}<br> + {{event("downloading")}}<br> + {{event("error")}}<br> + {{event("noupdate")}}<br> + {{event("obsolete")}}<br> + {{event("updateready")}}</p> + +<h3 id="Eventos_de_alteração_de_valor">Eventos de alteração de valor</h3> + +<p>{{event("broadcast")}}<br> + {{event("CheckboxStateChange")}}<br> + {{event("hashchange")}}<br> + {{event("input")}}<br> + {{event("RadioStateChange")}}<br> + {{event("readystatechange")}}<br> + {{event("ValueChange")}}</p> + +<h3 id="Eventos_não_categorizados">Eventos não categorizados</h3> + +<p>{{event("invalid")}}<br> + {{event("localized")}}<br> + <code><a href="/en-US/docs/Web/Reference/Events/message_webworker">message</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/message_webmessaging">message</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/message_serversentevents">message</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/open_serversentevents">open</a></code><br> + {{event("show")}}</p> + +<h2 id="Eventos_menos_comuns_e_não_padrão">Eventos menos comuns e não padrão</h2> + +<h3 id="Eventos_de_Abortable_Fetch">Eventos de <em>Abortable Fetch</em></h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("abort_(dom_abort_api)", "abort")}}</td> + <td>A DOM request is aborted, i.e. using {{domxref("AbortController.abort()")}}.</td> + </tr> + </tbody> +</table> + +<h3 id="Eventos_de_WebVR">Eventos de WebVR</h3> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Nome do Evento</th> + <th scope="col">Executado quando</th> + </tr> + <tr> + <td>{{event("vrdisplayconnect")}}</td> + <td>when a compatible {{domxref("VRDisplay")}} is connected to the computer.</td> + </tr> + <tr> + <td>{{event("vrdisplaydisconnect")}}</td> + <td>When a compatible {{domxref("VRDisplay")}} is disconnected from the computer.</td> + </tr> + <tr> + <td>{{event("vrdisplayactivate")}}</td> + <td>When a VR display is able to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.</td> + </tr> + <tr> + <td>{{event("vrdisplaydeactivate")}}</td> + <td>When a {{domxref("VRDisplay")}} can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.</td> + </tr> + <tr> + <td>{{event("vrdisplayblur")}}</td> + <td>when presentation to a {{domxref("VRDisplay")}} has been paused for some reason by the browser, OS, or VR hardware — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.</td> + </tr> + <tr> + <td>{{event("vrdisplayfocus")}}</td> + <td>When presentation to a {{domxref("VRDisplay")}} has resumed after being blurred.</td> + </tr> + <tr> + <td>{{event("vrdisplaypresentchange")}}</td> + <td>The presenting state of a {{domxref("VRDisplay")}} changes — i.e. goes from presenting to not presenting, or vice versa.</td> + </tr> + </thead> +</table> + +<h3 id="Eventos_de_SVG">Eventos de SVG</h3> + +<p>{{event("SVGAbort")}}<br> + {{event("SVGError")}}<br> + {{event("SVGLoad")}}<br> + {{event("SVGResize")}}<br> + {{event("SVGScroll")}}<br> + {{event("SVGUnload")}}<br> + {{event("SVGZoom")}}</p> + +<h3 id="Eventos_de_base_de_dados">Eventos de base de dados</h3> + +<p><code><a href="/en-US/docs/Web/Reference/Events/abort_indexedDB">abort</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/blocked_indexedDB">blocked</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/complete_indexedDB">complete</a></code><br> + {{event("error")}} (<a href="/en-US/docs/Web/Reference/Events/error">link</a>)<br> + <code><a href="/en-US/docs/Web/Reference/Events/success_indexedDB">success</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/upgradeneeded_indexedDB">upgradeneeded</a></code><br> + <code><a href="/en-US/docs/Web/Reference/Events/versionchange_indexedDB">versionchange</a></code></p> + +<h3 id="Eventos_de_notificação">Eventos de notificação</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/AlertActive">AlertActive</a><br> + <a href="/en-US/docs/Web/Reference/Events/AlertClose">AlertClose</a></p> + +<h3 id="Eventos_de_CSS">Eventos de CSS</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">CssRuleViewRefreshed</a><br> + <a href="/en-US/docs/Web/Reference/Events/CssRuleViewChanged">CssRuleViewChanged</a><br> + <a href="/en-US/docs/Web/Reference/Events/CssRuleViewCSSLinkClicked">CssRuleViewCSSLinkClicked</a><br> + {{event("transitionend")}}</p> + +<h3 id="eventos_de_script">eventos de <em>script</em></h3> + +<p>{{event("afterscriptexecute")}}<br> + {{event("beforescriptexecute")}}</p> + +<h3 id="eventos_de_menu">eventos de menu</h3> + +<p>{{event("DOMMenuItemActive")}}<br> + {{event("DOMMenuItemInactive")}}</p> + +<h3 id="Eventos_de_janela">Eventos de janela</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/DOMWindowCreated">DOMWindowCreated</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMTitleChanged">DOMTitleChanged</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMWindowClose">DOMWindowClose</a><br> + <a href="/en-US/docs/Web/Reference/Events/SSWindowClosing">SSWindowClosing</a><br> + <a href="/en-US/docs/Web/Reference/Events/SSWindowStateReady">SSWindowStateReady</a><br> + <a href="/en-US/docs/Web/Reference/Events/SSWindowStateBusy">SSWindowStateBusy</a><br> + <a href="/en-US/docs/Web/Reference/Events/close_event">close</a></p> + +<h3 id="Eventos_de_documento">Eventos de documento</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/DOMLinkAdded">DOMLinkAdded</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMLinkRemoved">DOMLinkRemoved</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMMetaAdded">DOMMetaAdded</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMMetaRemoved">DOMMetaRemoved</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMWillOpenModalDialog">DOMWillOpenModalDialog</a><br> + <a href="/en-US/docs/Web/Reference/Events/DOMModalDialogClosed">DOMModalDialogClosed</a></p> + +<h3 id="Eventos_de_janela_(Popup)">Eventos de janela (<em>Popup</em>)</h3> + +<p>{{event("popuphidden")}}<br> + {{event("popuphiding")}}<br> + {{event("popupshowing")}}<br> + {{event("popupshown")}}<br> + <a href="/en-US/docs/Web/Reference/Events/DOMPopupBlocked">DOMPopupBlocked</a></p> + +<h3 id="Eventos_de_separador">Eventos de separador</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/TabOpen">TabOpen</a><br> + <a href="/en-US/docs/Web/Reference/Events/TabClose">TabClose</a><br> + <a href="/en-US/docs/Web/Reference/Events/TabSelect">TabSelect</a><br> + <a href="/en-US/docs/Web/Reference/Events/TabShow">TabShow</a><br> + <a href="/en-US/docs/Web/Reference/Events/TabHide">TabHide</a><br> + <a href="/en-US/docs/Web/Reference/Events/TabPinned">TabPinned</a><br> + <a href="/en-US/docs/Web/Reference/Events/TabUnpinned">TabUnpinned</a><br> + <a href="/en-US/docs/Web/Reference/Events/SSTabClosing">SSTabClosing</a><br> + <a href="/en-US/docs/Web/Reference/Events/SSTabRestoring">SSTabRestoring</a><br> + <a href="/en-US/docs/Web/Reference/Events/SSTabRestored">SSTabRestored</a><br> + {{event("visibilitychange")}}</p> + +<h3 id="Eventos_de_bateria">Eventos de bateria</h3> + +<p>{{event("chargingchange")}}<br> + {{event("chargingtimechange")}}<br> + {{event("dischargingtimechange")}}<br> + {{event("levelchange")}}</p> + +<h3 id="Eventos_de_chamada">Eventos de chamada</h3> + +<p>{{event("alerting")}}<br> + {{event("busy")}}<br> + {{event("callschanged")}}<br> + {{event("cfstatechange")}}<br> + {{event("connected")}}<br> + {{event("connecting")}}<br> + {{event("dialing")}}<br> + {{event("disconnected")}}<br> + {{event("disconnecting")}}<br> + {{event("error_(Telephony)","error")}}<br> + {{event("held")}}, {{event("holding")}}<br> + {{event("incoming")}}<br> + {{event("resuming")}}<br> + {{event("statechange")}}<br> + {{event("voicechange")}}</p> + +<h3 id="Eventos_de_sensor">Eventos de sensor</h3> + +<p>{{event("compassneedscalibration")}}<br> + {{event("devicelight")}}<br> + {{event("devicemotion")}}<br> + {{event("deviceorientation")}}<br> + {{event("deviceproximity")}}<br> + {{event("MozOrientation")}}<br> + {{event("orientationchange")}}<br> + {{event("userproximity")}}</p> + +<h3 id="Eventos_de_Smartcard">Eventos de <em>Smartcard</em></h3> + +<p>{{event("icccardlockerror")}}<br> + {{event("iccinfochange")}}<br> + {{event("smartcard-insert")}}<br> + {{event("smartcard-remove")}}<br> + {{event("stkcommand")}}<br> + {{event("stksessionend")}}<br> + {{event("cardstatechange")}}</p> + +<h3 id="Eventos_de_SMS_e_USSD">Eventos de SMS e USSD</h3> + +<p>{{event("delivered")}}<br> + {{event("received")}}<br> + {{event("sent")}}<br> + {{event("ussdreceived")}}</p> + +<h3 id="Eventos_de_frame">Eventos de <em>frame</em></h3> + +<p>{{event("mozbrowserclose")}}<br> + {{event("mozbrowsercontextmenu")}}<br> + {{event("mozbrowsererror")}}<br> + {{event("mozbrowsericonchange")}}<br> + {{event("mozbrowserlocationchange")}}<br> + {{event("mozbrowserloadend")}}<br> + {{event("mozbrowserloadstart")}}<br> + {{event("mozbrowseropenwindow")}}<br> + {{event("mozbrowsersecuritychange")}}<br> + {{event("mozbrowsershowmodalprompt")}} (<a href="/en-US/docs/Web/Reference/Events/mozbrowsershowmodalprompt">link</a>)<br> + {{event("mozbrowsertitlechange")}}<br> + <a href="/en-US/docs/Web/Reference/Events/DOMFrameContentLoaded">DOMFrameContentLoaded</a></p> + +<h3 id="Eventos_de_mutação_de_DOM">Eventos de mutação de DOM</h3> + +<p><code><a href="/en-US/docs/DOM/Mutation_events">DOMAttributeNameChanged</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMAttrModified</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMCharacterDataModified</a></code><br> + {{event("DOMContentLoaded")}}<br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMElementNameChanged</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeInserted</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeInsertedIntoDocument</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeRemoved</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeRemovedFromDocument</a></code><br> + <code><a href="/en-US/docs/DOM/Mutation_events">DOMSubtreeModified</a></code></p> + +<h3 id="Eventos_de_toque">Eventos de toque</h3> + +<p><a href="/en-US/docs/Web/Reference/Events/MozEdgeUIGesture">MozEdgeUIGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozMagnifyGesture">MozMagnifyGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozMagnifyGestureStart">MozMagnifyGestureStart</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozMagnifyGestureUpdate">MozMagnifyGestureUpdate</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozPressTapGesture">MozPressTapGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozRotateGesture">MozRotateGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozRotateGestureStart">MozRotateGestureStart</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozRotateGestureUpdate">MozRotateGestureUpdate</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozSwipeGesture">MozSwipeGesture</a><br> + <a href="/en-US/docs/Web/Reference/Events/MozTapGesture">MozTapGesture</a><br> + <a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchDown</a><br> + <a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchMove</a><br> + <a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchUp</a><br> + {{event("touchcancel")}}<br> + {{event("touchend")}}<br> + {{event("touchenter")}}<br> + {{event("touchleave")}}<br> + {{event("touchmove")}}<br> + {{event("touchstart")}}</p> + +<h3 id="Eventos_de_pointer">Eventos de <em>pointer</em></h3> + +<p>{{event("pointerover")}}<br> + {{event("pointerenter")}}<br> + {{event("pointerdown")}}<br> + {{event("pointermove")}}<br> + {{event("pointerup")}}<br> + {{event("pointercancel")}}<br> + {{event("pointerout")}}<br> + {{event("pointerleave")}}<br> + {{event("gotpointercapture")}}<br> + {{event("lostpointercapture")}}</p> + +<h2 id="Eventos_padrão">Eventos padrão</h2> + +<p>These events are defined in official Web specifications, and should be common across browsers. Each event is listed along with the interface representing the object sent to recipients of the event (so you can find information about what data is provided with each event) as well as a link to the specification or specifications that define the event.</p> + +<table class="standard-table" style="height: 9388px; width: 1781px;"> + <thead> + <tr> + <th class="header" style="width: 220px;">Nome do Evento</th> + <th class="header" style="width: 90px;">Tipo de Evento</th> + <th class="header" style="width: 100px;">Especificação</th> + <th class="header">Executado quando...</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("abort")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-abort">DOM L3</a></td> + <td>The loading of a resource has been aborted.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/abort_(ProgressEvent)">abort</a></code></td> + <td>{{domxref("ProgressEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/progress-events/">Progress</a> and <a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-abort">XMLHttpRequest</a></td> + <td>Progression has been terminated (not due to an error).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/abort_indexedDB">abort</a></code></td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/IndexedDB/#database-interface">IndexedDB</a></td> + <td>A transaction has been aborted.</td> + </tr> + <tr> + <td>{{event("afterprint")}}{{gecko_minversion_inline("6")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/html5/webappapis.html#printing">HTML5</a></td> + <td>The associated document has started printing or the print preview has been closed.</td> + </tr> + <tr> + <td>{{event("animationend")}}</td> + <td>{{domxref("AnimationEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/css3-animations/#animation-events">CSS Animations</a></td> + <td>A <a href="/en-US/docs/CSS/CSS_animations">CSS animation</a> has completed.</td> + </tr> + <tr> + <td>{{event("animationiteration")}}</td> + <td>{{domxref("AnimationEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/css3-animations/#animation-events">CSS Animations</a></td> + <td>A <a href="/en-US/docs/CSS/CSS_animations">CSS animation</a> is repeated.</td> + </tr> + <tr> + <td>{{event("animationstart")}}</td> + <td>{{domxref("AnimationEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/css3-animations/#animation-events">CSS Animations</a></td> + <td>A <a href="/en-US/docs/CSS/CSS_animations">CSS animation</a> has started.</td> + </tr> + <tr> + <td>{{event("appinstalled")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="/en-US/docs/Web/Manifest">Web App Manifest</a></td> + <td>A web application is successfully installed as a <a href="https://developer.mozilla.org/en-US/Apps/Progressive">progressive web app</a>.</td> + </tr> + <tr> + <td>{{event("audioprocess")}}</td> + <td>{{domxref("AudioProcessingEvent")}} {{deprecated_inline}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}</td> + <td>The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.</td> + </tr> + <tr> + <td>{{event("audioend")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The user agent has finished capturing audio for speech recognition.</td> + </tr> + <tr> + <td>{{event("audiostart")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The user agent has started to capture audio for speech recognition.</td> + </tr> + <tr> + <td>{{event("beforeprint")}} {{gecko_minversion_inline("6")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/html5/webappapis.html#printing">HTML5</a></td> + <td>The associated document is about to be printed or previewed for printing.</td> + </tr> + <tr> + <td>{{event("beforeunload")}}</td> + <td>{{domxref("BeforeUnloadEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/html5/browsers.html#unloading-documents">HTML5 </a></td> + <td>The window, the document and its resources are about to be unloaded.</td> + </tr> + <tr> + <td>{{event("beginEvent")}}</td> + <td>{{domxref("TimeEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>A <a href="/en-US/docs/SVG/SVG_animation_with_SMIL">SMIL</a> animation element begins.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/blocked_indexedDB">blocked</a></code></td> + <td> </td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/IndexedDB/#request-api">IndexedDB</a></td> + <td>An open connection to a database is blocking a <code>versionchange</code> transaction on the same database.</td> + </tr> + <tr> + <td>{{event("blur")}}</td> + <td>{{domxref("FocusEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-blur">DOM L3</a></td> + <td>An element has lost focus (does not bubble).</td> + </tr> + <tr> + <td>{{event("boundary")}} {{experimental_inline}}</td> + <td>{{domxref("SpeechSynthesisEvent")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The spoken utterance reaches a word or sentence boundary</td> + </tr> + <tr> + <td>{{event("cached")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The resources listed in the manifest have been downloaded, and the application is now cached.</td> + </tr> + <tr> + <td>{{event("canplay")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-canplay">HTML5 media</a></td> + <td>The user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.</td> + </tr> + <tr> + <td>{{event("canplaythrough")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-canplaythrough">HTML5 media</a></td> + <td>The user agent can play the media up to its end without having to stop for further buffering of content.</td> + </tr> + <tr> + <td>{{event("change")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">DOM L2</a>, <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#event-input-change">HTML5</a></td> + <td>The <code>change</code> event is fired for {{HTMLElement("input")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}} elements when a change to the element's value is committed by the user.</td> + </tr> + <tr> + <td>{{event("chargingchange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="https://dvcs.w3.org/hg/dap/raw-file/tip/battery/Overview.html">Battery status</a></td> + <td>The battery begins or stops charging.</td> + </tr> + <tr> + <td>{{event("chargingtimechange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="https://dvcs.w3.org/hg/dap/raw-file/tip/battery/Overview.html">Battery status</a></td> + <td>The <code>chargingTime</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{event("checking")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The user agent is checking for an update, or attempting to download the cache manifest for the first time.</td> + </tr> + <tr> + <td>{{event("click")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-click">DOM L3</a></td> + <td>A pointing device button has been pressed and released on an element.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/close_websocket">close</a></code></td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/websockets/">WebSocket</a></td> + <td>A WebSocket connection has been closed.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/complete_indexedDB">complete</a></code></td> + <td> </td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/IndexedDB/#transaction">IndexedDB</a></td> + <td>A transaction successfully completed.</td> + </tr> + <tr> + <td>{{event("complete")}}</td> + <td>{{domxref("OfflineAudioCompletionEvent")}} {{deprecated_inline}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}</td> + <td>The rendering of an {{domxref("OfflineAudioContext")}} is terminated.</td> + </tr> + <tr> + <td>{{event("compositionend")}}{{gecko_minversion_inline("9")}}</td> + <td>{{domxref("CompositionEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-compositionend">DOM L3</a></td> + <td>The composition of a passage of text has been completed or canceled.</td> + </tr> + <tr> + <td>{{event("compositionstart")}}{{gecko_minversion_inline("9")}}</td> + <td>{{domxref("CompositionEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-compositionstart">DOM L3</a></td> + <td>The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).</td> + </tr> + <tr> + <td>{{event("compositionupdate")}}{{gecko_minversion_inline("9")}}</td> + <td>{{domxref("CompositionEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-compositionupdate">DOM L3</a></td> + <td>A character is added to a passage of text being composed.</td> + </tr> + <tr> + <td>{{event("contextmenu")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="https://html.spec.whatwg.org/multipage/forms.html#context-menus">HTML5</a></td> + <td>The right button of the mouse is clicked (before the context menu is displayed).</td> + </tr> + <tr> + <td>{{event("copy")}}</td> + <td>{{domxref("ClipboardEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/clipboard-apis/#copy-event">Clipboard</a></td> + <td>The text selection has been added to the clipboard.</td> + </tr> + <tr> + <td>{{event("cut")}}</td> + <td>{{domxref("ClipboardEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/clipboard-apis/#cut-event">Clipboard</a></td> + <td>The text selection has been removed from the document and added to the clipboard.</td> + </tr> + <tr> + <td>{{event("dblclick")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-dblclick">DOM L3</a></td> + <td>A pointing device button is clicked twice on an element.</td> + </tr> + <tr> + <td>{{event("devicechange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName("Media Capture")}}</td> + <td>A media device such as a camera, microphone, or speaker is connected or removed from the system.</td> + </tr> + <tr> + <td>{{event("devicelight")}}</td> + <td>{{domxref("DeviceLightEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a class="external" href="http://dvcs.w3.org/hg/dap/raw-file/tip/light/Overview.html" lang="en" title="The definition of 'Ambient Light Events' in that specification.">Ambient Light Events</a></td> + <td>Fresh data is available from a light sensor.</td> + </tr> + <tr> + <td>{{event("devicemotion")}}</td> + <td>{{domxref("DeviceMotionEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a class="external" href="http://dev.w3.org/geo/api/spec-source-orientation.html" lang="en" title="The 'Device Orientation Events' specification">Device Orientation Events</a></td> + <td>Fresh data is available from a motion sensor.</td> + </tr> + <tr> + <td>{{event("deviceorientation")}}</td> + <td>{{domxref("DeviceOrientationEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a class="external" href="http://dev.w3.org/geo/api/spec-source-orientation.html" lang="en" title="The 'Device Orientation Events' specification">Device Orientation Events</a></td> + <td>Fresh data is available from an orientation sensor.</td> + </tr> + <tr> + <td>{{event("deviceproximity")}}</td> + <td>{{domxref("DeviceProximityEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a class="external" href="http://dvcs.w3.org/hg/dap/raw-file/tip/proximity/Overview.html" lang="en" title="The definition of 'Proximity Events' in that specification.">Proximity Events</a></td> + <td>Fresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).</td> + </tr> + <tr> + <td>{{event("dischargingtimechange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="https://dvcs.w3.org/hg/dap/raw-file/tip/battery/Overview.html">Battery status</a></td> + <td>The <code>dischargingTime</code> attribute has been updated.</td> + </tr> + <tr> + <td><code>DOMActivate</code> {{deprecated_inline}}</td> + <td>{{domxref("UIEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMActivate">DOM L3</a></td> + <td>A button, link or state changing element is activated (use {{event("click")}} instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMAttributeNameChanged</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationNameEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/2011/WD-DOM-Level-3-Events-20110531/#event-type-DOMAttributeNameChanged">DOM L3</a> Removed</td> + <td>The name of an attribute changed (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMAttrModified</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMAttrModified">DOM L3</a></td> + <td>The value of an attribute has been modified (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMCharacterDataModified</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMCharacterDataModified">DOM L3</a></td> + <td>A text or another <a href="/en-US/docs/DOM/CharacterData">CharacterData</a> has changed (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td>{{event("DOMContentLoaded")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#the-end">HTML5</a></td> + <td>The document has finished loading (but not its dependent resources).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMElementNameChanged</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationNameEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/2011/WD-DOM-Level-3-Events-20110531/#event-type-DOMElementNameChanged">DOM L3</a> Removed</td> + <td>The name of an element changed (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code>DOMFocusIn</code> {{deprecated_inline}}</td> + <td>{{domxref("FocusEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMFocusIn">DOM L3</a></td> + <td>An element has received focus (use {{event("focus")}} or {{event("focusin")}} instead).</td> + </tr> + <tr> + <td><code>DOMFocusOut</code> {{deprecated_inline}}</td> + <td>{{domxref("FocusEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMFocusOut">DOM L3</a></td> + <td>An element has lost focus (use {{event("blur")}} or {{event("focusout")}} instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeInserted</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted">DOM L3</a></td> + <td>A node has been added as a child of another node (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeInsertedIntoDocument</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInsertedIntoDocument">DOM L3</a></td> + <td>A node has been inserted into the document (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeRemoved</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemoved">DOM L3</a></td> + <td>A node has been removed from its parent node (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMNodeRemovedFromDocument</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemovedFromDocument">DOM L3</a></td> + <td>A node has been removed from the document (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/DOM/Mutation_events">DOMSubtreeModified</a></code> {{deprecated_inline}}</td> + <td>{{domxref("MutationEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMSubtreeModified">DOM L3</a></td> + <td>A change happened in the document (use <a href="/en-US/docs/DOM/MutationObserver">mutation observers</a> instead).</td> + </tr> + <tr> + <td>{{event("downloading")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.</td> + </tr> + <tr> + <td>{{event("drag")}}</td> + <td>{{domxref("DragEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-drag">HTML5</a></td> + <td>An element or text selection is being dragged (every 350ms).</td> + </tr> + <tr> + <td>{{event("dragend")}}</td> + <td>{{domxref("DragEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragend">HTML5</a></td> + <td>A drag operation is being ended (by releasing a mouse button or hitting the escape key).</td> + </tr> + <tr> + <td>{{event("dragenter")}}</td> + <td>{{domxref("DragEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragenter">HTML5</a></td> + <td>A dragged element or text selection enters a valid drop target.</td> + </tr> + <tr> + <td>{{event("dragleave")}}</td> + <td>{{domxref("DragEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragleave">HTML5</a></td> + <td>A dragged element or text selection leaves a valid drop target.</td> + </tr> + <tr> + <td>{{event("dragover")}}</td> + <td>{{domxref("DragEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragover">HTML5</a></td> + <td>An element or text selection is being dragged over a valid drop target (every 350ms).</td> + </tr> + <tr> + <td>{{event("dragstart")}}</td> + <td>{{domxref("DragEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-dragstart">HTML5</a></td> + <td>The user starts dragging an element or text selection.</td> + </tr> + <tr> + <td>{{event("drop")}}</td> + <td>{{domxref("DragEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#event-drop">HTML5</a></td> + <td>An element is dropped on a valid drop target.</td> + </tr> + <tr> + <td>{{event("durationchange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-durationchange">HTML5 media</a></td> + <td>The <code>duration</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{event("emptied")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-emptied">HTML5 media</a></td> + <td>The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the <a href="/en-US/docs/XPCOM_Interface_Reference/NsIDOMHTMLMediaElement" rel="internal"><code>load()</code></a> method is called to reload it.</td> + </tr> + <tr> + <td>{{event("end_(SpeechRecognition)","end")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The speech recognition service has disconnected.</td> + </tr> + <tr> + <td>{{event("end_(SpeechSynthesis)","end")}} {{experimental_inline}}</td> + <td>{{domxref("SpeechSynthesisEvent")}}</td> + <td style="white-space: nowrap;">{{SpecName("Web Speech API")}}</td> + <td>The utterance has finished being spoken.</td> + </tr> + <tr> + <td>{{event("ended")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-ended">HTML5 media</a></td> + <td>Playback has stopped because the end of the media was reached.</td> + </tr> + <tr> + <td>{{event("ended_(Web_Audio)", "ended")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName("Web Audio API")}}</td> + <td>Playback has stopped because the end of the media was reached.</td> + </tr> + <tr> + <td>{{event("endEvent")}}</td> + <td>{{domxref("TimeEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>A <a href="/en-US/docs/SVG/SVG_animation_with_SMIL">SMIL</a> animation element ends.</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-error">DOM L3</a></td> + <td>A resource failed to load.</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>{{domxref("ProgressEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/progress-events/">Progress</a><span> and </span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-error">XMLHttpRequest</a></td> + <td>Progresso falhou.</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>An error occurred while downloading the cache manifest or updating the content of the application.</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/websockets/">WebSocket</a></td> + <td>A WebSocket connection has been closed with prejudice (some data couldn't be sent for example).</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://dev.w3.org/html5/eventsource/">Server Sent Events</a></td> + <td>An event source connection has been failed.</td> + </tr> + <tr> + <td>{{event("error")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/IndexedDB/#request-api">IndexedDB</a></td> + <td>A request caused an error and failed.</td> + </tr> + <tr> + <td>{{event("error_(SpeechRecognitionError)","error")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>A speech recognition error occurs.</td> + </tr> + <tr> + <td>{{event("error_(SpeechSynthesisError)","error")}}</td> + <td>{{domxref("SpeechSynthesisErrorEvent")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>An error occurs that prevents the utterance from being successfully spoken.</td> + </tr> + <tr> + <td>{{event("focus")}}</td> + <td>{{domxref("FocusEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-focus">DOM L3</a></td> + <td>An element has received focus (does not bubble).</td> + </tr> + <tr> + <td>{{event("focusin")}}</td> + <td>{{domxref("FocusEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-focusIn">DOM L3</a></td> + <td>An element is about to receive focus (bubbles).</td> + </tr> + <tr> + <td>{{event("focusout")}}</td> + <td>{{domxref("FocusEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-focusout">DOM L3</a></td> + <td>An element is about to lose focus (bubbles).</td> + </tr> + <tr> + <td>{{event("fullscreenchange")}}{{gecko_minversion_inline("9")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html#api">Full Screen</a></td> + <td>An element was turned to fullscreen mode or back to normal mode.</td> + </tr> + <tr> + <td>{{event("fullscreenerror")}}{{gecko_minversion_inline("9")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html#api">Full Screen</a></td> + <td>It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.</td> + </tr> + <tr> + <td>{{event("gamepadconnected")}}</td> + <td>{{domxref("GamepadEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/gamepad/#the-gamepadconnected-event">Gamepad</a></td> + <td>A gamepad has been connected.</td> + </tr> + <tr> + <td>{{event("gamepaddisconnected")}}</td> + <td>{{domxref("GamepadEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/gamepad/#the-gamepaddisconnected-event">Gamepad</a></td> + <td>A gamepad has been disconnected.</td> + </tr> + <tr> + <td>{{event("gotpointercapture")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-gotpointercapture-event">Pointer Events</a></td> + <td>Element receives pointer capture.</td> + </tr> + <tr> + <td>{{event("hashchange")}}</td> + <td>{{domxref("HashChangeEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-hashchange">HTML5</a></td> + <td>The fragment identifier of the URL has changed (the part of the URL after the #).</td> + </tr> + <tr> + <td>{{event("lostpointercapture")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-lostpointercapture-event">Pointer Events</a></td> + <td>Element lost pointer capture.</td> + </tr> + <tr> + <td>{{event("input")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/html5/forms.html#common-event-behaviors">HTML5</a></td> + <td>The value of an element changes or the content of an element with the attribute <a href="/en-US/docs/DOM/Element.contentEditable">contenteditable</a> is modified.</td> + </tr> + <tr> + <td>{{event("invalid")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#constraint-validation">HTML5</a></td> + <td>A submittable element has been checked and doesn't satisfy its constraints.</td> + </tr> + <tr> + <td>{{event("keydown")}}</td> + <td>{{domxref("KeyboardEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keydown">DOM L3</a></td> + <td>A key is pressed down.</td> + </tr> + <tr> + <td>{{event("keypress")}}</td> + <td>{{domxref("KeyboardEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keypress">DOM L3</a></td> + <td>A key is pressed down and that key normally produces a character value (use input instead).</td> + </tr> + <tr> + <td>{{event("keyup")}}</td> + <td>{{domxref("KeyboardEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-keyup">DOM L3</a></td> + <td>A key is released.</td> + </tr> + <tr> + <td>{{event("languagechange")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}</td> + <td>The user's preferred languages have changed.</td> + </tr> + <tr> + <td>{{event("levelchange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="https://dvcs.w3.org/hg/dap/raw-file/tip/battery/Overview.html">Battery status</a></td> + <td>The <code>level</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{event("load")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-load">DOM L3</a></td> + <td>A resource and its dependent resources have finished loading.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/load_(ProgressEvent)">load</a></code></td> + <td>{{domxref("ProgressEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/progress-events/">Progress</a><span> <span>and </span></span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-load">XMLHttpRequest</a></td> + <td>Progression has been successful.</td> + </tr> + <tr> + <td>{{event("loadeddata")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-loadeddata">HTML5 media</a></td> + <td>The first frame of the media has finished loading.</td> + </tr> + <tr> + <td>{{event("loadedmetadata")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-loadedmetadata">HTML5 media</a></td> + <td>The metadata has been loaded.</td> + </tr> + <tr> + <td>{{event("loadend")}}</td> + <td>{{domxref("ProgressEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/progress-events/">Progress</a><span> <span>and </span></span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-loadend">XMLHttpRequest</a></td> + <td>Progress has stopped (after "error", "abort" or "load" have been dispatched).</td> + </tr> + <tr> + <td>{{event("loadstart")}}</td> + <td>{{domxref("ProgressEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/progress-events/">Progress </a><span>and </span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-loadstart">XMLHttpRequest</a></td> + <td>Progresso começou.</td> + </tr> + <tr> + <td>{{event("mark")}} {{experimental_inline}}</td> + <td>{{domxref("SpeechSynthesisEvent")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The spoken utterance reaches a named SSML "mark" tag.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_websocket">message</a></code></td> + <td>{{domxref("MessageEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/websockets/">WebSocket</a></td> + <td>A message is received through a WebSocket.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_webworker">message</a></code></td> + <td>{{domxref("MessageEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/workers/#communicating-with-a-dedicated-worker">Web Workers</a></td> + <td>A message is received from a Web Worker.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_webmessaging">message</a></code></td> + <td>{{domxref("MessageEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/webmessaging/">Web Messaging</a></td> + <td>A message is received from a child (i)frame or a parent window.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/message_serversentevents">message</a></code></td> + <td>{{domxref("MessageEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://dev.w3.org/html5/eventsource/">Server Sent Events</a></td> + <td>A message is received through an event source.</td> + </tr> + <tr> + <td>{{event("messageerror")}}</td> + <td>{{domxref("MessageEvent")}}</td> + <td style="white-space: nowrap;">{{domxref("MessagePort")}}, <a href="/en-US/docs/Web/API/Web_Workers_API">Web Workers</a>, <a href="/en-US/docs/Web/API/Broadcast_Channel_API">Broadcast Channel</a>, {{domxref("Window")}}</td> + <td>A message error is raised when a message is received by an object.</td> + </tr> + <tr> + <td>{{event("message_(ServiceWorker)","message")}} {{experimental_inline}}</td> + <td>{{domxref("ServiceWorkerMessageEvent")}} or {{domxref("ExtendableMessageEvent")}}, depending on context.</td> + <td style="white-space: nowrap;"><a href="/en-US/docs/Web/API/Service_Worker_API">Service Workers</a></td> + <td>A message is received from a service worker, or a message is received in a service worker from another context.</td> + </tr> + <tr> + <td>{{event("mousedown")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mousedown">DOM L3</a></td> + <td>A pointing device button (usually a mouse) is pressed on an element.</td> + </tr> + <tr> + <td>{{event("mouseenter")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseenter">DOM L3</a></td> + <td>A pointing device is moved onto the element that has the listener attached.</td> + </tr> + <tr> + <td>{{event("mouseleave")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseleave">DOM L3</a></td> + <td>A pointing device is moved off the element that has the listener attached.</td> + </tr> + <tr> + <td>{{event("mousemove")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mousemove">DOM L3</a></td> + <td>A pointing device is moved over an element.</td> + </tr> + <tr> + <td>{{event("mouseout")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseout">DOM L3</a></td> + <td>A pointing device is moved off the element that has the listener attached or off one of its children.</td> + </tr> + <tr> + <td>{{event("mouseover")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseover">DOM L3</a></td> + <td>A pointing device is moved onto the element that has the listener attached or onto one of its children.</td> + </tr> + <tr> + <td>{{event("mouseup")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseup">DOM L3</a></td> + <td>A pointing device button is released over an element.</td> + </tr> + <tr> + <td>{{event("nomatch")}} {{experimental_inline}}</td> + <td>{{domxref("SpeechRecognitionEvent")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The speech recognition service returns a final result with no significant recognition.</td> + </tr> + <tr> + <td>{{event("notificationclick")}}</td> + <td>{{domxref("NotificationEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}</td> + <td>A system notification<span style="line-height: 19.0909080505371px;"> spawned by {{domxref("ServiceWorkerRegistration.showNotification()")}} has been clicked.</span></td> + </tr> + <tr> + <td>{{event("noupdate")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The manifest hadn't changed.</td> + </tr> + <tr> + <td>{{event("obsolete")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The manifest was found to have become a 404 or 410 page, so the application cache is being deleted.</td> + </tr> + <tr> + <td>{{event("offline")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#event-offline">HTML5 offline</a></td> + <td>The browser has lost access to the network.</td> + </tr> + <tr> + <td>{{event("online")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#event-online">HTML5 offline</a></td> + <td>The browser has gained access to the network (but particular websites might be unreachable).</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/open_websocket">open</a></code></td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/websockets/">WebSocket</a></td> + <td>A WebSocket connection has been established.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/open_serversentevents">open</a></code></td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://dev.w3.org/html5/eventsource/">Server Sent Events</a></td> + <td>An event source connection has been established.</td> + </tr> + <tr> + <td>{{event("orientationchange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/screen-orientation/">Screen Orientation</a></td> + <td>The orientation of the device (portrait/landscape) has changed</td> + </tr> + <tr> + <td>{{event("pagehide")}}</td> + <td>{{domxref("PageTransitionEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-pagehide">HTML5</a></td> + <td>A session history entry is being traversed from.</td> + </tr> + <tr> + <td>{{event("pageshow")}}</td> + <td>{{domxref("PageTransitionEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-pageshow">HTML5</a></td> + <td>A session history entry is being traversed to.</td> + </tr> + <tr> + <td>{{event("paste")}}</td> + <td>{{domxref("ClipboardEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/clipboard-apis/#paste-event">Clipboard</a></td> + <td>Data has been transferred from the system clipboard to the document.</td> + </tr> + <tr> + <td>{{event("pause")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-pause">HTML5 media</a></td> + <td>Playback has been paused.</td> + </tr> + <tr> + <td>{{event("pause_(SpeechSynthesis)", "pause")}} {{experimental_inline}}</td> + <td>{{domxref("SpeechSynthesisEvent")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The utterance is paused part way through.</td> + </tr> + <tr> + <td>{{event("pointercancel")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-pointercancel-event">Pointer Events</a></td> + <td>The pointer is unlikely to produce any more events.</td> + </tr> + <tr> + <td>{{event("pointerdown")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-pointerdown-event">Pointer Events</a></td> + <td>The pointer enters the active buttons state.</td> + </tr> + <tr> + <td>{{event("pointerenter")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-pointerenter-event">Pointer Events</a></td> + <td>Pointing device is moved inside the hit-testing boundary.</td> + </tr> + <tr> + <td>{{event("pointerleave")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-pointerleave-event">Pointer Events</a></td> + <td>Pointing device is moved out of the hit-testing boundary.</td> + </tr> + <tr> + <td>{{event("pointerlockchange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerlock/#pointerlockchange-and-pointerlockerror-events">Pointer Lock</a></td> + <td>The pointer was locked or released.</td> + </tr> + <tr> + <td>{{event("pointerlockerror")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerlock/#pointerlockchange-and-pointerlockerror-events">Pointer Lock</a></td> + <td>It was impossible to lock the pointer for technical reasons or because the permission was denied.</td> + </tr> + <tr> + <td>{{event("pointermove")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-pointermove-event">Pointer Events</a></td> + <td>The pointer changed coordinates.</td> + </tr> + <tr> + <td>{{event("pointerout")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-pointerout-event">Pointer Events</a></td> + <td>The pointing device moved out of hit-testing boundary or leaves detectable hover range.</td> + </tr> + <tr> + <td>{{event("pointerover")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-pointerover-event">Pointer Events</a></td> + <td>The pointing device is moved into the hit-testing boundary.</td> + </tr> + <tr> + <td>{{event("pointerup")}}</td> + <td>{{domxref("PointerEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/pointerevents/#the-pointerup-event">Pointer Events</a></td> + <td>The pointer leaves the active buttons state.</td> + </tr> + <tr> + <td>{{event("play")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-play">HTML5 media</a></td> + <td>Playback has begun.</td> + </tr> + <tr> + <td>{{event("playing")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-playing">HTML5 media</a></td> + <td>Playback is ready to start after having been paused or delayed due to lack of data.</td> + </tr> + <tr> + <td>{{event("popstate")}}</td> + <td>{{domxref("PopStateEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-popstate">HTML5</a></td> + <td>A session history entry is being navigated to (in certain cases).</td> + </tr> + <tr> + <td>{{event("progress")}}</td> + <td>{{domxref("ProgressEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/progress-events/">Progress</a><span> <span>and </span></span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-progress">XMLHttpRequest</a></td> + <td>Em progresso.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/progress_(appcache_event)">progress</a></code></td> + <td>{{domxref("ProgressEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/html/wg/drafts/html/master/browsers.html#offline">Offline</a></td> + <td>The user agent is downloading resources listed by the manifest.</td> + </tr> + <tr> + <td>{{event("push")}}</td> + <td>{{domxref("PushEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;">{{SpecName("Push API")}}</td> + <td>A <a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker</a> has received a push message.</td> + </tr> + <tr> + <td>{{event("pushsubscriptionchange")}}</td> + <td>{{domxref("PushEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;">{{SpecName("Push API")}}</td> + <td>A <a href="/en-US/docs/Web/API/PushSubscription">PushSubscription</a> has expired.</td> + </tr> + <tr> + <td>{{event("ratechange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-ratechange">HTML5 media</a></td> + <td>The playback rate has changed.</td> + </tr> + <tr> + <td>{{event("readystatechange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><span>HTML5 <span>and </span></span><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-readystatechange">XMLHttpRequest</a></td> + <td>The readyState attribute of a document has changed.</td> + </tr> + <tr> + <td>{{event("repeatEvent")}}</td> + <td>{{domxref("TimeEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>A <a href="/en-US/docs/SVG/SVG_animation_with_SMIL">SMIL</a> animation element is repeated.</td> + </tr> + <tr> + <td>{{event("reset")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">DOM L2</a>, <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-0#resetting-a-form">HTML5</a></td> + <td>A form is reset.</td> + </tr> + <tr> + <td>{{event("resize")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-resize">DOM L3</a></td> + <td>The document view has been resized.</td> + </tr> + <tr> + <td>{{event("resourcetimingbufferfull")}}</td> + <td>{{domxref("Performance")}}</td> + <td style="white-space: nowrap;"><a href="https://w3c.github.io/resource-timing/#dom-performance-onresourcetimingbufferfull">Resource Timing</a></td> + <td>The browser's resource timing buffer is full.</td> + </tr> + <tr> + <td>{{event("result")}} {{experimental_inline}}</td> + <td>{{domxref("SpeechRecognitionEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.</td> + </tr> + <tr> + <td>{{event("resume")}} {{experimental_inline}}</td> + <td>{{domxref("SpeechSynthesisEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>A paused utterance is resumed.</td> + </tr> + <tr> + <td>{{event("scroll")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-scroll">DOM L3</a></td> + <td>The document view or an element has been scrolled.</td> + </tr> + <tr> + <td>{{event("seeked")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-seeked">HTML5 media</a></td> + <td>A <em>seek</em> operation completed.</td> + </tr> + <tr> + <td>{{event("seeking")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-seeking">HTML5 media</a></td> + <td>A <em>seek</em> operation began.</td> + </tr> + <tr> + <td>{{event("select")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-select">DOM L3</a></td> + <td>Some text is being selected.</td> + </tr> + <tr> + <td>{{event("selectstart")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{ SpecName('Selection API')}}</td> + <td>A selection just started.</td> + </tr> + <tr> + <td>{{event("selectionchange")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{ SpecName('Selection API')}}</td> + <td>The selection in the document has been changed.</td> + </tr> + <tr> + <td>{{event("show")}}</td> + <td>{{domxref("MouseEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/html5/interactive-elements.html#context-menus">HTML5</a></td> + <td>A contextmenu event was fired on/bubbled to an element that has a <a href="/en-US/docs/DOM/element.contextmenu">contextmenu</a> attribute</td> + </tr> + <tr> + <td>{{event("soundend")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>Any sound — recognisable speech or not — has stopped being detected.</td> + </tr> + <tr> + <td>{{event("soundstart")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>Any sound — recognisable speech or not — has been detected.</td> + </tr> + <tr> + <td>{{event("speechend")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>Speech recognised by the speech recognition service has stopped being detected.</td> + </tr> + <tr> + <td>{{event("speechstart")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>Sound that is recognised by the speech recognition service as speech has been detected.</td> + </tr> + <tr> + <td>{{event("stalled")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-stalled">HTML5 media</a></td> + <td>The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.</td> + </tr> + <tr> + <td>{{event("start_(SpeechRecognition)","start")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current <code>SpeechRecognition</code>.</td> + </tr> + <tr> + <td>{{event("start_(SpeechSynthesis)","start")}}</td> + <td>{{domxref("SpeechSynthesisEvent")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The utterance has begun to be spoken.</td> + </tr> + <tr> + <td>{{event("storage")}}</td> + <td>{{domxref("StorageEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/webstorage/#the-storage-event">Web Storage</a></td> + <td>A storage area (<a href="/en-US/docs/DOM/Storage#localStorage">localStorage</a> or <a href="/en-US/docs/DOM/Storage#sessionStorage">sessionStorage</a>) has changed.</td> + </tr> + <tr> + <td>{{event("submit")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">DOM L2</a>, <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-submission-algorithm">HTML5</a></td> + <td>A form is submitted.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/success_indexedDB">success</a></code></td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/IndexedDB/#request-api">IndexedDB</a></td> + <td>A request successfully completed.</td> + </tr> + <tr> + <td>{{event("suspend")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-suspend">HTML5 media</a></td> + <td>Media data loading has been suspended.</td> + </tr> + <tr> + <td>{{event("SVGAbort")}}</td> + <td>{{domxref("SVGEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>Page loading has been stopped before the <a href="/en-US/docs/SVG">SVG</a> was loaded.</td> + </tr> + <tr> + <td>{{event("SVGError")}}</td> + <td>{{domxref("SVGEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An error has occurred before the <a href="/en-US/docs/SVG">SVG</a> was loaded.</td> + </tr> + <tr> + <td>{{event("SVGLoad")}}</td> + <td>{{domxref("SVGEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document has been loaded and parsed.</td> + </tr> + <tr> + <td>{{event("SVGResize")}}</td> + <td>{{domxref("SVGEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document is being resized.</td> + </tr> + <tr> + <td>{{event("SVGScroll")}}</td> + <td>{{domxref("SVGEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document is being scrolled.</td> + </tr> + <tr> + <td>{{event("SVGUnload")}}</td> + <td>{{domxref("SVGEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document has been removed from a window or frame.</td> + </tr> + <tr> + <td>{{event("SVGZoom")}}</td> + <td>{{domxref("SVGZoomEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/SVG/interact.html#SVGEvents">SVG</a></td> + <td>An <a href="/en-US/docs/SVG">SVG</a> document is being zoomed.</td> + </tr> + <tr> + <td>{{event("timeout")}}</td> + <td>{{domxref("ProgressEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/XMLHttpRequest/#event-xhr-timeout">XMLHttpRequest</a></td> + <td> </td> + </tr> + <tr> + <td>{{event("timeupdate")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-timeupdate">HTML5 media</a></td> + <td>The time indicated by the <code>currentTime</code> attribute has been updated.</td> + </tr> + <tr> + <td>{{event("touchcancel")}}</td> + <td>{{domxref("TouchEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/touch-events/">Touch Events</a></td> + <td>A touch point has been disrupted in an implementation-specific manners (too many touch points for example).</td> + </tr> + <tr> + <td>{{event("touchend")}}</td> + <td>{{domxref("TouchEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/touch-events/#the-touchend-event">Touch Events</a></td> + <td>A touch point is removed from the touch surface.</td> + </tr> + <tr> + <td>{{event("touchmove")}}</td> + <td>{{domxref("TouchEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/touch-events/#the-touchmove-event">Touch Events</a></td> + <td>A touch point is moved along the touch surface.</td> + </tr> + <tr> + <td>{{event("touchstart")}}</td> + <td>{{domxref("TouchEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/touch-events/#the-touchstart---------event">Touch Events</a></td> + <td>A touch point is placed on the touch surface.</td> + </tr> + <tr> + <td>{{event("transitionend")}}</td> + <td>{{domxref("TransitionEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/css3-transitions/#transition-events">CSS Transitions</a></td> + <td>A <a href="/en-US/docs/CSS/CSS_transitions">CSS transition</a> has completed.</td> + </tr> + <tr> + <td>{{event("unload")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-unload">DOM L3</a></td> + <td>The document or a dependent resource is being unloaded.</td> + </tr> + <tr> + <td>{{event("updateready")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://dev.w3.org/html5/spec/offline.html">Offline</a></td> + <td>The resources listed in the manifest have been newly redownloaded, and the script can use <code>swapCache()</code> to switch to the new cache.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/upgradeneeded_indexedDB">upgradeneeded</a></code></td> + <td> </td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/IndexedDB/#request-api">IndexedDB</a></td> + <td>An attempt was made to open a database with a version number higher than its current version. A <code>versionchange</code> transaction has been created.</td> + </tr> + <tr> + <td>{{event("userproximity")}}</td> + <td>{{domxref("UserProximityEvent")}} {{experimental_inline}}</td> + <td style="white-space: nowrap;">{{SpecName("Proximity Events")}}</td> + <td>Fresh data is available from a proximity sensor (indicates whether the nearby object is <code>near</code> the device or not).</td> + </tr> + <tr> + <td>{{event("voiceschanged")}} {{experimental_inline}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;">{{SpecName('Web Speech API')}}</td> + <td>The list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the {{event("voiceschanged")}} event fires.)</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/Reference/Events/versionchange_indexedDB">versionchange</a></code></td> + <td> </td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/IndexedDB/#database-interface">IndexedDB</a></td> + <td>A <code>versionchange</code> transaction completed.</td> + </tr> + <tr> + <td>{{event("visibilitychange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/page-visibility/#sec-visibilitychange-event">Page visibility</a></td> + <td>The content of a tab has become visible or has been hidden.</td> + </tr> + <tr> + <td>{{event("volumechange")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-volumechange">HTML5 media</a></td> + <td>The volume has changed.</td> + </tr> + <tr> + <td>{{event("waiting")}}</td> + <td>{{domxref("Event")}}</td> + <td style="white-space: nowrap;"><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#event-media-waiting">HTML5 media</a></td> + <td>Playback has stopped because of a temporary lack of data.</td> + </tr> + <tr> + <td>{{event("wheel")}}{{gecko_minversion_inline("17")}}</td> + <td>{{domxref("WheelEvent")}}</td> + <td style="white-space: nowrap;"><a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-wheel">DOM L3</a></td> + <td>A wheel button of a pointing device is rotated in any direction.</td> + </tr> + </tbody> +</table> + +<h2 id="Eventos_não_padrão">Eventos não padrão</h2> + +<table class="standard-table" style="width: 100%;"> + <thead> + <tr> + <th class="header" style="width: 220px;">Nome do Evento</th> + <th class="header" style="width: 90px;">Tipo de Evento</th> + <th class="header" style="width: 100px;">Especificação</th> + <th class="header">Executado quando...</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{event("afterscriptexecute")}}</td> + <td>{{domxref("Event")}}</td> + <td><em>Mozilla Specific</em></td> + <td>A script has been executed.</td> + </tr> + <tr> + <td>{{event("beforescriptexecute")}}</td> + <td>{{domxref("Event")}}</td> + <td><em>Mozilla Specific</em></td> + <td>A script is about to be executed.</td> + </tr> + <tr> + <td>{{event("beforeinstallprompt")}}</td> + <td>{{domxref("Event")}}</td> + <td><em>Chrome specific</em></td> + <td>A user is prompted to save a web site to a home screen on mobile.</td> + </tr> + <tr> + <td>{{event("cardstatechange")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>The {{domxref("MozMobileConnection.cardState")}} property changes value.</td> + </tr> + <tr> + <td>{{event("change")}}</td> + <td>{{domxref("DeviceStorageChangeEvent")}}</td> + <td><em>Firefox OS specific</em></td> + <td>This event is triggered each time a file is created, modified or deleted on a given storage area.</td> + </tr> + <tr> + <td>{{event("connectionInfoUpdate")}}</td> + <td> </td> + <td><a href="http://mxr.mozilla.org/mozilla-central/source/dom/wifi/nsIWifi.idl?rev=3e586802f478#176"><em>Firefox OS specific</em></a></td> + <td>The informations about the signal strength and the link speed have been updated.</td> + </tr> + <tr> + <td>{{event("cfstatechange")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>The call forwarding state changes.</td> + </tr> + <tr> + <td>{{event("datachange")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>The {{domxref("MozMobileConnection.data")}} object changes values.</td> + </tr> + <tr> + <td>{{event("dataerror")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>The {{domxref("MozMobileConnection.data")}} object receive an error from the <abbr title="Radio Interface Layer">RIL</abbr>.</td> + </tr> + <tr> + <td>{{event("DOMMouseScroll")}}{{deprecated_inline}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>The wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{event("wheel")}} instead)</td> + </tr> + <tr> + <td><code>dragdrop</code> {{deprecated_inline}}</td> + <td><code>DragEvent</code></td> + <td><em>Mozilla specific</em></td> + <td>An element is dropped (use {{event("drop")}} instead).</td> + </tr> + <tr> + <td><code>dragexit</code> {{deprecated_inline}}</td> + <td><code>DragEvent</code></td> + <td><em>Mozilla specific</em></td> + <td>A drag operation is being ended(use {{event("dragend")}} instead).</td> + </tr> + <tr> + <td><code>draggesture</code> {{deprecated_inline}}</td> + <td><code>DragEvent</code></td> + <td><em>Mozilla specific</em></td> + <td>The user starts dragging an element or text selection (use {{event("dragstart")}} instead).</td> + </tr> + <tr> + <td>{{event("icccardlockerror")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>the {{domxref("MozMobileConnection.unlockCardLock()")}} or {{domxref("MozMobileConnection.setCardLock()")}} methods fails.</td> + </tr> + <tr> + <td>{{event("iccinfochange")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>The {{domxref("MozMobileConnection.iccInfo")}} object changes.</td> + </tr> + <tr> + <td>{{event("localized")}}</td> + <td> </td> + <td><em><a href="https://github.com/fabi1cazenave/webL10n">Mozilla Specific</a></em></td> + <td>The page has been localized using data-l10n-* attributes.</td> + </tr> + <tr> + <td>{{event("mousewheel")}}{{deprecated_inline}}</td> + <td> </td> + <td><a href="http://msdn.microsoft.com/en-us/library/ie/ms536951%28v=vs.85%29.aspx"><em>IE invented</em></a></td> + <td>The wheel button of a pointing device is rotated.</td> + </tr> + <tr> + <td>{{event("MozAudioAvailable")}}</td> + <td>{{domxref("Event")}}</td> + <td><em>Mozilla specific</em></td> + <td>The audio buffer is full and the corresponding raw samples are available.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozBeforeResize"><code>MozBeforeResize</code></a> {{obsolete_inline}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>Uma janela está prestes a ser redimensionada.</td> + </tr> + <tr> + <td>{{event("mozbrowseractivitydone")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when some activity has been completed (complete description TBD.)</td> + </tr> + <tr> + <td>{{event("mozbrowserasyncscroll")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the scroll position within a browser<code> </code>{{HTMLElement("iframe")}} changes.</td> + </tr> + <tr> + <td>{{event("mozbrowseraudioplaybackchange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when audio starts or stops playing within the browser {{HTMLElement("iframe")}} content.</td> + </tr> + <tr> + <td>{{event("mozbrowsercaretstatechanged")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the text selected inside the browser {{HTMLElement("iframe")}} content changes.</td> + </tr> + <tr> + <td>{{event("mozbrowserclose")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when window.close() is called within a browser {{HTMLElement("iframe")}}.</td> + </tr> + <tr> + <td>{{event("mozbrowsercontextmenu")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a browser {{HTMLElement("iframe")}} try to open a context menu.</td> + </tr> + <tr> + <td>{{event("mozbrowserdocumentfirstpaint")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a new paint occurs on any document in the browser {{HTMLElement("iframe")}}.</td> + </tr> + <tr> + <td>{{event("mozbrowsererror")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when an error occured while trying to load a content within a browser iframe</td> + </tr> + <tr> + <td>{{event("mozbrowserfindchange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a search operation is performed on the browser {{HTMLElement("iframe")}} content (see <a href="/en-US/docs/Web/API/HTMLIFrameElement#Search_methods">HTMLIFrameElement search methods</a>.)</td> + </tr> + <tr> + <td>{{event("mozbrowserfirstpaint")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the {{HTMLElement("iframe")}} paints content for the first time (this doesn't include the initial paint from <em>about:blank</em>.)</td> + </tr> + <tr> + <td>{{event("mozbrowsericonchange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the favicon of a browser iframe changes.</td> + </tr> + <tr> + <td>{{event("mozbrowserlocationchange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when an browser iframe's location changes.</td> + </tr> + <tr> + <td>{{event("mozbrowserloadend")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the browser iframe has finished loading all its assets.</td> + </tr> + <tr> + <td>{{event("mozbrowserloadstart")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the browser iframe starts to load a new page.</td> + </tr> + <tr> + <td>{{event("mozbrowsermanifestchange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a the path to the app manifest changes, in the case of a browser {{HTMLElement("iframe")}} with an open web app embedded in it.</td> + </tr> + <tr> + <td>{{event("mozbrowsermetachange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a {{htmlelement("meta")}} elelment is added to, removed from or changed in the browser {{HTMLElement("iframe")}}'s content.</td> + </tr> + <tr> + <td>{{event("mozbrowseropensearch")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a link to a search engine is found.</td> + </tr> + <tr> + <td>{{event("mozbrowseropentab")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when a new tab is opened within a browser {{HTMLElement("iframe")}} as a result of the user issuing a command to open a link target in a new tab (for example <kbd>ctrl</kbd>/<kbd>cmd</kbd> + click.)</td> + </tr> + <tr> + <td>{{event("mozbrowseropenwindow")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when {{domxref("window.open()")}} is called within a browser iframe.</td> + </tr> + <tr> + <td>{{event("mozbrowserresize")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the browser {{HTMLElement("iframe")}}'s window size has changed.</td> + </tr> + <tr> + <td>{{event("mozbrowserscroll")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the browser {{HTMLElement("iframe")}} content scrolls.</td> + </tr> + <tr> + <td>{{event("mozbrowserscrollareachanged")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the available scrolling area in the browser {{HTMLElement("iframe")}} changes. This can occur on resize and when the page size changes (while loading for example.)</td> + </tr> + <tr> + <td>{{event("mozbrowserscrollviewchange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when asynchronous scrolling (i.e. APCZ) starts or stops.</td> + </tr> + <tr> + <td>{{event("mozbrowsersecuritychange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the SSL state changes within a browser iframe.</td> + </tr> + <tr> + <td>{{event("mozbrowserselectionstatechanged")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the text selected inside the browser {{HTMLElement("iframe")}} content changes. Note that this is deprecated, and newer implementations use {{event("mozbrowsercaretstatechanged")}} instead.</td> + </tr> + <tr> + <td>{{event("mozbrowsershowmodalprompt")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when {{domxref("window.alert","alert()")}}, {{domxref("window.confirm","confirm()")}} or {{domxref("window.prompt","prompt()")}} are called within a browser iframe</td> + </tr> + <tr> + <td>{{event("mozbrowsertitlechange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the document.title changes within a browser iframe.</td> + </tr> + <tr> + <td>{{event("mozbrowserusernameandpasswordrequired")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when an HTTP authentification is requested.</td> + </tr> + <tr> + <td>{{event("mozbrowservisibilitychange")}}</td> + <td> </td> + <td><em>Firefox OS <a href="/en-US/docs/Web/API/Browser_API">Browser API</a>-specific</em></td> + <td>Sent when the visibility state of the current browser iframe {{HTMLElement("iframe")}} changes, for example due to a call to {{domxref("HTMLIFrameElement.setVisible","setVisible()")}}.</td> + </tr> + <tr> + <td>{{event("MozGamepadButtonDown")}}</td> + <td> </td> + <td><em>To be specified</em></td> + <td>A gamepad button is pressed down.</td> + </tr> + <tr> + <td>{{event("MozGamepadButtonUp")}}</td> + <td> </td> + <td><em>To be specified</em></td> + <td>A gamepad button is released.</td> + </tr> + <tr> + <td>{{event("MozMousePixelScroll")}} {{deprecated_inline}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>The wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)</td> + </tr> + <tr> + <td>{{event("MozOrientation")}} {{deprecated_inline}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>Fresh data is available from an orientation sensor (see deviceorientation).</td> + </tr> + <tr> + <td>{{event("MozScrolledAreaChanged")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td><em>Mozilla specific</em></td> + <td>The document view has been scrolled or resized.</td> + </tr> + <tr> + <td>{{event("moztimechange")}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>The time of the device has been changed.</td> + </tr> + <tr> + <td><a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchDown</a> {{deprecated_inline}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>A touch point is placed on the touch surface (use touchstart instead).</td> + </tr> + <tr> + <td><a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchMove</a> {{deprecated_inline}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>A touch point is moved along the touch surface (use touchmove instead).</td> + </tr> + <tr> + <td><a href="/en-US/DOM/Touch_events_(Mozilla_experimental)">MozTouchUp</a> {{deprecated_inline}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>A touch point is removed from the touch surface (use touchend instead).</td> + </tr> + <tr> + <td>{{event("alerting")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>The correspondent is being alerted (his/her phone is ringing).</td> + </tr> + <tr> + <td>{{event("busy")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>The line of the correspondent is busy.</td> + </tr> + <tr> + <td>{{event("callschanged")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call has been added or removed from the list of current calls.</td> + </tr> + <tr> + <td><a href="/en-US/docs/DOM/onconnected">onconnected</a> {{event("connected")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call has been connected.</td> + </tr> + <tr> + <td>{{event("connecting")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is about to connect.</td> + </tr> + <tr> + <td>{{event("delivered")}}</td> + <td>{{domxref("SMSEvent")}}</td> + <td><em>To be specified</em></td> + <td>An SMS has been successfully delivered.</td> + </tr> + <tr> + <td>{{event("dialing")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>The number of a correspondent has been dialed.</td> + </tr> + <tr> + <td>{{event("disabled")}}</td> + <td> </td> + <td><a href="http://mxr.mozilla.org/mozilla-central/source/dom/wifi/nsIWifi.idl?rev=3e586802f478#182"><em>Firefox OS specific</em></a></td> + <td>Wifi has been disabled on the device.</td> + </tr> + <tr> + <td>{{event("disconnected")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call has been disconnected.</td> + </tr> + <tr> + <td>{{event("disconnecting")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is about to disconnect.</td> + </tr> + <tr> + <td>{{event("enabled")}}</td> + <td> </td> + <td><a href="http://mxr.mozilla.org/mozilla-central/source/dom/wifi/nsIWifi.idl?rev=3e586802f478#182"><em>Firefox OS specific</em></a></td> + <td>Wifi has been enabled on the device.</td> + </tr> + <tr> + <td>{{event("error_(Telephony)","error")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>An error occurred.</td> + </tr> + <tr> + <td>{{event("held")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call has been held.</td> + </tr> + <tr> + <td>{{event("holding")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is about to be held.</td> + </tr> + <tr> + <td>{{event("incoming")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is being received.</td> + </tr> + <tr> + <td>{{event("received")}}</td> + <td>{{domxref("SMSEvent")}}</td> + <td><em>To be specified</em></td> + <td>An SMS has been received.</td> + </tr> + <tr> + <td>{{event("resuming")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>A call is about to resume.</td> + </tr> + <tr> + <td>{{event("sent")}}</td> + <td>{{domxref("SMSEvent")}}</td> + <td><em>To be specified</em></td> + <td>An SMS has been sent.</td> + </tr> + <tr> + <td>{{event("statechange")}}</td> + <td>{{domxref("CallEvent")}}</td> + <td><em>To be specified</em></td> + <td>The state of a call has changed.</td> + </tr> + <tr> + <td>{{event("statuschange")}}</td> + <td> </td> + <td><a href="http://mxr.mozilla.org/mozilla-central/source/dom/wifi/nsIWifi.idl?rev=3e586802f478#156"><em>Firefox OS specific</em></a></td> + <td>The status of the Wifi connection changed.</td> + </tr> + <tr> + <td>{{event("overflow")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td><em>Mozilla specific</em></td> + <td>An element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with <code>overflow</code> != <code>visible</code>).</td> + </tr> + <tr> + <td>{{event("smartcard-insert")}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>A <a href="/en-US/docs/JavaScript_crypto">smartcard</a> has been inserted.</td> + </tr> + <tr> + <td>{{event("smartcard-remove")}}</td> + <td> </td> + <td><em>Mozilla specific</em></td> + <td>A <a href="/en-US/docs/JavaScript_crypto">smartcard</a> has been removed.</td> + </tr> + <tr> + <td>{{event("stkcommand")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>The <abbr title="SIM Application Toolkit">STK</abbr> Proactive Command is issued from <abbr title="Integrated Circuit Card">ICC</abbr>.</td> + </tr> + <tr> + <td>{{event("stksessionend")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>The <abbr title="SIM Application Toolkit">STK</abbr> Session is terminated by <abbr title="Integrated Circuit Card">ICC</abbr>.</td> + </tr> + <tr> + <td><code>text</code></td> + <td> </td> + <td><em>Mozilla Specific</em></td> + <td>A generic composition event occurred.</td> + </tr> + <tr> + <td>{{event("touchenter")}}</td> + <td>{{domxref("TouchEvent")}}</td> + <td><a href="http://www.w3.org/TR/touch-events/#the-touchstart---------event">Touch Events</a> Removed</td> + <td> </td> + </tr> + <tr> + <td>{{event("touchleave")}}</td> + <td>{{domxref("TouchEvent")}}</td> + <td><a href="http://www.w3.org/TR/touch-events/#the-touchstart---------event">Touch Events</a> Removed</td> + <td> </td> + </tr> + <tr> + <td>{{event("underflow")}}</td> + <td>{{domxref("UIEvent")}}</td> + <td><em>Mozilla specific</em></td> + <td>An element is no longer overflowed by its content (only works for elements styled with <code>overflow</code> != <code>visible</code>).</td> + </tr> + <tr> + <td><code>uploadprogress</code> {{deprecated_inline}}</td> + <td>{{domxref("ProgressEvent")}}</td> + <td><em>Mozilla Specific</em></td> + <td>Upload is in progress (see {{event("progress")}}).</td> + </tr> + <tr> + <td> + <p>{{event("ussdreceived")}}</p> + </td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>A new <abbr title="Unstructured Supplementary Service Data">USSD</abbr> message is received</td> + </tr> + <tr> + <td>{{event("voicechange")}}</td> + <td> </td> + <td><em>Firefox OS specific</em></td> + <td>The {{domxref("MozMobileConnection.voice")}} object changes values.</td> + </tr> + </tbody> +</table> + +<h2 id="Eventos_específicos_da_Mozilla">Eventos específicos da Mozilla</h2> + +<div class="note"> +<p><strong>Nota:</strong> esses eventos nunca são expostos ao conteúdo da Web e só podem ser utilizados no contexto de conteúdo do Chrome.</p> +</div> + +<h3 id="Eventos_de_XUL">Eventos de XUL</h3> + +<table class="standard-table" style="height: 554px; width: 1033px;"> + <tbody> + <tr> + <th class="header" style="width: 220px;">Nome do Evento</th> + <th class="header" style="width: 90px;">Tipo de Evento</th> + <th class="header" style="width: 100px;">Especificação</th> + <th class="header">Executado quando...</th> + </tr> + <tr> + <td>{{event("broadcast")}}</td> + <td> </td> + <td><a href="/en-US/docs/XUL/Tutorial/Broadcasters_and_Observers#Broadcast_event">XUL</a></td> + <td>An <code>observer</code> noticed a change to the attributes of a watched broadcaster.</td> + </tr> + <tr> + <td>{{event("CheckboxStateChange")}}</td> + <td> </td> + <td>XUL</td> + <td>The state of a <code>checkbox</code> has been changed either by a user action or by a script (useful for accessibility).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/close_event">close</a></td> + <td> </td> + <td>XUL</td> + <td>The close button of the window has been clicked.</td> + </tr> + <tr> + <td>{{event("command")}}</td> + <td> </td> + <td>XUL</td> + <td>An element has been activated.</td> + </tr> + <tr> + <td>{{event("commandupdate")}}</td> + <td> </td> + <td>XUL</td> + <td>A command update occurred on a <code>commandset</code> element.</td> + </tr> + <tr> + <td>{{event("DOMMenuItemActive")}}</td> + <td> </td> + <td>XUL</td> + <td>A menu or menuitem has been hovered or highlighted.</td> + </tr> + <tr> + <td>{{event("DOMMenuItemInactive")}}</td> + <td> </td> + <td><em>XUL</em></td> + <td>A menu or menuitem is no longer hovered or highlighted.</td> + </tr> + <tr> + <td>{{event("popuphidden")}}</td> + <td><code>PopupEvent</code></td> + <td><a href="/en-US/docs/XUL/PopupGuide/PopupEvents"><em>XUL</em></a></td> + <td>A menupopup, panel or tooltip has been hidden.</td> + </tr> + <tr> + <td>{{event("popuphiding")}}</td> + <td><code>PopupEvent</code></td> + <td><a href="/en-US/docs/XUL/PopupGuide/PopupEvents"><em>XUL</em></a></td> + <td>A menupopup, panel or tooltip is about to be hidden.</td> + </tr> + <tr> + <td>{{event("popupshowing")}}</td> + <td><code>PopupEvent</code></td> + <td><a href="/en-US/docs/XUL/PopupGuide/PopupEvents"><em>XUL</em></a></td> + <td>A menupopup, panel or tooltip is about to become visible.</td> + </tr> + <tr> + <td>{{event("popupshown")}}</td> + <td><code>PopupEvent</code></td> + <td><a href="/en-US/docs/XUL/PopupGuide/PopupEvents"><em>XUL</em></a></td> + <td>A menupopup, panel or tooltip has become visible.</td> + </tr> + <tr> + <td>{{event("RadioStateChange")}}</td> + <td> </td> + <td>XUL</td> + <td>The state of a <code>radio</code> has been changed either by a user action or by a script (useful for accessibility).</td> + </tr> + <tr> + <td>{{event("ValueChange")}}</td> + <td> </td> + <td>XUL</td> + <td>The value of an element has changed (a progress bar for example, useful for accessibility).</td> + </tr> + </tbody> +</table> + +<h3 id="Enventos_específicos_de_extras">Enventos específicos de extras</h3> + +<table class="standard-table" style="width: 100%;"> + <tbody> + <tr> + <th class="header" style="width: 220px;">Nome do Evento</th> + <th class="header" style="width: 90px;">Tipo de Evento</th> + <th class="header" style="width: 100px;">Especificação</th> + <th class="header">Executado quando...</th> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozSwipeGesture">MozSwipeGesture</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A touch point is swiped across the touch surface</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozMagnifyGestureStart">MozMagnifyGestureStart</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Two touch points start to move away from each other.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozMagnifyGestureUpdate">MozMagnifyGestureUpdate</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Two touch points move away from each other (after a MozMagnifyGestureStart).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozMagnifyGesture">MozMagnifyGesture</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Two touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozRotateGestureStart">MozRotateGestureStart</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Two touch points start to rotate around a point.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozRotateGestureUpdate">MozRotateGestureUpdate</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Two touch points rotate around a point (after a MozRotateGestureStart).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozRotateGesture">MozRotateGesture</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Two touch points rotate around a point (after a sequence of MozRotateGestureUpdate).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozTapGesture">MozTapGesture</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Two touch points are tapped on the touch surface.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozPressTapGesture">MozPressTapGesture</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozEdgeUIGesture">MozEdgeUIGesture</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A touch point is swiped across the touch surface to invoke the edge UI (Win8 only).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozAfterPaint">MozAfterPaint</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Content has been repainted.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMPopupBlocked">DOMPopupBlocked</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A popup has been blocked</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMWindowCreated">DOMWindowCreated</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A window has been created.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMWindowClose">DOMWindowClose</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A window is about to be closed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMTitleChanged">DOMTitleChanged</a></td> + <td> </td> + <td><em>Addons specifc</em></td> + <td>The title of a window has changed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMLinkAdded">DOMLinkAdded</a></td> + <td> </td> + <td><em>Addons specifc</em></td> + <td>A link has been added a document.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMLinkRemoved">DOMLinkRemoved</a></td> + <td> </td> + <td><em>Addons specifc</em></td> + <td>A link has been removed inside from a document.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMMetaAdded">DOMMetaAdded</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A <code>meta</code> element has been added to a document.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMMetaRemoved">DOMMetaRemoved</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A <code>meta</code> element has been removed from a document.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMWillOpenModalDialog">DOMWillOpenModalDialog</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A modal dialog is about to open.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMModalDialogClosed">DOMModalDialogClosed</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A modal dialog has been closed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMAutoComplete">DOMAutoComplete</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>The content of an element has been auto-completed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/DOMFrameContentLoaded">DOMFrameContentLoaded</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>The frame has finished loading (but not its dependent resources).</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/AlertActive">AlertActive</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A <code><a href="/en-US/docs/XUL/notification">notification</a></code> element is shown.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/AlertClose">AlertClose</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A <code><a href="/en-US/docs/XUL/notification">notification</a></code> element is closed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/fullscreen">fullscreen</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Browser fullscreen mode has been entered or left.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/sizemodechange">sizemodechange</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>Window has entered/left fullscreen mode, or has been minimized/unminimized.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/MozEnteredDomFullscreen">MozEnteredDomFullscreen</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td><a href="/en-US/docs/DOM/Using_full-screen_mode">DOM fullscreen</a> mode has been entered.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSWindowClosing">SSWindowClosing</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>The session store will stop tracking this window.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSTabClosing">SSTabClosing</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>The session store will stop tracking this tab.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSTabRestoring">SSTabRestoring</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab is about to be restored.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSTabRestored">SSTabRestored</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab has been restored.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSWindowStateReady">SSWindowStateReady</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A window state has switched to "ready".</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/SSWindowStateBusy">SSWindowStateBusy</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A window state has switched to "busy".</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabOpen">TabOpen</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab has been opened.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabClose">TabClose</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab has been closed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabSelect">TabSelect</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab has been selected.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabShow">TabShow</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab has been shown.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabHide">TabHide</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab has been hidden.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabPinned">TabPinned</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab has been pinned.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/TabUnpinned">TabUnpinned</a></td> + <td> </td> + <td><em>Addons specific</em></td> + <td>A tab has been unpinned.</td> + </tr> + </tbody> +</table> + +<h3 id="Eventos_específicos_da_ferramenta_do_programador">Eventos específicos da ferramenta do programador</h3> + +<table class="standard-table" style="width: 100%;"> + <tbody> + <tr> + <th class="header" style="width: 220px;">Nome do Evento</th> + <th class="header" style="width: 90px;">Tipo de Evento</th> + <th class="header" style="width: 100px;">Especificação</th> + <th class="header">Executado quando...</th> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/CssRuleViewRefreshed">CssRuleViewRefreshed</a></td> + <td> </td> + <td><em>devtools specific</em></td> + <td>The "Rules" view of the style inspector has been updated.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/CssRuleViewChanged">CssRuleViewChanged</a></td> + <td> </td> + <td><em>devtools specific</em></td> + <td>The "Rules" view of the style inspector has been changed.</td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/Reference/Events/CssRuleViewCSSLinkClicked">CssRuleViewCSSLinkClicked</a></td> + <td> </td> + <td><em>devtools specific</em></td> + <td>A link to a CSS file has been clicked in the "Rules" view of the style inspector.</td> + </tr> + </tbody> +</table> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{domxref("Event")}}</li> + <li><a href="/pt-PT/docs/Web/Guide/Eventos">Guia de desenvolvimento de eventos</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: 0% 0% repeat scroll rgba(0, 0, 0, 0); opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result"> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/guide/ajax/como_começar/index.html b/files/pt-pt/web/guide/ajax/como_começar/index.html new file mode 100644 index 0000000000..f067252d2d --- /dev/null +++ b/files/pt-pt/web/guide/ajax/como_começar/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 +--- +<p class="summary">Este artigo guia-o através do essencial do AJAX e oferece-lhe dois exemplos práticos simples para poder começar.</p> + +<h3 id="O_que_é_AJAX">O que é AJAX?</h3> + +<p>AJAX (JavaScript Assíncrono e XML) em poucas palavras, é a utilização do objeto <code><a href="/pt-PT/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code> 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.</p> + +<p>As duas principais funcionalidades do AJAX são as seguintes:</p> + +<ul> + <li>Efetuar pedidos ao servidor sem ter de recarregar a página</li> + <li>Receber e trabalhar com dados a partir do servidor</li> +</ul> + +<h3 id="Passo_1_-_Como_efetuar_um_pedido_de_HTTP">Passo 1 - Como efetuar um pedido de HTTP</h3> + +<p>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 <code>XMLHTTP</code>. Depois, o Mozilla, o Safari e outros browsers fizeram o mesmo, implementando uma classe de nome <code>XMLHttpRequest</code> que suporta os métodos e as propriedades do objecto ActiveX original da Microsoft.</p> + +<p>Por isso, para criar uma instância (objeto) da classe pretendida compatível com multiplos navegadores, você pode fazer:</p> + +<pre>if (window.XMLHttpRequest) { // Mozilla, Safari, ... + http_request = new XMLHttpRequest(); +} else if (window.ActiveXObject) { // IE + http_request = new ActiveXObject("Microsoft.XMLHTTP"); +} + +</pre> + +<p>(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.)</p> + +<p>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 <code>text/xml</code>.</p> + +<pre>http_request = new XMLHttpRequest(); +http_request.overrideMimeType('text/xml'); +</pre> + +<p>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 <code>onreadystatechange</code> do objeto ao nome da função JavaScript que pretende utilizar, por exemplo:</p> + +<p><code>http_request.onreadystatechange = NomedaFunção;</code></p> + +<p>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:</p> + +<pre>http_request.onreadystatechange = function(){ + // processar resposta do servidor +}; +</pre> + +<p>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 <code>open()</code> e <code>send()</code> da classe pedido HTTP, por exemplo:</p> + +<pre>http_request.open('GET', 'http://www.dominio.com.br/arquivo.extensao', true); +http_request.send(null); +</pre> + +<ul> + <li>O primeiro parâmetro da chamada do método <code>open()</code> é o método pedido HTML – GET, POST, HEAD ou outro método qualquer que queira usar e que seja suportado pelo seu servidor. Mantenha o nome do método em maiúsculas para obedecer às normas HTTP senão certos browsers (como o Firefox) podem não processar o pedido. Para obter mais informação sobre os possíveis métodos pedido HTTP pode dar uma olhadela em <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">W3C specs</a></li> + <li>O segundo parâmetro é a URL da página que está a pedir. Como medida de segurança, não pode efectuar pedidos de páginas de domínios externos. Certifique-se que usa o nome exacto do domínio em todas as suas páginas ou irá receber um erro "Permissão Negada" quando efectua uma chamada <code>open()</code>. Um erro comum é aceder ao seu domínio através de domínio.tld ao mesmo tempo que tenta chamar páginas com www.domínio.tld.</li> + <li>O terceiro parâmetro define se o pedido é assíncrono. Se <code>TRUE</code>, a execução da função JavaScript irá continuar enquanto que a resposta do servidor ainda não foi recebida. Isto é o A de AJAX.</li> +</ul> + +<p>O parâmetro do método <code>send()</code> 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:</p> + +<p><code>name=value&anothername=othervalue&so=on</code></p> + +<p>ou em vários outros formatos, incluindo JSON, SOAP, etc.</p> + +<p>Note-se que se pretende enviar (POST) dados, você deve alterar o tipo MIME do pedido usando a seguinte linha:</p> + +<pre>http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); +</pre> + +<p>De outra forma o servidor irá ignorar os dados (post).</p> + +<p>Pode-se também colocar o charset desejado assim:</p> + +<pre>http_request.setRequestHeader('Content-Type', + "application/x-www-form-urlencoded; charset=iso-8859-1"); +</pre> + +<p>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:</p> + +<pre> 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"); +</pre> + +<h3 id="Passo_2_-_Manipular_a_resposta_do_servidor">Passo 2 - Manipular a resposta do servidor</h3> + +<p>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.</p> + +<p><code>http_request.onreadystatechange = nameOfTheFunction;</code></p> + +<p>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.</p> + +<pre>if (http_request.readyState == 4) { + // everything is good, the response is received +} else { + // still not ready +} +</pre> + +<p>A lista completa dos valores <code>readyState</code> é a seguinte:</p> + +<ul> + <li>0 (não inicializado)</li> + <li>1 (a carregar)</li> + <li>2 (carregado)</li> + <li>3 (interativo)</li> + <li>4 (completo)</li> +</ul> + +<p>(<a class="external" href="http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/readystate_1.asp">Source</a>)</p> + +<p>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 <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">página W3C</a>. Para os nossos objectivos nós só estamos interessados na resposta <code>200 OK</code>.</p> + +<pre>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 +} +</pre> + +<p>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:</p> + +<ul> + <li><code>http_request.responseText</code> – irá devolver a resposta do servidor como uma linha de texto</li> + <li><code>http_request.responseXML</code> – irá devolver a resposta do servidor como um objecto <code>XMLDocument</code> que pode percorrer usando as funções DOM de JavaScript.</li> +</ul> + +<p> </p> + +<h3 id="Passo_3_–_Um_exemplo_simples">Passo 3 – Um exemplo simples</h3> + +<p>Vamos agora pôr tudo junto e efectuar um simples pedido HTTP. O nosso JavaScript vai pedir um documento HTML, <code>teste.html</code>, que contém o texto "Sou um teste." e então vamos <code>alert()</code> os conteúdos do ficheiro <code>teste.html</code>.</p> + +<pre><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> +</pre> + +<p>Neste exemplo:</p> + +<ul> + <li>O utilizador clicka no atalho "efectuar pedido" no browser;</li> + <li>Isto chama a função <code>makeRequest()</code> com um parâmetro -- o nome <code>teste.html</code> de um ficheiro HTML no mesmo directório;</li> + <li>O pedido é feito e então (<code>onreadystatechange</code>) a execução é passada a <code>alertContents()</code>;</li> + <li><code>alertContents()</code> verifica se a resposta foi recebida e se é um OK e então alerta (<code>alert()</code>) os conteúdos do ficheiro <code>test.html</code>.</li> +</ul> + +<p>Você pode testar o exemplo <a class="external" href="http://www.w3clubs.com/mozdev/httprequest_test.html">aqui</a> e pode ver o ficheiro de teste <a class="external" href="http://www.w3clubs.com/mozdev/test.html">aqui</a>.</p> + +<div class="note"><strong>Nota</strong>: <span id="result_box" lang="pt"><span class="hps"><span id="result_box" lang="pt"><span class="alt-edited hps">Se você está enviando</span> <span class="alt-edited hps">uma solicitação para um</span> <span class="hps">pedaço de código</span> <span class="alt-edited hps">que retornará</span> <span class="hps">XML</span><span>, ao invés de</span> <span class="hps">um arquivo</span> <span class="hps">XML</span> <span class="hps">estático</span><span>, é necessário definir</span> <span class="hps">alguns</span> <span class="hps">cabeçalhos de resposta</span> <span class="hps">se a sua página</span> <span class="alt-edited hps">deve trabalhar</span> <span class="alt-edited hps">com o Internet Explorer</span><span>, além de</span> <span class="hps">Mozilla.</span> <span class="hps">Se</span> <span class="hps">você não definir</span> <span class="hps">cabeçalho</span> <code><span class="hps">Content-Type</span><span>: application /</span> <span class="hps">xml</span></code><span>, o IE irá</span> <span class="hps">lançar um erro</span> <span class="hps">JavaScript,</span> <span class="atn hps">"</span><span>Objeto esperado</span><span>"</span><span>,</span> <span class="hps">após a linha</span> <span class="hps">onde você tentar</span> <span class="hps">acessar um elemento</span> <span class="hps">XML.</span></span>.</span></span></div> + +<div class="note"><strong>Nota 2</strong>: <span id="result_box" lang="pt"><span class="hps">Se</span> <span class="hps">você não definir</span> <span class="hps">cabeçalho</span> <code><span class="atn hps">Cache-</span><span>Control: no</span><span>-cache</span></code> <span class="alt-edited hps">o navegador</span> <span class="alt-edited hps">armazenará em cache</span> <span class="hps">a resposta</span> <span class="alt-edited hps">e jamais</span> <span class="alt-edited hps">voltará a submeter</span> <span class="hps">o pedido</span><span>, tornando</span> <span class="hps">a depuração</span> <span class="atn hps">"</span><span class="alt-edited">desafiadora".</span> <span class="alt-edited hps">Também é</span> <span class="alt-edited hps">possível acrescentar</span> <span class="hps">um parâmetro</span> <span class="hps">GET</span> <span class="hps">adicional</span> <span class="hps">sempre</span> <span class="hps">diferente,</span> <span class="hps">como o</span> <span class="hps">timestamp</span> <span class="hps">ou</span> <span class="hps">um número aleatório</span> <span class="atn hps">(</span><span>veja</span> <a href="https://developer.mozilla.org/en/DOM/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache" title="https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache">bypassing the cache</a><span class="hps">).</span></span></div> + +<div class="note"><strong>Nota 3</strong>: <span id="result_box" lang="pt"><span class="hps">Se a variável</span> <span class="hps">httpRequest</span> <span class="alt-edited hps">é utilizada</span> <span class="hps">globalmente</span><span class="alt-edited">, funções</span> <span class="alt-edited hps">concorrentes</span> <span class="hps">chamando</span> <code><span class="hps">makeRequest</span> </code><span class="alt-edited hps"><code>()</code> podem</span> <span class="alt-edited hps">sobrescrever</span> <span class="hps">o outro,</span> <span class="hps">causando</span> <span class="hps">uma condição de corrida</span><span>.</span> <span class="hps">Declarando</span> <span class="hps">o</span> <span class="hps">httpRequest</span> <span class="hps">variável local para</span> <span class="hps">um <a href="https://developer.mozilla.org/en/JavaScript/Guide/Closures" title="https://developer.mozilla.org/en/JavaScript/Guide/Closures">closure</a></span> <span class="hps">contendo as funções</span> <span class="hps">AJAX</span> <span class="hps">impede</span> <span class="hps">a condição de corrida</span><span>.</span></span></div> + +<div class="note"><strong>Nota 4</strong>: Caso ocorra um erro de comunicação (tal como a queda de do servidor web), uma exceção será lançada no método <code>onreadystatechange</code> quando o campo <code>status</code> for acessado. Tenha a certeza de envolver sua declaração <code>if..then</code> dentro de um bloco <code>try...catch</code>. (Veja: {{ Bug(238559) }}).</div> + +<h3 id="Passo_4_–_Trabalhar_com_a_resposta_XML">Passo 4 – Trabalhar com a resposta XML</h3> + +<p>No exemplo anterior, após termos recebido a resposta ao pedido HTTP, nós usamos a propriedade <code>reponseText</code> do objecto de pedido e continha os conteúdos do ficheiro <code>test.html</code>. Agora vamos experimentar a propriedade <code>responseXML</code>.</p> + +<p>Antes de tudo, vamos criar um documento XML válido que vamos pedir mais à frente. O documento (test.xml) contém o seguinte:</p> + +<p> </p> + +<pre><?xml version="1.0" ?> +<root> + I'm a test. +</root> +</pre> + +<p>No guião só precisamos de alterar a linha do pedido com:</p> + +<pre>... +onclick="makeRequest('test.xml')"> +... +</pre> + +<p>Então em <code>alertContents()</code> nós precisamos de substituir a linha de alerta (<code>alert(http_request.responseText);</code>) com:</p> + +<pre>var xmldoc = http_request.responseXML; +var root_node = xmldoc.getElementsByTagName('root').item(0); +alert(root_node.firstChild.data); +</pre> + +<p>Este código pega o objeto <code>XMLDocument</code> obtido por <code>responseXML</code> e utiliza métodos DOM para acessar alguns dados contidos no documento XML. Você pode ver o <code>test.xml</code> <a class="external" href="http://www.w3clubs.com/mozdev/test.xml">aqui</a> e o script de teste atualizado <a class="external" href="http://www.w3clubs.com/mozdev/httprequest_test_xml.html">aqui</a>.</p> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> + +<h3 id="Passo_5_–_Tabalhar_com_dados">Passo 5 – Tabalhar com dados</h3> + +<p>Finalmente, vamos enviar algum dado para o servidor e obter a resposta. Desta vez, nosso JavaScript solicitará um página dinâmica (<code>test.php</code>) que receberá os dados que enviamos e retornará um string computada - "<code>Hello, [user data]!</code>" - visualizada através de <code>alert().</code></p> + +<p>Primeiro, vamos adicionar uma text box em nosso HTML de modo que o usuário possa digitar o seu nome:</p> + +<pre class="brush: html"><label>Your name: + <input type="text" id="ajaxTextbox" /> +</label> +<span id="ajaxButton" style="cursor: pointer; text-decoration: underline"> + Make a request +</span></pre> + +<p>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 <code>makeRequest()</code> juntamente com a URL do nosso script do lado do servidor (server-side):</p> + +<pre class="brush: js">document.getElementById("ajaxButton").onclick = function() { + var userName = document.getElementById("ajaxTextbox").value; + makeRequest('test.php',userName); + };</pre> + +<p><span id="result_box" lang="pt"><span class="hps">Precisamos</span> <span class="hps">modificar</span> <code><span class="hps">makeRequest</span> </code><span class="hps"><code>()</code> para aceitar</span> <span class="hps">os dados do usuário</span> <span class="hps">e</span> <span class="hps">passá-lo para</span> <span class="hps">o servidor</span></span>. Vamos mudar o método de requisição de <code>GET</code> para <code>POST</code>, e incluir nossos dados como um parâmetro na chamada para <code>httpRequest.send()</code>:</p> + +<pre class="brush: js">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)); + } +</pre> + +<p>A função <code>alertContents()</code> pode ser escrita da mesma forma que se encontrava no <strong>Passo 3</strong> para alertar (<code>alert()</code>) 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:</p> + +<p><code>{"userData":"Jane","computedString":"Hi, Jane!"}</code></p> + +<p><span class="short_text" id="result_box" lang="pt"><span class="hps">Para utilizar</span> <span class="hps">estes dados</span> <span class="hps">dentro de </span></span><code>alertContents()</code>, nós não podemos simplesmente exibir com <code>alert()</code> a propriedade <code>responseText</code>. Temos que analisar (parse it) <code>computedString</code> a propriedade que queremos:</p> + +<pre class="brush: js">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.'); + } +}</pre> + +<p><code>Para mais métodos DOM, certifique-se que consulta os documentos sobre a <a class="external" href="/pt-PT/docs/DOM/DOM_Reference">implementação de DOM da Mozilla</a></code></p> diff --git a/files/pt-pt/web/guide/ajax/comunidade/index.html b/files/pt-pt/web/guide/ajax/comunidade/index.html new file mode 100644 index 0000000000..98a2936999 --- /dev/null +++ b/files/pt-pt/web/guide/ajax/comunidade/index.html @@ -0,0 +1,22 @@ +--- +title: Comunidade +slug: Web/Guide/AJAX/Comunidade +tags: + - AJAX +translation_of: Web/Guide/AJAX/Community +--- +<p>Se conhece listas de discussão úteis, grupos de notícias, fóruns, ou outras comunidades relacionadas com AJAX, interligue-os aqui.</p> + +<h2 id="Ajax_Resources" name="Ajax_Resources">Recursos Ajax</h2> + +<h2 id="Ajax_Workshops_&_Courses" name="Ajax_Workshops_&_Courses">Ajax - Conferências e Cursos</h2> + +<ul> + <li><a class="external" href="http://skillsmatter.com/go/ajax-ria">skillsmatter.com</a>: cursos e eventos de JavaScript, Ajax e Tecnologias Reversas Ajax</li> + <li><a href="https://www.telerik.com/forums/aspnet-ajax" rel="noopener">telerik.com</a>: um fórum da comunidade ativo para Ajax</li> + <li><a href="https://community.tableau.com/search.jspa?q=ajax" rel="noopener">community.tableau.com</a>: fórum de apoio da comunidade e cursos disponíveis para Ajax</li> + <li><a href="https://www.codementor.io/community/search?q=ajax" rel="noopener">codementor.io</a>: plataforma social com fóruns e tutoriais de Ajax</li> + <li><a href="https://www.lynda.com/search?q=ajax" rel="noopener">lynda.com</a>: tutoriai disponíveis para aprender o essencial do Ajax<span class="comment">Interwiki links</span></li> +</ul> + +<p>{{ languages( { "ja": "ja/AJAX/Community", "fr": "fr/AJAX/Communaut\u00e9" } ) }}</p> diff --git a/files/pt-pt/web/guide/ajax/index.html b/files/pt-pt/web/guide/ajax/index.html new file mode 100644 index 0000000000..d994ea7b96 --- /dev/null +++ b/files/pt-pt/web/guide/ajax/index.html @@ -0,0 +1,131 @@ +--- +title: AJAX +slug: Web/Guide/AJAX +tags: + - AJAX + - DOM + - JSON + - JavaScript + - Referências + - XML + - XMLHttRequest +translation_of: Web/Guide/AJAX +--- +<p> </p> + +<div class="callout-box"><strong><a href="/pt-PT/docs/Web/Guide/AJAX/Como_começar">Primeiros Passos</a></strong> + +<p>Uma introdução ao AJAX</p> +</div> + +<div> +<p><strong>JavaScript Assíncrono e XML,</strong> enquanto não uma tecnologia em si, é um termo criado em 2005 por Jesse James Garret, que descreve uma "nova" abordagem para utilizar uma série de tecnologias existentes em conjunto, incluindo <a href="/pt-PT/docs/Web/HTML">HTML</a> ou <a href="/pt-PT/docs/XHTML">XHTML</a>, <a href="/pt-PT/docs/Web/CSS">Cascading Style Sheets</a>, <a href="/pt-PT/docs/Web/JavaScript">JavaScript</a>, <a href="/pt-PT/docs/DOM/DOM_Reference">Document Object Model</a>, <a href="/pt-PT/docs/Introducao_a_XML">XML</a>, <a href="/pt-PT/docs/XSLT">XSLT</a> e o objeto <a href="/pt-PT/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a>.<br> + Quando estas tecnologias são combinadas no modelo AJAX, as aplicações da Web são capazes de efetuar atualizações incrementais e rápidas na interface do utilizador sem recarregar toda a página. Isto torna a aplicação mais rápida e mais responsiva para as ações do do utilizador.</p> +</div> + +<p>Although X in Ajax stands for XML, <a href="/en-US/docs/JSON" title="https://developer.mozilla.org/en-US/docs/JSON">JSON</a> is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in Ajax model.</p> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Documentação">Documentação</h2> + +<dl> + <dt><a href="/en-US/docs/AJAX/Getting_Started" title="en-US/docs/AJAX/Getting_Started">Primeiros Passos</a></dt> + <dd>This article guides you through the Ajax basics and gives you two simple hands-on examples to get you started.</dd> + <dt><a href="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest" title="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest">Utilizar a API XMLHttpRequest</a></dt> + <dd>The <a href="/en-US/docs/DOM/XMLHttpRequest" title="XMLHttpRequest"><code>XMLHttpRequest</code> API</a> is the core of Ajax. This article will explain how to use some Ajax techniques, like: + <ul> + <li><a href="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Handling_responses" title="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Handling_responses">analyzing and manipulating the response of the server</a></li> + <li><a href="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress" title="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress">monitoring the progress of a request</a></li> + <li><a href="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files" title="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files">submitting forms and upload binary files</a> – in <em>pure</em> Ajax, or using <a href="/en-US/docs/DOM/XMLHttpRequest/FormData" title="DOM/XMLHttpRequest/FormData"><code>FormData</code></a> objects</li> + <li><a href="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Types_of_requests" title="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Types_of_requests">creating synchronous or asynchronous requests</a></li> + <li>using Ajax within <a href="/en-US/docs/DOM/Worker" title="/en-US/docs/DOM/Worker">Web workers</a></li> + </ul> + </dd> + <dt><a href="/en-US/docs/Web/API/Fetch_API">API Fetch</a></dt> + <dd>The Fetch API provides an interface for fetching resources. It will seem familiar to anyone who has used {{domxref("XMLHTTPRequest")}}, but this API provides a more powerful and flexible feature set.</dd> + <dt><a href="/en-US/docs/Server-sent_events" title="/en-US/docs/Server-sent_events">Eventos de envio do servidor</a></dt> + <dd>Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as <em><a href="/en-US/docs/DOM/event" title="DOM/Event">Events</a> + data</em> inside the web page. See also: <a href="/en-US/docs/Server-sent_events/Using_server-sent_events" title="/en-US/docs/Server-sent_events/Using_server-sent_events">Using server-sent events</a>.</dd> + <dt><a href="/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history/Example" title="/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history/Example"><em>Pure-Ajax</em> navigation example</a></dt> + <dd>This article provides a working (minimalist) example of a <em>pure-Ajax</em> website composed only of three pages.</dd> + <dt><a href="/en-US/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data" title="/en-US/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data">Enviar e Receber Dados Binário</a></dt> + <dd>The <code>responseType</code> property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), <code>"arraybuffer"</code>, <code>"blob"</code>, <code>"document"</code>, <code>"json"</code>, and <code>"text"</code>. The <code>response</code> property will contain the entity body according to <code>responseType</code>, as an <code>ArrayBuffer</code>, <code>Blob</code>, <code>Document</code>, <code>JSON</code>, or string. This article will show some Ajax I/O techniques.</dd> + <dt><a href="/en-US/docs/XML" title="XML">XML</a></dt> + <dd>The <strong>Extensible Markup Language (XML)</strong> is a W3C-recommended general-purpose markup language for creating special-purpose markup languages. It is a simplified subset of SGML, capable of describing many different kinds of data. Its primary purpose is to facilitate the sharing of data across different systems, particularly systems connected via the Internet.</dd> + <dt><a href="/en-US/docs/JXON" title="JXON">JXON</a></dt> + <dd>JXON stands for lossless <strong>J</strong>avascript <strong>X</strong>ML <strong>O</strong>bject <strong>N</strong>otation, it is a generic name by which is defined the representation of Javascript object trees (JSON) using XML.</dd> + <dt><a href="/en-US/docs/Parsing_and_serializing_XML" title="Parsing_and_serializing_XML">Analisar e serializar XML</a></dt> + <dd>How to parse an XML document from a string, a file or via javascript and how to serialize XML documents to strings, Javascript Object trees (JXON) or files.</dd> + <dt><a href="/en-US/docs/XPath" title="XPath">XPath</a></dt> + <dd>XPath stands for <strong>X</strong>ML <strong>Path</strong> Language, it uses a non-XML syntax that provides a flexible way of addressing (pointing to) different parts of an <a href="/en-US/docs/XML" title="XML">XML</a> document. As well as this, it can also be used to test addressed nodes within a document to determine whether they match a pattern or not.</dd> + <dt><a href="/en-US/docs/DOM/FileReader" title="/en-US/docs/DOM/FileReader">A API <code>FileReader</code></a></dt> + <dd>The <code>FileReader</code> API lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using <a href="https://developer.mozilla.org/en-US/docs/DOM/File" title="/en-US/docs/DOM/File"><code>File</code></a> or <a href="https://developer.mozilla.org/en-US/docs/DOM/Blob" title="/en-US/docs/DOM/Blob"><code>Blob</code></a> objects to specify the file or data to read. File objects may be obtained from a <a href="https://developer.mozilla.org/en-US/docs/DOM/FileList" title="/en-US/docs/DOM/FileList"><code>FileList</code></a> object returned as a result of a user selecting files using the <code><a href="https://developer.mozilla.org/en-US/docs/HTML/Element/input" title="<input>"><input></a></code> element, from a drag and drop operation's <a href="https://developer.mozilla.org/En/DragDrop/DataTransfer" title="En/DragDrop/DataTransfer"><code>DataTransfer</code></a> object, or from the <code>mozGetAsFile()</code> API on an <a href="https://developer.mozilla.org/en-US/docs/DOM/HTMLCanvasElement" title="/en-US/docs/DOM/HTMLCanvasElement"><code>HTMLCanvasElement</code></a>.</dd> + <dt><a href="/en-US/docs/HTML_in_XMLHttpRequest" title="en-US/docs/HTML_in_XMLHttpRequest">HTML no XMLHttpRequest</a></dt> + <dd>The W3C <a class="external" href="http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html">XMLHttpRequest</a> specification adds HTML parsing support to <a href="/en/DOM/XMLHttpRequest" title="en/DOM/XMLHttpRequest"><code>XMLHttpRequest</code></a>, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using <code>XMLHttpRequest</code>.</dd> + <dt><a href="/en-US/docs/AJAX/Other_Resources" title="en-US/docs/AJAX/Other_Resources">Outros recursos</a></dt> + <dd>Outros recursos Ajax que poderão ser úteis.</dd> +</dl> + +<p><span class="alllinks"><a href="/pt-PT/docs/tag/AJAX" title="en-US/docs/tag/AJAX">Ver Todos...</a></span></p> + +<h2 class="Other" id="Consulte_também">Consulte também</h2> + +<dl> + <dt><a href="http://www.webreference.com/programming/ajax_tech/">Alternate Ajax Techniques</a></dt> + <dd>Most articles on Ajax have focused on using XMLHttp as the means to achieving such communication, but Ajax techniques are not limited to just XMLHttp. There are several other methods.</dd> + <dt><a href="http://adaptivepath.org/ideas/ajax-new-approach-web-applications/">Ajax: A New Approach to Web Applications</a></dt> + <dd>Jesse James Garrett, of <a href="http://www.adaptivepath.com">adaptive path</a>, wrote this article in February 2005, introducing Ajax and its related concepts.</dd> + <dt><a href="http://www.onlamp.com/pub/a/onlamp/2005/05/19/xmlhttprequest.html">A Simpler Ajax Path</a></dt> + <dd>"As it turns out, it's pretty easy to take advantage of the XMLHttpRequest object to make a web app act more like a desktop app while still using traditional tools like web forms for collecting user input."</dd> + <dt><a href="http://alexbosworth.backpackit.com/pub/67688">Ajax Mistakes</a></dt> + <dd>Alex Bosworth has written this article outlining some of the mistakes Ajax application developers can make.</dd> + <dt><a href="http://www.xul.fr/en-xml-ajax.html">Tutorial</a> with examples.</dt> + <dd> </dd> + <dt><a href="http://www.w3.org/TR/XMLHttpRequest/">XMLHttpRequest specification</a></dt> + <dd>W3C Working draft</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Community" id="Comunidade">Comunidade</h2> + +<ul> + <li>View Mozilla forums...</li> +</ul> + +<div>{{ DiscussionList("dev-ajax", "mozilla.dev.ajax") }}</div> + +<ul> + <li><a href="/pt-PT/docs/Web/Guide/AJAX/Comunidade" title="en-US/docs/AJAX/Community">Hiperligações da comunidade do Ajax</a></li> +</ul> + +<h2 class="Tools" id="Ferramentas">Ferramentas</h2> + +<ul> + <li><a href="http://www.ajaxprojects.com">Toolkits and frameworks</a></li> + <li><a href="http://www.getfirebug.com/">Firebug - Ajax/Web development tool</a></li> + <li><a href="http://blog.monstuff.com/archives/000252.html">AJAX Debugging Tool</a></li> + <li><a href="http://www.osflash.org/doku.php?id=flashjs">Flash/AJAX Integration Kit</a></li> + <li><a href="http://xkr.us/code/javascript/XHConn/">A Simple XMLHTTP Interface Library</a></li> +</ul> + +<p><span class="alllinks"><a href="/en-US/docs/AJAX:Tools" title="en-US/docs/AJAX:Tools">View All...</a></span></p> + +<h2 id="Exemplos">Exemplos</h2> + +<ul> + <li><a href="http://www.dhtmlgoodies.com/index.html?whichScript=ajax-poller">Ajax poller script</a></li> + <li><a href="http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=9">Ajax Chat Tutorial</a></li> + <li><a href="http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=13">RSS Ticker with Ajax</a></li> + <li><a href="http://www.thinkvitamin.com/features/ajax/create-your-own-ajax-effects">Create your own Ajax effects</a></li> + <li><a href="http://codinginparadise.org/weblog/2005/08/ajax-creating-huge-bookmarklets.html">Ajax: Creating Huge Bookmarklets</a></li> + <li><a href="http://www.hotajax.org">Ajax: Hot!Ajax There are many cool examples</a></li> +</ul> + +<h2 class="Related_Topics" id="Tópicos_Relacionados">Tópicos Relacionados</h2> + +<p><a href="/en-US/docs/HTML" title="en-US/docs/HTML">HTML</a>, <a href="/en-US/docs/XHTML" title="en-US/docs/XHTML">XHTML</a>, <a href="/en-US/docs/CSS" title="en-US/docs/CSS">CSS</a>, <a href="/en-US/docs/DOM" title="en-US/docs/DOM">DOM</a>, <a href="/en-US/docs/JavaScript" title="en-US/docs/JavaScript">JavaScript</a>, <a href="/en-US/docs/XML" title="en-US/docs/XML">XML</a>, <a href="/en-US/docs/nsIXMLHttpRequest" title="en-US/docs/XMLHttpRequest">XMLHttpRequest</a>, <a href="/en-US/docs/XSLT" title="en-US/docs/XSLT">XSLT</a>, <a href="/en-US/docs/DHTML" title="en-US/docs/DHTML">DHTML</a>, <a href="/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript" title="en-US/docs/JavaScript/Same_origin_policy_for_JavaScript">Same Origin Policy</a></p> +</div> +</div> + +<p>{{ListSubpages}}</p> diff --git a/files/pt-pt/web/guide/eventos/index.html b/files/pt-pt/web/guide/eventos/index.html new file mode 100644 index 0000000000..99e7f2f492 --- /dev/null +++ b/files/pt-pt/web/guide/eventos/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 +--- +<p>{{draft()}}</p> + +<p>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.</p> + +<p>The <a href="/en-US/docs/Web/Guide/API/DOM/Events/Overview_of_Events_and_Handlers">overview page</a> 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.</p> + +<p>The <a href="/en-US/docs/Web/Guide/API/DOM/Events/Creating_and_triggering_events">custom events page</a> 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.</p> + +<p>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.</p> + +<p>The <strong>device</strong> 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 <a href="/en-US/docs/Web/Guide/API/DOM/Events/Orientation_and_motion_data_explained">page on orientation coordinate systems</a> and the <a href="/en-US/docs/Web/Guide/API/DOM/Events/Using_device_orientation_with_3D_transforms">page on the use of 3D transforms</a>. That is different, but similar, to the change in device vertical orientation. </p> + +<p>The <strong>window</strong> in which the browser is displayed can trigger events; for example, change size if the user maximizes the window or otherwise changes it.</p> + +<p>The <strong>process</strong> 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.</p> + +<p>The <strong>user interaction</strong> 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:</p> + +<ul> + <li>the original 'click' event,</li> + <li>mouse events,</li> + <li><a href="/en-US/docs/Web/Guide/API/DOM/Events/Mouse_gesture_events">mouse gesture events</a>, and</li> + <li>both <a href="/en-US/docs/Web/Guide/API/DOM/Events/Touch_events">touch events</a> and the earlier <a href="/en-US/docs/Web/Guide/API/DOM/Events/Touch_events_(Mozilla_experimental)">mozilla experimental touch events</a>, now deprecated.</li> +</ul> + +<p>The <strong>modification of the web page</strong> in structure or content might trigger some events, as explained in the <a href="/en-US/docs/Web/Guide/API/DOM/Events/Mutation_events">mutation events page</a>, but the use of these events has been deprecated in favour of the lighter <a href="/en-US/docs/Web/API/MutationObserver">Mutation Observer</a> approach.</p> + +<p>The <strong>media streams</strong> embedded in the HTML documents might trigger some events, as explained in the <a href="/en-US/docs/Web/Guide/API/DOM/Events/Media_events">media events</a> page.</p> + +<p>The <strong>network requests</strong> made by a web page might trigger some events.</p> + +<p>There are many other sources of events defined by web browsers for which pages are not yet available in this guide.</p> + +<div class="note"> +<p>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.</p> +</div> + +<h2 id="Documentos">Documentos</h2> + +<p>{{LandingPageListSubpages}}</p> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: none; opacity: 1;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/guide/gráficos/index.html b/files/pt-pt/web/guide/gráficos/index.html new file mode 100644 index 0000000000..c18d703bc5 --- /dev/null +++ b/files/pt-pt/web/guide/gráficos/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 +--- +<p><span class="seoSummary">Web sites e aplicações necessitam frequentemente de apresentar gráficos.</span> 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. <span class="seoSummary">Este artigo disponibiliza toda a informação necessária. </span></p> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Gráficos_2D">Gráficos 2D</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/API/API_de_canvas">Canvas</a></dt> + <dd>O elemento {{HTMLElement("canvas")}} fornece APIs para desenhar gráficos em 2D com recurso a JavaScript.</dd> + <dt><a href="/pt-PT/docs/Web/SVG">SVG</a></dt> + <dd>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.</dd> +</dl> + +<p><span class="alllinks"><a href="/en-US/docs/tag/Graphics">View All...</a></span></p> +</div> + +<div class="section"> +<h2 class="Documentation" id="Gráficos_3D">Gráficos 3D</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/API/WebGL_API">WebGL</a></dt> + <dd>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.</dd> +</dl> + +<h2 id="Vídeo">Vídeo</h2> + +<dl> + <dt><a href="/pt-PT/docs/Learn/HTML/Multimedia_e_integracao/Conteudo_de_audio_e_vídeo">Utilizar áudio e vídeo em HTML5</a></dt> + <dd>Incorporar video e/ou audio numa página web e controlar a sua reprodução.</dd> + <dt><a href="/pt-PT/docs/Web/API/API_WebRTC">WebRTC</a></dt> + <dd>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).</dd> +</dl> +</div> +</div> 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 new file mode 100644 index 0000000000..9a7c08ee9a --- /dev/null +++ b/files/pt-pt/web/guide/html/categorias_de_conteudo/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 +--- +<p><span class="seoSummary">Every <a href="/en-US/docs/Web/HTML">HTML</a> element is a member of one or more <strong>content categories</strong>, which group elements that share characteristics.</span> 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 <em>any</em> of these categories.</p> + +<p>There are three types of content categories:</p> + +<ul> + <li>Main content categories, which describe common rules shared by many elements.</li> + <li>Form-related content categories, which describe rules common to form-related elements.</li> + <li>Specific content categories, which describe rare categories shared only by a few elements, sometimes only in a specific context.</li> +</ul> + +<div class="note"> +<p><strong>Nota:</strong> 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 <a href="https://html.spec.whatwg.org/multipage/dom.html#kinds-of-content">relevant portions of the HTML specification</a>.</p> +</div> + +<p><a href="/@api/deki/files/6244/=Content_categories_venn.png"><img alt="A Venn diagram showing how the various content categories interrelate. The following sections explain these relationships in text." class="default internal" src="/@api/deki/files/6244/=Content_categories_venn.png?size=webview" style="height: 200px; width: 350px;"></a></p> + +<h2 id="Main_content_categories">Main content categories</h2> + +<h3 id="Metadata_content">Metadata content</h3> + +<p>Elements belonging to the <em>metadata content</em> category modify the presentation or the behavior of the rest of the document, set up links to other documents, or convey other <em>out of band</em> information.</p> + +<p>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")}}.</p> + +<h3 id="Flow_content">Flow content</h3> + +<p>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.</p> + +<p>A few other elements belong to this category, but only if a specific condition is fulfilled:</p> + +<ul> + <li>{{HTMLElement("area")}}, if it is a descendant of a {{HTMLElement("map")}} element</li> + <li>{{HTMLElement("link")}}, if the <a href="/en-US/docs/HTML/Global_attributes#attr-itemprop">itemprop</a> attribute is present</li> + <li>{{HTMLElement("meta")}}, if the <a href="/en-US/docs/HTML/Global_attributes#attr-itemprop"><strong>itemprop</strong></a> attribute is present</li> + <li>{{HTMLElement("style")}}, if the {{htmlattrxref("scoped","style")}} attribute is present</li> +</ul> + +<h3 id="Sectioning_content">Sectioning content</h3> + +<p>Elements belonging to the sectioning content model create a <a href="/en-US/docs/Sections_and_Outlines_of_an_HTML5_document" title="Sections and Outlines of an HTML5 document">section in the current outline</a> that defines the scope of {{HTMLElement("header")}} elements, {{HTMLElement("footer")}} elements, and <a href="#Heading_content">heading content</a>.</p> + +<p>Elements belonging to this category are {{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("nav")}} and {{HTMLElement("section")}}.</p> + +<div class="note"> +<p>Do not confuse this content model with the <a href="/en-US/docs/Sections_and_Outlines_of_an_HTML5_document#sectioning_root" title="Sections and Outlines of an HTML5 document#sectioning root">sectioning root</a> category, which isolates its content from the regular outline.</p> +</div> + +<h3 id="Heading_content">Heading content</h3> + +<p>Heading content defines the title of a section, whether marked by an explicit <a href="#Sectioning_content">sectioning content</a> element, or implicitly defined by the heading content itself.</p> + +<p>Elements belonging to this category are {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}} and {{HTMLElement("hgroup")}}.</p> + +<div class="note"> +<p>Though likely to contain heading content, the {{HTMLElement("header")}} is not heading content itself.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> 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.</p> +</div> + +<h3 id="Phrasing_content">Phrasing content</h3> + +<p>Phrasing content defines the text and the mark-up it contains. Runs of phrasing content make up paragraphs.</p> + +<p>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).</p> + +<p>A few other elements belong to this category, but only if a specific condition is fulfilled:</p> + +<ul> + <li>{{HTMLElement("a")}}, if it contains only phrasing content</li> + <li>{{HTMLElement("area")}}, if it is a descendant of a {{HTMLElement("map")}} element</li> + <li>{{HTMLElement("del")}}, if it contains only phrasing content</li> + <li>{{HTMLElement("ins")}}, if it contains only phrasing content</li> + <li>{{HTMLElement("link")}}, if the <a href="/en-US/docs/HTML/Global_attributes#itemprop"><strong>itemprop</strong></a> attribute is present</li> + <li>{{HTMLElement("map")}}, if it contains only phrasing content</li> + <li>{{HTMLElement("meta")}}, if the <a href="/en-US/docs/HTML/Global_attributes#itemprop"><strong>itemprop</strong></a> attribute is present</li> +</ul> + +<h3 id="Embedded_content">Embedded content</h3> + +<p>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")}}.</p> + +<h3 id="Interactive_content">Interactive content</h3> + +<p>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")}}.<br> + Some elements belong to this category only under specific conditions:</p> + +<ul> + <li>{{HTMLElement("audio")}}, if the {{htmlattrxref("controls", "audio")}} attribute is present</li> + <li>{{HTMLElement("img")}}, if the {{htmlattrxref("usemap", "img")}} attribute is present</li> + <li>{{HTMLElement("input")}}, if the {{htmlattrxref("type", "input")}} attribute is not in the hidden state</li> + <li>{{HTMLElement("menu")}}, if the {{htmlattrxref("type", "menu")}} attribute is in the toolbar state</li> + <li>{{HTMLElement("object")}}, if the {{htmlattrxref("usemap", "object")}} attribute is present</li> + <li>{{HTMLElement("video")}}, if the {{htmlattrxref("controls", "video")}} attribute is present</li> +</ul> + +<h3 id="Palpable_content">Palpable content</h3> + +<p>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.</p> + +<h3 id="Form-associated_content">Form-associated content</h3> + +<p>Form-associated content comprises elements that have a form owner, exposed by a <strong>form</strong> attribute. A form owner is either the containing {{HTMLElement("form")}} element or the element whose id is specified in the <strong>form</strong> attribute.</p> + +<ul> + <li>{{HTMLElement("button")}}</li> + <li>{{HTMLElement("fieldset")}}</li> + <li>{{HTMLElement("input")}}</li> + <li>{{deprecated_inline()}}{{HTMLElement("keygen")}}</li> + <li>{{HTMLElement("label")}}</li> + <li>{{HTMLElement("meter")}}</li> + <li>{{HTMLElement("object")}}</li> + <li>{{HTMLElement("output")}}</li> + <li>{{HTMLElement("progress")}}</li> + <li>{{HTMLElement("select")}}</li> + <li>{{HTMLElement("textarea")}}</li> +</ul> + +<p>This category contains several sub-categories:</p> + +<dl> + <dt id="Form_listed">listed</dt> + <dd>Elements that are listed in the <a href="/en-US/docs/DOM/form.elements" title="DOM/form.elements">form.elements</a> 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")}}.</dd> + <dt id="Form_labelable">labelable</dt> + <dd>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")}}.</dd> + <dt id="Form_submittable">submittable</dt> + <dd>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")}}.</dd> + <dt id="Form_resettable">resettable</dt> + <dd>Elements that can be affected when a form is reset. Contains {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("output")}},{{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.</dd> +</dl> + +<h2 id="Secondary_categories">Secondary categories</h2> + +<p>There are some secondary classifications of elements that can be useful to be aware of as well.</p> + +<h3 id="Script-supporting_elements">Script-supporting elements</h3> + +<p><strong>Script-supporting elements</strong> 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.</p> + +<p>The script-supporting elements are:</p> + +<ul> + <li>{{HTMLElement("script")}}</li> + <li>{{HTMLElement("template")}}</li> +</ul> + +<h2 id="Transparent_content_model">Transparent content model</h2> + +<p>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.</p> + +<p>For example, the {{HTMLElement("del")}} and {{HTMLELement("ins")}} elements are transparent:</p> + +<pre><p>We hold these truths to be <del><em>sacred &amp; undeniable</em></del> <ins>self-evident</ins>.</p> +</pre> + +<p>If those elements were removed, this fragment would still be valid HTML (if not correct English).</p> + +<pre><p>We hold these truths to be <em>sacred &amp; undeniable</em> self-evident.</p> +</pre> + +<h2 id="Outros_modelos_de_conteúdo">Outros modelos de conteúdo</h2> + +<p>Seção raiz.</p> 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 new file mode 100644 index 0000000000..fd11f62887 --- /dev/null +++ b/files/pt-pt/web/guide/html/utilizar_estruturas_e_seccoes_de_html/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 +--- +<div class="warning"> +<p><strong>Importante</strong>: 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 <a href="http://www.w3.org/TR/html5/sections.html#outline">estrutura</a> não pode ser invocado para transmitir a estrutura do documento aos utilizadores. Recomenda-se que os autores utilizem <a href="http://www.w3.org/TR/html5/sections.html#rank">rank</a> (<code><a href="http://www.w3.org/TR/html5/sections.html#the-h1,-h2,-h3,-h4,-h5,-and-h6-elements">h1</a></code>-<code><a href="http://www.w3.org/TR/html5/sections.html#the-h1,-h2,-h3,-h4,-h5,-and-h6-elements">h6</a></code>) para transmitir a estrutura do documento.</p> +</div> + +<p>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.</p> + +<h2 id="Estrutura_de_um_documento_em_HTML_4">Estrutura de um documento em HTML 4</h2> + +<p>A estrutura de um documento, por exemplo, a estrutura de semântica do que está entre <code><body></code> e <code></body></code>, é 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.</p> + +<p>So the following mark-up:</p> + +<div style="overflow: hidden;"> +<pre class="brush:xml"><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> +</pre> +</div> + +<p>leads to the following outline (without the implicit level numbers displayed):</p> + +<pre>1. Forest elephants + 1.1 Habitat +</pre> + +<p>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,</p> + +<pre class="brush:xml"><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> +</pre> + +<p>leads to the following outline:</p> + +<pre>1. Forest elephants + 1.1 Habitat + 1.2 Diet +2. Mongolian gerbils +</pre> + +<h2 id="Problemas_resolvidos_pelo_HTML5">Problemas resolvidos pelo HTML5</h2> + +<p>The HTML 4 definition of the structure of a document and its implied outlining algorithm is very rough and leads to numerous problems:</p> + +<ol> + <li>Usage of {{HTMLElement("div")}} for defining semantic sections, without defining specific values for the <strong>class</strong> 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 <a class="external" href="http://en.wikipedia.org/wiki/Assistive_technology" title="http://en.wikipedia.org/wiki/Assistive_technology">assistive technology</a>, 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.</li> + <li>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.</li> + <li>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.</li> + <li>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.</li> +</ol> + +<p>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.</p> + +<h2 id="O_algoritmo_de_estrutura_de_HTML5">O algoritmo de estrutura de HTML5</h2> + +<p>Let's consider the algorithms underlying the way HTML handles sections and outlines.</p> + +<h3 id="Definir_secções">Definir secções</h3> + +<p>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. </p> + +<div class="note">Each section can have its own heading hierarchy. Therefore, even a nested section can have an {{HTMLElement("h1")}}. See {{anch("Defining headings")}}</div> + +<p>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:</p> + +<pre class="brush:xml"><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></pre> + +<p>This leads to the following outline:</p> + +<pre>1. Forest elephants + 1.1 Introduction + 1.2 Habitat +</pre> + +<h3 id="Definir_cabeçalhos">Definir cabeçalhos</h3> + +<p>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.</p> + +<p>The heading elements have a <em>rank</em> given by the number in the element name, where {{HTMLElement("h1")}} has the <em>highest</em> rank, and {{HTMLElement("h6")}} has the <em>lowest</em> 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:</p> + +<pre class="brush:xml"><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></pre> + +<p>This creates the following outline:</p> + +<pre>1. Forest elephants + 1.1 Habitat +2. Mongolian gerbils</pre> + +<p>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.)</p> + +<h3 id="Implicit_sectioning">Implicit sectioning</h3> + +<p>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 <em>implicit sectioning</em>.</p> + +<p>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:</p> + +<pre class="brush:xml"><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></pre> + +<p>leading to the following outline:</p> + +<pre>1. Forest elephants + 1.1 Habitat <em>(implicitly defined by the h3 element)</em> +</pre> + +<p>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: </p> + +<pre class="brush:xml"><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></pre> + +<p>leading to the following outline: </p> + +<pre>1. Forest elephants +2. Mongolian gerbils <em>(implicitly defined by the h1 element, which closed the previous section at the same time)</em> +</pre> + +<p>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:</p> + +<pre class="brush:xml"><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></pre> + +<p>leading to the following outline:</p> + +<pre>1. Mammals + 1.1 Whales <em>(implicitly defined by the h2 element)</em> + 1.2 Forest elephants <em>(explicitly defined by the section element)</em> + 1.3 Mongolian gerbils <em>(implicitly defined by the h3 element, which closes the previous section at the same time)</em> +2. Reptiles <em>(implicitly defined by the h2 element, which closes the previous section at the same time)</em> +</pre> + +<p>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.</p> + +<p>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.</p> + +<h3 id="Sectioning_roots"><a name="sectioning_root">Sectioning roots</a></h3> + +<p> A <a id="sectioning root" name="sectioning root">sectioning root</a> 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")}}.</p> + +<p>Example:</p> + +<pre class="brush:xml"><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> +</pre> + +<p>This example results in the following outline:</p> + +<pre>1. Forest elephants + 1.1 Introduction + 1.2 Habitat</pre> + +<p>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.</p> + +<h3 id="Sections_outside_the_outline">Sections outside the outline</h3> + +<p> HTML5 introduces two new elements that allow defining sections that don't belong to the main outline of a web document:</p> + +<ol> + <li>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.</li> + <li>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.</li> +</ol> + +<h3 id="Cabeçalhos_e_Rodapés">Cabeçalhos e Rodapés</h3> + +<p>HTML5 also introduces two new elements that can be used to mark up the header and the footer of a section:</p> + +<ol> + <li>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.</li> + <li>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.</li> +</ol> + +<p>These do not create new sections in the outline, rather, they mark up content inside sections of the page.</p> + +<h2 id="Addresses_in_sectioning_elements">Addresses in sectioning elements</h2> + +<p>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.</p> + +<p>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.</p> + +<h2 id="Utilizar_elementos_de_HTML5_nos_navegadores_não_HTML5">Utilizar elementos de HTML5 nos navegadores não HTML5</h2> + +<p>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 <code>display:inline</code> by default:</p> + +<pre class="brush: css">article, aside, footer, header, hgroup, nav, section { + display:block; +} +</pre> + +<p>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.</p> + +<p>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:</p> + +<pre class="brush:xml"><!--[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]--> +</pre> + +<p>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:</p> + +<pre class="brush:xml"><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> +</pre> + +<p>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:</p> + +<pre class="brush:xml"><!--[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]--> +</pre> + +<h2 id="Conclusão">Conclusão</h2> + +<p>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.</p> + +<div>{{HTML5ArticleTOC()}}</div> diff --git a/files/pt-pt/web/guide/index.html b/files/pt-pt/web/guide/index.html new file mode 100644 index 0000000000..8ba5341845 --- /dev/null +++ b/files/pt-pt/web/guide/index.html @@ -0,0 +1,63 @@ +--- +title: Guias do Programador +slug: Web/Guide +tags: + - API + - Guía + - Landing + - Web +translation_of: Web/Guide +--- +<p>Estes artigos proporcionam informação de como começar, para o ajudar a utilizar as tecnologias da Web específicas e APIs.</p> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt class="landingPageList"><a href="/pt-PT/docs/Learn/HTML">Aprender HTML; Guias e Tutoriais</a></dt> + <dd class="landingPageList"><strong>Linguagem de Marcacao em Hiper Texto (HTML)</strong> e a linguaguem padrao de quase todos os navegadores. Maior parte do que voce ve na janela do seu navegador e descrito, fundamentalmente, usando HTML.</dd> + <dt class="landingPageList"><a href="/pt-PT/docs/Learn/CSS">Aprender a estilizar HTML, utilizando CSS</a></dt> + <dd class="landingPageList">Folhas de Estilo em Cascata (CSS) e uma linguaguem baseada em folhas de estilos usada para definir a apresentacao do documento escrito com HTML.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/Guide/Audio_and_video_delivery">Apresentacao de videos e audios</a></dt> + <dd class="landingPageList">Nos conseguimos apresentar videos e audios na web de diversas maneiras, desde ficheiros 'estaticos' a fluxos de adaptacoes em directo. Este artigo e precebido como o ponto inicial para a exploracao de varios mecanismos de apresentacao baseados na comunicao i compatiilidade com os navegadores populares.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/Guide/Audio_and_video_manipulation">Manipulacao de videos e audios</a></dt> + <dd class="landingPageList">A beleza da web e que voce pode combinar tecnologias para criar novos formularios. Tendo audios e videos nativos no navegador significa que nos podemos usar este fluxo de dados com tecnologias como {{htmelement('canvas')}}, <a href="/pt-PT/docs/Web/WebGL">WebGL</a> ou <a href="/pt-PT/docs/Web/API/Web_Audio_API">API de Áudio da Web</a> para modificar o audio e o video directamente, por exemplo adicionando efeitos como ressonancia/compressao ao audio, ou filtros como escala de cinza/sepia aos videos. Este artigo providencia as referencias para explicar o que voce precisa.</dd> + <dt class="landingPageList"><a href="/pt-PT/docs/Web/Guide/Eventos" style="">Guia do programador de eventos</a></dt> + <dd class="landingPageList">Eventos referem se a duas coisas: o design padrao usado para manter a sincronizacao de varios incidentes que ocorrem durante a execucao da pagina web; i a nomenclatura, caracterizacao, i uso de varios i diversos tipos de ocorrencias.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/Guide/AJAX">AJAX</a></dt> + <dd class="landingPageList">AJAX is a term that defines a group of technologies allowing web applications to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions.</dd> + <dt class="landingPageList"><a href="/pt-PT/docs/Web/Guide/Gráficos">Gráficos na Web</a></dt> + <dd class="landingPageList">Modern web sites and applications often need to present graphics of varying sophistication.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API">Guide to web APIs</a></dt> + <dd class="landingPageList">A list of all web APIs and what they do.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/JavaScript" title="/en-US/docs/JavaScript">JavaScript</a></dt> + <dd>JavaScript is the powerful scripting language used to create applications for the Web.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Localizations_and_character_encodings">Localizations and character encodings</a></dt> + <dd class="landingPageList">Browsers process text as Unicode internally. However, a way of representing characters in terms of bytes (character encoding) is used for transferring text over the network to the browser. The <a class="external external-icon" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#charset">HTML specification recommends the use of the UTF-8 encoding</a> (which can represent all of Unicode), and regardless of the encoding used requires Web content to declare that encoding.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Mobile">Mobile web development</a></dt> + <dd class="landingPageList">This article provides an overview of some of the main techniques needed to design web sites that work well on mobile devices. If you're looking for information on Mozilla's Firefox OS project, see the <a href="https://developer.mozilla.org/en/Mozilla/Firefox_OS" title="Boot to Gecko">Firefox OS</a> page. Or you might be interested in details about <a href="https://developer.mozilla.org/pt-PT/docs/Mozilla/Firefox_for_Android">Firefox para Android</a>.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/Apps/Progressive#Core_PWA_guides">Progressive web apps</a></dt> + <dd class="landingPageList">Progressive web apps (PWAs) use modern web APIs along with traditional progressive enhancement strategy to create cross-platform web applications. These apps work everywhere and provide several features that give them the same user experience advantages as native apps. This set of guides tells you all you need to know about PWAs.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Performance">Optimization and performance</a></dt> + <dd class="landingPageList">When building modern web apps and sites, it's important to make your content work quickly and efficiently. This lets it perform effectively for both powerful desktop systems and weaker handheld devices.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML">Parsing and serializing XML</a></dt> + <dd class="landingPageList">The web platform provides different methods of parsing and serializing XML, each with its own pros and cons.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/WOFF">The Web Open Font Format (WOFF)</a></dt> + <dd class="landingPageList">WOFF (Web Open Font Format) is a font file format that is free for anyone to use on the web.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects">Using FormData objects</a></dt> + <dd class="landingPageList">The <a href="https://developer.mozilla.org/en/DOM/XMLHttpRequest/FormData"><code>FormData</code></a> object lets you compile a set of key/value pairs to send using <code>XMLHttpRequest</code>. It's primarily intended for sending form data, but can be used independently from forms in order to transmit keyed data. The transmission is in the same format that the form's <code>submit()</code> method would use to send the data if the form's encoding type were set to "multipart/form-data".</dd> + <dt class="landingPageList"><a href="/en-US/docs/Glossary">Glossary</a></dt> + <dd class="landingPageList">Defines numerous technical terms related to the Web and Internet.</dd> +</dl> +</div> +</div> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/Reference" title="/en-US/docs/Web/Reference">Referências de Tecnologia da Web</a></li> +</ul> diff --git a/files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html b/files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html new file mode 100644 index 0000000000..2aaefab31d --- /dev/null +++ b/files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html @@ -0,0 +1,581 @@ +--- +title: Aplicar cor aos elementos de HTML utilizando CSS +slug: Web/HTML/Aplicar_cor_elementos_HTML_utilizando_CSS +tags: + - CSS + - Cores de CSS + - Cores de HTML + - Estilo de HTML + - Estilos de HTML + - Guía + - HTML + - Principiante + - cor +translation_of: Web/HTML/Applying_color +--- +<div>{{HTMLRef}}</div> + +<p>A utilização de cor é uma forma fundamental da expressão humana. Children experiment with color before they even have the manual dexterity to draw. Maybe that's why color is one of the first things people often want to experiment with when learning to develop web sites. <span class="seoSummary">With <a href="/en-US/docs/Web/CSS">CSS</a>, there lots of ways to add color to your <a href="/en-US/docs/Web/HTML">HTML</a> <a href="/en-US/docs/Web/HTML/Element">elements</a> to create just the look you want. This article is a primer introducing each of the ways CSS color can be used in HTML.</span></p> + +<p>Fortunately, adding color to your HTML is actually really easy to do, and you can add color to nearly anything.</p> + +<p>We're going to touch on most of what you'll need to know when using color, including a {{anch("Things that can have color", "list of what you can color and what CSS properties are involved")}}, {{anch("How to describe a color", "how you describe colors")}}, and how to actually {{anch("Using color", "use colors both in stylesheets and in scripts")}}. We'll also take a look at how to {{anch("Letting the user picka color", "let the user pick a color")}}.</p> + +<p>Then we'll wrap things up with a brief discussion of how to {{anch("Using color wisely", "use color wisely")}}: how to select appropriate colors, keeping in mind the needs of people with differing visual capabilities.</p> + +<h2 id="Coisas_que_podem_ter_cor">Coisas que podem ter cor</h2> + +<p>At the element level, everything in HTML can have color applied to it. Instead, let's look at things in terms of the kinds of things that are drawn in the elements, such as text and borders and so forth. For each, we'll see a list of the CSS properties that apply color to them.</p> + +<p>At a fundamental level, the {{cssxref("color")}} property defines the foreground color of an HTML element's content and the {{cssxref("background-color")}} property defines the element's background color. These can be used on just about any element.</p> + +<h3 id="Texto">Texto</h3> + +<p>Whenever an element is rendered, these properties are used to determine the color of the text, its background, and any decorations on the text.</p> + +<dl> + <dt>{{cssxref("color")}}</dt> + <dd>The color to use when drawing the text and any <a href="/en-US/docs/Learn/CSS/Styling_text/Fundamentals#Font_style_font_weight_text_transform_and_text_decoration">text decorations</a> (such as the addition of under- or overlines, strike-through lines, and so forth.</dd> + <dt>{{cssxref("background-color")}}</dt> + <dd>The text's background color.</dd> + <dt>{{cssxref("text-shadow")}}</dt> + <dd>Configures a shadow effect to apply to text. Among the options for the shadow is the shadow's base color (which is then blurred and blended with the background based on the other parameters). See {{SectionOnPage("/en-US/docs/Learn/CSS/Styling_text/Fundamentals", "Text drop shadows")}} to learn more.</dd> + <dt>{{cssxref("text-decoration-color")}}</dt> + <dd>By default, text decorations (such as underlines, strikethroughs, etc) use the <code>color</code> property as their colors. However, you can override that behavior and use a different color for them with the <code>text-decoration-color</code> property.</dd> + <dt>{{cssxref("text-emphasis-color")}}</dt> + <dd>The color to use when drawing emphasis symbols adjacent to each character in the text. This is used primarily when drawing text for East Asian languages.</dd> + <dt>{{cssxref("caret-color")}}</dt> + <dd>The color to use when drawing the {{Glossary("caret")}} (sometimes referred to as the text input cursor) within the element. This is only useful in elements that are editable, such as {{HTMLElement("input")}} and {{HTMLElement("textarea")}} or elements whose HTML {{htmlattrxref("contenteditable")}} attribute is set.</dd> +</dl> + +<h3 id="Caixas">Caixas</h3> + +<p>Every element is a box with some sort of content, and has a background and a border in addition to whatever contents the box may have.</p> + +<dl> + <dt>{{anch("Borders")}}</dt> + <dd>See the section {{anch("Borders")}} for a list of the CSS properties you can use to set the colors of a box's borders.</dd> + <dt>{{cssxref("background-color")}}</dt> + <dd>The background color to use in areas of the element that have no foreground content.</dd> + <dt>{{cssxref("column-rule-color")}}</dt> + <dd>The color to use when drawing the line separating columns of text.</dd> + <dt>{{cssxref("outline-color")}}</dt> + <dd>The color to use when drawing an outline around the outside of the element. This outline is different from the border in that it doesn't get space set aside for it in the document (so it may overlap other content). It's generally used as a focus indicator, to show which element will receive input events.</dd> +</dl> + +<h3 id="Contornos">Contornos</h3> + +<p>Any element can have a <a href="/en-US/docs/Learn/CSS/Styling_boxes/Borders">border</a> drawn around it. A basic element border is a line drawn around the edges of the element's content. See {{SectionOnPage("/en-US/docs/Learn/CSS/Introduction_to_CSS/Box_model", "Box properties")}} to learn about the relationship between elements and their borders, and the article <a href="/en-US/docs/Learn/CSS/Styling_boxes/Borders">Styling borders using CSS</a> to learn more about applying styles to borders.</p> + +<p>You can use the {{cssxref("border")}} shorthand property, which lets you configure everything about the border in one shot (including non-color features of borders, such as its <a href="/en-US/docs/Web/CSS/border-width">width</a>, <a href="/en-US/docs/Web/CSS/border-style">style</a> (solid, dashed, etc.), and so forth.</p> + +<dl> + <dt>{{cssxref("border-color")}}</dt> + <dd>Specifies a single color to use for every side of the element's border.</dd> + <dt>{{cssxref("border-left-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-top-color")}}, and {{cssxref("border-bottom-color")}}</dt> + <dd>Lets you set the color of the corresponding side of the element's border.</dd> + <dt>{{cssxref("border-block-start-color")}} and {{cssxref("border-block-end-color")}}</dt> + <dd>With these, you can set the color used to draw the borders which are closest to the start and end of the block the border surrounds. In a left-to-right writing mode (such as the way English is written), the block start border is the top edge and the block end is the bottom. This differs from the inline start and end, which are the left and right edges (corresponding to where each line of text in the box begins and ends).</dd> + <dt>{{cssxref("border-inline-start-color")}} and {{cssxref("border-inline-end-color")}}</dt> + <dd>These let you color the edges of the border closest to to the beginning and the end of the start of lines of text within the box. Which side this is will vary depending on the {{cssxref("writing-mode")}}, {{cssxref("direction")}}, and {{cssxref("text-orientation")}} properties, which are typically (but not always) used to adjust text directionality based on the language being displayed. For example, if the box's text is being rendered right-to-left, then the <code>border-inline-start-color</code> is applied to the right side of the border.</dd> +</dl> + +<h3 id="Outros_modos_para_utilizar_a_cor">Outros modos para utilizar a cor</h3> + +<p>CSS isn't the only web technology that supports color. There are graphics technologies that are available on the web which also support color.</p> + +<dl> + <dt>The HTML <a href="/en-US/docs/Web/API/Canvas_API">Canvas API</a></dt> + <dd>Lets you draw 2D bitmapped graphics in a {{HTMLElement("canvas")}} element. See our <a href="/en-US/docs/Web/API/Canvas_API/Tutorial">Canvas tutorial</a> to learn more.</dd> + <dt><a href="/en-US/docs/Web/SVG">SVG</a> (Scalable Vector Graphics)</dt> + <dd>Lets you draw images using commands that draw specific shapes, patterns, and lines to produce an image. SVG commands are formatted as XML, and can be embedded directly into a web page or can be placed in he page using the {{HTMLElement("img")}} element, just like any other type of image.</dd> + <dt><a href="/en-US/docs/Web/API/WebGL_API">WebGL</a></dt> + <dd>The Web Graphics Library is an OpenGL ES-based API for drawing high-performance 2D and 3D graphics on the Web. See <a href="/en-US/docs/Learn/WebGL">Learn WebGL for 2D and 3D</a> graphics to find out more.</dd> +</dl> + +<h2 id="Como_descrever_uma_cor">Como descrever uma cor</h2> + +<p>In order to represent a color in CSS, you have to find a way to translate the analog concept of "color" into a digital form that a computer can use. This is typically done by breaking down the color into components, such as how much of each of a set of primary colors to mix together, or how bright to make the color. As such, there are several ways you can describe color in CSS.</p> + +<p>For more detailed discussion of each of the color value types, see the reference for the CSS {{cssxref("<color>")}} unit.</p> + +<h3 id="Palavras-chave">Palavras-chave</h3> + +<p>A set of standard color names have been defined, letting you use these keywords instead of numeric representations of colors if you choose to do so and there's a keyword representing the exact color you want to use. Color keywords include the standard primary and secondary colors (such as <code>red</code>, <code>blue</code>, or <code>orange</code>), shades of gray (from <code>black</code> to <code>white</code>, including colors like <code>darkgray</code> and <code>lightgrey</code>), and a variety of other blended colors including <code>lightseagreen</code>, <code>cornflowerblue</code>, and <code>rebeccapurple</code>.</p> + +<p>See {{SectionOnPage("/en-US/docs/Web/CSS/color_value", "Color keywords", "code")}} for a list of all available color keywords.</p> + +<h3 id="Valores_RGB">Valores RGB</h3> + +<p>There are three ways to represent an RGB color in CSS.</p> + +<h4 id="Hexadecimal_string_notation">Hexadecimal string notation</h4> + +<p>Hexadecimal string notation represents a color using hexadecimal digits to represent each of the color components (red, green, and blue). It may also include a fourth compoment: the alpha channel (or opacity). Each color component can be represented as a number between 0 and 255 (0x00 and 0xFF) or, optionally, as a number between 0 and 15 (0x0 and 0xF). All components <em>must</em> be specified using the same number of digits. If you use the single-digit notation, the final color is computed by using each component's digit twice; that is, <code>"#D"</code> becomes <code>"#DD"</code> when drawing.</p> + +<p>A color in hexadecimal string notation always begins with the character <code>"#"</code>. After that come the hexadecimal digits of the color code. The string is case-insensitive.</p> + +<dl> + <dt><code>"#rrggbb"</code></dt> + <dd>Specifies a fully-opaque color whose red component is the hexadecimal number <code>0xrr</code>, green component is <code>0xgg</code>, and blue component is <code>0xbb</code>.</dd> + <dt><code>"#rrggbbaa"</code></dt> + <dd>Specifies a color whose red component is the hexadecimal number <code>0xrr</code>, green component is <code>0xgg</code>, and blue component is <code>0xbb</code>. The alpha channel is specified by <code>0xaa</code>; the lower this value is, the more translucent the color becomes.</dd> + <dt><code>"#rgb"</code></dt> + <dd>Specifies a color whose red component is the hexadecimal number <code>0xrr</code>, green component is <code>0xgg</code>, and blue component is <code>0xbb</code>.</dd> + <dt><code>"#rgba"</code></dt> + <dd>Specifies a color whose red component is the hexadecimal number <code>0xrr</code>, green component is <code>0xgg</code>, and blue component is <code>0xbb</code>. The alpha channel is specified by <code>0xaa</code>; the lower this value is, the more translucent the color becomes.</dd> +</dl> + +<p>As an example, you can represent the opaque color bright blue as <code>"#0000ff"</code> or <code>"#00f"</code>. To make it 25% opaque, you can use <code>"#0000ff44"</code> or <code>"#00f4"</code>.</p> + +<h4 id="RGB_functional_notation">RGB functional notation</h4> + +<p>RGB (Red/Green/Blue) functional notation, like hexadecimal string notation, represents colors using their red, green, and blue components (as well as, optionally, an alpha channel component for opacity). However, instead of using a string, the color is defined using the CSS function {{cssxref("rgb()")}}. This function accepts as its input parameters the values of the red, green, and blue components and an optional fourth parameter, the value for the alpha channel.</p> + +<p>Legal values for each of these parameters are:</p> + +<dl> + <dt><code>red</code>, <code>green</code>, and <code>blue</code></dt> + <dd>Each must be an {{cssxref("<integer>")}} value between 0 and 255 (inclusive), or a {{cssxref("<percentage>")}} from 0% to 100%.</dd> + <dt><code>alpha</code></dt> + <dd>The alpha channel is a number between 0.0 (fully transparent) and 1.0 (fully opaque). You can also specify a percentage where 0% is the same as 0.0 and 100% is the same as 1.0.</dd> +</dl> + +<p>For example, a bright red that's 50% opaque can be represented as <code>rgb(255, 0, 0, 0.5)</code> or <code>rgb(100%, 0, 0, 50%)</code>.</p> + +<h3 id="Notação_funcional_de_HSL">Notação funcional de HSL</h3> + +<p>Designers and artists often prefer to work using the {{interwiki("wikipedia", "HSL and HSV", "HSL")}} (Hue/Saturation/Luminosity) color method. On the web, HSL colors are represented using HSL functional notation. The <code>hsl()</code> CSS function is very similar to the <code>rgb()</code> function in usage otherwise.</p> + +<div style="padding-bottom: 20px;"> +<figure style="width: 500px;"><img alt="HSL color cylinder" src="https://mdn.mozillademos.org/files/15445/1200px-HSL_color_solid_cylinder_alpha_lowgamma.png" style="height: 375px; width: 500px;"> +<figcaption><em><strong>Figure 1. An HSL color cylinder.</strong> Hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. Saturation is a percentage of how much of the way between being a shade of gray and having the maximum possible amount of the given hue. As the value of luminance (or lightness) increases, the color transitions from the darkest possible to the brightest possible (from black to white). Image courtesy of user <a href="http://commons.wikimedia.org/wiki/User:SharkD">SharkD</a> on <a href="https://www.wikipedia.org/">Wikipedia</a>, distributed under the <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY-SA 3.0</a> license.</em></figcaption> +</figure> +</div> + +<p>The value of the hue (H) component of an HSL color is an angle from red around through yellow, green, cyan, blue, and magenta (ending up back at red again at 360°) that identifies what the base color is. The value can be specified in any {{cssxref("<angle>")}} unit supported by CSS, including degrees (<code>deg</code>), radians (<code>rad</code>), gradians (<code>grad</code>), or turns (<code>turn</code>). But this doesn't control how vivid or dull, or how bright or dark the color is.</p> + +<p>The saturation (S) component of the color specifies what percentage of the final color is comprised of the specified hue. The rest is defined by the grey level provided by the luminance (L) component.</p> + +<p>Think of it like creating the perfect paint color:</p> + +<ol> + <li>You start with base paint that's the maximum intensity possible for a given color, such as the most intense blue that can be represented by the user's screen. This is the <strong>hue</strong> (H) component: a value representing the angle around the color wheel for the vivid hue we want to use as our base.</li> + <li>Then select a greyscale paint that corresponds how bright you want the color to be; this is the luminance. Do you want it to be very bright and nearly white, or very dark and closer to black, or somewhere in between? This is specified using a percentage, where 0% is perfectly black and 100% is perfectly white. (regardless of the saturation or hue). In between values are a literal grey area.</li> + <li>Now that you have a grey paint and a perfectly vivid color, you need to mix them together. The saturation (S) component of the color indicates what percentage of the final color should be comprised of that perfectly vivid color. The rest of the final color is made up of the grey paint that represents the saturation.</li> +</ol> + +<p>You can also optionally include an alpha channel, to make the color less than 100% opaque.</p> + +<p>Here are some sample colors in HSL notation:</p> + +<div id="hsl-swatches"> +<div class="hidden"> +<pre class="brush: css">table { + border: 1px solid black; + font: 16px "Open Sans", Helvetica, Arial, sans-serif; + border-spacing: 0; + border-collapse: collapse; +} + +th, td { + border: 1px solid black; + padding:4px 6px; + text-align: left; +} + +th { + background-color: hsl(0, 0%, 75%); +}</pre> + +<pre class="brush: html"><table> + <thead> + <tr> + <th scope="col">Color in HSL notation</th> + <th scope="col">Example</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>hsl(90deg, 100%, 50%)</code></td> + <td style="background-color: hsl(90deg, 100%, 50%);">&nbsp;</td> + </tr> + <tr> + <td><code>hsl(90, 100%, 50%)</code></td> + <td style="background-color: hsl(90, 100%, 50%);">&nbsp;</td> + </tr> + <tr> + <td><code>hsl(0.15turn, 50%, 75%)</code></td> + <td style="background-color: hsl(0.15turn, 50%, 75%);">&nbsp;</td> + </tr> + <tr> + <td><code>hsl(0.15turn, 90%, 75%)</code></td> + <td style="background-color: hsl(0.15turn, 90%, 75%);">&nbsp;</td> + </tr> + <tr> + <td><code>hsl(0.15turn, 90%, 50%)</code></td> + <td style="background-color: hsl(0.15turn, 90%, 50%);">&nbsp;</td> + </tr> + <tr> + <td><code>hsl(270deg, 90%, 50%)</code></td> + <td style="background-color: hsl(270deg, 90%, 50%);">&nbsp;</td> + </tr> + </tbody> +</table></pre> +</div> + +<p>{{EmbedLiveSample("hsl-swatches", 300, 260)}}</p> +</div> + +<div class="note"> +<p>Note that when you omit the hue's unit, it's assumed to be in degrees (<code>deg</code>).</p> +</div> + +<h2 id="Utilizar_a_cor">Utilizar a cor</h2> + +<p>Now that you know what CSS properties exist that let you apply color to elements and the formats you can use to describe colors, you can put this together to begin to make use of color. As you may have seen from the list under {{anch("Things that can have color")}}, there are plenty of things you can color with CSS. Let's look at this from two sides: using color within a {{Glossary("stylesheet")}}, and adding and changing color using {{Glossary("JavaScript")}} code to alter the styles of elements.</p> + +<h3 id="Especificar_cores_nas_folhas_de_estilo">Especificar cores nas folhas de estilo</h3> + +<p>The easiest way to apply color to elements—and the way you'll usually do it—is to simply specify colors in the CSS that's used when rendering elements. While we won't use every single property mentioned previously, we'll look at a couple of examples. The concept is the same anywhere you use color.</p> + +<p>Let's take a look at an example, starting by looking at the results we're trying to achieve:</p> + +<div>{{EmbedLiveSample("Specifying_colors_in_stylesheets", 650, 150)}}</div> + +<h4 id="HTML">HTML</h4> + +<p>The HTML responsible for creating the above example is shown here:</p> + +<pre class="brush: html"><div class="wrapper"> + <div class="box boxLeft"> + <p> + This is the first box. + </p> + </div> + <div class="box boxRight"> + <p> + This is the second box. + </p> + </div> +</div></pre> + +<p>This is pretty simple, using a {{HTMLElement("div")}} as a wrapper around the contents, which consists of two more <code><div></code>s, each styled differently with a single paragraph ({{HTMLElement("p")}}) in each box.</p> + +<p>The magic happens, as usual, in the CSS, where we'll apply colors define the layout for the HTML above.</p> + +<h4 id="CSS">CSS</h4> + +<p>We'll look at the CSS to create the above results a piece at a time, so we can review the interesting parts one by one.</p> + +<pre class="brush: css">.wrapper { + width: 620px; + height: 110px; + margin: 0; + padding: 10px; + border: 6px solid mediumturquoise; +}</pre> + +<p>The <code>.wrapper</code> class is used to assign styles to the {{HTMLElement("div")}} that encloses all of our other content. This establishes thesize of the container using {{cssxref("width")}} and {{cssxref("height")}} as well as its {{cssxref("margin")}} and {{cssxref("padding")}}.</p> + +<p>Of more interest to our discussion here is the use of the {{cssxref("border")}} property to establish a border around the outside edge of the element. This border is a solid line, 6 pixels wide, in the color <code>mediumturquoise</code>.</p> + +<p>Our two colored boxes share a number of properties in common, so next we establish a class, <code>.box</code>, that defines those shared properties:</p> + +<pre class="brush: css">.box { + width: 290px; + height: 100px; + margin: 0; + padding: 4px 6px; + font: 28px "Marker Felt", "Zapfino", cursive; + display: flex; + justify-content: center; + align-items: center; +}</pre> + +<p>In brief, <code>.box</code> establishes the size of each box, as well as the configuration of the font used within. We also take advantage of <a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout">CSS Flexbox</a> to easily center the contents of each box. We enable <code>flex</code> mode using {{cssxref("display", "display: flex")}}, and set both {{cssxref("justify-content")}} and {{cssxref("align-items")}} to <code>center</code>. Then we can create a class for each of the two boxes that defines the propeties that differ between the two.</p> + +<pre class="brush: css">.boxLeft { + float: left; + background-color: rgb(245, 130, 130); + outline: 2px solid darkred; +}</pre> + +<p>The <code>.boxLeft</code> class—which, cleverly, is used to style the box on the left—floats the box to the left, then sets up the colors:</p> + +<ul> + <li>The box's background color is set by changing the value of the CSS {{cssxref("background-color")}} property to <code>rgb(245, 130, 130)</code>.</li> + <li>An outline is defined for the box. Unlike the more commonly used <code>border</code>, {{cssxref("outline")}} doesn't affect layout at all; it draws over the top of whatever may happen to be outside the element's box instead of making room as <code>border</code> does. This outline is a solid, dark red line that's two pixels thick. Note the use of the <code>darkred</code> keyword when specifying the color.</li> + <li>Notice that we're not explicitly setting the text color. That means the value of {{cssxref("color")}} will be inherited from the nearest containing element that defines it. By default, that's black.</li> +</ul> + +<pre class="brush: css">.boxRight { + float: right; + background-color: hsl(270deg, 50%, 75%); + outline: 4px dashed rgb(110, 20, 120); + color: hsl(0deg, 100%, 100%); + text-decoration: underline wavy #88ff88; + text-shadow: 2px 2px 3px black; +}</pre> + +<p>Finally, the <code>.boxRight</code> class describes the unique properties of the box that's drawn on the right. It's configured to float the box to the right so that it appears next to the previous box. Then the following colors are established:</p> + +<ul> + <li>The <code>background-color</code> is set using the HSL value specified using <code>hsl(270deg, 50%, 75%)</code>. This is a medium purple color.</li> + <li>The box's <code>outline</code> is used to specify that the box should be enclosed in a four pixel thick dashed line whose color is a somewhat deeper purple (<code>rgb(110, 20, 120)</code>).</li> + <li>The foreground (text) color is specified by setting the {{cssxref("color")}} property to <code>hsl(0deg, 100%, 100%)</code>. This is one of many ways to specify the color white.</li> + <li>We add a green wavy line under the text with {{cssxref("text-decoration")}}.</li> + <li>Finally, a bit of a shadow is added to the text using {{cssxref("text-shadow")}}. Its <code>color</code> parameter is set to <code>black</code>.</li> +</ul> + +<h2 id="Deixar_que_o_utilizador_escolha_uma_cor">Deixar que o utilizador escolha uma cor</h2> + +<p>There are many situations in which your web site may need to let the user select a color. Perhaps you have a customizable user interface, or you're implementing a drawing app. Maybe you have editable text and need to let the user choose the text color. Or perhaps your app lets the user assign colors to folders or items. Although historically it's been necessary to implement your own {{interwiki("wikipedia", "color picker")}}, HTML now provides support for browsers to provide one for your use through the {{HTMLElement("input")}} element, by using <code>"color"</code> as the value of its {{htmlattrxref("type", "input")}} attribute.</p> + +<p>The <code><input></code> element represents a color only in the {{anch("Hexadecimal string notation", "hexadecimal string notation")}} covered above.</p> + +<h3 id="Exemplo_Escolher_uma_cor">Exemplo: Escolher uma cor</h3> + +<p>Let's look at a simple example, in which the user can choose a color. As the user adjusts the color, the border around the example changes to reflect the new color. After finishing up and picking the final color, the color picker's value is displayed.</p> + +<p>{{EmbedLiveSample("Example_Picking_a_color", 525, 275)}}</p> + +<div class="note"> +<p>On macOS, you indicate that you've finalized selection of the color by closing the color picker window.</p> +</div> + +<h4 id="HTML_2">HTML</h4> + +<p>The HTML here creates a box that contains a color picker control (with a label created using the {{HTMLElement("label")}} element) and an empty paragraph element ({{HTMLElement("p")}}) into which we'll output some text from our JavaScript code.</p> + +<pre class="brush: html"><div id="box"> + <label for="colorPicker">Border color:</label> + <input type="color" value="#8888ff" id="colorPicker"> + <p id="output"></p> +</div></pre> + +<h4 id="CSS_2">CSS</h4> + +<p>The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won't last, courtesy of the JavaScript below...</p> + +<pre class="brush: css">#box { + width: 500px; + height: 200px; + border: 2px solid rgb(245, 220, 225); + padding: 4px 6px; + font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif" +}</pre> + +<h4 id="JavaScript">JavaScript</h4> + +<p>The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <code><a href="/en-US/docs/Web/HTML/Element/input/color"><input type="color"></a></code> element.</p> + +<pre class="brush: js">let colorPicker = document.getElementById("colorPicker"); +let box = document.getElementById("box"); +let output = document.getElementById("output"); + +box.style.borderColor = colorPicker.value; + +colorPicker.addEventListener("input", function(event) { + box.style.borderColor = event.target.value; +}, false); + +colorPicker.addEventListener("change", function(event) { + output.innerText = "Color set to " + colorPicker.value + "."; +}, false);</pre> + +<p>The {{event("input")}} event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker. Each time this event arrives, we set the box's border color to match the color picker's current value.</p> + +<p>The {{event("change")}} event is received when the color picker's value is finalized. We respond by setting the contents of the <code><p></code> element with the ID <code>"output"</code> to a string describing the finally selected color.</p> + +<h2 id="Utilizar_a_cor_com_sabedoria">Utilizar a cor com sabedoria</h2> + +<p>Making the right choices when selecting colors when designing a web site can be a tricky process, especially if you aren't well-grounded in art, design, or at least basic color theory. The wrong color choice can render your site unattractive, or even worse, leave the content unreadable due to problems with contrast or conflicting colors. Worse still, if using the wrong colors can result in your content being outright unusable by people withcertain vision problems, particularly color blindness.</p> + +<h3 id="Encontrar_as_cores_corretas">Encontrar as cores corretas</h3> + +<p>Coming up with just the right colors can be tricky, especially without training in art or design. Fortunately, there are tools available that can help you. While they can't replace having a good designer helping you make these decisions, they can definitely get you started.</p> + +<h4 id="Cor_base">Cor base</h4> + +<p>The first step is to choose your <strong>base color</strong>. This is the color that in some way defines your web site or the subject matter of the site. Just as we associate green with the beverage {{interwiki("wikipedia", "Mountain Dew")}} and one might think of the color blue in relationship with the sky or the ocean, choosing an appropriate base color to represent your site is a good place to start. There are plenty of ways to select a base color; a few ideas include:</p> + +<ul> + <li>A color that is naturally associated with the topic of your content, such as the existing color identified with a product or idea or a color representative of the emotion you wish to convey.</li> + <li>A color that comes from imagery associated with what your content is about. If you're creating a web site about a given item or product, choose a color that's physically present on that item.</li> + <li>Browse web sites that let you look at lots of existing color palettes and imags to find inspiration.</li> +</ul> + +<p>When trying to decide upon a base color, you may find that browser extensions that let you select colors from web content can be particularly handy. Some of these are even specifically designed to help with this sort of work. For example, the web site <a href="http://www.colorzilla.com/">ColorZilla</a> offers an extension (<a href="http://www.colorzilla.com/chrome">Chrome</a> / <a href="http://www.colorzilla.com/firefox">Firefox</a>) that offers an eyedropper tool for picking colors from the web. It can also take averages of the colors of pixels in various sized areas or even a selected area of the page.</p> + +<div class="note"> +<p>The advantage to averaging colors can be that often what looks like a solid color is actually a surprisingly varied number of related colors all used in concert, blending to create a desired effect. Picking just one of these pixels can result in getting a color that on its own looks very out of place.</p> +</div> + +<h4 id="Fleshing_out_the_palette">Fleshing out the palette</h4> + +<p>Once you have decided on your base color, there are plenty of online tools that can help you build out a palette of appropriate colors to use along with your base color by applying color theory to your base color to determine appropriate added colors. Many of these tools also support viewing the colors filtered so you can see what they would look like to people with various forms of color blindness. See {{anch("Color and accessibility")}} for a brief explanation of why this matters.</p> + +<p>A few examples (all free to use as of the time this list was last revised):</p> + +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Colors/Color_picker_tool">MDN's color picker tool</a></li> + <li><a href="http://paletton.com">Paletton</a></li> + <li><a href="https://color.adobe.com/create/color-wheel">Adobe Color CC online color wheel</a></li> +</ul> + +<p>When designing your palette, be sure to keep in mind that in addition to the colors these tools typically generate, you'll probably also need to add some core neutral colors such as white (or nearly white), black (or nearly black), and some number of shades of gray.</p> + +<div class="note"> +<p>Usually, you are far better off using the smallest number of colors possible. By using color to accentuate rather than adding color to everything on the page, you keep your content easy to read and the colors you do use have far more impact.</p> +</div> + +<h3 id="Color_theory_resources">Color theory resources</h3> + +<p>A full review of color theory is beyond the scope of this article, but there are plenty of articles about color theory available, as well as courses you can find at nearby schools and universities. A couple of useful resources about color theory:</p> + +<dl> + <dt><a href="https://www.khanacademy.org/partner-content/pixar/color">Color Science</a> (<a href="https://www.khanacademy.org/">Khan Academy</a> in association with <a href="https://www.pixar.com/">Pixar</a>)</dt> + <dd>An online course which introduces concepts such as what color is, how it's percieved, and how to use colors to express ideas. Presented by Pixar artists and designers.</dd> + <dt>{{interwiki("wikipedia", "Color theory")}} on Wikipedia</dt> + <dd>Wikipedia's entry on color theory, which has a lot of great information from a technical perspective. It's not really a resource for helping you with the color sleection process, but is still full of useful information.</dd> +</dl> + +<h3 id="Cor_e_acessibilidade">Cor e acessibilidade</h3> + +<p>There are several ways color can be an {{Glossary("accessibility")}} problem. Improper or careless use of color can result in a web site or app that a percentage of your target audience may not be able to use adequately, resulting in lost traffic, lost business, and possibly even a public relations problem. So it's important to consider your use of color carefully.</p> + +<p>You should do at least basic research into {{interwiki("wikipedia", "color blindness")}}. There are several kinds; the most common is red-green color blindness, which causes people to be unable to differentiate between the colors red and green. There are others, too, ranging from inabilities to tell the difference between certain colors to total inability to see color at all.</p> + +<div class="note"> +<p>The most important rule: never use color as the only way to know something. If, for example, you indicate success or failure of an operation by changing the color of a shape from white to green for success and red for failure, users with red-green color-blindness won't be able to use your site properly. Instead, perhaps use both text and color together, so that everyone can understand what's happening.</p> +</div> + +<p>For more information about color blindness, see the following articles:</p> + +<ul> + <li><a href="https://medlineplus.gov/colorblindness.html">Medline Plus: Color Blindness</a> (United States National Institute of Health)</li> + <li><a href="https://www.aao.org/eye-health/diseases/what-is-color-blindness">American Academy of Ophthamology: What Is Color Blindness?</a></li> + <li><a href="https://www.usability.gov/get-involved/blog/2010/02/color-blindness.html">Color Blindness & Web Design</a> (Usability.gov: United States Department of Health and Human Services)</li> +</ul> + +<h3 id="Exemplo_da_paleta_de_desenho">Exemplo da paleta de desenho</h3> + +<p>Let's consider a quick example of selecting an appropriate color palette for a site. Imagine that you're building a web site for a new game that takes place on the planet Mars. So let's do a <a href="https://www.google.com/search?q=Mars&tbm=isch">Google search for photos of Mars</a>. Lots of good examples of Martian coloration there. We carefully avoid the mockups and the photos from movies. And we decide to use a photo taken by one of the Mars landers humanity has parked on the surface over the last few decades, since the game takes place on the planet's surface. We use a color picker tool to select a sample of the color we choose.</p> + +<p>Using an eyedropper tool, we identify a color we like and determine that the color in question is <code>#D79C7A</code>, which is an appropriate rusty orange-red color that's so stereotypical of the Martian surface.</p> + +<p>Having selected our base color, we need to build out our palette. We decide to use <a href="http://www.paletteon.com/">Paletteon</a> to come up with the other colors we need. Upon opening Paletton, we see:</p> + +<p><img alt="Right after loading Paletton." src="https://mdn.mozillademos.org/files/15451/paletton1.png" style="height: 361px; width: 600px;"></p> + +<p>Next, we enter our color's hex code (<code>D79C7A</code>) into the "Base RGB" box at the bottom-left corner of the tool:</p> + +<p><img alt="After entering base color" src="https://mdn.mozillademos.org/files/15453/paletton2.png" style="height: 361px; width: 600px;"></p> + +<p>We now see a monochromatic palette based on the color we picked from the Mars photo. If you need a lot of related colors for some reason, those are likely to be good ones. But what we really want is an accent color. Something that will pop along side the base color. To find that, we click the "add complementary" toggle underneath the menu that lets you select the palette type (currently "Monochromatic"). Paletton computes an appropriate accent color; clicking on the accent color down in the bottom-right corner tells us that this color is <code>#508D7C</code>.</p> + +<p><img alt="Now with complementary colors included." src="https://mdn.mozillademos.org/files/15455/paletton3.png" style="height: 361px; width: 600px;"></p> + +<p>If you're unhappy with the color that's proposed to you, you can change the color scheme, to see if you find something you like better. For example, if we don't like the proposed greenish-blue color, we can click the Triad color scheme icon, which presents us with the following:</p> + +<p><img alt="Triad color scheme selected" src="https://mdn.mozillademos.org/files/15457/paletton4.png" style="height: 361px; width: 600px;"></p> + +<p>That greyish blue in the top-right looks pretty good. Clicking on it, we find that it's <code>#556E8D</code>. That would be used as the accent color, to be used sparingly to make things stand out, such as in headlines or in the highlighting of tabs or other indicators on the site:</p> + +<p><img alt="Triad color scheme selected" src="https://mdn.mozillademos.org/files/15459/paletton-color-detail.png" style="height: 370px; width: 526px;"></p> + +<p>Now we have our base color and our accent. On top of that, we have a few complementary shades of each, just in case we need them for gradients and the like. The colors can then be exported in a number of formats so you can make use of them.</p> + +<p>Once you have these colors, you will probably still need to select appropriate neutral colors. Common design practice is to try to find the sweet spot where there's just enough contrast that the text is crisp and readable but not enough contrast to become harsh for the eyes. It's easy to go too far in one way or another so be sure to get feedback on your colors once you've selected them and have examples of them in use available. If the contrast is too low, your text will tend to be washed out by the background, leaving it unreadable, but if your contrast is too high, the user may find your site garish and unpleasant to look at.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics">Drawing graphics</a></li> + <li><a href="/en-US/docs/Web/Guide/Graphics">Graphics on the web</a></li> + <li><a href="/en-US/docs/Tools/DevToolsColors">MDN's color picker tool</a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: block; opacity: 0; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none; margin-top: 30px; margin-left: 1px; direction: ltr; text-align: left;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/html/atributos/index.html b/files/pt-pt/web/html/atributos/index.html new file mode 100644 index 0000000000..84ea814756 --- /dev/null +++ b/files/pt-pt/web/html/atributos/index.html @@ -0,0 +1,659 @@ +--- +title: Lista de atributos HTML +slug: Web/HTML/Atributos +tags: + - HTML + - Referencia + - Web + - atributo +translation_of: Web/HTML/Attributes +--- +<p>Elementos em HTML têm <strong>atributos</strong>; estes são valores adicionais que configuram os elementos ou ajustam o seu comportamento em vários modos para corresponderem aos critérios que os utilizadores pretendem.</p> + +<h2 id="Lista_de_Atributos">Lista de Atributos</h2> + +<table class="standard-table"> + <thead> + <tr> + <th>Nome do Atributo</th> + <th>Elementos</th> + <th>Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>accept</code></td> + <td>{{ HTMLElement("form") }}, {{ HTMLElement("input") }}</td> + <td>Lista de tipos que o servidor aceita, é usualmente um tipo de ficheiro.</td> + </tr> + <tr> + <td><code>accept-charset</code></td> + <td>{{ HTMLElement("form") }}</td> + <td>Lista de codificações de caracteres (charsets) que são suportadas.</td> + </tr> + <tr> + <td><code>accesskey</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Atributo global</a></td> + <td>Define um atalho do teclado para activar ou adicionar foco ao elemento.</td> + </tr> + <tr> + <td><code>action</code></td> + <td>{{ HTMLElement("form") }}</td> + <td>O URI dum programa que processa a informação submetida através deste formulário.</td> + </tr> + <tr> + <td><code>align</code></td> + <td>{{ HTMLElement("applet") }}, {{ HTMLElement("caption") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("hr") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("td") }}, {{ HTMLElement("tfoot") }} , {{ HTMLElement("th") }}, {{ HTMLElement("thead") }}, {{ HTMLElement("tr") }}</td> + <td>Especifica o alinhamento horizontal do elemento.</td> + </tr> + <tr> + <td><code>alt</code></td> + <td>{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}</td> + <td>Texto alternativo no caso de uma imagem não poder ser mostrada.</td> + </tr> + <tr> + <td><code>async</code></td> + <td>{{ HTMLElement("script") }}</td> + <td>Indicates that the script should be executed asynchronously.</td> + </tr> + <tr> + <td><code>autocomplete</code></td> + <td>{{ HTMLElement("form") }}, {{ HTMLElement("input") }}</td> + <td>Indicates whether controls in this form can by default have their values automatically completed by the browser.</td> + </tr> + <tr> + <td><code>autofocus</code></td> + <td>{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}</td> + <td>The element should be automatically focused after the page loaded.</td> + </tr> + <tr> + <td><code>autoplay</code></td> + <td>{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}</td> + <td>The audio or video should play as soon as possible.</td> + </tr> + <tr> + <td><code>autosave</code></td> + <td>{{ HTMLElement("input") }}</td> + <td>Previous values should persist dropdowns of selectable values across page loads.</td> + </tr> + <tr> + <td><code>bgcolor</code></td> + <td>{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }}</td> + <td> + <p>Background color of the element.</p> + + <div class="note"> + <p><strong>Nota:</strong> This is a legacy attribute. Please use the CSS {{ Cssxref("background-color") }} property instead.</p> + </div> + </td> + </tr> + <tr> + <td><code>border</code></td> + <td>{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }}</td> + <td> + <p>The border width.</p> + + <div class="note"> + <p><strong>Nota:</strong> This is a legacy attribute. Please use the CSS {{ Cssxref("border") }} property instead.</p> + </div> + </td> + </tr> + <tr> + <td><code>buffered</code></td> + <td>{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}</td> + <td>Contains the time range of already buffered media.</td> + </tr> + <tr> + <td><code>challenge</code></td> + <td>{{ HTMLElement("keygen") }}</td> + <td>A challenge string that is submitted along with the public key.</td> + </tr> + <tr> + <td><code>charset</code></td> + <td>{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}</td> + <td>Declares the character encoding of the page or script.</td> + </tr> + <tr> + <td><code>checked</code></td> + <td>{{ HTMLElement("command") }}, {{ HTMLElement("input") }}</td> + <td>Indicates whether the element should be checked on page load.</td> + </tr> + <tr> + <td><code>cite</code></td> + <td>{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}</td> + <td>Contains a URI which points to the source of the quote or change.</td> + </tr> + <tr> + <td><code>class</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Often used with CSS to style elements with common properties.</td> + </tr> + <tr> + <td><code>code</code></td> + <td>{{ HTMLElement("applet") }}</td> + <td>Specifies the URL of the applet's class file to be loaded and executed.</td> + </tr> + <tr> + <td><code>codebase</code></td> + <td>{{ HTMLElement("applet") }}</td> + <td>This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.</td> + </tr> + <tr> + <td><code>color</code></td> + <td>{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }}</td> + <td> + <p>This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.</p> + + <div class="note"> + <p><strong>Nota:</strong> This is a legacy attribute. Please use the CSS {{ Cssxref("color") }} property instead.</p> + </div> + </td> + </tr> + <tr> + <td><code>cols</code></td> + <td>{{ HTMLElement("textarea") }}</td> + <td>Defines the number of columns in a textarea.</td> + </tr> + <tr> + <td><code>colspan</code></td> + <td>{{ HTMLElement("td") }}, {{ HTMLElement("th") }}</td> + <td>The colspan attribute defines the number of columns a cell should span.</td> + </tr> + <tr> + <td><code>content</code></td> + <td>{{ HTMLElement("meta") }}</td> + <td>A value associated with <code>http-equiv</code> or <code>name</code> depending on the context.</td> + </tr> + <tr> + <td><code>contenteditable</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Indicates whether the element's content is editable.</td> + </tr> + <tr> + <td><code>contextmenu</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Defines the ID of a {{ HTMLElement("menu") }} element which will serve as the element's context menu.</td> + </tr> + <tr> + <td><code>controls</code></td> + <td>{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}</td> + <td>Indicates whether the browser should show playback controls to the user.</td> + </tr> + <tr> + <td><code>coords</code></td> + <td>{{ HTMLElement("area") }}</td> + <td>A set of values specifying the coordinates of the hot-spot region.</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/CORS_settings_attributes">crossorigin</a></code></td> + <td>{{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }}</td> + <td>How the element handles cross-origin requests</td> + </tr> + <tr> + <td><code>data</code></td> + <td>{{ HTMLElement("object") }}</td> + <td>Specifies the URL of the resource.</td> + </tr> + <tr> + <td><code>data-*</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Lets you attach custom attributes to an HTML element.</td> + </tr> + <tr> + <td><code>datetime</code></td> + <td>{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}</td> + <td>Indicates the date and time associated with the element.</td> + </tr> + <tr> + <td><code>default</code></td> + <td>{{ HTMLElement("track") }}</td> + <td>Indicates that the track should be enabled unless the user's preferences indicate something different.</td> + </tr> + <tr> + <td><code>defer</code></td> + <td>{{ HTMLElement("script") }}</td> + <td>Indicates that the script should be executed after the page has been parsed.</td> + </tr> + <tr> + <td><code>dir</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)</td> + </tr> + <tr> + <td><code>dirname</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}</td> + <td> </td> + </tr> + <tr> + <td><code>disabled</code></td> + <td>{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}</td> + <td>Indicates whether the user can interact with the element.</td> + </tr> + <tr> + <td><code>download</code></td> + <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}</td> + <td>Indicates that the hyperlink is to be used for downloading a resource.</td> + </tr> + <tr> + <td><code>draggable</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Defines whether the element can be dragged.</td> + </tr> + <tr> + <td><code>dropzone</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Indicates that the element accept the dropping of content on it.</td> + </tr> + <tr> + <td><code>enctype</code></td> + <td>{{ HTMLElement("form") }}</td> + <td>Defines the content type of the form date when the <code>method</code> is POST.</td> + </tr> + <tr> + <td><code>for</code></td> + <td>{{ HTMLElement("label") }}, {{ HTMLElement("output") }}</td> + <td>Describes elements which belongs to this one.</td> + </tr> + <tr> + <td><code>form</code></td> + <td>{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}</td> + <td>Indicates the form that is the owner of the element.</td> + </tr> + <tr> + <td><code>formaction</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("button") }}</td> + <td>Indicates the action of the element, overriding the action defined in the {{ HTMLElement("form") }}.</td> + </tr> + <tr> + <td><code>headers</code></td> + <td>{{ HTMLElement("td") }}, {{ HTMLElement("th") }}</td> + <td>IDs of the <code><th></code> elements which applies to this element.</td> + </tr> + <tr> + <td><code>height</code></td> + <td>{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }}</td> + <td> + <p>Specifies the height of elements listed here. For all other elements, use the CSS {{cssxref("height")}} property.</p> + + <div class="note"> + <p><strong>Nota:</strong> In some instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("height") }} property should be used instead.</p> + </div> + </td> + </tr> + <tr> + <td><code>hidden</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Prevents rendering of given element, while keeping child elements, e.g. script elements, active.</td> + </tr> + <tr> + <td><code>high</code></td> + <td>{{ HTMLElement("meter") }}</td> + <td>Indicates the lower bound of the upper range.</td> + </tr> + <tr> + <td><code>href</code></td> + <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }}</td> + <td> The URL of a linked resource.</td> + </tr> + <tr> + <td><code>hreflang</code></td> + <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}</td> + <td>Specifies the language of the linked resource.</td> + </tr> + <tr> + <td><code>http-equiv</code></td> + <td>{{ HTMLElement("meta") }}</td> + <td> </td> + </tr> + <tr> + <td><code>icon</code></td> + <td>{{ HTMLElement("command") }}</td> + <td>Specifies a picture which represents the command.</td> + </tr> + <tr> + <td><code>id</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Often used with CSS to style a specific element. The value of this attribute must be unique.</td> + </tr> + <tr> + <td><code>integrity</code></td> + <td>{{ HTMLElement("link") }}, {{ HTMLElement("script") }} </td> + <td> + <p>Security Feature that allows browsers to verify what they fetch. </p> + + <p><a href="/en-US/docs/">MDN Link</a></p> + </td> + </tr> + <tr> + <td><code>ismap</code></td> + <td>{{ HTMLElement("img") }}</td> + <td>Indicates that the image is part of a server-side image map.</td> + </tr> + <tr> + <td><code>itemprop</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td> </td> + </tr> + <tr> + <td><code>keytype</code></td> + <td>{{ HTMLElement("keygen") }}</td> + <td>Specifies the type of key generated.</td> + </tr> + <tr> + <td><code>kind</code></td> + <td>{{ HTMLElement("track") }}</td> + <td>Specifies the kind of text track.</td> + </tr> + <tr> + <td><code>label</code></td> + <td>{{ HTMLElement("track") }}</td> + <td>Specifies a user-readable title of the text track.</td> + </tr> + <tr> + <td><code>lang</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Defines the language used in the element.</td> + </tr> + <tr> + <td><code>language</code></td> + <td>{{ HTMLElement("script") }}</td> + <td>Defines the script language used in the element.</td> + </tr> + <tr> + <td><code>list</code></td> + <td>{{ HTMLElement("input") }}</td> + <td>Identifies a list of pre-defined options to suggest to the user.</td> + </tr> + <tr> + <td><code>loop</code></td> + <td>{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}</td> + <td>Indicates whether the media should start playing from the start when it's finished.</td> + </tr> + <tr> + <td><code>low</code></td> + <td>{{ HTMLElement("meter") }}</td> + <td>Indicates the upper bound of the lower range.</td> + </tr> + <tr> + <td><code>manifest</code></td> + <td>{{ HTMLElement("html") }}</td> + <td>Specifies the URL of the document's cache manifest.</td> + </tr> + <tr> + <td><code>max</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}</td> + <td>Indicates the maximum value allowed.</td> + </tr> + <tr> + <td><code>maxlength</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}</td> + <td>Defines the maximum number of characters allowed in the element.</td> + </tr> + <tr> + <td><code>media</code></td> + <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}</td> + <td>Specifies a hint of the media for which the linked resource was designed.</td> + </tr> + <tr> + <td><code>method</code></td> + <td>{{ HTMLElement("form") }}</td> + <td>Defines which <a href="/en-US/docs/Web/HTTP">HTTP</a> method to use when submitting the form. Can be <code>GET</code> (default) or <code>POST</code>.</td> + </tr> + <tr> + <td><code>min</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}</td> + <td>Indicates the minimum value allowed.</td> + </tr> + <tr> + <td><code>multiple</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("select") }}</td> + <td>Indicates whether multiple values can be entered in an input of the type <code>email</code> or <code>file</code>.</td> + </tr> + <tr> + <td><code>muted</code></td> + <td>{{ HTMLElement("video") }}</td> + <td>Indicates whether the audio will be initially silenced on page load.</td> + </tr> + <tr> + <td><code>name</code></td> + <td>{{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}, {{ HTMLElement("map") }}, {{ HTMLElement("meta") }}, {{ HTMLElement("param") }}</td> + <td>Name of the element. For example used by the server to identify the fields in form submits.</td> + </tr> + <tr> + <td><code>novalidate</code></td> + <td>{{ HTMLElement("form") }}</td> + <td>This attribute indicates that the form shouldn't be validated when submitted.</td> + </tr> + <tr> + <td><code>open</code></td> + <td>{{ HTMLElement("details") }}</td> + <td>Indicates whether the details will be shown on page load.</td> + </tr> + <tr> + <td><code>optimum</code></td> + <td>{{ HTMLElement("meter") }}</td> + <td>Indicates the optimal numeric value.</td> + </tr> + <tr> + <td><code>pattern</code></td> + <td>{{ HTMLElement("input") }}</td> + <td>Defines a regular expression which the element's value will be validated against.</td> + </tr> + <tr> + <td><code>ping</code></td> + <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}</td> + <td> </td> + </tr> + <tr> + <td><code>placeholder</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}</td> + <td>Provides a hint to the user of what can be entered in the field.</td> + </tr> + <tr> + <td><code>poster</code></td> + <td>{{ HTMLElement("video") }}</td> + <td>A URL indicating a poster frame to show until the user plays or seeks.</td> + </tr> + <tr> + <td><code>preload</code></td> + <td>{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}</td> + <td>Indicates whether the whole resource, parts of it or nothing should be preloaded.</td> + </tr> + <tr> + <td><code>radiogroup</code></td> + <td>{{ HTMLElement("command") }}</td> + <td> </td> + </tr> + <tr> + <td><code>readonly</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}</td> + <td>Indicates whether the element can be edited.</td> + </tr> + <tr> + <td><code>rel</code></td> + <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}</td> + <td>Specifies the relationship of the target object to the link object.</td> + </tr> + <tr> + <td><code>required</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}</td> + <td>Indicates whether this element is required to fill out or not.</td> + </tr> + <tr> + <td><code>reversed</code></td> + <td>{{ HTMLElement("ol") }}</td> + <td>Indicates whether the list should be displayed in a descending order instead of a ascending.</td> + </tr> + <tr> + <td><code>rows</code></td> + <td>{{ HTMLElement("textarea") }}</td> + <td>Defines the number of rows in a text area.</td> + </tr> + <tr> + <td><code>rowspan</code></td> + <td>{{ HTMLElement("td") }}, {{ HTMLElement("th") }}</td> + <td>Defines the number of rows a table cell should span over.</td> + </tr> + <tr> + <td><code>sandbox</code></td> + <td>{{ HTMLElement("iframe") }}</td> + <td> </td> + </tr> + <tr> + <td><code>scope</code></td> + <td>{{ HTMLElement("th") }}</td> + <td> </td> + </tr> + <tr> + <td><code>scoped</code></td> + <td>{{ HTMLElement("style") }}</td> + <td> </td> + </tr> + <tr> + <td><code>seamless</code></td> + <td>{{ HTMLElement("iframe") }}</td> + <td> </td> + </tr> + <tr> + <td><code>selected</code></td> + <td>{{ HTMLElement("option") }}</td> + <td>Defines a value which will be selected on page load.</td> + </tr> + <tr> + <td><code>shape</code></td> + <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}</td> + <td> </td> + </tr> + <tr> + <td><code>size</code></td> + <td>{{ HTMLElement("input") }}, {{ HTMLElement("select") }}</td> + <td>Defines the width of the element (in pixels). If the element's <code>type</code> attribute is <code>text</code> or <code>password</code> then it's the number of characters.</td> + </tr> + <tr> + <td><code>sizes</code></td> + <td>{{ HTMLElement("link") }}, {{ HTMLElement("img") }}, {{ HTMLElement("source") }}</td> + <td> </td> + </tr> + <tr> + <td><code>slot</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Assigns a slot in a shadow DOM shadow tree to an element.</td> + </tr> + <tr> + <td><code>span</code></td> + <td>{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}</td> + <td> </td> + </tr> + <tr> + <td><code>spellcheck</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Indicates whether spell checking is allowed for the element.</td> + </tr> + <tr> + <td><code>src</code></td> + <td>{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}</td> + <td>The URL of the embeddable content.</td> + </tr> + <tr> + <td><code>srcdoc</code></td> + <td>{{ HTMLElement("iframe") }}</td> + <td> </td> + </tr> + <tr> + <td><code>srclang</code></td> + <td>{{ HTMLElement("track") }}</td> + <td> </td> + </tr> + <tr> + <td><code>srcset</code></td> + <td>{{ HTMLElement("img") }}</td> + <td> </td> + </tr> + <tr> + <td><code>start</code></td> + <td>{{ HTMLElement("ol") }}</td> + <td>Defines the first number if other than 1.</td> + </tr> + <tr> + <td><code>step</code></td> + <td>{{ HTMLElement("input") }}</td> + <td> </td> + </tr> + <tr> + <td><code>style</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Defines CSS styles which will override styles previously set.</td> + </tr> + <tr> + <td><code>summary</code></td> + <td>{{ HTMLElement("table") }}</td> + <td> </td> + </tr> + <tr> + <td><code>tabindex</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Overrides the browser's default tab order and follows the one specified instead.</td> + </tr> + <tr> + <td><code>target</code></td> + <td>{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }}</td> + <td> </td> + </tr> + <tr> + <td><code>title</code></td> + <td><a href="/en-US/docs/HTML/Global_attributes">Global attribute</a></td> + <td>Text to be displayed in a tooltip when hovering over the element.</td> + </tr> + <tr> + <td><code>type</code></td> + <td>{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}</td> + <td>Defines the type of the element.</td> + </tr> + <tr> + <td><code>usemap</code></td> + <td>{{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}</td> + <td> </td> + </tr> + <tr> + <td><code>value</code></td> + <td>{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}</td> + <td>Defines a default value which will be displayed in the element on page load.</td> + </tr> + <tr> + <td><code>width</code></td> + <td>{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }}</td> + <td> + <p>For the elements listed here, this establishes the element's width.</p> + + <div class="note"> + <p><strong>Nota:</strong> For all other instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("width") }} property should be used instead.</p> + </div> + </td> + </tr> + <tr> + <td><code>wrap</code></td> + <td>{{ HTMLElement("textarea") }}</td> + <td>Indicates whether the text should be wrapped.</td> + </tr> + </tbody> +</table> + +<h2 id="Conteúdo_versus_atributos_IDL">Conteúdo versus atributos IDL</h2> + +<p>In HTML, most attributes have two faces: the <strong>content attribute</strong> and the <strong>IDL attribute</strong>.</p> + +<p>The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via {{domxref("element.setAttribute()")}} or {{domxref("element.getAttribute()")}}. The content attribute is always a string even when the expected value should be an integer. For example, to set an {{HTMLElement("input")}} element's <code>maxlength</code> to 42 using the content attribute, you have to call <code>setAttribute("maxlength", "42")</code> on that element.</p> + +<p>The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like <code class="moz-txt-verticalline">element.foo</code>. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.</p> + +<p>Most of the time, IDL attributes will return their values as they are really used. For example, the default <code>type</code> for {{HTMLElement("input")}} elements is "text", so if you set <code>input.type="foobar"</code>, the <code><input></code> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the <code>type</code> IDL attribute will return the string "text".</p> + +<p>IDL attributes are not always strings; for example, <code>input.maxlength</code> is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so <code>input.maxlength</code> is always going to return a number and when you set <code>input.maxlength</code> ,it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.</p> + +<p>IDL attributes can <a href="https://www.whatwg.org/specs/web-apps/current-work/multipage/urls.html#reflecting-content-attributes-in-idl-attributes">reflect other types</a> such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow <a href="https://www.whatwg.org/specs/web-apps/current-work/multipage/urls.html#reflecting-content-attributes-in-idl-attributes">the rules laid out in the specification</a>, but sometimes it doesn't. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (<code>select.size</code>, for example) and you should read the specifications to understand how exactly they behave.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/HTML/Elemento">Elementos de HTML</a></li> +</ul> diff --git a/files/pt-pt/web/html/atributos/rel/index.html b/files/pt-pt/web/html/atributos/rel/index.html new file mode 100644 index 0000000000..fe8307f0c0 --- /dev/null +++ b/files/pt-pt/web/html/atributos/rel/index.html @@ -0,0 +1,418 @@ +--- +title: 'HTML attribute: rel' +slug: Web/HTML/Atributos/rel +translation_of: Web/HTML/Attributes/rel +--- +<p>{{draft}}</p> + +<p class="summary">O atributo <strong><code>rel</code></strong> define a relação entre um recurso ligado e o documento atual. É válido em {{htmlelement('link')}}, {{htmlelement('a')}}, {{htmlelement('area')}}, e {{htmlelement('form')}}. Os valores suportados dependem do elemento em que o atributo é usado.</p> + +<p>O tipo de relação (da ligação) é definido pelo atributo <strong><em><code>rel</code></em></strong> que, se existir, tem de ter um valor que é um conjunto de palavras-chave (<em>keywords</em>) únicas, desordenadas, e separadas por espaços. As palavras-chave possíveis estão na tabela em baixo.</p> + +<table class="standard-table"> + <caption>Valores possíves para o atributo <code>rel</code>, e os elementos em que são relevantes</caption> + <thead> + <tr> + <th><code>rel</code> (valor)</th> + <th>Descrição</th> + <th><code>{{htmlelement('link')}}</code></th> + <th><code>{{htmlelement('a')}}</code> e <code>{{htmlelement('area')}}</code></th> + <th><code>{{htmlelement('form')}}</code></th> + </tr> + </thead> + <tbody> + <tr> + <td><code>{{anch("attr-alternate", "alternate")}}</code></td> + <td>Representações alternativas do documento atual.</td> + <td><em>Link</em></td> + <td><em>Link</em></td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code>{{anch("attr-author", "author")}}</code></td> + <td>Autor do documento ou artigo atual.</td> + <td><em>Link</em></td> + <td><em>Link</em></td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code>{{anch("attr-bookmark", "bookmark")}}</code></td> + <td><em>Permalink</em> para a secção antecessora mais próxima.</td> + <td class="not-allowed">Não permitido</td> + <td><em>Link</em></td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code>{{anch("attr-canonical", "canonical")}}</code></td> + <td>URL ideal para o documento atual.</td> + <td><em>Link</em></td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/Link_types/dns-prefetch">dns-prefetch</a></code></td> + <td>Pede ao <em>browser</em> para antecipadamente efetuar a resolução de DNS para o <em>link</em> em questão.</td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code>{{anch("attr-external", "external")}}</code></td> + <td>O documento referenciado não pertence ao <em>site</em> do documento atual.</td> + <td class="not-allowed">Não permitido</td> + <td>Anotação</td> + <td>Anotação</td> + </tr> + <tr> + <td><code>{{anch("attr-help", "help")}}</code></td> + <td><em>Link</em> para material de apoio sobre o contexto atual.</td> + <td><em>Link</em></td> + <td><em>Link</em></td> + <td><em>Link</em></td> + </tr> + <tr> + <td><code>{{anch("attr-icon", "icon")}}</code></td> + <td>Um ícone representativo do documento atual.</td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code>{{anch("attr-license", "license")}}</code></td> + <td>O conteúdo principal do documento atual está protegido pela licença de direitos de autor<em> </em>referida no <em>link</em>.</td> + <td><em>Link</em></td> + <td><em>Link</em></td> + <td><em>Link</em></td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/Link_types/manifest">manifest</a></code></td> + <td><em>Web</em> <em>app</em> <em>manifest</em></td> + <td class="not-allowed"><em>Link</em></td> + <td>Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/Link_types/modulepreload">modulepreload</a></code></td> + <td>Pede ao <em>browser</em> para antecipadamente descarregar o <em>script </em>e guardá-lo no mapa de módulos do documento, para avaliar depois. As dependências do módulo também podem ser descarregadas, opcionalmente.</td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code>{{anch("attr-next", "next")}}</code></td> + <td>Indica que o documento atual pertence a uma série de documentos, e que o documento referenciado por este <em>link </em>é o seguinte.</td> + <td><em>Link</em></td> + <td><em>Link</em></td> + <td><em>Link</em></td> + </tr> + <tr> + <td><code>{{anch("attr-nofollow", "nofollow")}}</code></td> + <td>Indica que o autor ou editor do documento atual não aprova o documento referenciado.</td> + <td class="not-allowed">Não permitido</td> + <td>Anotação</td> + <td>Anotação</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/Link_types/noopener">noopener</a></code></td> + <td>Cria um contexto de navegação de nível superior e não é "auxiliar" (não está relacionado com outro contexto de navegação), mesmo que a hiperligação estivesse configurada para criar outro tipo de contexto (atribuindo um certo valor ao atributo<code> target</code>, por exemplo).</td> + <td class="not-allowed">Não permitido</td> + <td>Anotação</td> + <td>Anotação</td> + </tr> + <tr> + <td><code>{{anch("attr-noreferrer", "noreferrer")}}</code></td> + <td>Comporta-se do mesmo modo que <code>noopener</code>, mas exclui o <em>header</em> <code>Referer</code> do pedido.</td> + <td class="not-allowed">Não permitido</td> + <td>Anotação</td> + <td>Anotação</td> + </tr> + <tr> + <td><code>{{anch("attr-opener", "opener")}}</code></td> + <td>Cria um contexto de navegação auxiliar, mesmo que a hiperligação fosse criar um contexto de navegação de nível superior que não fosse auxiliar (por exemplo, no caso de um link com "<code>_blank</code>" como valor do atributo <code>target</code>).</td> + <td class="not-allowed">Não permitido</td> + <td>Anotação</td> + <td>Anotação</td> + </tr> + <tr> + <td><code>{{anch("attr-pingback", "pingback")}}</code></td> + <td>Indica o endereço do servidor <em>pingback</em> que controla <em>pingbacks</em> para o document atual.</td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/Link_types/preconnect">preconnect</a></code></td> + <td>Informa o <em>user agent</em> de que este deve ligar-se antecipadamente à origem do recurso apontado pelo <em>link</em>.</td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/Link_types/prefetch">prefetch</a></code></td> + <td>Informa o <em>user agent</em> de que este deve antecipadamente descarregar o recurso apontado e guardá-lo em <em>cache</em>, porque é provável que este seja necessário numa futura navegação.</td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/Link_types/preload">preload</a></code></td> + <td> + <p>Informa o <em>user agent</em> de que este deve antecipadamente descarregar o recurso apontado e guardá-lo em <em>cache. </em>Tal deverá ocorrer para para que o recurso seja usado na navegação atual, com base no atributo <code><a href="as">as</a></code> (e na prioridade associada ao recurso apontado).</p> + </td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code><a href="/en-US/docs/Web/HTML/Link_types/prerender">prerender</a></code></td> + <td>Informa o <em>user agent</em> de que este deve antecipadamente descarregar o recurso apontado e futuramente responder mais rapidamente ao mesmo pedido.</td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code>{{anch("attr-prev", "prev")}}</code></td> + <td>Indica que o documento atual pertence a uma série de documentos, e que o documento referenciado por este <em>link </em>é o anterior.</td> + <td><em>Link</em></td> + <td><em>Link</em></td> + <td><em>Link</em></td> + </tr> + <tr> + <td><code>{{anch("attr-search", "search")}}</code></td> + <td>Aponta para um recurso onde se pode pesquisar por conteúdo do documento atual e de páginas relacionadas.</td> + <td><em>Link</em></td> + <td><em>Link</em></td> + <td><em>Link</em></td> + </tr> + <tr> + <td><code>{{anch("attr-stylesheet", "stylesheet")}}</code></td> + <td>Importa uma <em>style sheet</em>.</td> + <td>Recurso externo</td> + <td class="not-allowed">Não permitido</td> + <td class="not-allowed">Não permitido</td> + </tr> + <tr> + <td><code>{{anch("attr-tag", "tag")}}</code></td> + <td>Fornece uma <em>tag</em> (identificada pelo endereço referido) a ser usada no documento atual.</td> + <td class="not-allowed">Não permitido</td> + <td><em>Link</em></td> + <td class="not-allowed">Não aplicado</td> + </tr> + </tbody> +</table> + +<p>O atributo <code>rel</code> é relevate para os elementos {{htmlelement('link')}}, {{htmlelement('a')}}, {{htmlelement('area')}}, e {{htmlelement('form')}}. No entanto, alguns dos valores só são relevantes para casos específicos deste grupo de elementos. Para o valor de <code>rel</code>, não há diferenciação entre maiúsculas e minúsculas, tal como em nos atributos HTML em geral.</p> + +<p><code>rel</code> não tem um valor por defeito. Se o atributo for omitido ou se os seus valores forem inválidos, então não existe qualquer relação entre o documento atual e o recurso apontado, fora a existência de uma hiperligação. Por exemplo, para {{htmlelement('link')}} e {{htmlelement('form')}}, se <code>rel</code> for omitido, ou se não tiver pelo menos uma das <em>keywords</em> em cima (separadas por espaços), então não são criadas hiperligações. Mas se o mesmo acontecer com os elementos {{htmlelement('a')}} ou {{htmlelement('area')}}, então os elementos criam hiperligações sem uma relação específica.</p> + +<h2 id="Valores">Valores</h2> + +<p>Se houverem vários elementos <code><link rel="icon"></code>, o <em>browser</em> verifica os atributos <a href="media"><code>media</code></a>, <a href="type"><code>type</code></a> e <a href="sizes"><code>sizes</code></a> destes para selecionar o ícone mais adequado. Se mais do que um elemento for adequado, é o último que é usado. Se o ícone selecionado acabar por não ser apropriado (porque usa um formato não suportado, por exemplo), o <em>browser </em>seleciona o próximo elemento mais adequado.</p> + +<p><strong>Nota:</strong> Sistemas Apple iOS não usam este tipo de <em>link</em>, nem o atributo <a href="sizes"><code>sizes</code></a> (usado por outros <em>browsers </em>para dispositivos móveis), para escolher um ícone para um Web Clip ou para um <em>placeholder</em> visível no arranque. Sistemas iOS usam <a class="external external-icon" href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW4"><code>apple-touch-icon</code></a> e <a class="external external-icon" href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW6"><code>apple-touch-startup-image</code></a> respetivamente, atributos que não são padrão.</p> + +<p class="note">O tipo de <em>link</em> <code>shortcut</code> é frequentemente encontrado antes de <code>icon</code>, mas não é padrão, é ignorado, e <strong>já não deve ser usado por autores para a<em> web</em></strong>.</p> + +<dl> + <dt>{{htmlattrdef("alternate")}}</dt> + <dd>Aponta para uma versão alternativa do documento atual. É compatível com elementos <code>link</code>, <code>a</code>, e <code>area</code>. O efeito de <code>alternate</code> depende do valor de outros atributos: + <ul> + <li>Em conjunto com <code>{{anch('stylesheet')}} num </code><code>link</code>, <code>alternate</code> cria uma folha de estilo (<em>style sheet)</em> alternativa. + <pre class="brush:html notranslate"><!-- uma folha de estilo persistente --> +<link rel="stylesheet" href="default.css"> +<!-- folhas de estilo alternativas --> +<link rel="alternate stylesheet" href="highcontrast.css" title="High contrast"></pre> + </li> + <li>Com um atributo <code><a href="hreflang">hreflang</a></code> que tenha um valor diferente da língua do documento, <code>alternate</code> aponta para uma versão traduzida do documento.</li> + <li>Com um atributo <code><a href="type">type</a></code>, aponta para um documento com o mesmo contexto mas formato diferente. Por exemplo, com <code>type="application/rss+xml"</code> cria uma hiperligação para um <em>feed RSS</em>. + <pre class="brush:html notranslate"><link rel="alternate" type="application/atom+xml" href="posts.xml" title="Blog"></pre> + </li> + <li>Os atributos <a href="hreflang">hreflang</a> e <a href="type">type</a> apontam para versões do documento atua com formatos ou línguas diferentes, que podem ser dedicados a outros <em>media</em> + <pre class="brush:html notranslate"><link rel=alternate href="/fr/html/print" hreflang=fr type=text/html media=print title="French HTML (for printing)"> +<link rel=alternate href="/fr/pdf" hreflang=fr type=application/pdf title="French PDF"></pre> + </li> + </ul> + </dd> + <dt>{{htmlattrdef("author")}}</dt> + <dd>Cria uma hiperligação que indica o autor do documento ou artigo atual. Compatível com elementos {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando usado com {{htmlelement('a')}} ou {{htmlelement('area')}}, aponta para um documento (ou <code>mailto:</code>) com informação sobre o autor ou do {{htmlelement('article')}} pai mais próximo (se existir), ou do documento em si. No caso de um elemento {{htmlelement('link')}}, aponta para informação sobre o autor do documento atual. + <p class="note">Nota: O atributo obsoleto <code>rev="made"</code> é tratado como <code>rel="alternate"</code></p> + </dd> + <dt>{{htmlattrdef("bookmark")}}</dt> + <dd>Compatível com elementos {{htmlelement('a')}} e {{htmlelement('area')}}, <code>bookmark</code> informa que o <em>link é</em> um <em>permalink</em> para uma secção pai, que pode ser o {{htmlelement('article')}} ou {{htmlelement('section')}} mais próximo. Se tal secção não existir, o <em>link</em> refere-se ou ao <em>heading</em> mais próximo (que pode ser irmão do link, ou descender de um pai comum).</dd> + <dt>{{htmlattrdef("canonical")}}</dt> + <dd>Compatível com {{htmlelement('link')}}. Define o URL ideal para o documento atual, que é útil para motores de busca.</dd> + <dt>{{htmlattrdef("dns-prefetch")}}</dt> + <dd>Compatível com {{htmlelement('link')}}, seja dentro do {{htmlelement('body')}} ou do {{htmlelement('head')}}. Alerta o <em>browser</em> para antecipadamente efetuar resolução de DNS para a origem do recurso apontado. É útil para recursos que provavelmente serão úteis para o utilizador, porque este será capaz de aceder aos recursos mais rapidamente. Consulte a página sobre <a href="/pt-PT/docs/">como utilizar o DNS <em>prefetch</em></a> para mais informações.</dd> + <dt>{{htmlattrdef("external")}}</dt> + <dd>Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Indica que o documento referenciado não pertence ao <em>site </em>atual. Este valor é útil para estilizar links externos, e assim informar os utilizadores de que, se ativarem o elemento, vão abandonar o site atual.</dd> + <dt>{{htmlattrdef("help")}}</dt> + <dd>Compatível com {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Usado para representar uma ligação para conteúdo informativo sobre o pai do elemento com a hiperligação (e descendentes desse mesmo pai). Se um <code><link></code> contiver este valor, então o documento referenciado serve de apoio para o documento atual (em geral). Quando o valor está presente num elemento {{htmlelement('a')}} ou {{htmlelement('area')}}, o cursor {{cssxref('cursor')}} passará a <code>help</code> em vez de <code>pointer</code> (se possível).</dd> + <dt>{{htmlattrdef("icon")}}</dt> + <dd> + <p>Compatível com {{htmlelement('link')}}. Indica que o recurso referenciado é um ícone representativo do documento atual.</p> + + <p>Este valor é principalmente utilizado para definir um <em>favicon</em>:</p> + + <pre class="brush: html notranslate"><link rel="icon" href="favicon.ico"></pre> + + <p>Se houverem vários elementos <code><link rel="icon"></code>, então o <em>browser</em> deduz que <em>favicon</em> utilizar com base nos atributos <a href="media"><code>media</code></a>, <a href="type"><code>type</code></a>, e <a href="sizes"><code>sizes</code></a>. Caso mais que um destes elementos sejam os mais adequados (com base nestes critérios), então o <em>browser</em> seleciona o último destes. Se, posteriormente, o ícone mais adequado deixar de o ser, então o <em>browser </em>passa a usar o próximo ícone mais adequado.</p> + + <p><strong>Nota:</strong> para selecionar um ícone para um Web Clip ou para <em>placeholder</em> de arranque, o sistema iOS da Apple não usa nem este tipo de <em>link</em> nem o atributo <a href="sizes"><code>sizes</code></a>. Ao contrário de outros <em>browsers mobile</em>, este sistema usa os valores <a class="external external-icon" href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW4"><code>apple-touch-icon</code></a> e <a class="external external-icon" href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW6"><code>apple-touch-startup-image</code></a> respetivamente. Estes valores não são considerados <em>standard</em>.</p> + + <p class="note">O valor <code>shortcut</code> é frequentemente encontrado antes de <code>icon</code>, mas <strong>já não deve ser utilizado por autores na <em>web</em></strong>. <em>shortcut</em> não pertence a uma especificação, e é ignorado por diversos <em>browsers.</em> </p> + </dd> + <dt>{{htmlattrdef("license")}}</dt> + <dd> + <p>Compatível com elementos {{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("form")}}, {{HTMLElement("link")}}. O valor indica que a hiperligação aponta para informação de licenciamento relativa ao documento atual. Deste modo, sabe-se que o conteúdo principal do documento atual está protegido pela licença de <em>copyright </em>descrita no documento referenciado. Mesmo quando utilizado num descendente que não pertence ao elemento {{HTMLElement("head")}}, não há distinção entre uma hiperligação para uma licença associada ou a parte do documento ou ao documento em geral. Esta distinção só é possível através da informação na página.</p> + + <pre class="brush: html notranslate"><link rel="license" href="#license"></pre> + + <p><strong>Nota:</strong> Apesar de reconhecido, o valor "equivalente" <code>copyright</code> não é correto, pelo que deve ser evitado.</p> + </dd> + <dt>{{htmlattrdef("manifest")}}</dt> + <dd><a href="/en-US/docs/Web/Manifest">Manifesto <em>web app</em></a>. Requer o protocolo CORS para adquirir dados de origens diferentes (<em>cross-origin</em>).</dd> + <dt>{{htmlattrdef("modulepreload")}}</dt> + <dd>Útil para questões de <em>performance</em>, compatível com elementos {{htmlelement('link')}} em todo o documento. Informa o <em>browser </em>de que este deve antecipadamente descarregar o <em>script </em>referenciado (com as dependências respetivas), e armazená-lo no módulo de mapa de módulos para futura avaliação. Hiperligações com <code>modulepreload</code> podem ser usados para garantir que o recurso é descarregado com o módulo pronto (mas não avaliado) no mapa de módulo ainda antes de ser necessário. Veja também a página sobre <a href="/en-US/docs/Web/HTML/Link_types/modulepreload">tipos de <em>link</em>: <code>modulepreload</code></a>.</dd> + <dt>{{htmlattrdef("next")}}</dt> + <dd>Compatível com {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Indica que o documento atual pertence a uma série de documentos, e que o documento na série que se segue é referenciado pelo elemento em questão. Quando o valor está presente num elemento <code><link></code>, os <em>browsers</em> podem assumir que este recurso vai ser necessário posteriormente, e considerar esta informação uma "resource hint" (dica de recurso que podem descarregar antecipadamente).</dd> + <dt>{{htmlattrdef("nofollow")}}</dt> + <dd>Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. <code>nofollow</code> informa <em>spiders </em>(de motores de busca) de que devem ignorar a relação definida pelo <em>link</em>. Este valor pode indicar que o dono do documento atual não confia ou aprova o documento referenciado. <code>nofollow</code> é frequentemente incluído por <em>Search Engine Optimizers</em> (otimizadores de motores de busca) para dar a impressão de que os seus <em>link farms</em> não são páginas de <em>spam</em>.</dd> + <dt>{{htmlattrdef("noopener")}}</dt> + <dd>Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando selecionado, o <em>link</em> cria um contexto de navegação de topo (<em>top-level browsing context</em>) que não é auxiliar (<em>auxiliary</em>), mesmo que tenha condições para criar um contexto auxiliar (ex.: por ter um valor para<code> target </code>adequado). Por outras palavras, o <em>link</em> comporta-se como se <code><a href="/en-US/docs/Web/API/Window/opener">window.opener</a></code> fosse nulo e <code><a href="target">target</a>="_parent"</code> estivesse definido.<br> + <br> + <code>noopener</code> faz o contrário de {{anch("opener")}}.</dd> + <dt>{{htmlattrdef("noreferrer")}}</dt> + <dd>Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando incluído, o <em>referrer </em>(página com referência para o recurso) desconhecido. Deste modo, o pedido não inclui <code>Referer</code> no <em>header, </em>e cria um contexto de navegação de topo (<em>top-level browsing context</em>), como se <code>noopener</code> também estivesse definido.</dd> + <dt>{{htmlattrdef("opener")}}</dt> + <dd>Cria um contexto de navegação auxiliar (<em>auxiliary browsing context</em>), mesmo que o <em>link</em> tenha características para criar um contexto de navegação que não fosse auxiliar (via <code>target="_blank"</code>).</dd> + <dd><code>opener</code> faz o contrário de {{anch("noopener")}}.</dd> + <dt>{{htmlattrdef("pingback")}}</dt> + <dd>Define o endereço do servidor de <em>pingback</em> que controla <em>pingbacks</em> para o documento atual.</dd> + <dt>{{htmlattrdef("preconnect")}}</dt> + <dd>Define que o <em>user agent </em>deve antecipadamente conectar-se à origem do recurso apontado.</dd> + <dt>{{htmlattrdef("prefetch")}}</dt> + <dd>Define que o <em>user agent</em> deve antecipadamente descarregar e guardar em <em>cache</em> o recurso apontado. Deste modo, o recurso fica pronto se requisitado posteriormente.</dd> + <dt>{{htmlattrdef("preload")}}</dt> + <dd>Define que o <em>user agent</em> deve antecipadamente descarregar e guardar em <em>cache</em> o recurso apontado para a navegação atual. Deste modo, o recurso está preparado para ser usado num potencial destino da navegação, definido pelo atributo <code><a href="as">as</a></code> (a prioridade associada a este destino também é considerada).</dd> + <dt>{{htmlattrdef("prerender")}}</dt> + <dd>Define que o <em>user agent </em>deve antecipadamente descarregar e renderizar o recurso apontado, acelerando respostas a pedidos equivalentes.</dd> + <dt>{{htmlattrdef("prev")}}</dt> + <dd> + <p>Equivalente à palavra-chave {{anch("next")}}, compatível com os elementos {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. O valor <code>prev</code> indica que o documento atual pertence a uma série de documentos, sendo o link referenciado para o documento que se segue ao atual.</p> + + <p>Nota: O valor sinónimo <code>previous</code> não deve ser usado incorrect and should not be used, porque é incorreto.</p> + </dd> + <dt>{{htmlattrdef("search")}}</dt> + <dd> + <p>Compatível com elementos {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. <code>search</code> indica que o <em>link</em> referencia um documento com uma <em>interface</em> para pesquisar por conteúdo do documento atual, seja no <em>site </em>ou em recursos relacionados.</p> + + <p>Se o atributo <code><a href="type">type</a></code> do elemento for <code>application/opensearchdescription+xml,</code> então o recurso apontado é um <em>plugin</em> <a href="/en-US/docs/Creating_OpenSearch_plugins_for_Firefox">OpenSearch</a> que pode ser facilmente adicionado a alguns <em>browsers,</em> como o Firefox ou o Internet Explorer.</p> + </dd> + <dt>{{htmlattrdef("stylesheet")}}</dt> + <dd> + <p>Compatível com elementos {{htmlelement('link')}}. Importa um recurso externo que é uma <em>stylesheet</em> (folha de estilos). Caso o <em>link</em> aponte para uma <em>stylesheet</em> do tipo <code>text/css</code>, então pode-se omitir o atributo <code><a href="type">type</a></code>.</p> + + <p>Apesar do valor identificar o <em>link </em>como uma <em>stylesheet</em>, outros atributos ou valores poderão determinar se esta é descarregada ou usada.</p> + + <p>Quando o valor <code>stylesheet</code> é usado em conjunto com {{anch('alternate')}}, passa a definir uma <em>stylesheet</em> alternativa. Neste caso, deve ter o atributo <code><a href="type">title</a></code> com um valor não-vazio.</p> + + <p>O recurso <em>stylesheet</em> externo não será usado nem descarregado em contextos multimédia que não correspondam ao definido pelo atributo <code><a href="media">media</a></code> (ex.: se o <em>link</em> para a <em>stylesheet </em>tiver um atributo <code>media </code>com valor "print", então a <em>stylesheet</em> não será descarregada quando a página é renderizada numa tela).</p> + + <p>Requer o uso do protocolo CORS para pedidos com origens diferentes.</p> + </dd> + <dt>{{htmlattrdef("tag")}}</dt> + <dd>Compatível com elementos {{htmlelement('a')}} e {{htmlelement('area')}}. Define que o <em>link </em>referenciado identifica uma palavra-chave<em> </em>que se aplica ao documento atual. Este tipo de <em>link</em> não deve identificar palavras-chave numa <em>tag cloud</em>, porque estas aplicam-se apenas a um grupo de páginas, e não a uma página só (que é o objetivo do valor <code>tag</code>).</dd> +</dl> + +<h3 id="Valores_que_não_são_standard">Valores que não são <em>standard</em></h3> + +<dl> + <dt>apple-touch-icon-precomposed</dt> + <dd> + <pre class="brush: html notranslate"> <!-- iPad de terceira geração com tela Retina de alta resolução: --> + <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/static/img/favicon144.e7e21ca263ca.png"> + <!-- iPhone com tela Retina de alta resolução: --> + <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/static/img/favicon114.d526f38b09c5.png"> + <!-- iPad de primeira e segunda gerações: --> + <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/static/img/favicon72.cc65d1d762a0.png"> + <!-- iPhone e iPod Touch sem telas Retina, e dispositivos Android 2.1 ou superior: --> + <link rel="apple-touch-icon-precomposed" href="/static/img/favicon57.de33179910ae.png"> + <!-- favicon básico --> + <link rel="shortcut icon" href="/static/img/favicon32.7f3da72dcea1.png"></pre> + </dd> +</dl> + +<h2 id="Compatibilidade_de_Browsers_do_atributo_rel_em_geral">Compatibilidade de Browsers do atributo <em>rel </em>em geral</h2> + +<div class="hidden">Esta tabela de compatibilidade de <em>browsers</em> é gerada automaticamente a partir de dados organizados. Se quiser contribuir ao atualizar os dados, veja <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um <em>pull request</em>.</div> + +<p>{{Compat("html.elements.attributes.rel")}}</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'links.html#linkTypes', 'rel attribute')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Adicionado <code>opener</code>. <code>noopener</code> passou a ser definido por omissão com <code>target="_blank"</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'links.html#linkTypes', 'rel attribute')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Adicionados <code>tag</code>, <code>search</code>, <code>prefetch</code>, <code>noreferrer</code>, <code>nofollow</code>, <code>icon</code>, e <code>author</code>.<br> + <code>copyright</code> passou a ser <code>license</code>.<br> + Removidos <code>start</code>, <code>chapter</code>, <code>section</code>, <code>subsection</code>, e <code>appendix</code></td> + </tr> + <tr> + <td>{{SpecName("Preload", "#x2.link-type-preload", "preload")}}</td> + <td>{{Spec2("Preload")}}</td> + <td>Adicionado <code>preload</code>.</td> + </tr> + <tr> + <td>{{SpecName("Resource Hints", "#dfn-preconnect", "preconnect")}}</td> + <td>{{Spec2("Resource Hints")}}</td> + <td>Adicionados <code>dns-prefetch</code>, <code>preconnect</code>, e <code>prerender</code>.</td> + </tr> + <tr> + <td>{{SpecName("HTML4.01", "types.html#type-links", "link types")}}</td> + <td>{{Spec2("HTML4.01")}}</td> + <td>Adicionados <code>alternate</code>, <code>stylesheet</code>, <code>start</code>, <code>chapter</code>, <code>section</code>, <code>subsection</code>, <code>appendix</code>, e <code>bookmark</code>.<br> + <code>previous</code> passou a ser <code>prev</code>.<br> + Removidos <code>top</code>, e <code>search</code>.</td> + </tr> + <tr> + <td>{{SpecName("HTML3.2", "#link", "<link>")}}</td> + <td> + <p>{{Spec2("HTML3.2")}}<span class="spec-Obsolete"> (Obsoleto)</span></p> + </td> + <td>Adicionados <code>top</code>, <code>contents</code>, <code>index</code>, <code>glossary</code>, <code>copyright</code>, <code>next</code>, <code>previous</code>, <code>help</code>, e <code>search</code>.</td> + </tr> + <tr> + <td>{{RFC(1866, "HTML 2.0")}}</td> + <td>{{Spec2("HTML2.0")}}<span class="spec-Obsolete">(Obsolete)</span></td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_Browsers_de_valores_rel_para_elementos_link">Compatibilidade de <em>Browsers </em>de valores <em>rel </em>para elementos <em>link</em></h2> + +<p class="hidden">Esta tabela de compatibilidade de <em>browsers</em> é gerada automaticamente a partir de dados organizados. Se quiser contribuir ao atualizar os dados, veja <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um <em>pull request</em>.</p> + +<p>{{Compat("html.elements.link.rel")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{domxref("HTMLLinkElement.relList")}}</li> + <li>{{domxref("HTMLAnchorElement.relList")}}</li> + <li>{{domxref("HTMLAreaElement.relList")}}</li> +</ul> diff --git a/files/pt-pt/web/html/atributos_globais/index.html b/files/pt-pt/web/html/atributos_globais/index.html new file mode 100644 index 0000000000..2b4a86e833 --- /dev/null +++ b/files/pt-pt/web/html/atributos_globais/index.html @@ -0,0 +1,480 @@ +--- +title: Atributos globais +slug: Web/HTML/Atributos_globais +tags: + - HTML + - Precisa Compatibilidade Navegador + - Referencia + - Web + - atributo +translation_of: Web/HTML/Global_attributes +--- +<div>{{HTMLSidebar("Global_attributes")}}</div> + +<div class="summary"> +<p>Os<strong> 'Atributos Globais' </strong>são atributos comuns a todos os elementos HTML; estes podem ser utilziados em todos os elementos, embora os atributos poderão não ter efeito em alguns elementos.</p> +</div> + +<p>Os atributos globais podem ser especificados em todos os <a href="/pt-PT/docs/Web/HTML/Elemento">elementos HTML</a>, <em> mesmo aqueles que não estão especificados no padrão</em>. Isso significa que qualquer elemento não padrão ainda deve permitir esses atributos, mesmo que utilizando esses elementos significa que o documento já não é mais compatível com HTML5. Por exemplo, navegadores compatíveis com HTML5 ocultam conteúdo marcado como <code><foo hidden>...<foo></code><code>, </code>mesmo que <code><foo></code> não seja um elemento HTML válido.</p> + +<p>Além dos atributos globais HTML básicos, também existem os seguintes atributos globais:</p> + +<ul> + <li><strong><code>xml:lang</code></strong> and <code><strong>xml:base</strong></code> — these are inherited from the XHTML specifications and deprecated, but kept for compatibility purposes.</li> + <li>The multiple <code><strong><a href="/en-US/docs/Web/Accessibility/ARIA">aria-*</a></strong></code> attributes, used for improving accessibility.</li> + <li>The event handler attributes: <code><strong>onabort</strong></code>, <code><strong>onautocomplete</strong></code>, <code><strong>onautocompleteerror</strong></code>, <code><strong>onblur</strong></code>, <code><strong>oncancel</strong></code>, <code><strong>oncanplay</strong></code>, <code><strong>oncanplaythrough</strong></code>, <code><strong>onchange</strong></code>, <code><strong>onclick</strong></code>, <code><strong>onclose</strong></code>, <code><strong>oncontextmenu</strong></code>, <code><strong>oncuechange</strong></code>, <code><strong>ondblclick</strong></code>, <code><strong>ondrag</strong></code>, <code><strong>ondragend</strong></code>, <code><strong>ondragenter</strong></code>, <code><strong>ondragexit</strong></code>, <code><strong>ondragleave</strong></code>, <code><strong>ondragover</strong></code>, <code><strong>ondragstart</strong></code>, <code><strong>ondrop</strong></code>, <code><strong>ondurationchange</strong></code>, <code><strong>onemptied</strong></code>, <code><strong>onended</strong></code>, <code><strong>onerror</strong></code>, <code><strong>onfocus</strong></code>, <code><strong>oninput</strong></code>, <code><strong>oninvalid</strong></code>, <code><strong>onkeydown</strong></code>, <code><strong>onkeypress</strong></code>, <code><strong>onkeyup</strong></code>, <code><strong>onload</strong></code>, <code><strong>onloadeddata</strong></code>, <code><strong>onloadedmetadata</strong></code>, <code><strong>onloadstart</strong></code>, <code><strong>onmousedown</strong></code>, <code><strong>onmouseenter</strong></code>, <code><strong>onmouseleave</strong></code>, <code><strong>onmousemove</strong></code>, <code><strong>onmouseout</strong></code>, <code><strong>onmouseover</strong></code>, <code><strong>onmouseup</strong></code>, <code><strong>onmousewheel</strong></code>, <code><strong>onpause</strong></code>, <code><strong>onplay</strong></code>, <code><strong>onplaying</strong></code>, <code><strong>onprogress</strong></code>, <code><strong>onratechange</strong></code>, <code><strong>onreset</strong></code>, <code><strong>onresize</strong></code>, <code><strong>onscroll</strong></code>, <code><strong>onseeked</strong></code>, <code><strong>onseeking</strong></code>, <code><strong>onselect</strong></code>, <code><strong>onshow</strong></code>, <code><strong>onsort</strong></code>, <code><strong>onstalled</strong></code>, <code><strong>onsubmit</strong></code>, <code><strong>onsuspend</strong></code>, <code><strong>ontimeupdate</strong></code>, <code><strong>ontoggle</strong></code>, <code><strong>onvolumechange</strong></code>, <code><strong>onwaiting</strong></code>.</li> +</ul> + +<h2 id="Descrição">Descrição</h2> + +<dl> + <dt id="attr-accesskey"><code><a href="/en-US/docs/Web/HTML/Global_attributes/accesskey">accesskey</a></code></dt> + <dd>Provides a hint for generating a keyboard shortcut for the current element. This attribute consists of a space-separated list of characters. The browser should use the first one that exists on the computer keyboard layout.</dd> + <dt id="attr-class"><code><a href="/en-US/docs/Web/HTML/Global_attributes/class">class</a></code></dt> + <dd>Is a space-separated list of the classes of the element. Classes allows CSS and JavaScript to select and access specific elements via the <a href="/en-US/docs/Web/CSS/Class_selectors">class selectors</a> or functions like the method {{domxref("Document.getElementsByClassName()")}}.</dd> + <dt id="attr-contenteditable"><code><a href="/en-US/docs/Web/HTML/Global_attributes/contenteditable">contenteditable</a></code></dt> + <dd>Is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. The attribute must take one of the following values: + <ul> + <li><code>true</code> or the <em>empty string</em>, which indicates that the element must be editable;</li> + <li><code>false</code>, which indicates that the element must not be editable.</li> + </ul> + </dd> + <dt id="attr-contextmenu"><code><a href="/en-US/docs/Web/HTML/Global_attributes/contextmenu">contextmenu</a></code></dt> + <dd>Is the <code><a href="#attr-id"><strong>id</strong></a></code> of an {{HTMLElement("menu")}} to use as the contextual menu for this element.</dd> + <dt id="attr-dataset"><code><a href="/en-US/docs/Web/HTML/Global_attributes/data-*">data-*</a></code></dt> + <dd>Forms a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between the <a href="/en-US/docs/Web/HTML">HTML</a> and its <a href="/en-US/docs/Glossary/DOM">DOM</a> representation that may be used by scripts. All such custom data are available via the {{domxref("HTMLElement")}} interface of the element the attribute is set on. The {{domxref("HTMLElement.dataset")}} property gives access to them.</dd> + <dt id="attr-dir"><code><a href="/en-US/docs/Web/HTML/Global_attributes/dir">dir</a></code></dt> + <dd>Is an enumerated attribute indicating the directionality of the element's text. It can have the following values: + <ul> + <li><code>ltr</code>, which means <em>left to right </em>and is to be used for languages that are written from the left to the right (like English);</li> + <li><code>rtl</code>, which means <em>right to left</em> and is to be used for languages that are written from the right to the left (like Arabic);</li> + <li><code>auto</code>, which let the user agent decides. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then apply that directionality to the whole element.</li> + </ul> + </dd> + <dt id="attr-draggable"><code><a href="/en-US/docs/Web/HTML/Global_attributes/draggable">draggable</a></code></dt> + <dd>Is an enumerated attribute indicating whether the element can be dragged, using the <a href="/en-us/docs/DragDrop/Drag_and_Drop">Drag and Drop API</a>. It can have the following values: + <ul> + <li><code>true</code>, which indicates that the element may be dragged</li> + <li><code>false</code>, which indicates that the element may not be dragged.</li> + </ul> + </dd> + <dt id="attr-dropzone"><code><a href="/en-US/docs/Web/HTML/Global_attributes/dropzone">dropzone</a></code> {{experimental_inline}}</dt> + <dd>Is an enumerated attribute indicating what types of content can be dropped on an element, using the <a href="/en-US/docs/DragDrop/Drag_and_Drop">Drag and Drop API</a>. It can have the following values: + <ul> + <li><code>copy</code>, which indicates that dropping will create a copy of the element that was dragged</li> + <li><code>move</code>, which indicates that the element that was dragged will be moved to this new location.</li> + <li><code>link</code>, will create a link to the dragged data.</li> + </ul> + </dd> + <dt id="attr-hidden"><code><a href="/en-US/docs/Web/HTML/Global_attributes/hidden">hidden</a></code></dt> + <dd>Is a Boolean attribute indicates that the element is not yet, or is no longer, <em>relevant</em>. For example, it can be used to hide elements of the page that can't be used until the login process has been completed. The browser won't render such elements. This attribute must not be used to hide content that could legitimately be shown.</dd> + <dt id="attr-id"><code><a href="/en-US/docs/Web/HTML/Global_attributes/id">id</a></code></dt> + <dd>Defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).</dd> +</dl> + +<div class="note"> +<p><strong>Nota: </strong>os atributos <code>item*</code> são parte de uma <a class="external" href="https://html.spec.whatwg.org/multipage/microdata.html#microdata">funcionalidade Microdados HTML de WHATWG</a>.</p> +</div> + +<dl> + <dt id="attr-itemid"><code><a href="/en-US/docs/Web/HTML/Global_attributes/itemid">itemid</a></code> {{experimental_inline}}</dt> + <dd>The unique, global identifier of an item.</dd> + <dt id="attr-itemprop"><code><a href="/en-US/docs/Web/HTML/Global_attributes/itemprop">itemprop</a></code> {{experimental_inline}}</dt> + <dd>Used to add properties to an item. Every HTML element may have an itemprop attribute specified, where an itemprop consists of a name and value pair.</dd> + <dt id="attr-itemref"><code><a href="/en-US/docs/Web/HTML/Global_attributes/itemref">itemref</a></code> {{experimental_inline}}</dt> + <dd>Properties that are not descendants of an element with the <code>itemscope</code> attribute can be associated with the item using an <strong>itemref</strong>. Itemref provides a list of element ids (not <code>itemid</code>s) with additional properties elsewhere in the document.</dd> + <dt id="attr-itemscope"><code><a href="/en-US/docs/Web/HTML/Global_attributes/itemscope">itemscope</a> </code>{{experimental_inline}}</dt> + <dd>Itemscope (usually) works along with <a href="/en-US/docs/Web/HTML/Global_attributes/itemtype">itemtype </a>to specify that the HTML contained in a block is about a particular item. itemscope creates the Item and defines the scope of the itemtype associated with it. itemtype is a valid URL of a vocabulary (such as <a class="external external-icon" href="https://schema.org/">schema.org</a>) that describes the item and its properties context.</dd> + <dt id="attr-itemtype"><code><a href="/en-US/docs/Web/HTML/Global_attributes/itemtype">itemtype</a></code> {{experimental_inline}}</dt> + <dd>Specifies the URL of the vocabulary that will be used to define itemprop's (item properties) in the data structure. <a href="/en-US/docs/Web/HTML/Global_attributes/itemscope">Itemscope</a> is used to set the scope of where in the data structure the vocabulary set by itemtype will be active.</dd> + <dt id="attr-lang"><code><a href="/en-US/docs/Web/HTML/Global_attributes/lang">lang</a></code></dt> + <dd>Participates in defining the language of the element, the language that non-editable elements are written in or the language that editable elements should be written in. The tag contains one single entry value in the format defined in the <a class="external" href="https://www.ietf.org/rfc/bcp/bcp47.txt"><em>Tags for Identifying Languages (BCP47)</em></a> IETF document. <a href="#attr-xml:lang"><strong>xml:lang</strong></a> has priority over it.</dd> +</dl> + +<dl> + <dt id="attr-slot"><code><a href="/en-US/docs/Web/HTML/Global_attributes/slot">slot</a></code> {{experimental_inline}}</dt> + <dd>Assigns a slot in a <a href="/en-US/docs/Web/Web_Components/Shadow_DOM">shadow DOM</a> shadow tree to an element: An element with a <code>slot</code> attribute is assigned to the slot created by the {{HTMLElement("slot")}} element whose {{htmlattrxref("name", "slot")}} attribute's value matches that <code>slot</code> attribute's value.</dd> +</dl> + +<dl> + <dt id="attr-spellcheck"><code><a href="/en-US/docs/Web/HTML/Global_attributes/spellcheck">spellcheck</a></code> {{experimental_inline}}</dt> + <dd>Is an enumerated attribute defines whether the element may be checked for spelling errors. It may have the following values: + <ul> + <li><code>true</code>, which indicates that the element should be, if possible, checked for spelling errors;</li> + <li><code>false</code>, which indicates that the element should not be checked for spelling errors.</li> + </ul> + </dd> + <dt id="attr-style"><code><a href="/en-US/docs/Web/HTML/Global_attributes/style">style</a></code></dt> + <dd>Contains <a href="/en-US/docs/Web/CSS">CSS</a> styling declarations to be applied to the element. Note that it is recommended for styles to be defined in a separate file or files. This attribute and the {{HTMLElement("style")}} element have mainly the purpose of allowing for quick styling, for example for testing purposes.</dd> + <dt id="attr-tabindex"><code><a href="/en-US/docs/Web/HTML/Global_attributes/tabindex">tabindex</a></code></dt> + <dd>Is an integer attribute indicating if the element can take input focus (is <em>focusable</em>), if it should participate to sequential keyboard navigation, and if so, at what position. It can takes several values: + <ul> + <li>a <em>negative value</em> means that the element should be focusable, but should not be reachable via sequential keyboard navigation;</li> + <li><code>0</code> means that the element should be focusable and reachable via sequential keyboard navigation, but its relative order is defined by the platform convention;</li> + <li>a <em>positive value</em> which means should be focusable and reachable via sequential keyboard navigation; its relative order is defined by the value of the attribute: the sequential follow the increasing number of the <a href="#attr-tabindex"><strong>tabindex</strong></a>. If several elements share the same tabindex, their relative order follows their relative position in the document).</li> + </ul> + </dd> + <dt id="attr-title"><code><a href="/en-US/docs/Web/HTML/Global_attributes/title">title</a></code></dt> + <dd>Contains a text representing advisory information related to the element it belongs to. Such information can typically, but not necessarily, be presented to the user as a tooltip.</dd> + <dt id="attr-translate"><code><a href="/en-US/docs/Web/HTML/Global_attributes/translate">translate</a></code> {{experimental_inline}}</dt> + <dd>Is an enumerated attribute that is used to specify whether an element's attribute values and the values of its {{domxref("Text")}} node children are to be translated when the page is localized, or whether to leave them unchanged. It can have the following values: + <ul> + <li>empty string and <code>"yes"</code>, which indicates that the element will be translated.</li> + <li><code>"no"</code>, which indicates that the element will not be translated.</li> + </ul> + </dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "dom.html#global-attributes", "Global attributes")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>From latest snapshot, {{SpecName('HTML5.1')}}, <code>itemid</code>, <code>itemprop</code>, <code>itemref</code>, <code>itemscope</code>, and <code>itemtype</code> have been added.</td> + </tr> + <tr> + <td>{{SpecName('HTML5.1', "dom.html#global-attributes", "Global attributes")}}</td> + <td>{{Spec2('HTML5.1')}}</td> + <td>Snapshot of {{SpecName('HTML WHATWG')}}. From {{SpecName('HTML5 W3C')}}, <code>spellcheck</code>, <code>draggable</code>, and <code>dropzone</code> have been added.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', "dom.html#global-attributes", "Global attributes")}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Snapshot of {{SpecName('HTML WHATWG')}}. From {{SpecName("HTML4.01")}}, the concept of global attributes is introduced and the <code>dir</code>, <code>lang</code>, <code>style</code>, <code>id</code>, <code>class</code>, <code>tabindex</code>, <code>accesskey</code>, and <code>title</code> are now true global attributes.<br> + <code>xml:lang</code> which was initially part of XHTML, is now also part of HTML.<br> + <code>hidden</code>, <code>data-*</code>, <code>contextmenu</code>, <code>contenteditable</code>, and <code>translate</code> have been added.</td> + </tr> + <tr> + <td>{{SpecName('HTML4.01')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td>There are no global attributes defined. Several attributes that will become global attributes in subsequent specifications are defined on a subset of elements.<br> + <code>class</code> and <code>style</code> are supported on all elements but {{HTMLElement("base")}}, {{HTMLElement("basefont")}}, {{HTMLElement("head")}}, {{HTMLElement("html")}}, {{HTMLElement("meta")}}, {{HTMLElement("param")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}}, and {{HTMLElement("title")}}.<br> + <code>dir</code> is supported on all elements but {{HTMLElement("applet")}}, {{HTMLElement("base")}}, {{HTMLElement("basefont")}}, {{HTMLElement("bdo")}}, {{HTMLElement("br")}}, {{HTMLElement("frame")}}, {{HTMLElement("frameset")}}, {{HTMLElement("iframe")}}, {{HTMLElement("param")}}, and {{HTMLElement("script")}}.<br> + <code>id</code> is supported on all elements but {{HTMLElement("base")}}, {{HTMLElement("head")}}, {{HTMLElement("html")}}, {{HTMLElement("meta")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}}, and {{HTMLElement("title")}}.<br> + <code>lang</code> is supported on all elements but {{HTMLElement("applet")}}, {{HTMLElement("base")}}, {{HTMLElement("basefont")}}, {{HTMLElement("br")}}, {{HTMLElement("frame")}}, {{HTMLElement("frameset")}}, {{HTMLElement("iframe")}}, {{HTMLElement("param")}}, and {{HTMLElement("script")}}.<br> + <code>tabindex</code> is only supported on {{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("button")}}, {{HTMLElement("object")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.<br> + <code>accesskey</code> is only supported on {{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{HTMLElement("label")}}, {{HTMLElement("legend")}} and {{HTMLElement("textarea")}}.<br> + <code>title</code> is supported on all elements but {{HTMLElement("base")}}, {{HTMLElement("basefont")}}, {{HTMLElement("head")}}, {{HTMLElement("html")}}, {{HTMLElement("meta")}}, {{HTMLElement("param")}}, {{HTMLElement("script")}}, and {{HTMLElement("title")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td><code>accesskey</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>class</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>contenteditable</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>contextmenu</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoDesktop(9)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>data-*</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("6")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>dir</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>draggable</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.8.1")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>dropzone</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>hidden</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>id</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>itemid</code>, <code>itemprop</code>, <code>itemref</code>, <code>itemscope</code>, <code>itemtype</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>lang</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>spellcheck</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.8.1")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>style</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>tabindex</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>title</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td><code>accesskey</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>class</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>contenteditable</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.9")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>contextmenu</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>data-*</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("6")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>dir</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>draggable</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.8.1")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>dropzone</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>hidden</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>id</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>itemid</code>, <code>itemprop</code>, <code>itemref</code>, <code>itemscope</code>, <code>itemtype</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>lang</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>spellcheck</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.8.1")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>style</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>tabindex</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>title</code></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li>Interfaces {{domxref("Element")}} e {{domxref("GlobalEventHandlers")}} que permitem-lhe consultar a maioria dos atributos globais.</li> +</ul> diff --git a/files/pt-pt/web/html/cors_settings_attributes/index.html b/files/pt-pt/web/html/cors_settings_attributes/index.html new file mode 100644 index 0000000000..42f32f77e8 --- /dev/null +++ b/files/pt-pt/web/html/cors_settings_attributes/index.html @@ -0,0 +1,87 @@ +--- +title: 'Atributo CORS: Solicitar acesso CORS para o conteúdo' +slug: Web/HTML/CORS_settings_attributes +tags: + - Avançado + - CORS + - HTML + - Precisa de Exemplo + - Referencia + - Segurança +translation_of: Web/HTML/Attributes/crossorigin +--- +<p><span class="seoSummary">In HTML5, some HTML elements which provide support for <a href="/en-US/docs/Web/HTTP/CORS">CORS</a>, such as {{ HTMLElement("img") }}, {{ HTMLElement("video") }} or {{ HTMLElement("script") }}, have a <code>crossorigin</code> attribute (<code>crossOrigin</code> property), which lets you configure the CORS requests for the element's fetched data.</span> These attributes are enumerated, and have the following possible values:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Keyword</td> + <td class="header">Description</td> + </tr> + <tr> + <td><code>anonymous</code></td> + <td>CORS requests for this element will have the credentials flag set to 'same-origin'.</td> + </tr> + <tr> + <td><code>use-credentials</code></td> + <td>CORS requests for this element will have the credentials flag set to 'include'.</td> + </tr> + </tbody> +</table> + +<p>By default (that is, when the attribute is not specified), CORS is not used at all. The "anonymous" keyword means that there will be no exchange of <strong>user credentials</strong> via cookies, client-side SSL certificates or HTTP authentication as described in the <a class="external" href="http://www.w3.org/TR/cors/#user-credentials">Terminology section of the CORS specification</a>, unless it is in the same origin.</p> + +<p>An invalid keyword and an empty string will be handled as the <code>anonymous</code> keyword.</p> + +<h3 id="Exemplo_crossorigin_with_the_script_element">Exemplo: crossorigin with the script element</h3> + +<p>You can use the following {{HTMLElement("script")}} element to tell a browser to execute the <code>https://example.com/example-framework.js</code> script without sending user-credentials.</p> + +<pre class="brush: html"><script src="https://example.com/example-framework.js" + crossorigin="anonymous"></script></pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'infrastructure.html#cors-settings-attributes', 'CORS settings attributes')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'embedded-content.html#attr-img-crossorigin', 'crossorigin')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<h3 id="<script_crossorigin>"><script crossorigin></h3> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("html.elements.script.crossorigin")}}</p> + +<h3 id="<video_crossorigin>"><video crossorigin></h3> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("html.elements.video.crossorigin")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing (CORS)</a></li> +</ul> + +<div>{{QuickLinksWithSubpages("/en-US/docs/Web/HTML/")}}</div> diff --git a/files/pt-pt/web/html/elemento/audio/index.html b/files/pt-pt/web/html/elemento/audio/index.html new file mode 100644 index 0000000000..f8b7c3229b --- /dev/null +++ b/files/pt-pt/web/html/elemento/audio/index.html @@ -0,0 +1,47 @@ +--- +title: Audio +slug: Web/HTML/Elemento/Audio +translation_of: Web/HTML/Element/audio +--- +<p>{{ gecko_minversion_header("1.9.1") }}</p> +<p>O elemento <code>audio</code> é usado para embutir conteúdo de som em um documento HTML or XHTML. O elemento <code>audio</code> foi adicionado como parte do HTML 5.</p> +<ul> + <li>Tipo do Elemento: <a class="internal" href="/en/HTML/Block-level_elements" title="en/HTML/Block-level elements">block-level</a> (en)</li> + <li>Conteúdo Permitido: texto alternativo</li> +</ul> +<div class="note"> + <strong>Nota:</strong> Atualmente, o Firefox suporta apenas Vorbis, em recipientes Ogg, assim como o formato WAV. O servidor também deve servir o arquivo usando o MIME type correto para que o Firefox o reproduza corretamente.</div> +<h2 id="Atributos">Atributos</h2> +<dl> + <dt> + autoplay</dt> + <dd> + Um atributo boleano; se especificado (mesmo se o valor for "false"!), o áudio começará a tocar automaticamente assim que ele conseguir, portanto, sem parar para finalizar o carregamento dos dados.</dd> + <dt> + controls {{ unimplemented_inline() }} {{ bug(449149) }}</dt> + <dd> + Se este atributo estiver presente, o navegador oferecerá controles para permitir que o usuário controle a reprodução do áudio, incluindo volume, procura, e pausa/continuar.</dd> + <dt> + loop {{ unimplemented_inline() }} {{ bug(449157) }}</dt> + <dd> + Um atributo boleano; se especificado, quando alcançar o fim do áudio, voltará ao início automaticamente.</dd> + <dt> + src</dt> + <dd> + A URL do áudio a embutir. Este é assunto para <a class="internal" href="/En/HTTP_access_control" title="En/HTTP access control">protocolos de acesso HTTP</a> (en).</dd> +</dl> +<p>O deslocamento de tempo é especificado como um valor de ponto flutuante indicando o número de segundos do deslocamento.</p> +<div class="note"> + <strong>Nota:</strong> A definição do valor de deslocamento de tempo ainda não está completa na especificação do HTML 5 e está sujeita a mudanças.</div> +<h2 id="Exemplos">Exemplos</h2> +<pre class="brush: html"><audio src="http://developer.mozilla.org/@api/deki/files/2926/=AudioTest_(1).ogg" autoplay> + Seu navegador não suporta o elemento <code>audio</code>. +</audio> +</pre> +<p>Reproduz o arquivo de áudio anexado à versão em inglês deste artigo.</p> +<h2 id="Veja_Também">Veja Também</h2> +<ul> + <li><a class="internal" href="/Pt/HTML/Elemento/Video" title="pt/HTML/Elemento/Video"><code>video</code></a></li> + <li><code>{{ interface("nsIDOMHTMLMediaElement") }}</code></li> + <li><a class="internal" href="/Pt/Usando_%C3%A1udio_e_v%C3%ADdeo_no_Firefox" title="pt/Usando áudio e vídeo no Firefox">Usando áudio e vídeo no Firefox</a></li> +</ul> diff --git a/files/pt-pt/web/html/elemento/fieldset/index.html b/files/pt-pt/web/html/elemento/fieldset/index.html new file mode 100644 index 0000000000..44fd353489 --- /dev/null +++ b/files/pt-pt/web/html/elemento/fieldset/index.html @@ -0,0 +1,177 @@ +--- +title: '<fieldset>: O elemento "Field Set"' +slug: Web/HTML/Elemento/fieldset +tags: + - Elemento + - Formulários HTML + - HTML + - Referencia + - Web + - formulários +translation_of: Web/HTML/Element/fieldset +--- +<p>O <strong>elemento HTML <code><fieldset></code> </strong>é utilizado para agrupar vários controlos, bem como as etiquetas ({{HTMLElement("label")}}) dentro de um formulário da Web.</p> + +<div>{{EmbedInteractiveExample("pages/tabbed/fieldset.html", "tabbed-standard")}}</div> + +<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples </a> and send us a pull request.</p> + +<p>As the example above shows, the <code><fieldset></code> element provides a grouping for a part of an HTML form, with a nested {{htmlelement("legend")}} element providing a caption for the <code><fieldset></code>. It takes few attributes, the most notable of which are <code>form</code>, which can contain the <code>id</code> of a {{htmlelement("form")}} on the same page, allowing you to make the <code><fieldset></code> part of that <code><form></code> even if it is not nested inside it, and <code>disabled</code>, which allows you to disable the <code><fieldset></code> and all its contents in one go.</p> + +<h2 id="Atributos">Atributos</h2> + +<p>This element includes the <a href="/en-US/docs/HTML/Global_attributes">global attributes</a>.</p> + +<dl> + <dt>{{htmlattrdef("disabled")}} {{HTMLVersionInline(5)}}</dt> + <dd>If this Boolean attribute is set, all form controls that are descendants of the <code><fieldset></code>, are disabled, meaning they are not editable but will be submitted along with <code><form></code> in comparison with {{htmlattrdef("disabled")}} attribute on form controls. They won't receive any browsing events, like mouse clicks or focus-related events. By default browsers display such controls grayed out. Note that form elements inside the {{HTMLElement("legend")}} element won't be disabled.</dd> + <dt>{{htmlattrdef("form")}} {{HTMLVersionInline(5)}}</dt> + <dd>This attribute takes the value of the <code>id</code> attribute of a {{HTMLElement("form")}} element you want the <code><fieldset></code> to be part of, even if it is not inside the form.</dd> + <dt>{{htmlattrdef("name")}} {{HTMLVersionInline(5)}}</dt> + <dd>The name associated with the group. + <div class="note"><strong>Note</strong>: The caption for the fieldset is given by the first {{HTMLElement("legend")}} element nested inside it.</div> + </dd> +</dl> + +<h2 id="Estilizar_com_CSS">Estilizar com CSS</h2> + +<p>There are several special styling considerations for <code><fieldset></code>.</p> + +<p>Its {{cssxref("display")}} value is <code>block</code> by default, and it establishes a block formatting context. If the <code><fieldset></code> is styled with an inline-level <code>display</code> value, it will behave as <code>inline-block</code>, otherwise it will behave as <code>block</code>. By default there is a 2px groove border surrounding the contents, and a small amount of default padding. The element has <code>min-inline-size: min-content</code> by default.</p> + +<p>If a <code><legend></code> is present, it is placed over the block-start border. The <code><legend></code> shrink-wraps, and also establishes a formatting context. The <code>display</code> value is blockified (for example, <code>display: inline</code> behaves as <code>block</code>).</p> + +<p>There will be an anonymous box holding the contents of the <code><fieldset></code>, which inherits certain properties from the <code><fieldset></code>. If the <code><fieldset></code> is styled with <code>display: grid</code> or <code>display: inline-grid</code>, then the anonymous box will be a grid formatting context. If the <code><fieldset></code> is styled with <code>display: flex</code> or <code>display: inline-flex</code>, then the anonymous box will be a flex formatting context. Otherwise it establishes a block formatting context.</p> + +<p>You can feel free to style the <code><fieldset></code> and <code><legend></code> in any way you want to suit your page design.</p> + +<div class="note"> +<p><strong>Nota: </strong>as of this writing, there are bugs in Microsoft Edge and Google Chrome which prevent <a href="/en-US/docs/Glossary/Flexbox">flexbox</a> and <a href="/en-US/docs/Web/CSS/CSS_Grid_Layout">grid </a>layouts from being used inside a {{HTMLElement("fieldset")}}. <a href="https://github.com/w3c/csswg-drafts/issues/321">This GitHub issue</a> provides bug tracking links.</p> +</div> + +<h2 id="Exemplo">Exemplo</h2> + +<h3 id="Simple_fieldset">Simple fieldset</h3> + +<p>This example shows a really simple <code><fieldset></code> example, with a <code><legend></code>, and a single control inside it.</p> + +<pre class="brush: html"><form action="#"> + <fieldset> + <legend>Simple fieldset</legend> + <input type="radio" id="radio"> + <label for="radio">Spirit of radio</label> + </fieldset> +</form></pre> + +<p>{{ EmbedLiveSample('Simple_fieldset', '100%', '80') }}</p> + +<h3 id="fieldset_desativado">"fieldset" desativado</h3> + +<p>This example shows a disabled <code><fieldset></code> with two controls inside it. Note how both the controls are disabled due to being inside a disabled <code><fieldset></code>.</p> + +<pre class="brush: html"><form action="#"> + <fieldset disabled> + <legend>Disabled fieldset</legend> + <div> + <label for="name">Name: </label> + <input type="text" id="name" value="Chris"> + </div> + <div> + <label for="pwd">Archetype: </label> + <input type="password" id="pwd" value="Wookie"> + </div> + </fieldset> +</form></pre> + +<p>{{ EmbedLiveSample('Disabled_fieldset', '100%', '110') }}</p> + +<h2 id="Resumo_técnico">Resumo técnico</h2> + +<table class="properties"> + <tbody> + <tr> + <th scope="row"><a href="/en-US/docs/HTML/Content_categories">Categorias de conteúdo</a></th> + <td><a href="/en-US/docs/HTML/Content_categories#Flow_content">Flow content</a>, <a href="/en-US/docs/Sections_and_Outlines_of_an_HTML5_document#sectioning_root">sectioning root</a>, <a href="/en-US/docs/HTML/Content_categories#form_listed">listed</a>, <a href="/en-US/docs/HTML/Content_categories#form-associated_content">form-associated</a> element, palpable content.</td> + </tr> + <tr> + <th scope="row">Conteúdo permitido</th> + <td>An optional {{HTMLElement("legend")}} element, followed by flow content.</td> + </tr> + <tr> + <th scope="row">Omissão de etiqueta</th> + <td>{{no_tag_omission}}</td> + </tr> + <tr> + <th scope="row">Permitted parents</th> + <td>Any element that accepts <a href="/en-US/docs/HTML/Content_categories#Flow_content">flow content</a>.</td> + </tr> + <tr> + <th scope="row">Permitted ARIA roles</th> + <td>{{ARIARole("group")}}, {{ARIARole("presentation")}}</td> + </tr> + <tr> + <th scope="row">Interface DOM</th> + <td>{{domxref("HTMLFieldSetElement")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'forms.html#the-fieldset-element', '<fieldset>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Definition of the <code>fieldset</code> element</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'forms.html#the-fieldset-element', '<fieldset>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('HTML4.01', 'interact/forms.html#h-17.10', '<fieldset>')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("html.elements.fieldset")}}</p> + +<h2 id="Consulte_também">Consulte também:</h2> + +<ul> + <li>Other form-related elements: + <ul> + <li>{{HTMLElement("form")}}</li> + <li>{{HTMLElement("legend")}}</li> + <li>{{HTMLElement("label")}}</li> + <li>{{HTMLElement("button")}}</li> + <li>{{HTMLElement("select")}}</li> + <li>{{HTMLElement("datalist")}}</li> + <li>{{HTMLElement("optgroup")}}</li> + <li>{{HTMLElement("option")}}</li> + <li>{{HTMLElement("textarea")}}</li> + <li>{{HTMLElement("keygen")}}</li> + <li>{{HTMLElement("input")}}</li> + <li>{{HTMLElement("output")}}</li> + <li>{{HTMLElement("progress")}}</li> + <li>{{HTMLElement("meter")}}</li> + </ul> + </li> +</ul> + +<div>{{HTMLRef}}</div> diff --git a/files/pt-pt/web/html/elemento/figcaption/index.html b/files/pt-pt/web/html/elemento/figcaption/index.html new file mode 100644 index 0000000000..e40a044136 --- /dev/null +++ b/files/pt-pt/web/html/elemento/figcaption/index.html @@ -0,0 +1,101 @@ +--- +title: figcaption +slug: Web/HTML/Elemento/figcaption +translation_of: Web/HTML/Element/figcaption +--- +<h2 id="Introdução">Introdução</h2> + +<p>O <em>Elemento HTML Figcaption</em>(<code><figcaption></code>) representa uma legenda ou uma legenda associada com uma figura ou ilustração descrita pelo resto dos dados do elemento {{ HTMLElement("figure") }} que seu elemento pai.</p> + +<h3 id="Contexto_de_Uso">Contexto de Uso</h3> + +<table class="standard-table"> + <tbody> + <tr> + <td>Conteúdo permitido</td> + <td><a href="/en/HTML/Content_categories#flow_content" title="en/HTML/Content categories#flow content">Flow content</a></td> + </tr> + <tr> + <td>Omissão de Tag</td> + <td> + <p>Nenhum, tanto a tag de início e fim são obrigatórias</p> + </td> + </tr> + <tr> + <td>Elemento Pai Permitido</td> + <td>Um Elemento {{ HTMLElement("figure") }}</td> + </tr> + <tr> + <td>Documento Normativo</td> + <td><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/grouping-content.html#the-figcaption-element" rel="external nofollow" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/grouping-content.html#the-figcaption-element">HTML5, section 4.5.12</a></td> + </tr> + </tbody> +</table> + +<h3 id="Atributos">Atributos</h3> + +<p>Esse elemento não tem nenhum outro atributo além dos <a href="/en/HTML/Global_attributes" rel="internal">atributos globais</a>, comum a todos os elementos.</p> + +<h3 class="editable" id="Interface_DOM">Interface DOM</h3> + +<p>Esse elemento implementa a interface <code><a href="/en/DOM/element" title="en/DOM/element">HTMLElement</a></code>.</p> + +<h3 id="Examples">Examples</h3> + +<p>Favor consulte o página {{ HTMLElement("figure") }} para exemplos de <figcaption>.</p> + +<h3 id="Compatibilidade">Compatibilidade</h3> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>8</td> + <td>{{ CompatGeckoDesktop("2.0") }}</td> + <td>9.0</td> + <td>11.10</td> + <td>5.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>3.0</td> + <td>{{ CompatGeckoMobile("2.0") }}</td> + <td>9.0</td> + <td>11.0</td> + <td>5.1 (iOS 5.0)</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Ver_Também">Ver Também</h3> + +<ul> + <li>O elemento {{ HTMLElement("figure") }}.</li> +</ul> diff --git a/files/pt-pt/web/html/elemento/head/index.html b/files/pt-pt/web/html/elemento/head/index.html new file mode 100644 index 0000000000..8285b2f2af --- /dev/null +++ b/files/pt-pt/web/html/elemento/head/index.html @@ -0,0 +1,108 @@ +--- +title: '<head> : O elemento dos metadados (Cabeçalho) do documento' +slug: Web/HTML/Elemento/head +tags: + - Elemento + - HTML + - 'HTML:Metadata content' + - Referencia + - Web +translation_of: Web/HTML/Element/head +--- +<div>{{HTMLRef}}</div> + +<p>O <strong>elemento</strong> <strong><code><head></code> </strong>de <strong>HTML </strong>fornece a informação geral (metadados) sobre o documento, incluindo o seu título e hiperligações para as suas folhas de estilo e <em>scripts</em>.</p> + +<table class="properties"> + <tbody> + <tr> + <th><a href="/en-US/docs/Web/HTML/Content_categories">Categorias de conteúdo</a></th> + <td>None.</td> + </tr> + <tr> + <th>Permitted content</th> + <td>If the document is an {{HTMLElement("iframe")}} {{htmlattrxref("srcdoc", "iframe")}} document, or if title information is available from a higher level protocol, zero or more elements of metadata content.<br> + Otherwise, one or more elements of metadata content where exactly one is a {{HTMLElement("title")}} element.</td> + </tr> + <tr> + <th>Tag omission</th> + <td>The start tag may be omitted if the first thing inside the head element is an element.<br> + The end tag may be omitted if the first thing following the head element is not a space character or a comment.</td> + </tr> + <tr> + <th>Permitted parents</th> + <td>An {{HTMLElement("html")}} element, as its first child.</td> + </tr> + <tr> + <th>Permitted ARIA roles</th> + <td>None</td> + </tr> + <tr> + <th>DOM interface</th> + <td>{{domxref("HTMLHeadElement")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Atributos">Atributos</h2> + +<p>Este elemento inclui os <a href="/pt-PT/docs/Web/HTML/Atributos_globais">atributos globais</a>.</p> + +<dl> + <dt>{{htmlattrdef("profile")}} {{obsolete_inline}}</dt> + <dd>Os <em>URIs </em>de um ou mais perfis de metadados, separados por um espaço em branco.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: html"><html> + <head> + <title>Document title</title> + </head> +</html> +</pre> + +<h2 id="Notas">Notas</h2> + +<p>Modern, HTML5-compliant browsers automatically construct a <code><head></code> element if the tags are omitted in the markup. <a class="external" href="https://www.stevesouders.com/blog/2010/05/12/autohead-my-first-browserscope-user-test/">This behavior cannot be guaranteed in ancient browsers</a>.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'semantics.html#the-head-element', '<head>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change from latest shapshot</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'document-metadata.html#the-head-element', '<head>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Obsoleted <code>profile</code></td> + </tr> + <tr> + <td>{{SpecName('HTML4.01', 'struct/global.html#h-7.4.1', '<head>')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("html.elements.head")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>Elements that can be used inside a <code><head></code> element: {{HTMLElement("title")}}, {{HTMLElement("base")}}, {{HTMLElement("link")}}, {{HTMLElement("style")}}, {{HTMLElement("meta")}}, {{HTMLElement("script")}}, {{HTMLElement("noscript")}}, {{HTMLElement("template")}}</li> +</ul> diff --git a/files/pt-pt/web/html/elemento/index.html b/files/pt-pt/web/html/elemento/index.html new file mode 100644 index 0000000000..c47907bce9 --- /dev/null +++ b/files/pt-pt/web/html/elemento/index.html @@ -0,0 +1,107 @@ +--- +title: Referência dos elementos HTML +slug: Web/HTML/Elemento +tags: + - Elemento + - HTML + - 'I10n:priority' + - Referencia + - Web + - básico +translation_of: Web/HTML/Element +--- +<div>{{HTMLSidebar("Elements")}}</div> + +<p><span class="seoSummary">Esta página lista todos os {{Glossary("HTML")}} {{Glossary("Element","elementos")}}.</span> Eles são agrupados por função para ajudá-lo a encontrar facilmente o que tem em mente. Uma lista alfabética de todos os elementos é fornecida na barra lateral na página de cada elemento, bem como nesta.</p> + +<div class="note"> +<p>Para mais informação sobre os conceitos básicos dos elementos e atributos HTML, consulte a <a href="/pt-PT/docs/Learn/HTML/Introducao_ao_HTML">secção sobre elementos no artigo de Introdução ao HTML</a>.</p> +</div> + +<h2 id="Raiz_principal">Raiz principal</h2> + +<p>{{HTMLRefTable("HTML Root Element")}}</p> + +<h2 id="Metadados_do_documento">Metadados do documento</h2> + +<p>Os metadados contêm informação acerca da página. Incluem informação sobre estilos, <em>scripts</em> e dados que ajudam a usar o software ({{Glossary("search engine", "motor de busca")}}, {{Glossary("Browser","Browsers")}}, etc.) e a interpretar a página. Os metadados para estilos e <em>scripts</em> devem ser definidos na página ou num link para um ficheiro que contém a informação.</p> + +<p>{{HTMLRefTable("HTML Document Metadata")}}</p> + +<h2 id="Secção_de_raiz">Secção de raiz</h2> + +<p>{{HTMLRefTable("Sectioning Root Element")}}</p> + +<h2 id="Segmentação_de_conteúdo">Segmentação de conteúdo</h2> + +<p>Os elementos de segmentação de conteúdo permitem-lhe organizar o documento em partes lógicas. Use os elementos de segmentação para criar um esquema vasto dos conteúdos da sua página, incluindo a navegação de cabeçalho e rodapé, e elementos de título para identificar secções de conteúdo.</p> + +<p>{{HTMLRefTable("HTML Sections")}}</p> + +<h2 id="Conteúdo_textual">Conteúdo textual</h2> + +<p>Use elementos textuais HTML para organizar blocos ou secções de conteúdo situados entre os elementos <code></body></code> de início {{HTMLElement("body")}} e fim. Sendo importantes para {{Glossary("accessibility")}} e {{Glossary("SEO")}}, estes elementos identificam o propósito ou estrutura desse conteúdo.</p> + +<p>{{HTMLRefTable("HTML Grouping Content")}}</p> + +<h2 id="Semântica_de_texto_em_linha">Semântica de texto em linha</h2> + +<p>Use a semântica de texto em linha do HTML para definir o significado, estrutura ou estilo de uma palavra, linha ou texto arbitrário.</p> + +<p>{{HTMLRefTable("HTML Text-Level Semantics")}}</p> + +<h2 id="Imagem_e_multimédia">Imagem e multimédia</h2> + +<p>O HTML suporta vários recursos multimédia como imagens, áudio e vídeo.</p> + +<p>{{HTMLRefTable("multimedia")}}</p> + +<h2 id="Conteúdo_incorporado">Conteúdo incorporado</h2> + +<p>Além do conteúdo multimédia regular, o HTML poderá incluir diversos outros conteúdos, ainda que a interação com este nem sempre seja fácil.</p> + +<p>{{HTMLRefTable({"include":["HTML embedded content"], "exclude":["multimedia"]})}}</p> + +<h2 id="Scripting"><em>Scripting</em></h2> + +<p>De modo a criar conteúdos dinâmicos e aplicações Web, o HTML suporta o uso de linguages de <em>script</em>, nomeadamente JavaScript. Certos elementos suportam esta capacidade.</p> + +<p>{{HTMLRefTable("HTML Scripting")}}</p> + +<h2 id="Edições_de_demarcação">Edições de demarcação</h2> + +<p>Estes elementos permitem-lhe dar indicações sobre que partes do texto específicas foram alteradas.</p> + +<p>{{HTMLRefTable("HTML Edits")}}</p> + +<h2 id="Conteúdo_de_tabela">Conteúdo de tabela</h2> + +<p>Estes elementos são usados para criar e manipular dados tabulares.</p> + +<p>{{HTMLRefTable("HTML tabular data")}}</p> + +<h2 id="Formulários">Formulários</h2> + +<p>O HTML fornece um número de elementos que podem ser usados em conjunto para criar formulários que o utilizador poderá preencher e submeter na página web ou aplicação. Existe uma considerável quantidade de informação sobre o mesmo disponível na página <a href="/en-US/docs/Web/Guide/HTML/Forms">HTML forms guide</a>.</p> + +<p>{{HTMLRefTable({"include": ["HTML forms"], "exclude":["Deprecated"]})}}</p> + +<h2 id="Elementos_interativos">Elementos interativos</h2> + +<p>O HTML oferece uma selecção de elementos que ajudam a criar objectos interativos de interface com o utilizador.</p> + +<p>{{HTMLRefTable("elementos interativos HTML")}}</p> + +<h2 id="Componentes_da_Web">Componentes da Web</h2> + +<p>Os Componentes Web são uma tecnologia relacionada com o HTML que possibilitam a criação e utilização de elementos personalizados como se se tratassem de elementos HTML vulgares. Adicionalmente, poderá criar versões personalizadas de elementos HTML standard.</p> + +<p>{{HTMLRefTable({"include":["Web Components"],"exclude":["Deprecated", "Obsolete"]})}}</p> + +<h2 id="Elementos_obsoletos_e_desaprovados">Elementos obsoletos e desaprovados</h2> + +<div class="warning"> +<p><strong>Aviso:</strong> Estes são elementos HTML antigos que foram desaprovados e não devem ser usados. <strong>Nunca deve usá-los em projectos novos, e deve substitui-los em antigos projectos assim que possa.</strong> Os mesmos são aqui listados apenas para informação.</p> +</div> + +<p>{{HTMLRefTable({"include":["Deprecated","Obsolete"]})}}</p> diff --git a/files/pt-pt/web/html/elemento/nav/index.html b/files/pt-pt/web/html/elemento/nav/index.html new file mode 100644 index 0000000000..3dfc714e23 --- /dev/null +++ b/files/pt-pt/web/html/elemento/nav/index.html @@ -0,0 +1,99 @@ +--- +title: <nav> +slug: Web/HTML/Elemento/nav +translation_of: Web/HTML/Element/nav +--- +<div>{{HTMLRef}}</div> + +<p><span class="seoSummary">O elemento de <strong>HTML <code><nav></code> </strong>representa a seção de uma página cujo propósito é providenciar links de navegação, tanto dentro do documento em questão como para outros documentos. Exemplos comuns de seções de navegação são menus, tabelas de conteúdo e indíces.</span></p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Categorias de conteúdo</th> + <td><a href="/en-US/docs/HTML/Content_categories#Flow_content">Flow content</a>, conteúdo de seccionamento, conteúdo palpável.</td> + </tr> + <tr> + <th scope="row">Conteúdo permitido</th> + <td><a href="/en-US/docs/HTML/Content_categories#Flow_content">Flow content</a>.</td> + </tr> + <tr> + <th scope="row">Omissão de tag</th> + <td>{{no_tag_omission}}</td> + </tr> + <tr> + <th scope="row">Pais permitidos</th> + <td>Qualquer elemento que permita <a href="/en-US/docs/HTML/Content_categories#Flow_content">flow content</a>.</td> + </tr> + <tr> + <th scope="row">Papeis ARIA permitidos</th> + <td>Nenhuns</td> + </tr> + <tr> + <th scope="row">interface DOM</th> + <td>{{domxref("HTMLElement")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Atributos">Atributos</h2> + +<p>Este elemento apenas inclui <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes">atributos globais</a>.</p> + +<h2 id="Notas_de_utilização">Notas de utilização</h2> + +<ul> + <li>Nem todos os links num documento devem estar contidos num elemento <code><nav></code>, que é direcionado apenas para blocos de hiper-ligações de navegação principal; tipicamente o elemento {{HTMLElement("footer")}} tem uma lista de hiper-ligações que não necessitam de estar contidos no elemento {{HTMLElement("nav")}}.</li> + <li>Um documento poderá ter vários elementos {{HTMLElement("nav")}}, por exemplo, um para navegação na página e outro para navegação exterior da mesma.</li> + <li>User agents, tais como leitores de ecrã direcionados para utilizadores com limitações, podem utilizar este elemento para determinar a omissão ou não da renderização inicial deste conteúdo.</li> +</ul> + +<h2 id="Exemplos">Exemplos</h2> + +<p>No exemplo seguinte, um bloco <code><nav></code> é usado para conter uma lista não ordenada ({{HTMLElement("ul")}}) de hiper-ligações. Com o CSS apropriado, a lista pode ser apresentada como uma barra de navegação ou menu "drop-down.</p> + +<pre class="brush: html"><nav class="menu"> + <ul> + <li><a href="#">Home</a></li> + <li><a href="#">Sobre</a></li> + <li><a href="#">Contactos</a></li> + </ul> +</nav> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('HTML WHATWG', 'sections.html#the-nav-element', '<nav>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Sem alterações desde o ultimo snapshot da W3C.</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'sections.html#the-nav-element', '<nav>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibidade_de_Navegadores">Compatibidade de Navegadores</h2> + +<div class="hidden">A tabela de compatibilidades nesta página é gerada através de dados estruturados.Se gostaria de contribuir para esta coleta de dados por favor dirija-se a<a href="https://github.com/mdn/browser-compat-data"> https://github.com/mdn/browser-compat-data</a> e envie-nos um pull request.</div> + +<p>{{Compat("html.elements.nav")}}</p> + +<p>Ver também</p> + +<ul> + <li>Outros elementos relacionados com a secção: {{HTMLElement("body")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("aside")}}, {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}, {{HTMLElement("hgroup")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("address")}};</li> + <li class="last"><a class="deki-ns current" href="/en-US/docs/Sections_and_Outlines_of_an_HTML5_document" title="Sections and Outlines of an HTML5 document">Sections and outlines of an HTML5 document</a>.</li> +</ul> diff --git a/files/pt-pt/web/html/elemento/progress/index.html b/files/pt-pt/web/html/elemento/progress/index.html new file mode 100644 index 0000000000..0b99ea2873 --- /dev/null +++ b/files/pt-pt/web/html/elemento/progress/index.html @@ -0,0 +1,128 @@ +--- +title: progress +slug: Web/HTML/Elemento/progress +translation_of: Web/HTML/Element/progress +--- +<h2 id="Resumo">Resumo</h2> + +<p>O HTML <em>progress</em> (<code><progress></code>) é o elemento usado para mostrar o progresso de uma tarefa. Enquanto os detalhes específicos de como ele é exibido é deixado para o desenvolvedor web, é tipicamente exibido como uma barra de progresso.</p> + +<h2 id="Contexto_de_uso">Contexto de uso</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td>Conteúdo permitido</td> + <td><a href="/en/HTML/Content_categories#Phrasing_content" title="en/HTML/Content categories#Phrasing content">Phrasing content</a></td> + </tr> + <tr> + <td>Tag omission</td> + <td>None, both, o inicio da tag e o final da tag são obrigatórios.</td> + </tr> + <tr> + <td>Elemento pai permitido</td> + <td><a href="/en/HTML/Content_categories#Phrasing_content" title="en/HTML/Content categories#Phrasing content">Phrasing content</a>, mas não deve haver descedentes no elemento progress .</td> + </tr> + <tr> + <td>Documento normativo</td> + <td><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html#the-progress-element" rel="external nofollow" title="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html#the-progress-element">HTML5, section 4.10.16</a></td> + </tr> + </tbody> +</table> + +<h2 id="Atributos">Atributos</h2> + +<p>Como todos os outros elementos HTML, este elemento possui os <a href="/en/HTML/Global_attributes" rel="internal">atributos globais</a>.</p> + +<dl> + <dt>{{ htmlattrdef("form") }}</dt> + <dd>This attribute specifies the form which the <code>progress</code> element belongs to.</dd> + <dt>{{ htmlattrdef("max") }}</dt> + <dd>This attribute describes how much work the task indicated by the <code>progress</code> element requires.</dd> + <dt>{{ htmlattrdef("value") }}</dt> + <dd>This attribute specifies how much of the task that has been completed. If there is no <code>value</code> attribute, the progress bar is indeterminate; this indicates that an activity is ongoing with no indication of how long it is expected to take.</dd> +</dl> + +<p>You can use the {{ cssxref("orient") }} property to specify whether the progress bar should be rendered horizontally (the default) or vertically. The {{ cssxref(":indeterminate") }} pseudo-class can be used to match against indeterminate progress bars.</p> + +<h2 id="DOM_interface">DOM interface</h2> + +<p>Este elemento implementa a interface <code><a href="/en/DOM/HTMLProgressElement" title="en/DOM/HTMLProgressElement">HTMLProgressElement</a></code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="script"><progress value="70" max="100">70 %</progress> +</pre> + +<h3 id="Resultado">Resultado</h3> + +<p><a href="/samples/html/progress.html">View Live Examples</a></p> + +<p>No Google Chrome, o resultado do progress parece deste modo:</p> + +<p><img alt="progress-1.png" class="default internal" src="/@api/deki/files/4946/=progress-1.png"></p> + +<h3 id="Exemplos_Adicionais">Exemplos Adicionais</h3> + +<p>Veja {{ cssxref("orient") }}.</p> + +<h2 id="Compatibilidade_dos_Browsers">Compatibilidade dos Browsers</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Características</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>6.0</td> + <td>{{ CompatGeckoDesktop("6.0") }}</td> + <td>No</td> + <td>11</td> + <td>nightlies</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Características</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + <td>{{ CompatUnknown() }}</td> + </tr> + </tbody> +</table> +</div> + +<h3 id="Gecko_notes">Gecko notes</h3> + +<p>Gecko provides the {{ cssxref("::-moz-progress-bar") }} pseudo-element, which lets you style the part of the interior of the progress bar representing the amount of work completed so far.</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{ cssxref("orient") }}</li> + <li>{{ cssxref(":indeterminate") }}</li> +</ul> diff --git a/files/pt-pt/web/html/elemento/video/index.html b/files/pt-pt/web/html/elemento/video/index.html new file mode 100644 index 0000000000..4870c14e23 --- /dev/null +++ b/files/pt-pt/web/html/elemento/video/index.html @@ -0,0 +1,69 @@ +--- +title: Video +slug: Web/HTML/Elemento/Video +translation_of: Web/HTML/Element/video +--- +<p>{{ gecko_minversion_header("1.9.1") }}</p> +<p>O elemento <code>video</code> é usado para inserir conteúdo de vídeo em um documento HTML ou XHTML. O elemento <code>video</code> foi adicionado como parte do HTML 5.</p> +<ul> + <li>Tipo de Elemento: <a class="internal" href="/en/HTML/Block-level_elements" title="en/HTML/Block-level elements">block-level</a></li> + <li>Conteúdo Permitido: alternate text</li> +</ul> +<div class="note"> + <strong>Nota:</strong> Atualmente, o Firefox suporta apenas Theora para vídeo, em recipientes Ogg. Além disso, o servidor precisa servir o arquivo utilizando o <em>MIME type</em> correto para que o Firefox o reproduza corretamente.</div> +<h2 id="Atributos">Atributos</h2> +<p>Note que diversos atributos ainda não são suportados pelo Firefox.</p> +<dl> + <dt> + autoplay</dt> + <dd> + Um atributo booleano; se especificado, o vídeo iniciará a reprodução automaticamente assim que puder, portanto, sem para para finalizar o carregamento dos dados.</dd> + <dt> + autobuffer</dt> + <dd> + Um atributo booleano; se especificado, o vídeo iniciará a leitura dos dados (<em>buffering</em>) mesmo se não estiver configurado para reproduzir automaticamente. Isto deve ser usado para casos em que provavelmente o vídeo será reproduzido (por exemplo, se o usuário navegou para a página exclusivamente para reproduzir o vídeo, não se o vídeo foi inserido junto a outro conteúdo). O vídeo é lido (<em>buffered</em>) até que o <em>cache</em> de mídia esteja cheio.</dd> + <dt> + controls</dt> + <dd> + Se este atributo estiver presente, Firefox oferecerá controles para permitir que o usuário controle a reprodução do vídeo, incluindo volume, procura, e pausa/continuar.</dd> + <dt> + height</dt> + <dd> + A altura da área de exibição do vídeo, em pixels CSS.</dd> + <dt> + loop {{ unimplemented_inline() }} {{ bug(449157) }}</dt> + <dd> + Um atributo booleano; se especificado, ao alcançar o fim do vídeo, voltará ao início automaticamente.</dd> + <dt> + poster {{ unimplemented_inline() }} {{ bug(449156) }}</dt> + <dd> + Uma URL indicando um quadro pôster para se exibir enquanto não houver dados do vídeo disponíveis. Se este atributo não for especificado, nada é exibido até o vídeo estar disponível para reprodução.</dd> + <dt> + src</dt> + <dd> + A URL do vídeo a ser embutido. Este atributo é opcional; em vez disso você pode usar o elemento <a class="internal" href="/En/HTML/Element/Source" title="En/HTML/Element/Source"><code>source</code></a> (en) dentro do bloco video para especificar o vídeo a embutir.</dd> + <dt> + width</dt> + <dd> + A largura da área de exibição do vídeo, em pixels CSS.</dd> +</dl> +<p>O deslocamento de tempo é especificado como um valor de ponto flutuante indicando o número de segundos do deslocamento.</p> +<div class="note"> + <strong>Nota:</strong> A definição do valor de deslocamento de tempo ainda não está completa na especificação do HTML 5 e está sujeita a mudanças.</div> +<h2 id="Exemplos">Exemplos</h2> +<pre class="brush: html"><video src="videofile.ogg" autoplay> + Seu navegador não suporta o elemento <code>video</code>. +</video> +</pre> +<p>Reproduz um vídeo, inicia a reprodução assim que tenha recebido o bastante do vídeo para permitir a reprodução sem pausas para baixar mais.</p> +<h2 id="Veja_também">Veja também</h2> +<ul> + <li><a class="internal" href="/En/Media_formats_supported_by_the_audio_and_video_elements" title="En/Media formats supported by the audio and video elements">Media formats supported by the audio and video elements</a> (EN)</li> + <li><a class="internal" href="/Pt/HTML/Element/Audio" title="Pt/HTML/Element/Audio"><code>audio</code></a></li> + <li><a class="internal" href="/Pt/Usando_%C3%A1udio_e_v%C3%ADdeo_no_Firefox" title="Pt/Usando áudio e vídeo no Firefox">Usando áudio e vídeo no Firefox</a></li> + <li><a class="internal" href="/En/Manipulating_video_using_canvas" title="En/Manipulating video using canvas">Manipulating video using canvas</a> (EN)</li> + <li><code>{{ interface("nsIDOMHTMLMediaElement") }}</code></li> + <li><a class="external" href="http://tinyvid.tv/" title="http://tinyvid.tv/">TinyVid</a> - exemplos utilizando arquivos ogg no HTML 5. (EN)</li> + <li><a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/#video" title="http://www.whatwg.org/specs/web-apps/current-work/#video">The <code>video</code> element</a> (HTML 5 specification)</li> +</ul> +<p>{{ languages( { "fr": "fr/HTML/Element/video" } ) }}</p> diff --git a/files/pt-pt/web/html/html5/forms_no_html5/index.html b/files/pt-pt/web/html/html5/forms_no_html5/index.html new file mode 100644 index 0000000000..93a5bfb4f8 --- /dev/null +++ b/files/pt-pt/web/html/html5/forms_no_html5/index.html @@ -0,0 +1,72 @@ +--- +title: Forms no HTML5 +slug: Web/HTML/HTML5/Forms_no_HTML5 +translation_of: Learn/HTML/Forms/HTML5_updates +--- +<p>{{ gecko_minversion_header("2") }}</p> +<p>Elementos e atributos de formulários no HTML5 fornecem um grau maior de marcação semântica do que o HTML4 e removem em grande parte a necessidade tediosa de estilos e scripts requerida no HTML4. Os recursos de formulários no HTML5 fornecem uma melhor experiência para os usuários, tornando os formulários mais consistentes através de diferentes web sites e dando retorno imediato ao usuário sobre a entrada de dados. Eles também fornecem esta experiência aos usuários que deixam os scripts desativados no navegador.</p> +<p>Este tópico descreve itens novos ou alterados que são suportados pelo Gecko/Firefox.</p> +<h3 id="O_elemento_<input>">O elemento <code><input></code></h3> +<p>O elemento <code>{{ HTMLElement("input") }}</code> tem novos valores para o atributo {{ htmlattrxref("type", "input") }}.</p> +<ul> + <li><span style="font-family: Courier New;">search</span>: O elemento representa um campo de entrada de busca. Quebras de linhas são automaticamente removidas do valor de entrada, mas nenhuma outra sintaxe é aplicada.</li> + <li><span style="font-family: Courier New;">tel</span>: O elemento representa um controle para a edição de um número de telefone. Quebras de linhas são automaticamente removidas do valor de entrada, mas nenhuma outra sintaxe é aplicada, pois números de telefone podem variar bastante internacionalmente. Você pode usar atributos como {{ htmlattrxref("pattern", "input") }} e {{ htmlattrxref("maxlength", "input") }} para restringir valores digitados no controle.</li> + <li><span style="font-family: Courier New;">url</span>: O elemento representa um controle para a edição de <a class="external" href="http://en.wikipedia.org/URL" title="http://en.wikipedia.org/URL">URL</a>. Quebras de linha e espaços, à direita e à esquerda, são automaticamente removidos do valor de entrada.</li> + <li> + <p><span style="font-family: Courier New;">email</span>: O elemento representa um endereço de e-mail. Quebras de linhas são automaticamente removidas do valor de entrada. Um endereço de e-mail inválido pode ser configurado, mas o campo de entrada somente será satisfeito se contiver um endereço de e-mail que satisfaça a produção ABNF <span style="font-family: Courier New;"><code><code title="">1*( atext / "." ) "@" ldh-str 1*( "." ldh-str )</code></code></span> na qual <code title="">atext</code> está definido na RFC 5322 section 3.2.3, e <code title="">ldh-str</code> está definido na RFC 1034 section 3.5.</p> + <div class="note"> + Nota: se o atributo {{ htmlattrxref("multiple", "input") }} é configurado, podem ser digitados múltiplos endereços de e-mail neste campo {{ HTMLElement("input") }}, como uma lista separada por espaços, mas atualmente isto não está implementado no Firefox.</div> + </li> +</ul> +<p>O elemento {{ HTMLElement("input") }} também tem novos atributos:</p> +<ul> + <li>{{ htmlattrxref("list", "input") }}: O ID de um elemento {{ HTMLElement("datalist") }} cujos conteúdos, elementos {{ HTMLElement("option") }}, podem ser usados como dicas e são exibidos como propostas na área de sugestões do campo de entrada.</li> + <li>{{ htmlattrxref("pattern", "input") }}: Uma expressão regular contra a qual o valor do elemento é checado, a qual deve ser usada com os valores <code>text</code>, <code>tel</code>, <code>search</code>, <code>url</code>, e <code>email </code>de {{ htmlattrxref("type", "input") }}.</li> + <li>{{ htmlattrxref("formmethod", "input") }}: Uma string indicando qual método HTTP (GET ou POST) deve ser usado na submissão; isto substitui o {{ htmlattrxref("method", "form") }} do elemento {{ HTMLElement("form") }}, se definido. O {{ htmlattrxref("formmethod", "input") }} se aplica somente quando {{ htmlattrxref("type", "input") }} é <span style="font-family: Courier New;">image</span> ou <span style="font-family: Courier New;">submit</span>.</li> + <li>{{ htmlattrxref("x-moz-errormessage", "input") }}: Uma string que é exibida como uma mensagem de erro quando a validação do campo falha. Esta é uma extenção da Mozilla, e não é um padrão.</li> +</ul> +<h3 id="O_elemento_<form>">O elemento <code><form></code></h3> +<p>O elemento {{ HTMLElement("form") }} tem um novo atributo:</p> +<ul> + <li>{{ htmlattrxref("novalidate", "form") }}: Este atributo previne o formulário de ser validado antes de sua submissão.</li> +</ul> +<h3 id="O_elemento_<datalist>">O elemento <code><datalist></code></h3> +<p>O elemento {{ HTMLElement("datalist") }} representa a lista de elementos {{ HTMLElement("option") }} para sugerir quando preencher um campo {{ HTMLElement("input") }}.</p> +<p>Você pode usar o atributo {{ htmlattrxref("list", "input") }} em um elemento {{ HTMLElement("input") }} para ligar um campo de entrada com um elemento {{ HTMLElement("datalist") }} específico.</p> +<h3 id="O_elemento_<output>">O elemento <code><output></code></h3> +<p>O elemento <code>{{ HTMLElement("output") }}</code> representa o resultado de um cálculo.</p> +<p>Você pode usar o atributo {{ htmlattrxref("for", "output") }} para especificar uma relação entre o elemento de saída e outros elementos no documento, afetados pelo resultado (por exemplo, como entradas ou parâmetros). O valor do atributo {{ htmlattrxref("for", "output") }} é uma lista de ID de outros elementos separada por espaços.</p> +<h3 id="O_atributo_de_espaço_reservado">O atributo de espaço reservado</h3> +<p>O atributo {{ htmlattrxref("placeholder", "input") }} nos elementos <code>{{ HTMLElement("input") }}</code> e <code>{{ HTMLElement("textarea") }}</code> fornece uma dica ao usuário do que deve ser digitado no campo. O espaço reservado de texto não deve conter novas linhas ou alimentação de linhas.</p> +<h3 id="O_atributo_de_autofoco">O atributo de autofoco</h3> +<p>O atributo <strong>autofocus</strong> permite especificar que um controle de formulário deve ter foco nas entradas quando a página carrega, a menos que o usuário sobreponha-se a isto, por exemplo digitando em um controle diferente. Somente um item do formulário pode ter o atributo <strong>autofocus</strong>, que é um Booleano. Este atributo pode ser aplicado aos elementos<code> {{ HTMLElement("input") }}</code>, <code>{{ HTMLElement("button") }}</code>, <code>{{ HTMLElement("select") }}</code>, e <code>{{ HTMLElement("textarea") }}</code>. A exceção é que o <strong>autofocus</strong> não pode ser aplicado em um elemento <code><input></code> se o atributo {{ htmlattrxref("type", "input") }} é configurado como <code>hidden</code> (isto é, você não pode configurar automaticamente o foco em um controle escondido).</p> +<h3 id="A_propriedade_label.control_do_DOM">A propriedade label.control do DOM</h3> +<p>A interface DOM <a href="/en/DOM/HTMLLabelElement" title="en/DOM/HTMLLabelElement">HTMLLabelElement</a> fornece uma propriedade extra, adicionalmente às propriedades que correspondem aos atributos do elemento <code>{{ HTMLElement("label") }}</code> do HTML. A propriedade <strong>control</strong> retorna um controle rotulado, isto é, o controle para este rótulo, o qual é determinado pelo atributo {{ htmlattrxref("for", "label") }} (se estiver definido) ou pelo primeiro elemento de controle descendente.</p> +<h3 id="Validação_de_restrições">Validação de restrições</h3> +<p>O HTML5 fornece itens de API e sintaxe para suportar a validação de formulários do lado do cliente. Enquanto esta funcionalidade não substitui a validação do lado do servidor, a qual ainda é necessária para a segurança e integridade dos dados, a validação do lado do cliente pode suportar uma melhor experiência ao usuário, dando ao usuário um retorno imediato sobre os dados digitados.</p> +<h4 id="Sintaxe_HTML_para_validação_de_restrições">Sintaxe HTML para validação de restrições</h4> +<p>Os seguintes itens da sintaxe do HTML5 podem ser usados para especificar restrições em dados de formulários.</p> +<ul> + <li>O atributo {{ htmlattrxref("required", "input") }} no elementos {{ HTMLElement("input") }}, {{ HTMLElement("select") }} e {{ HTMLElement("textarea") }} indica que um valor deve ser fornecido. (No elemento {{ HTMLElement("input") }}, {{ htmlattrxref("required", "input") }} aplica-se somente em conjunto com certos valores do atributo {{ htmlattrxref("type", "input") }}.)</li> + <li>O atributo {{ htmlattrxref("pattern", "input") }} no elemento {{ HTMLElement("input") }} obriga o valor a combinar com uma expressão regular específica.</li> + <li>Os atributos {{ htmlattrxref("min", "input") }} e {{ htmlattrxref("max", "input") }} do elemento {{ HTMLElement("input") }} limitam os valores mínimo e máximo que podem ser digitados.</li> + <li>O atributo {{ htmlattrxref("step", "input") }} do elemento {{ HTMLElement("input") }} (quando usado combinadamente com os atributos {{ htmlattrxref("min", "input") }} e {{ htmlattrxref("max", "input") }}) define a granularidade de valores que podem ser entrados. Um valor que não corresponda a um valor permitido não será validado.</li> + <li>O atributo {{ htmlattrxref("maxlength", "input") }} dos elementos {{ HTMLElement("input") }} e {{ HTMLElement("textarea") }} limita o número máximo de caracteres (em pontos de código Unicode) que o usuário pode entrar.</li> + <li>Os valores <code>url</code> e <code>email</code> para {{ htmlattrxref("type", "input") }} obrigam o valor a ser uma URL ou um endereço de e-mail válido, respectivamente.</li> +</ul> +<p>Adicionalmente, pode-se evitar a validação obrigatória especificando-se o atributo {{ htmlattrxref("novalidate", "form") }} no elemento {{ HTMLElement("form") }}, ou o atributo {{ htmlattrxref("formnovalidate", "button") }} no elemento {{ HTMLElement("button") }} e no elemento {{ HTMLElement("input") }} (quando {{ htmlattrxref("type", "input") }} é <code>submit</code> ou <code>image</code>). Estes atributos indicam que o formulário não será validado quando submetido.</p> +<h4 id="API_de_validação_de_restrições">API de validação de restrições</h4> +<p>As seguintes propriedades e métodos do DOM relacionados à validação de restrições estão disponíveis nos scripts do lado do cliente:</p> +<ul> + <li>Em objetos <a href="/en/DOM/HTMLFormElement" title="en/DOM/HTMLFormElement">HTMLFormElement</a>, o método <code>checkValidity()</code> retorna verdadeiro se todos os elementos do formulário com elementos associados com validação obrigatória são satisfeitos, e falso, caso contrário.</li> + <li>Em <a href="/en/HTML/Content_categories#form-associated" title="en/HTML/Content Categories#form-associated">elementos associados a formulários</a> (en): + <ul> + <li>A propriedade <code>willValidate</code>, a qual é falsa se o elemento possuir obrigatoriedades não satisfeitas.</li> + <li>A propriedade <code>validity</code>, a qual é um objeto de <a href="/en/DOM/ValidityState_Interface" title="en/DOM/ValidityState Interface">ValidityState</a>, que representa o estado de validação em que o elemento se encontra (isto é, falha ou sucesso nas condições obrigatórias).</li> + <li>A propriedade <code>validationMessage</code>, a qual é uma mensagem descrevendo qualquer valha de obrigatoriedade pertinente ao elemento.</li> + <li>O método <code>checkValidity()</code>, o qual retorna falso se o elemento falha em satisfazer qualquer das suas obrigatoriedades, ou verdadeiro, caso contrário.</li> + <li>O método <code>setCustomValidity()</code>, o qual define uma mensagem customizada de validação, permitindo às obrigações serem impostas e validadas além das já pré-definidas.</li> + </ul> + </li> +</ul> +<p>{{ HTML5ArticleTOC() }}</p> diff --git a/files/pt-pt/web/html/html5/index.html b/files/pt-pt/web/html/html5/index.html new file mode 100644 index 0000000000..87e542c8c8 --- /dev/null +++ b/files/pt-pt/web/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 +--- +<p class="summary">HTML5 é a última evolução no padrão que define o <a href="/pt-PT/docs/Web/HTML_Linguagem_de_marcacao_de_hipertexto" title="HTML">HTML</a>. O termo representa dois conceitos diferentes. Esta é uma nova versão da linguagem HTML, com novos elementos, atributos e comportamentos, <strong>e</strong> 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.</p> + +<p>Desenhado para ser utilizado por todos os programadores da <strong>Web Aberta</strong>, 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.</p> + +<ul> + <li><em>Semântica</em>: <span id="result_box" lang="pt"><span>permitindo que descreva mais precisamente o que é o seu conteúdo.</span></span></li> + <li><em>Conetividade</em>: permitindo que <span id="result_box" lang="pt"><span> comunique com o servidor de maneiras novas e inovadoras.</span></span></li> + <li><em>Off-line e armazenamento</em>: permitindo webpages <span id="result_box" lang="pt"><span> armazenem dados localmente </span></span><span lang="pt"><span>no client-side (lado do cliente) e operem offline de forma mais eficiente.</span></span></li> + <li><em>Multimédia</em>: <span id="result_box" lang="pt"><span>tornando o vídeo e áudio de primeira classe cidadãos na Open Web.</span></span></li> + <li><em>Gráficos e efeitos 2D/3D</em>: <span id="result_box" lang="pt"><span>permitindo uma gama muito mais diversificada de opções de apresentação.</span></span></li> + <li><em>Desempenho e integração</em>: <span id="result_box" lang="pt"><span>proporcionando maior otimização de velocidade e melhor uso do hardware do computador.</span></span></li> + <li><em>Acesso ao dispositivo</em>: <span id="result_box" lang="pt"><span>permitindo o uso de vários dispositivos de entrada e saída.</span></span></li> + <li><em>Estilização</em>: <span id="result_box" lang="pt"><span>permitindo que os autores escrevam temas mais sofisticados.</span></span></li> +</ul> + +<div class="cleared row topicpage-table"> +<div class="section"> +<h2 id="SemÂntIcA" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3827/HTML5_Semantics_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">SemÂntIcA</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/Guide/HTML/Utilizar_estruturas_e_seccoes_de_HTML" title="Sections and Outlines of an HTML5 document">Sections and outlines in HTML5</a></dt> + <dd>A look at the new outlining and sectioning elements in HTML5: {{HTMLElement("section")}}, {{HTMLElement("article")}}, {{HTMLElement("nav")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}} and {{HTMLElement("aside")}}.</dd> + <dt><a href="/en-US/docs/Using_HTML5_audio_and_video" title="Using_audio_and_video_in_Firefox">Using HTML5 audio and video</a></dt> + <dd>The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.</dd> + <dt><a href="/en-US/docs/Learn/HTML/Forms">Forms improvements</a></dt> + <dd>A look at the <a href="/en-US/docs/Learn/HTML/Forms/Form_validation">constraint validation API</a>, several new attributes, new values for the {{HTMLElement("input")}} attribute {{htmlattrxref("type", "input")}} and the new {{HTMLElement("output")}} element.</dd> + <dt>New semantic elements</dt> + <dd>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 <a href="/en-US/docs/HTML/HTML5/HTML5_element_list" title="HTML/HTML5/HTML5_element_list">valid HTML5 elements</a>.</dd> + <dt>Improvement in {{HTMLElement("iframe")}}</dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/MathML" title="MathML">MathML</a></dt> + <dd>Allows directly embedding mathematical formulas.</dd> + <dt><a href="/en-US/docs/HTML/HTML5/Introduction_to_HTML5" title="HTML/HTML5/Introduction_to_HTML5">Introduction to HTML5</a></dt> + <dd>This article introduces how to indicate to the browser that you are using HTML5 in your web design or web application.</dd> + <dt><a href="https://www.wpkube.com/html5-cheat-sheet/">HTML5 Cheat Sheet</a></dt> + <dd>A handy HTML 5 cheat sheet for beginners who want to master HTML 5, its elements, event attributes and compatibility.</dd> + <dt><a href="/en-US/docs/HTML/HTML5/HTML5_Parser" title="HTML/HTML5/HTML5 parser">HTML5-compliant parser</a></dt> + <dd>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.</dd> +</dl> + +<h2 id="ConetiviDADE" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3839/HTML5_Connectivity_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">ConetiviDADE</h2> + +<dl> + <dt><a href="/en-US/docs/WebSockets" title="WebSockets">Web Sockets</a></dt> + <dd>Allows creating a permanent connection between the page and the server and to exchange non-HTML data through that means.</dd> + <dt><a href="/en-US/docs/Server-sent_events/Using_server-sent_events" title="Server-sent_events/Using_server-sent_events">Server-sent events</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/WebRTC" title="WebRTC">WebRTC</a></dt> + <dd>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.</dd> +</dl> + +<h2 id="Off-line_e_ARMAZENAMENTO" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3833/HTML5_Offline_Storage_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">Off-line e ARMAZENAMENTO</h2> + +<dl> + <dt><a href="/en-US/docs/HTML/Using_the_application_cache" title="Offline_resources_in_Firefox">Offline resources: The application cache</a></dt> + <dd>Firefox fully supports the HTML5 offline resource specification. Most others have offline resource support at some level.</dd> + <dt><a href="/en-US/docs/Online_and_offline_events" title="Online_and_offline_events">Online and offline events</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/DOM/Storage" title="DOM/Storage">WHATWG client-side session and persistent storage (aka DOM storage)</a></dt> + <dd>Client-side session and persistent storage allows web applications to store structured data on the client side.</dd> + <dt><a href="/en-US/docs/IndexedDB" title="IndexedDB">IndexedDB</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/Using_files_from_web_applications" title="Using_files_from_web_applications">Using files from web applications</a></dt> + <dd>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 <span style="font-family: monospace;">{{HTMLElement("input")}}</span> of <a href="/en-US/docs/HTML/Element/Input#attr-type" title="HTML/Element/input#attr-type"><strong>type</strong></a> <span style="font-family: courier new;">file</span> HTML element's new <a href="/en-US/docs/HTML/Element/Input#attr-multiple" title="HTML/Element/input#attr-multiple"><strong>multiple</strong></a> attribute. There also is <a href="/en-US/docs/DOM/FileReader" title="DOM/FileReader"><code>FileReader</code></a>.</dd> +</dl> + +<h2 id="MultimÉdia" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3835/HTML5_Multimedia_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">MultimÉdia</h2> + +<dl> + <dt><a href="/en-US/docs/Using_HTML5_audio_and_video" title="Using_audio_and_video_in_Firefox">Using HTML5 audio and video</a></dt> + <dd>The {{HTMLElement("audio")}} and {{HTMLElement("video")}} elements embed and allow the manipulation of new multimedia content.</dd> + <dt><a href="/en-US/docs/WebRTC" title="WebRTC">WebRTC</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/DOM/Using_the_Camera_API" title="DOM/Using_the_Camera_API">Using the Camera API</a></dt> + <dd>Allows using, manipulating, and storing an image from the computer's camera.</dd> + <dt>Track and WebVTT</dt> + <dd>The {{HTMLElement("track")}} element allows subtitles and chapters. <a href="/en-US/docs/HTML/WebVTT" title="HTML/WebVTT">WebVTT</a> is a text track format.</dd> +</dl> + +<h2 id="GRÁFICOS_E_EFEITOS_3D" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3841/HTML5_3D_Effects_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">GRÁFICOS E EFEITOS 3D</h2> + +<dl> + <dt><a href="/en-US/docs/Canvas_tutorial" title="Canvas tutorial">Canvas tutorial</a></dt> + <dd>Learn about the new <code>{{HTMLElement("canvas")}}</code> element and how to draw graphs and other objects in Firefox.</dd> + <dt><a href="/en-US/docs/Drawing_text_using_a_canvas" title="Drawing_text_using_a_canvas">HTML5 Text API for <code><canvas></code> elements</a></dt> + <dd>The HTML5 text API is now supported by {{HTMLElement("canvas")}} elements.</dd> + <dt><a href="/en-US/docs/WebGL" title="WebGL">WebGL</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/SVG" title="SVG">SVG</a></dt> + <dd>An XML-based format of vectorial images that can directly be embedded in the HTML.</dd> +</dl> +</div> + +<div class="section"> +<h2 id="DESEMPENHO_E_IntegraÇÃO" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3831/HTML5_Performance_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">DESEMPENHO E IntegraÇÃO</h2> + +<dl> + <dt><a href="/en-US/docs/DOM/Using_web_workers" title="Using web workers">Web Workers</a></dt> + <dd>Allows delegation of JavaScript evaluation to background threads, allowing these activities to prevent slowing down interactive events.</dd> + <dt><code><a href="/en-US/docs/DOM/XMLHttpRequest" title="XMLHttpRequest">XMLHttpRequest</a></code> level 2</dt> + <dd>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 <a href="/en-US/docs/AJAX" title="AJAX">Ajax</a>.</dd> + <dt>JIT-compiling JavaScript engines</dt> + <dd>The new generation of JavaScript engines is much more powerful, leading to greater performance.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history" title="DOM/Manipulating_the_browser_history">History API</a></dt> + <dd>Allows the manipulation of the browser history. This is especially useful for pages loading interactively new information.</dd> + <dt><a href="/en-US/docs/HTML/Content_Editable" title="HTML/Content Editable">The contentEditable Attribute: Transform your website to a wiki!</a></dt> + <dd>HTML5 has standardized the contentEditable attribute. Learn more about this feature.</dd> + <dt><a href="/en-US/docs/DragDrop/Drag_and_Drop" title="DragDrop/Drag_and_Drop">Drag and drop</a></dt> + <dd>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.</dd> + <dt><a href="/en-US/docs/Focus_management_in_HTML" title="Focus_management_in_HTML">Focus management in HTML</a></dt> + <dd>The new HTML5 <code>activeElement</code> and <code>hasFocus</code> attributes are supported.</dd> + <dt><a href="/en-US/docs/Web-based_protocol_handlers" title="Web-based_protocol_handlers">Web-based protocol handlers</a></dt> + <dd>You can now register web applications as protocol handlers using the <code>navigator.registerProtocolHandler()</code> method.</dd> + <dt><a href="/en-US/docs/Web/API/Window/requestAnimationFrame" style="font-weight: bold;" title="Web-based_protocol_handlers">requestAnimationFrame</a></dt> + <dd>Allows control of animations rendering to obtain optimal performance.</dd> + <dt><a href="/en-US/docs/DOM/Using_full-screen_mode" title="DOM/Using_full-screen_mode">Fullscreen API</a></dt> + <dd>Controls the usage of the whole screen for a Web page or application, without the browser UI displayed.</dd> + <dt><a href="/en-US/docs/API/Pointer_Lock_API" title="API/Pointer_Lock_API">Pointer Lock API</a></dt> + <dd>Allows locking the pointer to the content, so games and similar applications don't lose focus when the pointer reaches the window limit.</dd> + <dt><a href="/en-US/docs/Online_and_offline_events" title="Online_and_offline_events">Online and offline events</a></dt> + <dd>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.</dd> +</dl> + +<h2 id="ACESSO_AO_DISPOSITIVO" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3837/HTML5_Device_Access_512.png" style="height: 66px; padding-right: 0.5em; vertical-align: middle; width: 77px;">ACESSO AO DISPOSITIVO</h2> + +<dl> + <dt><a href="/en-US/docs/DOM/Using_the_Camera_API" title="DOM/Using_the_Camera_API">Using the Camera API</a></dt> + <dd>Allows using, manipulating, and storing an image from the computer's camera.</dd> + <dt><a href="/en-US/docs/DOM/Touch_events" title="DOM/Touch_events">Touch events</a></dt> + <dd>Handlers to react to events created by a user pressing touch screens.</dd> + <dt><a href="/en-US/docs/Using_geolocation" title="Using geolocation">Using geolocation</a></dt> + <dd>Let browsers locate the position of the user using geolocation.</dd> + <dt><a href="/en-US/docs/Detecting_device_orientation" title="Detecting_device_orientation">Detecting device orientation</a></dt> + <dd>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).</dd> + <dt><a href="/en-US/docs/API/Pointer_Lock_API" title="API/Pointer_Lock_API">Pointer Lock API</a></dt> + <dd>Allows locking the pointer to the content, so games and similar application don't lose focus when the pointer reaches the window limit.</dd> +</dl> + +<h2 id="ESTILIZAÇÃO" style="margin: 0pt 0pt 0.25em; font: 200 24px/1 'Bebas Neue','League Gothic',Haettenschweiler,'Arial Narrow',sans-serif; letter-spacing: 1px; text-transform: uppercase; border: medium none;"><img alt="" src="/files/3829/HTML5_Styling_512.png" style="height: 64px; padding-right: 0.5em; vertical-align: middle; width: 64px;">ESTILIZAÇÃO</h2> + +<p id="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."><a href="/en-US/docs/CSS" title="CSS">CSS</a> has been extended to be able to style elements in a much more complex way. This is often referred as <a href="/en-US/docs/CSS/CSS3" title="CSS/CSS3">CSS3</a>, 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.</p> + +<dl> + <dt>New background styling features</dt> + <dd>It is now possible to put a shadow to a box, using {{cssxref("box-shadow")}} and <a href="/en-US/docs/CSS/Multiple_backgrounds" title="CSS/Multiple_backgrounds">multiple backgrounds</a> can be set.</dd> + <dt>More fancy borders</dt> + <dd>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.</dd> + <dt>Animating your style</dt> + <dd>Using <a href="/en-US/docs/CSS/Using_CSS_transitions" title="CSS/Using_CSS_transitions">CSS Transitions</a> to animate between different states or using <a href="/en-US/docs/CSS/Using_CSS_animations" title="CSS/Using_CSS_animations">CSS Animations</a> to animate parts of the page without a triggering event, you can now control mobile elements on your page.</dd> + <dt>Typography improvement</dt> + <dd>Authors have better control to reach better typography. They can control {{cssxref("text-overflow")}} and <a href="/en-US/docs/CSS/hyphens" title="CSS/hyphens">hyphenation</a>, but also can add a <a href="/en-US/docs/CSS/text-shadow" title="CSS/text-shadow">shadow</a> to it or control more precisely its <a href="/en-US/docs/CSS/text-decoration" title="SVG/Attribute/text-decoration">decorations</a>. Custom typefaces can be downloaded and applied thanks to the new {{cssxref("@font-face")}} at-rule.</dd> + <dt>New presentational layouts</dt> + <dd>In order to improve the flexibility of designs, two new layouts have been added: the <a href="/en-US/docs/CSS/Using_CSS_multi-column_layouts" title="CSS/Using_CSS_multi-column_layouts">CSS multi-column layouts</a> and <a href="/en-US/docs/CSS/Flexbox" title="CSS/Flexbox">CSS flexible box layout</a>.</dd> +</dl> +</div> +</div> diff --git a/files/pt-pt/web/html/html5/introdução_ao_html5/index.html b/files/pt-pt/web/html/html5/introdução_ao_html5/index.html new file mode 100644 index 0000000000..7a30759282 --- /dev/null +++ b/files/pt-pt/web/html/html5/introdução_ao_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 +--- +<p>O <a class="external" href="http://www.whatwg.org/specs/web-apps/current-work/" title="http://www.whatwg.org/specs/web-apps/current-work/">HTML5</a> (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.</p> + +<p>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 <a href="/pt/HTML/HTML5" title="pt/HTML/HTML5">página principal do HTML5</a>.</p> + +<h2 id="O_doctype_do_HTML5">O doctype do HTML5</h2> + +<p>O doctype para o HTML5 é muito simples. Para indicar que seu conteúdo HTML usa HTML5, simplesmente use:</p> + +<pre><!DOCTYPE html> +</pre> + +<p>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.</p> diff --git a/files/pt-pt/web/html/html5/parser_html5/index.html b/files/pt-pt/web/html/html5/parser_html5/index.html new file mode 100644 index 0000000000..eff96db73f --- /dev/null +++ b/files/pt-pt/web/html/html5/parser_html5/index.html @@ -0,0 +1,58 @@ +--- +title: Parser HTML5 +slug: Web/HTML/HTML5/Parser_HTML5 +translation_of: Web/Guide/HTML/HTML5/HTML5_Parser +--- +<p>{{ gecko_minversion_header("2") }}</p> +<p>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.</p> +<p>O novo analisador (parser) introduz estas melhorias maiores:</p> +<ul> + <li>Você pode agora usar o SVG e o MathML em linha em páginas HTML5, sem a sintaxe namespace XML.</li> + <li>O analizador (parsing) está completo em um processo separado do processo de interface de usuário do Firefox, melhorando a responsividade do navegador como um todo.</li> + <li>Chamadas para <code>innerHTML</code> estão muito mais rápidas.</li> + <li><a class="external" href="http://tinyurl.com/html-parser-bugs" title="https://bugzilla.mozilla.org/buglist.cgi?status_whiteboard_type=substring&status_whiteboard=[fixed%20by%20the%20HTML5%20parser]&resolution=FIXED">Dúzias de bugs relacionados à análise de longa data</a> (en) estão agora corrigidas.</li> +</ul> +<p>A <a class="external" href="http://www.w3.org/TR/html5/" title="http://www.w3.org/TR/html5/">especificação do HTML5</a> (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.</p> +<h2 id="Changed_parser_behaviors">Changed parser behaviors</h2> +<p>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.</p> +<h3 id="Tokenization_of_left_angle-bracket_within_a_tag">Tokenization of left angle-bracket within a tag</h3> +<p>Given the string <code><foo<bar></code>, the new parser reads it as one tag named <code>foo<bar</code>. This behavior is consistent with IE and Opera, and is different from Gecko 1.x and WebKit, which read it as two tags, <code>foo</code> and <code>bar</code>. 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.</p> +<h3 id="Calling_document.write()_during_parsing">Calling document.write() during parsing</h3> +<p>Prior to HTML5, Gecko and WebKit allowed calls to <a href="/en/DOM/document.write" title="en/DOM/document.write"><code>document.write()</code></a> <em>during parsing</em> to insert content into the source stream. This behavior was inherently <a class="external" href="http://en.wikipedia.org/wiki/Race_condition" title="http://en.wikipedia.org/wiki/Race_condition">racy</a>, 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 <a href="/en/DOM/document.open" title="en/DOM/document.open"><code>document.open()</code></a>, replacing the document. In HTML5, <code>document.write()</code> can only be called from a script that is created by a {{ HTMLElement("script") }} tag that does not have the <code><a href="/En/HTML/Element/Script#attr_async" title="En/HTML/Element/Script#attr async">async</a></code> or <code><a href="/En/HTML/Element/Script#attr_defer" title="En/HTML/Element/Script#attr defer">defer</a></code> attributes set. With the HTML5 parser, calls to <code>document.write()</code> in any other context either are ignored or replace the document.</p> +<p>Some contexts from which you should <em>not</em> call <code>document.write()</code> include:</p> +<ul> + <li>scripts created using <a href="/en/DOM/document.createElement" title="en/DOM/document.createElement">document.createElement()</a></li> + <li>event handlers</li> + <li><a href="/en/DOM/window.setTimeout" title="en/DOM/window.setTimeout">setTimeout()</a></li> + <li><a href="/en/DOM/window.setInterval" title="en/DOM/window.setInterval">setInterval()</a></li> + <li><code><script async src="..."></code></li> + <li><code><script defer src="..."></code></li> +</ul> +<p>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 <code>document.write()</code>.</p> +<h3 id="Lack_of_Reparsing">Lack of Reparsing</h3> +<p>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 <code></title></code> 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.</p> +<p>With HTML5, parsers no longer reparse documents. This change has the following consequences for web developers:</p> +<ul> + <li>If you omit the closing tag for <title>, <style>, <textarea>, or <xmp>, the page <em>will</em> fail to be parsed. IE already fails to parse documents with a missing </title> tag, so if you test with IE, you probably don't have that problem.</li> + <li>If you forget to close a comment, the page will most likely fail to be parsed. However, unclosed comments often already break in existing browsers for one reason or another, so it's unlikely that you have this issue in sites that are tested in multiple browsers.</li> + <li>In an inline script, in order to use the literal strings <code></script></code> and <code><!--</code>, you should prevent them from being parsed literally by expressing them as <code>\u003c/script></code> and <code>\u003c!--</code>. The older practice of escaping the string <code></script></code> by surrounding it with comment markers, while supported by HTML5, is problematic in cases where the closing comment marker is omitted (see preceding point). You can avoid such problems by using the character code for the initial '<' instead.</li> +</ul> +<h2 id="Performance_improvement_with_speculative_parsing">Performance improvement with speculative parsing</h2> +<p>Unrelated to the requirements of HTML5 specification, the Gecko 2 parser uses <em>speculative parsing</em>, 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.</p> +<p>To best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call <a href="/en/DOM/document.write" title="en/DOM/document.write">document.write()</a>, you write a <em>balanced sub-tree</em> 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 <code>document.write()</code> call, as long as they are within the same <code><script></code> tag.</p> +<p>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.)</p> +<p>For example, the following code writes a balanced sub-tree:</p> +<pre><script> + document.write("<div>"); + document.write("<p>Some content goes here.</p>"); + document.write("</div>"); +</script> +<!-- Non-script HTML goes here. --> +</pre> +<p>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.</p> +<pre><script>document.write("<div>");</script> +<p>Some content goes here.</p> +<script>document.write("</div>");</script> +</pre> +<p>For more information, see <a href="/en/HTML/HTML5/Optimizing_Your_Pages_for_Speculative_Parsing" title="en/Optimizing Your Pages for Speculative Parsing">Optimizing your pages for speculative parsing</a>.</p> +<p> </p> diff --git a/files/pt-pt/web/html/index.html b/files/pt-pt/web/html/index.html new file mode 100644 index 0000000000..c9cf09466b --- /dev/null +++ b/files/pt-pt/web/html/index.html @@ -0,0 +1,105 @@ +--- +title: 'HTML: Linguagem de Marcação de Hipertexto' +slug: Web/HTML +tags: + - HTML + - HTML5 + - Landing + - Web + - 'l10n:priority' +translation_of: Web/HTML +--- +<div>{{HTMLSidebar}}</div> + +<p class="summary"><span class="seoSummary">Linguagem de Marcação de Hipertexto (<strong>HTML</strong>) é o bloco de criação mais básico da Web. Este define o significado e estrutura de um conteúdo da Web<em>. </em>Outras tecnologias para além de HTML, são geralmente utilizadas para descrever a aparência/apresentação de uma página da Web </span> <span class="seoSummary">(<a href="/pt-PT/docs/Web/CSS">CSS</a>)</span> <span class="seoSummary"> ou funcionalidade/comportamento </span> <span class="seoSummary">(<a href="/pt-PT/docs/Web/JavaScript">JavaScript</a>)</span>.</p> + +<p>"Hipertexto" refere-se a hiperligações que ligam páginas da <em>web</em><em> </em>entre si, dentro de um único site da <em>web</em> ou entre sites da <em>web</em>. As hiperligações são um aspeto fundamental da <em>web</em>. Ao enviar conteúdo para a Internet e vinculá-lo às páginas criadas por outras pessoas, torna-o em um participante ativo na <em>World Wide Web</em>.</p> + +<p>HTML utiliza "markup" para anotar texto, imagens, e outro conteúdo para o exibir num navegador da Web. A marcação de HTML inclui "elementos" especiais, tais como {{HTMLElement("title")}}, {{HTMLElement("body")}}, {{HTMLElement("header")}}, {{HTMLElement("footer")}}, {{HTMLElement("article")}}, {{HTMLElement("section")}}, {{HTMLElement("p")}}, {{HTMLElement("div")}}, {{HTMLElement("span")}}, {{HTMLElement("img")}}, {{HTMLElement("aside")}}, {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("datalist")}}, {{HTMLElement("details")}}, {{HTMLElement("embed")}}, {{HTMLElement("nav")}}, {{HTMLElement("output")}}, {{HTMLElement("progress")}}, {{HTMLElement("video")}}, e muitos outros.</p> + +<p>Um elemento HTML é separado de outro texto num documento por "etiquetas", que consistem no nome do elemento entre "<" e ">". O nome de um elemento dentro de uma etiqueta é insensível a maiúsculas e minúsculas. Isto é, pode ser escrito em maiúsculas, minúsculas ou uma mistura. Por exemplo a etiqueta <<strong>title> </strong>pode ser escrita como <<strong>Title</strong>>, <<strong>TITLE</strong>> ou de outras formas.</p> + +<p>Os artigos abaixo, irão ajudá-lo a saber mais sobre o HTML.</p> + +<section class="cleared" id="sect1"> +<ul class="card-grid"> + <li><span>Introdução ao HTML</span> + + <p>Se for novo no desenvolvimento da Web, certifique-se que lê o nosso artigo <a href="/pt-PT/docs/Learn/Comecar_com_a_Web/HTML_basicos">essencial de HTML </a>para saber mais sobre o que é o HTML e como o utilizar.</p> + </li> + <li><span>Tutoriais de HTML</span> + <p>Para artigos sobre como utilizar o HTML, bem como tutorials e exemplos completos, consulte a nossa <a href="/pt-PT/docs/Learn/HTML">Área de Aprendizagem de HTML</a>.</p> + </li> + <li><span>Referência HTML</span> + <p>Na nossa secção extensa de <a href="/pt-PT/docs/Web/HTML/Referencia">Referência HTML</a>, irá encontrar os detalhes sobre cada elemento e atributo no HTML.</p> + </li> +</ul> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Tools" id="Tools" name="Tools">Tutoriais de principiante</h2> + +<p>Na nossa <a href="/pt-PT/docs/Learn/HTML">Área de Aprendizagem HTML</a> apresenta múltiplos módulos que ensinam HTML desde o início — não é necessário nenhum conhecimento prévio.</p> + +<dl> + <dt><a href="/pt-PT/docs/Learn/HTML/Introducao_ao_HTML">Introdução ao HTML</a></dt> + <dd>Este módulo define o palco, para que fique a conhecer os conceitos e sintaxe importantes, tais como a aplicação de HTML no texto, como criar hiperligações, e como utilizar HTML para estruturar uma página da Web.</dd> + <dt><a href="/pt-PT/docs/Learn/HTML/Multimedia_e_integracao">Multimédia e integração</a></dt> + <dd>Este módulo explora como usar o HTML para incluir multimédia nas suas páginas da web, incluindo as diferentes maneiras de como as imagens podem ser introduzidas, e como embutir vídeo, audio<span class="short_text" id="result_box" lang="pt"><span> e até mesmo outras páginas web inteiras.</span></span></dd> + <dt><a href="/pt-PT/docs/Learn/HTML/Tables">Tabelas de HTML</a></dt> + <dd>Representar dados em tabelas numa página web <span id="result_box" lang="pt"><span>de uma maneira compreensível e acessível pode ser um desafio. </span></span><span id="result_box" lang="pt"><span>Este módulo abrange a marcação básica de tabela, juntamente com recursos mais complexos, como a implementação de legendas e resumos.</span></span></dd> + <dt><a href="/pt-PT/docs/Learn/HTML/Formularios">Formulários HTML</a></dt> + <dd>Forms are a very important part of the Web — these provide much of the functionality you need for interacting with websites, e.g. registering and logging in, sending feedback, buying products, and more. This module gets you started with creating the client-side/front-end parts of forms.</dd> + <dt><a href="/pt-PT/docs/Learn/HTML/Como">Utilizar HTML para resolver problemas comuns</a></dt> + <dd>Provides links to sections of content explaining how to use HTML to solve very common problems when creating a web page: dealing with titles, adding images or videos, emphasizing content, creating a basic form, etc.</dd> +</dl> + +<h2 id="Tópicos_avançados">Tópicos avançados</h2> + +<dl> + <dt class="landingPageList"><a href="/pt-PT/docs/Web/HTML/CORS_enabled_image">Imagem CORS ativada</a></dt> + <dd class="landingPageList">O atributo <code><a href="/en-US/docs/Web/HTML/Element/img#attr-crossorigin">crossorigin</a></code>, em combinação com um cabeçalho <a class="glossaryLink" href="/en-US/docs/Glossary/CORS">CORS</a> apropriado, permite imagens definidas pelo elemento {{HTMLElement("img")}} para serem carregadas a partir de origens secundárias e utilziadas num elemento {{HTMLElement("canvas")}} como se fossem carregadas a partir de uma origem atual.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/CORS_settings_attributes">CORS settings attributes</a></dt> + <dd class="landingPageList">Some HTML elements that provide support for <a href="/en-US/docs/HTTP/Access_control_CORS">CORS</a>, such as {{HTMLElement("img")}} or {{HTMLElement("video")}}, have a <code>crossorigin</code> attribute (<code>crossOrigin</code> property), which lets you configure the CORS requests for the element's fetched data.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Focus_management_in_HTML">Focus management in HTML</a></dt> + <dd class="landingPageList">The <code><a href="/en-US/docs/Web/API/Document/activeElement">activeElement</a></code> DOM attribute and the <code><a href="/en-US/docs/Web/API/Document/hasFocus">hasFocus()</a></code> DOM method help you track and control a user's interactions with elements on a web page.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Using_the_application_cache">Using the application cache</a></dt> + <dd class="landingPageList">Application caching lets web-based applications run offline. You can use the <strong>Application Cache</strong> (<em>AppCache</em>) interface to specify resources that the browser should cache and make available to offline users. Applications that are cached load and work correctly even if users click the refresh button when they are offline.</dd> + <dt class="landingPageList"><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content">Preloading content with rel="preload"</a></dt> + <dd class="landingPageList">The <code>preload</code> value of the {{htmlelement("link")}} element's {{htmlattrxref("rel", "link")}} attribute allows you to write declarative fetch requests in your HTML {{htmlelement("head")}}, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements. This article provides a basic guide to how <code>preload</code> works.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Documentation" id="Referências">Referências</h2> + +<dl> + <dt class="landingPageList"><a href="/pt-PT/docs/Web/HTML/Referencia">Referência HTML</a></dt> + <dd class="landingPageList">HTML consists of <strong>elements</strong>, each of which may be modified by some number of <strong>attributes</strong>. HTML documents are connected to each other with <a href="/en-US/docs/Web/HTML/Link_types">links</a>.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Element">HTML element reference</a></dt> + <dd class="landingPageList">Browse a list of all <a class="glossaryLink" href="/en-US/docs/Glossary/HTML">HTML</a> <a class="glossaryLink" href="/en-US/docs/Glossary/Element">elements</a>.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Attributes">HTML attribute reference</a></dt> + <dd class="landingPageList">Elements in HTML have <strong>attributes</strong>. These are additional values that configure the elements or adjust their behavior in various ways.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Global_attributes">Global attributes</a></dt> + <dd class="landingPageList">Global attributes may be specified on all <a href="/en-US/docs/Web/HTML/Element">HTML elements</a>, <em>even those not specified in the standard</em>. This means that any non-standard elements must still permit these attributes, even though those elements make the document HTML5-noncompliant.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Inline_elements">Inline elements</a> and <a href="/en-US/docs/Web/HTML/Block-level_elements">block-level elements</a></dt> + <dd class="landingPageList">HTML elements are usually "inline" or "block-level" elements. An inline element occupies only the space bounded by the tags that define it. A block-level element occupies the entire space of its parent element (container), thereby creating a "block."</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Link_types">Link types</a></dt> + <dd class="landingPageList">In HTML, various link types can be used to establish and define the relationship between two documents. Link elements that types can be set on include <a href="/en-US/docs/Web/HTML/Element/a"><code><a></code></a>, <a href="/en-US/docs/Web/HTML/Element/area"><code><area></code></a> and <a href="/en-US/docs/Web/HTML/Element/link"><code><link></code></a>.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Supported_media_formats">Media formats supported by the HTML audio and video elements</a></dt> + <dd class="landingPageList">The <a href="/en-US/docs/Web/HTML/Element/audio"><code><audio></code></a> and <a href="/en-US/docs/Web/HTML/Element/video"><code><video></code></a> elements allow you to play audio and video media. These elements provide a browser-native alternative to similar capabilities found in Adobe Flash and other plug-ins.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Kinds_of_HTML_content">Kinds of HTML content</a></dt> + <dd class="landingPageList">HTML is comprised of several kinds of content, each of which is allowed to be used in certain contexts and is disallowed in others. Similarly, each has a set of other content categories they can contain and elements which can or can't be used in them. This is a guide to these categories.</dd> + <dt class="landingPageList"><a href="/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode">Quirks mode and standards mode</a></dt> + <dd class="landingPageList">Historical information on quirks mode and standards mode.</dd> +</dl> + +<h2 class="landingPageList" id="Tópicos_relacionados">Tópicos relacionados</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/HTML/Aplicar_cor__elementos_HTML_utilizando_CSS">Aplicar cor aos elementos HTML utilizando CSS</a></dt> + <dd>Este artigo aborda a maioria das formas em que utilzia CSS para adicionar cor ao conteúdo HTML, listando quais as partes dos documentos HTML que podem ser coloridas e quais as propriedades CSS que utilizam e quando o fazer. Inclui exemplos, hiperligações para ferramentas de criação de paletas e, mais.</dd> +</dl> +</div> +</div> +<span class="alllinks"><a href="/pt-PT/docs/tag/HTML">Ver Tudo...</a></span></section> diff --git a/files/pt-pt/web/html/referencia/index.html b/files/pt-pt/web/html/referencia/index.html new file mode 100644 index 0000000000..e2f5085a81 --- /dev/null +++ b/files/pt-pt/web/html/referencia/index.html @@ -0,0 +1,27 @@ +--- +title: Referência HTML +slug: Web/HTML/Referencia +tags: + - HTML + - Landing + - Referencia + - Web +translation_of: Web/HTML/Reference +--- +<div>{{HTMLSidebar}}</div> + +<p>Esta referência <a href="/en-US/docs/Web/HTML">HTML</a> descreve <strong>todos os elementos</strong> e<strong> atributos</strong> de HTML, incluindo os <strong>atributos globais</strong> que se aplicam a todos os elementos.</p> + +<dl> + <dd></dd> + <dt><a href="/pt-PT/docs/Web/HTML/Elemento">Referência de elementos HTML</a></dt> + <dd>Esta página lista todos os HTML elementos.</dd> + <dt><a href="/pt-PT/docs/Web/HTML/Atributos">Referência de atibuto HTML</a></dt> + <dd></dd> + <dt><a href="/pt-PT/docs/Web/HTML/Atributos_globais">Atributos globais</a></dt> + <dd></dd> + <dt><a href="/pt-PT/docs/Web/HTML/Tipos_de_hiperligacao">Tipos de hiperligação</a></dt> + <dd>Em HTML, os seguintes tipos de hiperligação indicam a relação entre dois documentos, em que uma se interliga com a outra, utilizando um elemento <a>, <area>, ou <link>.</dd> +</dl> + +<p><span class="alllinks"><a href="/pt-PT/docs/tag/HTML" title="Article tagged: HTML">Ver todas as páginas "HTML" etiquetadas...</a></span></p> diff --git a/files/pt-pt/web/html/tipos_de_hiperligacao/index.html b/files/pt-pt/web/html/tipos_de_hiperligacao/index.html new file mode 100644 index 0000000000..4f4f0cc17b --- /dev/null +++ b/files/pt-pt/web/html/tipos_de_hiperligacao/index.html @@ -0,0 +1,608 @@ +--- +title: Tipos de hiperligação +slug: Web/HTML/Tipos_de_hiperligacao +tags: + - HTML + - Hiperligação + - Referencia + - Tipos de hiperligação +translation_of: Web/HTML/Link_types +--- +<div>{{HTMLSidebar}}</div> + +<p>Em HTML, os seguintes tipos de hiperligação indicam a relação entre dois documentos, em que uma se interliga com a outra, utilizando um elemento {{HTMLElement("a")}}, {{HTMLElement("area")}}, ou {{HTMLElement("link")}}.</p> + +<table class="standard-table"> + <caption>List of the defined link types and their significance in HTML</caption> + <thead> + <tr> + <th scope="col">Tipo de Hiperligação</th> + <th scope="col">Descrição</th> + <th scope="col" style="width: 12em;">Permitido nestes elementos</th> + <th scope="col">Não permitido nestes elementos</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>alternate</code></td> + <td> + <ul> + <li>If the element is {{HTMLElement("link")}} and the {{htmlattrxref("rel", "link")}} attribute also contains the <code>stylesheet</code> type, the link defines an <a href="/en-US/docs/Alternative_style_sheets">alternative style sheet</a>; in that case the {{htmlattrxref("title", "link")}} attribute must be present and not be the empty string.</li> + <li>If the {{htmlattrxref("type","link")}} is set to <code>application/rss+xml</code> or <code>application/atom+xml</code>, the link defines a <a href="/en-US/docs/RSS/Getting_Started/Syndicating">syndication feed</a>. The first one defined on the page is the default.</li> + <li>Otherwise, the link defines an alternative page, of one of these types: + <ul> + <li>for another medium, like a handheld device (if the {{htmlattrxref("media","link")}} attribute is set)</li> + <li>in another language (if the {{htmlattrxref("hreflang","link")}} attribute is set),</li> + <li>in another format, such as a PDF (if the {{htmlattrxref("type","link")}} attribute is set)</li> + <li>a combination of these</li> + </ul> + </li> + </ul> + </td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None</em>.</td> + </tr> + <tr> + <td><code>archives</code> {{obsolete_inline}}</td> + <td>Defines a hyperlink to a document that contains an archive link to this one. For example, a blog entry could link to a monthly index page this way.<br> + <br> + <strong>Note:</strong> Although recognized, the singular <code>archive</code> is incorrect and must be avoided.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>author</code></td> + <td>Defines a hyperlink to a page describing the author or providing a way to contact the author.<br> + <br> + <strong>Note:</strong> This may be a <code>mailto:</code> hyperlink, but this is not recommended on public pages as robot harvesters will quickly lead to a lot of spam sent to the address. In that case, it is better to lead to a page containing a contact form.<br> + <br> + Although recognized, the {{htmlattrxref("rev", "link")}} attribute on {{HTMLElement("a")}}, {{HTMLElement("area")}} or{{HTMLElement("link")}} elements with a link type of <code>made</code> is incorrect and should be replaced by the {{htmlattrxref("rel", "link")}} attribute with this link type.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>bookmark</code></td> + <td>Indicates that the hyperlink is a <a href="/en-US/docs/Permalink">permalink</a> for the nearest ancestor {{HTMLElement("article")}} element. If none, it is a permalink for the <a href="/en-US/docs/Sections_and_Outlines_of_an_HTML5_document">section</a> that the element is most closely associated to.<br> + <br> + This allows for bookmarking a single article in a page containing multiple articles, such as on a monthly summary blog page, or a blog aggregator.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + <td>{{HTMLElement("link")}}</td> + </tr> + <tr> + <td><code>canonical</code></td> + <td>From Wikipedia, the free encyclopedia: <a href="https://en.wikipedia.org/wiki/Canonical_link_element">Canonical_link_element</a><br> + A canonical link element is an HTML element that helps webmasters prevent duplicate content issues by specifying the "canonical" or "preferred" version of a web page as part of search engine optimization.</td> + <td>{{HTMLElement("link")}}</td> + <td>???</td> + </tr> + <tr> + <td><code>dns-prefetch</code> {{experimental_inline}}</td> + <td>Hints to the browser that a resources is needed allowing the browser to do a DNS lookup and protocol handshaking before a user clicks the link.</td> + <td>{{HTMLElement("link")}}</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + </tr> + <tr> + <td><code>external</code></td> + <td>Indicates that the hyperlink leads to a resource outside the site of the current page; that is, following the link will make the user leave the site.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + <td>{{HTMLElement("link")}}</td> + </tr> + <tr> + <td><code>first</code> {{obsolete_inline}}</td> + <td>Indicates that the hyperlink leads to the first resource of the <em>sequence</em> the current page is in.<br> + <br> + <strong>Note:</strong> Other link types related to linking resources in the same sequence are <code>last</code>, <code>prev</code>, <code>next</code>.<br> + <br> + Although recognized, the synonyms <code>begin</code> and <code>start</code> are incorrect and must be avoided.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>help</code></td> + <td> + <ul> + <li>If the element is {{HTMLElement("a")}} or {{HTMLElement("area")}}, it indicates that the hyperlink leads to a resource giving further help about the parent of the element, and its descendants.</li> + <li>If the element is {{HTMLElement("link")}} it indicates that the hyperlink leads to a resource giving further help about the page as a whole.</li> + </ul> + </td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>icon</code></td> + <td>Defines a resource for representing the page in the user interface, usually an icon (auditory or visual).<br> + <br> + The {{htmlattrxref("media","link")}}, {{htmlattrxref("type","link")}} and {{htmlattrxref("sizes","link")}} attributes allow the browser to select the most appropriate icon for its context. If several resources match, the browser will select the last one declared, in tree order. As these attributes are merely hints, and the resources may be inappropriate upon further inspection, the browser will then select another one, if appropriate.<br> + <br> + <strong>Note:</strong> Apple's iOS does not use this link type, nor the {{htmlattrxref("sizes","link")}} attribute, like others mobile browsers do, to select a webpage icon for Web Clip or a start-up placeholder. Instead it uses the non-standard <a class="external external-icon" href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW4"><code>apple-touch-icon</code></a> and <a class="external external-icon" href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html#//apple_ref/doc/uid/TP40002051-CH3-SW6"><code>apple-touch-startup-image</code></a> respectively.<br> + <br> + The <code>shortcut</code> link type is often seen before <code>icon</code>, but this link type is non-conforming, ignored and <strong>web authors must not use it anymore</strong>.</td> + <td>{{HTMLElement("link")}}</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + </tr> + <tr> + <td><code>index</code> {{obsolete_inline}}</td> + <td>Indicates that the page is part of a <em>hierarchical</em> structure and that the hyperlink leads to the top level resource of that structure.<br> + <br> + If one or several <code>up</code> link types are also present, the number of these <code>up</code> indicates the depth of the current page in the hierarchy.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>last</code> {{obsolete_inline}}</td> + <td>Indicates that the hyperlink leads to the <em>last</em> resource of the <em>sequence</em> the current page is in.<br> + <br> + <strong>Note:</strong> Other link types related to linking resources in the same sequence are <code>first</code>, <code>prev</code>, <code>next</code>.<br> + <br> + Although recognized, the synonym <code>end</code> is incorrect and must be avoided.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>license</code></td> + <td>Indicates that the hyperlink leads to a document describing the licensing information. If not inside the {{HTMLElement("head")}} element, the standard doesn't distinguish between a hyperlink applying to a specific part of the document or to the document as a whole. Only the data on the page can indicate this.<br> + <br> + <strong>Note: </strong>Although recognized, the synonym <code>copyright</code> is incorrect and must be avoided.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>manifest</code></td> + <td>Indicates that the linked file is a <a href="https://developer.mozilla.org/en-US/docs/Web/Manifest">Web App Manifest</a>.</td> + <td>{{HTMLElement("link")}}</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + </tr> + <tr> + <td><code>next</code></td> + <td>Indicates that the hyperlink leads to the <em>next</em> resource of the <em>sequence</em> the current page is in.<br> + <br> + <strong>Note:</strong> Other link types related to linking resources in the same sequence are <code>first</code>, <code>prev</code>, <code>last</code>.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>nofollow</code></td> + <td>Indicates that the linked document is not endorsed by the author of this one, for example if it has no control over it, if it is a bad example or if there is commercial relationship between the two (sold link). This link type may be used by some search engines that use popularity ranking techniques.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + <td>{{HTMLElement("link")}}</td> + </tr> + <tr> + <td><code>noopener</code></td> + <td> + <p>Instructs the browser to open the link without granting the new browsing context access to the document that opened it — by not setting the {{domxref("Window.opener")}} property on the opened window (it returns <code>null</code>).<br> + <br> + This is especially useful when opening untrusted links, in order to ensure they cannot tamper with the originating document via the {{domxref("Window.opener")}} property (see <a href="https://mathiasbynens.github.io/rel-noopener/">About rel=noopener</a> for more details), while still providing the <code>Referer</code> HTTP header (unless <code>noreferrer</code> is used as well).</p> + + <p>Note that when <code>noopener</code> is used, nonempty target names other than <code>_top</code>, <code>_self</code>, and <code>_parent</code> are all treated like <code>_blank</code> in terms of deciding whether to open a new window/tab.</p> + </td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + <td>{{HTMLElement("link")}}</td> + </tr> + <tr> + <td><code>noreferrer</code></td> + <td> + <p>Prevents the browser, when navigating to another page, to send this page address, or any other value, as referrer via the <code>Referer:</code> HTTP header.<br> + (In Firefox, before Firefox 37, this worked only in links found in pages. Links clicked in the UI, like "Open in a new tab" via the contextual menu, ignored this).</p> + </td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + <td>{{HTMLElement("link")}}</td> + </tr> + <tr> + <td><code>pingback</code></td> + <td>Defines an external resource URI to call if one wishes to make a comment or a citation about the webpage. The protocol used to make such a call is defined in the <a href="http://www.hixie.ch/specs/pingback/pingback">Pingback 1.0</a> specification.<br> + <br> + <strong>Note:</strong> if the <code>X-Pingback:</code> HTTP header is also present, it supersedes the {{HTMLElement("link")}} element with this link type.</td> + <td>{{HTMLElement("link")}}</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + </tr> + <tr> + <td><code>preconnect</code> {{experimental_inline}}</td> + <td>Provides a hint to the browser suggesting that it open a connection to the linked web site in advance, without disclosing any private information or downloading any content, so that when the link is followed the linked content can be fetched more quickly.</td> + <td>{{HTMLElement("link")}}</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + </tr> + <tr> + <td><code>prefetch</code></td> + <td>Suggests that the browser fetch the linked resource in advance, as it is likely to be requested by the user. Starting with Firefox 44, the value of the {{htmlattrxref("crossorigin", "link")}} attribute is taken into consideration, making it possible to make anonymous prefetches.<br> + <br> + <strong>Note:</strong> The <a href="/en-US/docs/Link_prefetching_FAQ">Link Prefetch FAQ</a> has details on which links can be prefetched and on alternative methods.</td> + <td>{{HTMLElement("a")}} {{unimplemented_inline}},<br> + {{HTMLElement("area")}} {{unimplemented_inline}},<br> + {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>preload</code></td> + <td>Tells the browser to download a resource because this resource will be needed later during the current navigation. See <a href="/en-US/docs/Web/HTML/Preloading_content">Preloading content with rel="preload"</a> for more details.</td> + <td>{{HTMLElement("link")}}</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + </tr> + <tr> + <td><code>prerender</code> {{experimental_inline}}</td> + <td>Suggests that the browser fetch the linked resource in advance, and that it also render the prefetched content offscreen so it can be quickly presented to the user once needed.</td> + <td>{{HTMLElement("link")}}</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + </tr> + <tr> + <td><code>prev</code></td> + <td>Indicates that the hyperlink leads to the <em>preceding</em> resource of the <em>sequence</em> the current page is in.<br> + <br> + <strong>Note:</strong> You can also use the <code>next</code> keyword to specify a link to the next page in the sequence.<br> + <br> + Although recognized, the synonym <code>previous</code> is incorrect and must be avoided.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>search</code></td> + <td>Indicates that the hyperlink references a document whose interface is specially designed for searching in this document, or site, and its resources.<br> + <br> + If the {{htmlattrxref("type","link")}} attribute is set to <code>application/opensearchdescription+xml </code>the resource is an <a href="/en-US/docs/Creating_OpenSearch_plugins_for_Firefox">OpenSearch plugin</a> that can be easily added to the interface of some browsers like Firefox or Internet Explorer.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>shortlink</code></td> + <td>From Wikipedia, the free encyclopedia: <a href="https://en.wikipedia.org/wiki/URL_shortening">URL shortening</a><br> + Some websites create short links to make sharing links via instant messaging easier.</td> + <td>{{HTMLElement("link")}}</td> + <td>???</td> + </tr> + <tr> + <td><code>stylesheet</code></td> + <td>Defines an external resource to be used as a stylesheet. If the <code>type</code> is not set, the browser should assume it is a <code>text/css</code> stylesheet until further inspection.<br> + <br> + If used in combination with the <code>alternate</code> keyword, it defines an <a href="/en-US/docs/Alternative_style_sheets">alternative style sheet</a>; in that case the {{htmlattrxref("title", "link")}} attribute must be present and not be the empty string.</td> + <td>{{HTMLElement("link")}}</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + </tr> + <tr> + <td><code>sidebar</code> {{non-standard_inline}}</td> + <td>Indicates that the hyperlink leads to a resource that would be better suited for a secondary browsing context, like a <em>sidebar</em>. Browsers, that don't have such a context will ignore this keyword.<br> + <br> + While once part of the HTML specification, this has been removed from the spec and is only implemented by Firefox at this time.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + <tr> + <td><code>tag</code></td> + <td>Indicates that the hyperlink refers to a document describing a <em>tag</em> that applies to this document.<br> + <br> + <strong>Note:</strong> This link type should not be set on links to a member of a tag cloud as these do not apply to a single document but to a set of pages.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}</td> + <td>{{HTMLElement("link")}}</td> + </tr> + <tr> + <td><code>up</code> {{obsolete_inline}}</td> + <td>Indicates that the page is part of a <em>hierarchical</em> structure and that the hyperlink leads to the higher level resource of that structure.<br> + <br> + The number of <code>up</code> link types indicates the depth difference between the current page and the linked resource.</td> + <td>{{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("link")}}</td> + <td><em>None.</em></td> + </tr> + </tbody> +</table> + +<h2 id="Specifications" name="Specifications">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Preload','#x2.link-type-preload','preload')}}</td> + <td>{{Spec2('Preload')}}</td> + <td>Added <code>preload</code>.</td> + </tr> + <tr> + <td>{{SpecName('Resource Hints', '#dfn-preconnect', 'preconnect')}}</td> + <td>{{Spec2('Resource Hints')}}</td> + <td>Added <code>dns-prefetch</code>, <code>preconnect</code>, and <code>prerender</code> values.</td> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', 'semantics.html#the-link-element', '<link>')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>No change since last snapshot ({{SpecName('HTML WHATWG')}})</td> + </tr> + <tr> + <td>{{SpecName('HTML5 W3C', 'document-metadata.html#the-link-element', '<link>')}}</td> + <td>{{Spec2('HTML5 W3C')}}</td> + <td>Added <code>tag</code>, <code>stylesheet</code>, <code>search</code>, <code>prev</code>, <code>prefetch</code>, <code>noreferrer</code>, <code>nofollow</code>, <code>next</code>, <code>license</code>, <code>icon</code>, <code>help</code>, <code>bookmark</code>, <code>author</code>, and <code>alternate</code>.</td> + </tr> + <tr> + <td>{{SpecName('HTML4.01', 'struct/links.html#h-12.3', '<link>')}}</td> + <td>{{Spec2('HTML4.01')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Alternative stylesheets</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>prefetch</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>prerender</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}<sup>[4]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>preconnect</code></td> + <td>{{CompatChrome(46)}}</td> + <td>{{CompatGeckoDesktop("39")}}<sup>[1]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><code>dns-prefetch</code></td> + <td>{{CompatChrome(46)}}</td> + <td>{{CompatGeckoDesktop("1.9")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>preload</code></td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{CompatNo}}<sup>[3]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>noopener</code></td> + <td>{{CompatChrome(49.0)}}</td> + <td>{{CompatGeckoDesktop("52")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(36)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>manifest</code></td> + <td>{{CompatNo}}<sup>[2]</sup></td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("1.0")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Alternative stylesheets</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("2.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>prefetch</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>prerender</code></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatNo}}<sup>[4]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>preconnect</code></td> + <td>{{CompatChrome(46)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("39")}} </td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(42.0)}}<sup>[1]</sup></td> + </tr> + <tr> + <td><code>dns-prefetch</code></td> + <td>{{CompatChrome(46)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("1.9")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><code>preload</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(50.0)}}</td> + <td>{{CompatNo}}<sup>[3]</sup></td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(50.0)}}</td> + </tr> + <tr> + <td><code>noopener</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(49.0)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>32</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(49.0)}}</td> + </tr> + <tr> + <td><code>manifest</code></td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(39.0)}}</td> + <td> </td> + <td> </td> + <td> </td> + <td> </td> + <td>{{CompatChrome(39.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Before Firefox 41, it didn't obey the {{htmlattrxref("crossorigin", 'link')}} attribute.</p> + +<p>[2] Since this is a mobile feature, desktop ignores it rather than throwing an error.</p> + +<p>[3] This feature was available in Firefox 56, but only for cacheable resources. It has been disabled in Firefox 57 because of various web compatibility issues (e.g. {{bug(1405761)}}). An improved version that works for non-cacheable resources is expected to land in Firefox 59.</p> + +<p>[4] This was implemented behind a pref in Gecko 53 — <code>dom.linkPrerender.enabled</code>.— but then removed because of lack of uptake and removal in Chromium. See {{bug(1383876)}}.</p> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/html/utilizar_a_cache_de_aplicacao/index.html b/files/pt-pt/web/html/utilizar_a_cache_de_aplicacao/index.html new file mode 100644 index 0000000000..bd21f03e21 --- /dev/null +++ b/files/pt-pt/web/html/utilizar_a_cache_de_aplicacao/index.html @@ -0,0 +1,342 @@ +--- +title: Utilizar a cache de aplicação +slug: Web/HTML/Utilizar_a_cache_de_aplicacao +tags: + - Aplicação + - App + - Avançado + - Cache + - Guía + - HTML + - appcahe + - cache da aplicação + - cache da web + - web cache +translation_of: Web/HTML/Using_the_application_cache +--- +<div>{{DefaultAPISidebar("App Cache")}}{{SecureContext_Header}}{{Deprecated_Header}} +<div class="blockIndicator warning"> +<p>Using the <em>application caching</em> feature described here is at this point highly discouraged; it’s <a href="https://html.spec.whatwg.org/multipage/browsers.html#offline">in the process of being removed from the Web platform</a>. Use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service Workers</a> instead. In fact as of Firefox 44, when <a href="/en-US/docs/Web/HTML/Using_the_application_cache">AppCache</a> is used to provide offline support for a page a warning message is now displayed in the console advising developers to use <a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Service workers</a> instead ({{bug("1204581")}}).</p> +</div> +</div> + +<h2 id="Introdução">Introdução</h2> + +<p><a href="/en-US/docs/HTML/HTML5">HTML5</a> provides an <em>application caching</em> mechanism that lets web-based applications run offline. Developers can use the <strong>Application Cache</strong> (<em>AppCache</em>) interface to specify resources that the browser should cache and make available to offline users. Applications that are cached load and work correctly even if users click the refresh button when they are offline.</p> + +<p>Using an application cache gives an application the following benefits:</p> + +<ul> + <li>Offline browsing: users can navigate a site even when they are offline.</li> + <li>Speed: cached resources are local, and therefore load faster.</li> + <li>Reduced server load: the browser only downloads resources that have changed from the server.</li> +</ul> + +<h2 id="Como_é_que_funciona_a_cache_de_aplicação">Como é que funciona a cache de aplicação</h2> + +<h3 id="Ativar_a_cache_de_aplicação">Ativar a cache de aplicação</h3> + +<p>To enable the application cache for an application, you must include the {{HTMLAttrxRef("manifest", "html")}} attribute in the {{HTMLElement("html")}} element in your application's pages, as shown in the following example:</p> + +<pre class="brush: html"><html manifest="example.appcache"> + ... +</html> +</pre> + +<p>The manifest attribute references a <strong>cache manifest</strong> file, which is a text file that lists resources (files) that the browser should cache for your application.</p> + +<p>You should include the <code>manifest</code> attribute on every page of your application that you want cached. The browser does not cache pages that do not contain the <code>manifest</code> attribute, unless such pages are explicitly listed in the manifest file itself. You do not need to list all the pages you want cached in the manifest file, the browser implicitly adds every page that the user visits and that has the <code>manifest</code> attribute set to the application cache.</p> + +<p>Some browsers (e.g., Firefox) display a notification bar the first time a user loads an application that uses the application cache. The notification bar displays a message such as:</p> + +<p style="margin-left: 40px;">This website (<code>www.example.com</code>) is asking to store data on your computer for offline use. [Allow] [Never for This Site] [Not Now]</p> + +<p>The term "offline(-enabled) applications" sometimes refers specifically to applications that the user has allowed to use offline capabilities.</p> + +<h3 id="Carregar_documentos">Carregar documentos</h3> + +<p>The use of an application cache modifies the normal process of loading a document:</p> + +<ul> + <li>If an application cache exists, the browser loads the document and its associated resources directly from the cache, without accessing the network. This speeds up the document load time.</li> + <li>The browser then checks to see if the cache manifest has been updated on the server.</li> + <li>If the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest. This is done in the background and does not affect performance significantly.</li> +</ul> + +<p>The process for loading documents and updating the application cache is specified in greater detail below:</p> + +<ol> + <li>When the browser visits a document that includes the <code>manifest</code> attribute, if no application cache exists, the browser loads the document and then fetches all the entries listed in the manifest file, creating the first version of the application cache.</li> + <li>Subsequent visits to that document cause the browser to load the document and other assets specified in the manifest file from the application cache (not from the server). In addition, the browser also sends a <code>checking</code> event to the <code><a href="/en-US/docs/DOM/window.applicationCache">window.applicationCache</a></code> object, and fetches the manifest file, following the appropriate HTTP caching rules.</li> + <li>If the currently-cached copy of the manifest is up-to-date, the browser sends a <code>noupdate</code> event to the <code>applicationCache</code> object, and the update process is complete. Note that if you change any cached resources on the server, you must also change the manifest file itself, so that the browser knows it needs to fetch all the resources again.</li> + <li>If the manifest file <em>has</em> changed, all the files listed in the manifest—as well as those added to the cache by calling <code><a href="/en-US/docs/nsIDOMOfflineResourceList#add.28.29">applicationCache.add()</a></code>—are fetched into a temporary cache, following the appropriate HTTP caching rules. For each file fetched into this temporary cache, the browser sends a <code>progress</code> event to the <code>applicationCache</code> object. If any errors occur, the browser sends an <code>error</code> event, and the update halts.</li> + <li>Once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a <code>cached</code> event is sent to the <code>applicationCache</code> object. Since the document has already been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manually or programatically).</li> +</ol> + +<h2 id="Localização_do_armazenamento_e_limpeza_off-line_da_cache">Localização do armazenamento e limpeza off-line da cache</h2> + +<p>In Chrome you can clear the offline cache by selecting "Clear browsing data..." in the preferences or by visiting <a>chrome://appcache-internals/</a>. Safari has a similar "Empty cache" setting in its preferences but a browser restart may also be required.</p> + +<p>In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:</p> + +<ul> + <li>Windows Vista/7: <code>C:\Users\<username>\AppData\<strong>Local</strong>\Mozilla\Firefox\Profiles\<salt>.<profile name>\OfflineCache</code></li> + <li>Mac/Linux: <code>/Users/<username>/Library/Caches/Firefox/Profiles/<salt>.<profile name>/OfflineCache</code></li> +</ul> + +<p>In Firefox the current status of the offline cache can be inspected on the <code>about:cache</code> page (under the "Offline cache device" heading). The offline cache can be cleared for each site separately using the "Remove..." button in Tools -> Options -> Advanced -> Network -> Offline data.</p> + +<p>Prior to Firefox 11, neither Tools -> Clear Recent History nor Tools -> Options -> Advanced -> Network -> Offline data -> Clear Now cleared the offline cache. This has been fixed.</p> + +<p>On Linux, you can find the setting at Edit > Preferences > Advanced > Network > Offline Web Content and User Data</p> + +<p>See also <a href="/en-US/docs/DOM/Storage#Storage_location_and_clearing_the_data">clearing the DOM Storage data</a>.</p> + +<p>Application caches can also become obsolete. If an application's manifest file is removed from the server, the browser removes all application caches that use that manifest, and sends an "obsoleted" event to the <code>applicationCache</code> object. This sets the application cache's state to <code>OBSOLETE</code>.</p> + +<h2 id="O_ficheiro_manifest_da_cache">O ficheiro <em>manifest </em>da cache</h2> + +<h3 id="Referencing_a_cache_manifest_file">Referencing a cache manifest file</h3> + +<p>The <code>manifest</code> attribute in a web application can specify either the relative path of a cache manifest file or an absolute URL. (Absolute URLs must be from the same origin as the application). A cache manifest file can have any file extension, but it must be served with the MIME type <code>text/cache-manifest</code>.</p> + +<div class="note"><strong>Note: </strong>On Apache servers, the MIME type for manifest (.appcache) files can be set by adding <code>AddType text/cache-manifest .appcache</code> to a .htaccess file within either the root directory, or the same directory as the application.</div> + +<h3 id="Entries_in_a_cache_manifest_file">Entries in a cache manifest file</h3> + +<p>The cache manifest file is a simple text file that lists the resources the browser should cache for offline access. Resources are identified by URI. Entries listed in the cache manifest must have the same scheme, host, and port as the manifest.</p> + +<h3 id="Example_1_a_simple_cache_manifest_file">Example 1: a simple cache manifest file</h3> + +<p>The following is a simple cache manifest file, <code>example.appcache</code>, for an imaginary web site at <span class="nowiki">www.example.com</span>.</p> + +<pre class="eval">CACHE MANIFEST +# v1 - 2011-08-13 +# This is a comment. +<span class="nowiki">http://www.example.com/index.html</span> +<span class="nowiki">http://www.example.com/header.png</span> +<span class="nowiki">http://www.example.com/blah/blah</span> +</pre> + +<p>A cache manifest file can include three sections (<code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>, discussed below). In the example above, there is no section header, so all data lines are assumed to be in the explicit (<code>CACHE</code>) section, meaning that the browser should cache all the listed resources in the application cache. Resources can be specified using either absolute or relative URLs (e.g., <code>index.html</code>).</p> + +<p>The "v1" comment in the example above is there for a good reason. Browsers only update an application cache when the manifest file changes, byte for byte. If you change a cached resource (for example, you update the <code>header.png</code> image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache. You can make any change you want to the manifest file, but revising a version number is the recommended best practice.</p> + +<div class="warning"><strong>Important:</strong> Do not specify the manifest itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.</div> + +<h3 id="Sections_in_a_cache_manifest_file_CACHE_NETWORK_and_FALLBACK">Sections in a cache manifest file: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code></h3> + +<p>A manifest can have three distinct sections: <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK</code>.</p> + +<dl> + <dt><code>CACHE:</code></dt> + <dd>This is the default section for entries in a cache manifest file. Files listed under the <code>CACHE:</code> section header (or immediately after the <code>CACHE MANIFEST</code> line) are explicitly cached after they're downloaded for the first time.</dd> + <dt><code>NETWORK:</code></dt> + <dd>Files listed under the <code>NETWORK:</code> section header in the cache manifest file are white-listed resources that require a connection to the server. All requests to such resources bypass the cache, even if the user is offline. The wildcard character <code>*</code> can be used once. Most sites need <code>*</code>.</dd> + <dt><code>FALLBACK:</code></dt> + <dd>The <code>FALLBACK:</code> section specifies fallback pages the browser should use if a resource is inaccessible. Each entry in this section lists two URIs—the first is the resource, the second is the fallback. Both URIs must be relative and from the same origin as the manifest file. Wildcards may be used.</dd> +</dl> + +<p>The <code>CACHE</code>, <code>NETWORK</code>, and <code>FALLBACK </code>sections can be listed in any order in a cache manifest file, and each section can appear more than once in a single manifest.</p> + +<h3 id="Example_2_a_more_complete_cache_manifest_file">Example 2: a more complete cache manifest file</h3> + +<p>The following is a more complete cache manifest file for the imaginary web site at <span class="nowiki">www.example.com</span>:</p> + +<pre class="eval">CACHE MANIFEST +# v1 2011-08-14 +# This is another comment +index.html +cache.html +style.css +image1.png + +# Use from network if available +NETWORK: +network.html + +# Fallback content +FALLBACK: +. fallback.html +</pre> + +<p>This example uses <code>NETWORK</code> and <code>FALLBACK</code> sections to specify that the <code>network.html</code> page must always be retrieved from the network, and that the <code>fallback.html</code> page should be served as a fallback resource (e.g., in case a connection to the server cannot be established).</p> + +<h3 id="Structure_of_a_cache_manifest_file">Structure of a cache manifest file</h3> + +<p>Cache manifest files must be served with the <code>text/cache-manifest</code> MIME type. All resources served using this MIME type must follow the syntax for an application cache manifest, as defined in this section.</p> + +<p>Cache manifests are UTF-8 format text files, and may optionally include a BOM character. Newlines may be represented by line feed (<code>U+000A</code>), carriage return (<code>U+000D</code>), or carriage return and line feed both.</p> + +<p>The first line of the cache manifest must consist of the string <code>CACHE MANIFEST</code> (with a single <code>U+0020</code> space between the two words), followed by zero or more space or tab characters. Any other text on the line is ignored.</p> + +<p>The remainder of the cache manifest must be comprised of zero or more of the following lines:</p> + +<dl> + <dt>Blank line</dt> + <dd>You may use blank lines comprised of zero or more space and tab characters.</dd> + <dt>Comment</dt> + <dd>Comments consist of zero or more tabs or spaces followed by a single <code>#</code> character, followed by zero or more characters of comment text. Comments may only be used on their own lines (after the initial <code>CACHE MANIFEST</code> line), and cannot be appended to other lines. This means that you cannot specify fragment identifiers.</dd> + <dt>Section header</dt> + <dd>Section headers specify which section of the cache manifest is being manipulated. There are three possible section headers:</dd> +</dl> + +<blockquote> +<table class="standard-table"> + <tbody> + <tr> + <th>Secção cabeçalho</th> + <th>Descrição</th> + </tr> + <tr> + <td><code>CACHE:</code></td> + <td>Switches to the explicit section of the cache manifest (this is the default section).</td> + </tr> + <tr> + <td><code>NETWORK:</code></td> + <td>Switches to the online whitelist section of the cache manifest.</td> + </tr> + <tr> + <td><code>FALLBACK:</code></td> + <td>Switches to the fallback section of the cache manifest.</td> + </tr> + </tbody> +</table> +</blockquote> + +<dl> + <dd>The section header line may include whitespaces, but must include the colon (<code>:</code>) in the section name.</dd> + <dt>Dados da secção</dt> + <dd>The format for lines of data varies from section to section. In the explicit (<code>CACHE:</code>) section, each line is a valid URI or IRI reference to a resource to cache (no wildcard characters are allowed in this sections). Whitespace is allowed before and after the URI or IRI on each line. In the Fallback section each line is a valid URI or IRI reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. In the network section, each line is a valid URI or IRI reference to a resource to fetch from the network (or the wildcard character <code>*</code> can be used in this section). + <div class="note"><strong>Nota: </strong>Relative URIs are relative to the cache manifest's URI, not to the URI of the document referencing the manifest.</div> + </dd> +</dl> + +<p>Cache manifest files can switch from section to section at will (each section header can be used more than once), and sections are allowed to be empty.</p> + +<h2 id="Recursos_na_cache_de_aplicação">Recursos na cache de aplicação</h2> + +<p>An application cache always includes at least one resource, identified by URI. All resources fit into one of the following categories:</p> + +<dl> + <dt>Master entries</dt> + <dd>These are resources added to the cache because a browsing context visited by the user included a document that indicated that it was in this cache using its <code>manifest</code> attribute.</dd> + <dt>Explicit entries</dt> + <dd>These are resources explicitly listed in the application's cache manifest file.</dd> + <dt>Network entries</dt> + <dd>These are resources listed in the application's cache manifest files as network entries.</dd> + <dt>Fallback entries</dt> + <dd>These are resources listed in the application's cache manifest files as fallback entries.</dd> +</dl> + +<div class="note"><strong>Nota:</strong> Resources can be tagged with multiple categories, and can therefore be categorized as multiple entries. For example, an entry can be both an explicit entry and a fallback entry.</div> + +<p>Resource categories are described in greater detail below.</p> + +<h3 id="Master_entries">Master entries</h3> + +<p>Master entries are any HTML files that include a {{HTMLAttrxRef("manifest","html")}} attribute in their {{HTMLElement("html")}} element. For example, let's say we have the HTML file <a href="http://www.example.com/entry.html">http://www.example.com/entry.html</a>, which looks like this:</p> + +<pre class="brush: html"><html manifest="example.appcache"> + <h1>Application Cache Example</h1> +</html> +</pre> + +<p>If <code>entry.html</code> is not listed in the <code>example.appcache</code> cache manifest file, visiting the <code>entry.html</code> page causes <code>entry.html</code> to be added to the application cache as a master entry.</p> + +<h3 id="Explicit_entries">Explicit entries</h3> + +<p>Explicit entries are resources that are explicitly listed in the <code>CACHE </code>section of a cache manifest file.</p> + +<h3 id="Network_entries">Network entries</h3> + +<p>The <code>NETWORK</code> section of a cache manifest file specifies resources for which a web application requires online access. Network entries in an application cache are essentially an "online whitelist"—URIs specified in the <code>NETWORK</code> section are loaded from the server instead of the cache. This lets the browser's security model protect the user from potential security breaches by limiting access to approved resources.</p> + +<p>As an example, you can use network entries to load and execute scripts and other code from the server instead of the cache:</p> + +<pre class="eval">CACHE MANIFEST +NETWORK: +/api +</pre> + +<p>The cache manifest section listed above ensures that requests to load resources contained in the <code><a href="http://www.example.com/api/" rel="freelink">http://www.example.com/api/</a></code> subtree always go to the network without attempting to access the cache.</p> + +<div class="note"><strong>Note</strong>: Simply omitting master entries (files that have the <code>manifest</code> attribute set in the <code>html</code> element) from the manifest file would not have the same result, because master entries will be added—and subsequently served from—the application cache.</div> + +<h3 id="Fallback_entries">Fallback entries</h3> + +<p>Fallback entries are used when an attempt to load a resource fails. For example, let's say the cache manifest file <code><a href="http://www.example.com/example.appcache" rel="freelink">http://www.example.com/example.appcache</a></code> includes the following content:</p> + +<pre class="eval">CACHE MANIFEST +FALLBACK: +example/bar/ example.html +</pre> + +<p>Any request to <code><a href="http://www.example.com/example/bar/" rel="freelink">http://www.example.com/example/bar/</a></code> or any of its subdirectories and their content cause the browser to issue a network request to attempt to load the requested resource. If the attempt fails, due to either a network failure or a server error of some kind, the browser loads the file <code>example.html</code> instead.</p> + +<h2 id="Estados_da_cache">Estados da cache</h2> + +<p>Each application cache has a <strong>state</strong>, which indicates the current condition of the cache. Caches that share the same manifest URI share the same cache state, which can be one of the following:</p> + +<dl> + <dt><code>UNCACHED</code></dt> + <dd>A special value that indicates that an application cache object is not fully initialized.</dd> + <dt><code>IDLE</code></dt> + <dd>The application cache is not currently in the process of being updated.</dd> + <dt><code>CHECKING</code></dt> + <dd>The manifest is being fetched and checked for updates.</dd> + <dt><code>DOWNLOADING</code></dt> + <dd>Resources are being downloaded to be added to the cache, due to a changed resource manifest.</dd> + <dt><code>UPDATEREADY</code></dt> + <dd>There is a new version of the application cache available. There is a corresponding <code>updateready</code> event, which is fired instead of the <code>cached</code> event when a new update has been downloaded but not yet activated using the <code>swapCache()</code> method.</dd> + <dt><code>OBSOLETE</code></dt> + <dd>The application cache group is now obsolete.</dd> +</dl> + +<h2 id="Testing_for_updates_to_the_cache_manifest">Testing for updates to the cache manifest</h2> + +<p>You can programmatically test to see if an application has an updated cache manifest file, using JavaScript. Since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test <code>window.applicationCache.status</code>.</p> + +<pre class="brush: js">function onUpdateReady() { + console.log('found new version!'); +} +window.applicationCache.addEventListener('updateready', onUpdateReady); +if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { + onUpdateReady(); +}</pre> + +<p>To manually start testing for a new manifest file, you can use <code>window.applicationCache.update()</code>.</p> + +<h2 id="Gotchas">Gotchas</h2> + +<ul> + <li>Never access cached files by using traditional GET parameters (like <code>other-cached-page.html?parameterName=value</code>). This will make the browser bypass the cache and attempt to get it from network. To link to cached resources that have parameters parsed in JavaScript use parameters in the hash part of the link, such as <code>other-cached-page.html#whatever?parameterName=value</code>.</li> + <li>When applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. You must update the cache manifest file itself before the browser retrieves and uses the updated files. You can do this programmatically using <code>window.applicationCache.swapCache()</code>, though resources that have already been loaded will not be affected. To make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal.</li> + <li>It's a good idea to set expires headers on your web server for <code>*.appcache</code> files to expire immediately. This avoids the risk of caching manifest files. For example, in Apache you can specify such a configuration as follows:<br> + <code>ExpiresByType text/cache-manifest "access plus 0 seconds"</code></li> +</ul> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("html.elements.html.manifest")}}</p> + +<p><font face="x-locale-heading-primary, zillaslab, Palatino, Palatino Linotype, x-locale-heading-secondary, serif"><span style="font-size: 37.3333px;"><strong>Consultar também</strong></span></font></p> + +<ul> + <li><a href="http://www.html5rocks.com/en/tutorials/appcache/beginner/">HTML5Rocks - A Beginner's Guide to Using the Application Cache</a></li> + <li><a href="http://appcache.offline.technology/">Appcache Facts</a> - detailed information on AppCache idiosyncrasies</li> + <li><a href="http://alistapart.com/article/application-cache-is-a-douchebag">A List Apart: Application Cache is a Douchebag</a> + <ul> + <li><a href="http://flailingmonkey.com/application-cache-not-a-douchebag">The Application Cache is no longer a Douchebag</a> - an overview of the app cache debugging tools added in Firefox 23.</li> + </ul> + </li> + <li><a href="http://hacks.mozilla.org/2010/01/offline-web-applications/">offline web applications</a> at hacks.mozilla.org - showcases an offline app demo and explains how it works.</li> + <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/offline.html#offline">HTML 5 working draft: Offline web applications</a></li> + <li><a href="http://www.w3.org/TR/offline-webapps/">W3C Working Group Note: Offline Web Applications</a></li> + <li><a href="http://developer.teradata.com/blog/js186040/2011/11/html5-cache-manifest-an-off-label-usage">HTML5 Cache Manifest: An Off-label Usage</a></li> + <li><a href="http://www.ibm.com/developerworks/web/library/wa-ffox3/">Get ready for Firefox 3.0 - A Web developer's guide to the many new features in this popular browser, especially the offline application features</a> (IBM developerWorks)</li> + <li><a href="/en-US/docs/Application_cache_implementation_overview">Application cache implementation overview</a></li> + <li><a href="//www.onlinewebcheck.com/check.php?adv=1">OnlineWebCheck.com - Check cache manifest file syntax</a> (Desktop app for Windows)</li> +</ul> diff --git a/files/pt-pt/web/http/cors/errors/corsdidnotsucceed/index.html b/files/pt-pt/web/http/cors/errors/corsdidnotsucceed/index.html new file mode 100644 index 0000000000..b6b8001ab1 --- /dev/null +++ b/files/pt-pt/web/http/cors/errors/corsdidnotsucceed/index.html @@ -0,0 +1,22 @@ +--- +title: 'Reason: CORS request did not succeed' +slug: Web/HTTP/CORS/Errors/CORSDidNotSucceed +translation_of: Web/HTTP/CORS/Errors/CORSDidNotSucceed +--- +<div>{{HTTPSidebar}}</div> + +<h2 id="Motivo">Motivo</h2> + +<pre class="syntaxbox">Motivo: O pedido CORS não foi concluído com sucesso</pre> + +<h2 id="O_que_correu_mal">O que correu mal?</h2> + +<p>O {{Glossary("HTTP")}} pedido que faz uso do CORS falhou porque a conexão HTTP falhou a nivel da rede ou do protocolo de conexão. O error não está directamente relacionado com CORS, mas é algum tipo de erro da rede.</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors">Erros CORS</a></li> + <li>Glossário: {{Glossary("CORS")}}</li> + <li><a href="/en-US/docs/Web/HTTP/CORS">Introdução ao CORS</a></li> +</ul> diff --git a/files/pt-pt/web/http/cors/errors/index.html b/files/pt-pt/web/http/cors/errors/index.html new file mode 100644 index 0000000000..d1dd12dc75 --- /dev/null +++ b/files/pt-pt/web/http/cors/errors/index.html @@ -0,0 +1,76 @@ +--- +title: CORS errors +slug: Web/HTTP/CORS/Errors +tags: + - CORS + - Errors + - HTTP + - HTTPS + - Messages + - NeedsTranslation + - Same-origin + - Security + - TopicStub + - console + - troubleshooting +translation_of: Web/HTTP/CORS/Errors +--- +<div>{{HTTPSidebar}}</div> + +<p><span class="seoSummary"><a href="/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing</a> ({{Glossary("CORS")}}) is a standard that allows a server to relax the <a href="/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a>. This is used to explicitly allow some cross-origin requests while rejecting others.</span> For example, if a site offers an embeddable service, it may be necessary to relax certain restrictions. Setting up such a CORS configuration isn't necessarily easy and may present some challenges. In these pages, we'll look into some common CORS error messages and how to resolve them.</p> + +<p>If the CORS configuration isn't setup correctly, the browser console will present an error like <code>"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite"</code> indicating that the request was blocked due to violating the CORS security rules. This might not necessarily be a set-up mistake, though. It's possible that the request is in fact intentionally being disallowed by the user's web application and remote external service. However, If the endpoint is meant to be available, some debugging is needed to succeed.</p> + +<h2 id="Identifying_the_issue">Identifying the issue</h2> + +<p>To understand the underlying issue with the CORS configuration, you need to find out which request is at fault and why. These steps may help you do so:</p> + +<ol> + <li>Navigate to the web site or web app in question and open the <a href="/en-US/docs/Tools">Developer Tools</a>.</li> + <li>Now try to reproduce the failing transaction and check the <a href="/en-US/docs/Tools/Web_Console">console</a> if you are seeing a CORS violation error message. It will probably look like this:</li> +</ol> + +<p><img alt="Firefox console showing CORS error" src="https://mdn.mozillademos.org/files/16050/cors-error2.png"></p> + +<p>The text of the error message will be something similar to the following:</p> + +<pre>Cross<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body">-Origin Request Blocked: The Same Origin Policy disallows +reading the remote resource at <em>https://some-url-here</em>. (<em>Reason: +additional information here</em>).</span></span></span></pre> + +<div class="note"> +<p><span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><strong>Note:</strong> For security reasons, specifics about what went wrong with a CORS request <em>are not available to JavaScript code</em>. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details.</span></span></span></p> +</div> + +<h2 id="CORS_error_messages">CORS error messages</h2> + +<p>Firefox's console displays messages in its console when requests fail due to CORS. Part of the error text is a "reason" message that provides added insight into what went wrong. The reason messages are listed below; click the message to open an article explaining the error in more detail and offering possible solutions.</p> + +<ul> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSDisabled">Reason: CORS disabled</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSDidNotSucceed">Reason: CORS request did not succeed</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSOriginHeaderNotAdded">Reason: CORS header ‘Origin’ cannot be added</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSExternalRedirectNotAllowed">Reason: CORS request external redirect not allowed</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp">Reason: CORS request not http</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin">Reason: CORS header ‘Access-Control-Allow-Origin’ missing</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSAllowOriginNotMatchingOrigin">Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘xyz’</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials">Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSMethodNotFound">Reason: Did not find method in CORS header ‘Access-Control-Allow-Methods’</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowCredentials">Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSPreflightDidNotSucceed">Reason: CORS preflight channel did not succeed</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSInvalidAllowMethod">Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Methods’</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSInvalidAllowHeader">Reason: invalid token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowHeaderFromPreflight">Reason: missing token ‘xyz’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel</a></li> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors/CORSMultipleAllowOriginNotAllowed">Reason: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed</a></li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li>Glossary: {{Glossary("CORS")}}</li> + <li><a href="/en-US/docs/Web/HTTP/CORS">CORS introduction</a></li> + <li><a href="/en-US/docs/Web/HTTP/Server-Side_Access_Control">Server-side CORS settings</a></li> + <li><a href="/en-US/docs/Web/HTML/CORS_enabled_image">CORS enabled image</a></li> + <li><a href="/en-US/docs/Web/HTML/CORS_settings_attributes">CORS settings attributes</a></li> + <li><a href="https://www.test-cors.org">https://www.test-cors.org</a> – page to test CORS requests</li> +</ul> diff --git a/files/pt-pt/web/http/cors/index.html b/files/pt-pt/web/http/cors/index.html new file mode 100644 index 0000000000..1bfd447c17 --- /dev/null +++ b/files/pt-pt/web/http/cors/index.html @@ -0,0 +1,570 @@ +--- +title: Cross-Origin Resource Sharing (CORS) +slug: Web/HTTP/CORS +tags: + - AJAX + - CORS + - Cross-Origin Resource Sharing + - Fetch + - Fetch API + - HTTP + - HTTP Access Controls + - NeedsTranslation + - Same-origin policy + - Security + - TopicStub + - XMLHttpRequest + - 'l10n:priority' +translation_of: Web/HTTP/CORS +--- +<div>{{HTTPSidebar}}</div> + +<p><span class="seoSummary">Cross-Origin Resource Sharing ({{Glossary("CORS")}}) is a mechanism that uses additional {{Glossary("HTTP")}} headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.</span> A web application executes a <strong>cross-origin HTTP request</strong> when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.</p> + +<p>An example of a cross-origin request: The frontend JavaScript code for a web application served from <code>http://domain-a.com</code> uses {{domxref("XMLHttpRequest")}} to make a request for <code>http://api.domain-b.com/data.json</code>.</p> + +<p>For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, <code>XMLHttpRequest</code> and the <a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a> follow the <a href="/en-US/docs/Web/Security/Same-origin_policy">same-origin policy</a>. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14295/CORS_principle.png" style="height: 305px; width: 440px;"></p> + +<p>The CORS mechanism supports secure cross-origin requests and data transfers between browsers and web servers. Modern browsers use CORS in an API container such as <code>XMLHttpRequest</code> or <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a> to help mitigate the risks of cross-origin HTTP requests.</p> + +<h2 id="Who_should_read_this_article">Who should read this article?</h2> + +<p>Everyone, really.</p> + +<p>More specifically, this article is for web administrators, server developers, and front-end developers. Modern browsers handle the client-side components of cross-origin sharing, including headers and policy enforcement. But this new standard means servers have to handle new request and response headers. Another article for server developers discussing <a href="/en-US/docs/Web/HTTP/Server-Side_Access_Control">cross-origin sharing from a server perspective (with PHP code snippets)</a> is supplementary reading.</p> + +<h2 id="What_requests_use_CORS">What requests use CORS?</h2> + +<p>This <a class="external" href="https://fetch.spec.whatwg.org/#http-cors-protocol">cross-origin sharing standard</a> is used to enable cross-site HTTP requests for:</p> + +<ul> + <li>Invocations of the {{domxref("XMLHttpRequest")}} or <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a> APIs in a cross-site manner, as discussed above.</li> + <li>Web Fonts (for cross-domain font usage in <code>@font-face</code> within CSS), <a class="external" href="https://www.w3.org/TR/css-fonts-3/#font-fetching-requirements">so that servers can deploy TrueType fonts that can only be cross-site loaded and used by web sites that are permitted to do so.</a></li> + <li><a href="/en-US/docs/Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL">WebGL textures</a>.</li> + <li>Images/video frames drawn to a canvas using {{domxref("CanvasRenderingContext2D.drawImage()", "drawImage()")}}.</li> +</ul> + +<p>This article is a general discussion of Cross-Origin Resource Sharing and includes a discussion of the necessary HTTP headers.</p> + +<h2 id="Functional_overview">Functional overview</h2> + +<p>The Cross-Origin Resource Sharing standard works by adding new <a href="/en-US/docs/Web/HTTP/Headers">HTTP headers</a> that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on server's data (in particular, for HTTP methods other than {{HTTPMethod("GET")}}, or for {{HTTPMethod("POST")}} usage with certain <a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">MIME types</a>), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP {{HTTPMethod("OPTIONS")}} request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including <a href="/en-US/docs/Web/HTTP/Cookies">Cookies</a> and HTTP Authentication data) should be sent with requests.</p> + +<p>CORS failures result in errors, but for security reasons, specifics about what went wrong <em>are not available to JavaScript code</em>. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser's console for details.</p> + +<p>Subsequent sections discuss scenarios, as well as provide a breakdown of the HTTP headers used.</p> + +<h2 id="Examples_of_access_control_scenarios">Examples of access control scenarios</h2> + +<p>Here, we present three scenarios that illustrate how Cross-Origin Resource Sharing works. All of these examples use the {{domxref("XMLHttpRequest")}} object, which can be used to make cross-site invocations in any supporting browser.</p> + +<p>The JavaScript snippets included in these sections (and running instances of the server-code that correctly handles these cross-site requests) can be found "in action" at <a class="external" href="http://arunranga.com/examples/access-control/">http://arunranga.com/examples/access-control/</a>, and will work in browsers that support cross-site <code>XMLHttpRequest</code>.</p> + +<p>A discussion of Cross-Origin Resource Sharing from a server perspective (including PHP code snippets) can be found in the <a class="internal" href="/en-US/docs/Web/HTTP/Server-Side_Access_Control">Server-Side Access Control (CORS)</a> article.</p> + +<h3 id="Simple_requests">Simple requests</h3> + +<p>Some requests don’t trigger a <a href="#Preflighted_requests">CORS preflight</a>. Those are called “simple requests” in this article, though the {{SpecName('Fetch')}} spec (which defines CORS) doesn’t use that term. A request that doesn’t trigger a <a href="#Preflighted_requests">CORS preflight</a>—a so-called “simple request” — is one that <strong>meets all the following conditions</strong>:</p> + +<ul> + <li>The only allowed methods are: + <ul> + <li>{{HTTPMethod("GET")}}</li> + <li>{{HTTPMethod("HEAD")}}</li> + <li>{{HTTPMethod("POST")}}</li> + </ul> + </li> + <li>Apart from the headers set automatically by the user agent (for example, {{HTTPHeader("Connection")}}, {{HTTPHeader("User-Agent")}}, or <a href="https://fetch.spec.whatwg.org/#forbidden-header-name">any of the other headers with names defined in the Fetch spec as a “forbidden header name”</a>), the only headers which are allowed to be manually set are <a href="https://fetch.spec.whatwg.org/#cors-safelisted-request-header">those which the Fetch spec defines as being a “CORS-safelisted request-header”</a>, which are: + <ul> + <li>{{HTTPHeader("Accept")}}</li> + <li>{{HTTPHeader("Accept-Language")}}</li> + <li>{{HTTPHeader("Content-Language")}}</li> + <li>{{HTTPHeader("Content-Type")}} (but note the additional requirements below)</li> + <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#dpr">DPR</a></code></li> + <li>{{HTTPHeader("Downlink")}}</li> + <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#save-data">Save-Data</a></code></li> + <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#viewport-width">Viewport-Width</a></code></li> + <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#width">Width</a></code></li> + </ul> + </li> + <li>The only allowed values for the {{HTTPHeader("Content-Type")}} header are: + <ul> + <li><code>application/x-www-form-urlencoded</code></li> + <li><code>multipart/form-data</code></li> + <li><code>text/plain</code></li> + </ul> + </li> + <li>No event listeners are registered on any {{domxref("XMLHttpRequestUpload")}} object used in the request; these are accessed using the {{domxref("XMLHttpRequest.upload")}} property.</li> + <li>No {{domxref("ReadableStream")}} object is used in the request.</li> +</ul> + +<div class="note"><strong>Note:</strong> These are the same kinds of cross-site requests that web content can already issue, and no response data is released to the requester unless the server sends an appropriate header. Therefore, sites that prevent cross-site request forgery have nothing new to fear from HTTP access control.</div> + +<div class="note"><strong>Note:</strong> WebKit Nightly and Safari Technology Preview place additional restrictions on the values allowed in the {{HTTPHeader("Accept")}}, {{HTTPHeader("Accept-Language")}}, and {{HTTPHeader("Content-Language")}} headers. If any of those headers have ”non-standard” values, WebKit/Safari does not consider the request to meet the conditions for a “simple request”. What WebKit/Safari considers “non-standard” values for those headers is not documented except in the following WebKit bugs: <a href="https://bugs.webkit.org/show_bug.cgi?id=165178" rel="nofollow noreferrer">Require preflight for non-standard CORS-safelisted request headers Accept, Accept-Language, and Content-Language</a>, <a href="https://bugs.webkit.org/show_bug.cgi?id=165566" rel="nofollow noreferrer">Allow commas in Accept, Accept-Language, and Content-Language request headers for simple CORS</a>, and <a href="https://bugs.webkit.org/show_bug.cgi?id=166363" rel="nofollow noreferrer">Switch to a blacklist model for restricted Accept headers in simple CORS requests</a>. No other browsers implement those extra restrictions, because they’re not part of the spec.</div> + +<p>For example, suppose web content on domain <code class="plain">http://foo.example</code> wishes to invoke content on domain <code class="plain">http://bar.other</code>. Code of this sort might be used within JavaScript deployed on foo.example:</p> + +<pre class="brush: js" id="line1">const invocation = new XMLHttpRequest(); +const url = 'http://bar.other/resources/public-data/'; + +function callOtherDomain() { + if(invocation) { + invocation.open('GET', url, true); + invocation.onreadystatechange = handler; + invocation.send(); + } +} +</pre> + +<p>This will lead to a simple exchange between the client and the server, using CORS headers to handle the privileges:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14293/simple_req.png" style="height: 224px; width: 521px;"></p> + +<p>Let us look at what the browser will send to the server in this case, and let's see how the server responds:</p> + +<pre class="brush: shell;highlight:[10,16]">GET /resources/public-data/ HTTP/1.1 +Host: bar.other +User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre +Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 +Accept-Language: en-us,en;q=0.5 +Accept-Encoding: gzip,deflate +Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 +Connection: keep-alive +Referer: http://foo.example/examples/access-control/simpleXSInvocation.html +Origin: http://foo.example + + +HTTP/1.1 200 OK +Date: Mon, 01 Dec 2008 00:23:53 GMT +Server: Apache/2.0.61 +Access-Control-Allow-Origin: * +Keep-Alive: timeout=2, max=100 +Connection: Keep-Alive +Transfer-Encoding: chunked +Content-Type: application/xml + +[XML Data] +</pre> + +<p>Lines 1 - 10 are headers sent. The main HTTP request header of note here is the {{HTTPHeader("Origin")}} header on line 10 above, which shows that the invocation is coming from content on the domain <code class="plain">http://foo.example</code>.</p> + +<p>Lines 13 - 22 show the HTTP response from the server on domain <code class="plain">http://bar.other</code>. In response, the server sends back an {{HTTPHeader("Access-Control-Allow-Origin")}} header, shown above in line 16. The use of the {{HTTPHeader("Origin")}} header and of {{HTTPHeader("Access-Control-Allow-Origin")}} show the access control protocol in its simplest use. In this case, the server responds with a <code>Access-Control-Allow-Origin: *</code> which means that the resource can be accessed by <strong>any</strong> domain in a cross-site manner. If the resource owners at <code class="plain">http://bar.other</code> wished to restrict access to the resource to requests only from <code class="plain">http://foo.example</code>, they would send back:</p> + +<p><code class="plain">Access-Control-Allow-Origin: http://foo.example</code></p> + +<p>Note that now, no domain other than <code class="plain">http://foo.example</code> (identified by the ORIGIN: header in the request, as in line 10 above) can access the resource in a cross-site manner. The <code>Access-Control-Allow-Origin</code> header should contain the value that was sent in the request's <code>Origin</code> header.</p> + +<h3 id="Preflighted_requests">Preflighted requests</h3> + +<p>Unlike <a href="#Simple_requests">“simple requests” (discussed above)</a>, "preflighted" requests first send an HTTP request by the {{HTTPMethod("OPTIONS")}} method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data.</p> + +<p>In particular, a request is preflighted if <strong>any of the following conditions</strong> is true:</p> + +<ul> + <li><strong>If</strong> the request uses any of the following methods: + + <ul> + <li>{{HTTPMethod("PUT")}}</li> + <li>{{HTTPMethod("DELETE")}}</li> + <li>{{HTTPMethod("CONNECT")}}</li> + <li>{{HTTPMethod("OPTIONS")}}</li> + <li>{{HTTPMethod("TRACE")}}</li> + <li>{{HTTPMethod("PATCH")}}</li> + </ul> + </li> + <li><strong>Or if</strong>, apart from the headers set automatically by the user agent (for example, {{HTTPHeader("Connection")}}, {{HTTPHeader("User-Agent")}}, or <a href="https://fetch.spec.whatwg.org/#forbidden-header-name">any of the <strong>OTHER</strong> header with a name defined in the Fetch spec as a “forbidden header name”</a>), the request includes any headers other than <a href="https://fetch.spec.whatwg.org/#cors-safelisted-request-header">those which the Fetch spec defines as being a “CORS-safelisted request-header”</a>, which are the following: + <ul> + <li>{{HTTPHeader("Accept")}}</li> + <li>{{HTTPHeader("Accept-Language")}}</li> + <li>{{HTTPHeader("Content-Language")}}</li> + <li>{{HTTPHeader("Content-Type")}} (but note the additional requirements below)</li> + <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#dpr">DPR</a></code></li> + <li>{{HTTPHeader("Downlink")}}</li> + <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#save-data">Save-Data</a></code></li> + <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#viewport-width">Viewport-Width</a></code></li> + <li><code><a href="http://httpwg.org/http-extensions/client-hints.html#width">Width</a></code></li> + </ul> + </li> + <li><strong>Or if</strong> the {{HTTPHeader("Content-Type")}} header has a value <strong>OTHER THAN</strong> the following: + <ul> + <li><code>application/x-www-form-urlencoded</code></li> + <li><code>multipart/form-data</code></li> + <li><code>text/plain</code></li> + </ul> + </li> + <li><strong>Or if</strong> one or more event listeners are registered on an {{domxref("XMLHttpRequestUpload")}} object used in the request.</li> + <li><strong>Or if</strong> a {{domxref("ReadableStream")}} object is used in the request.</li> +</ul> + +<div class="note"><strong>Note:</strong> WebKit Nightly and Safari Technology Preview place additional restrictions on the values allowed in the {{HTTPHeader("Accept")}}, {{HTTPHeader("Accept-Language")}}, and {{HTTPHeader("Content-Language")}} headers. If any of those headers have ”non-standard” values, WebKit/Safari preflights the request. What WebKit/Safari considers “non-standard” values for those headers is not documented except in the following WebKit bugs: <a href="https://bugs.webkit.org/show_bug.cgi?id=165178" rel="nofollow noreferrer">Require preflight for non-standard CORS-safelisted request headers Accept, Accept-Language, and Content-Language</a>, <a href="https://bugs.webkit.org/show_bug.cgi?id=165566" rel="nofollow noreferrer">Allow commas in Accept, Accept-Language, and Content-Language request headers for simple CORS</a>, and <a href="https://bugs.webkit.org/show_bug.cgi?id=166363" rel="nofollow noreferrer">Switch to a blacklist model for restricted Accept headers in simple CORS requests</a>. No other browsers implement those extra restrictions, because they’re not part of the spec.</div> + +<p>The following is an example of a request that will be preflighted.</p> + +<pre class="brush: js" id="line1">const invocation = new XMLHttpRequest(); +const url = 'http://bar.other/resources/post-here/'; +const body = '<?xml version="1.0"?><person><name>Arun</name></person>'; + +function callOtherDomain(){ + if(invocation) + { + invocation.open('POST', url, true); + invocation.setRequestHeader('X-PINGOTHER', 'pingpong'); + invocation.setRequestHeader('Content-Type', 'application/xml'); + invocation.onreadystatechange = handler; + invocation.send(body); + } +} + +...... +</pre> + +<p>In the example above, line 3 creates an XML body to send with the <code>POST</code> request in line 8. Also, on line 9, a "customized" (non-standard) HTTP request header is set (<code>X-PINGOTHER: pingpong</code>). Such headers are not part of the HTTP/1.1 protocol, but are generally useful to web applications. Since the request uses a Content-Type of <code>application/xml</code>, and since a custom header is set, this request is preflighted.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/16401/preflight_.png" style="height: 555px; width: 538px;"></p> + +<p>(Note: as described below, the actual POST request does not include the Access-Control-Request-* headers; they are needed only for the OPTIONS request.)</p> + +<p>Let's take a look at the full exchange between client and server. The first exchange is the <em>preflight request/response</em>:</p> + +<pre class="brush: none;highlight:[1,10,11,17-20]">OPTIONS /resources/post-here/ HTTP/1.1 +Host: bar.other +User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre +Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 +Accept-Language: en-us,en;q=0.5 +Accept-Encoding: gzip,deflate +Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 +Connection: keep-alive +Origin: http://foo.example +Access-Control-Request-Method: POST +Access-Control-Request-Headers: X-PINGOTHER, Content-Type + + +HTTP/1.1 200 OK +Date: Mon, 01 Dec 2008 01:15:39 GMT +Server: Apache/2.0.61 (Unix) +Access-Control-Allow-Origin: http://foo.example +Access-Control-Allow-Methods: POST, GET, OPTIONS +Access-Control-Allow-Headers: X-PINGOTHER, Content-Type +Access-Control-Max-Age: 86400 +Vary: Accept-Encoding, Origin +Content-Encoding: gzip +Content-Length: 0 +Keep-Alive: timeout=2, max=100 +Connection: Keep-Alive +Content-Type: text/plain +</pre> + +<p>Once the preflight request is complete, the real request is sent:</p> + +<pre class="brush: none;">POST /resources/post-here/ HTTP/1.1 +Host: bar.other +User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre +Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 +Accept-Language: en-us,en;q=0.5 +Accept-Encoding: gzip,deflate +Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 +Connection: keep-alive +X-PINGOTHER: pingpong +Content-Type: text/xml; charset=UTF-8 +Referer: http://foo.example/examples/preflightInvocation.html +Content-Length: 55 +Origin: http://foo.example +Pragma: no-cache +Cache-Control: no-cache + +<?xml version="1.0"?><person><name>Arun</name></person> + + +HTTP/1.1 200 OK +Date: Mon, 01 Dec 2008 01:15:40 GMT +Server: Apache/2.0.61 (Unix) +Access-Control-Allow-Origin: http://foo.example +Vary: Accept-Encoding, Origin +Content-Encoding: gzip +Content-Length: 235 +Keep-Alive: timeout=2, max=99 +Connection: Keep-Alive +Content-Type: text/plain + +[Some GZIP'd payload] +</pre> + +<p>Lines 1 - 12 above represent the preflight request with the {{HTTPMethod("OPTIONS")}} method. The browser determines that it needs to send this based on the request parameters that the JavaScript code snippet above was using, so that the server can respond whether it is acceptable to send the request with the actual request parameters. OPTIONS is an HTTP/1.1 method that is used to determine further information from servers, and is a {{Glossary("safe")}} method, meaning that it can't be used to change the resource. Note that along with the OPTIONS request, two other request headers are sent (lines 10 and 11 respectively):</p> + +<pre class="brush: none">Access-Control-Request-Method: POST +Access-Control-Request-Headers: X-PINGOTHER, Content-Type +</pre> + +<p>The {{HTTPHeader("Access-Control-Request-Method")}} header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a <code>POST</code> request method. The {{HTTPHeader("Access-Control-Request-Headers")}} header notifies the server that when the actual request is sent, it will be sent with a <code>X-PINGOTHER</code> and <code>Content-Type</code> custom headers. The server now has an opportunity to determine whether it wishes to accept a request under these circumstances.</p> + +<p>Lines 14 - 26 above are the response that the server sends back indicating that the request method (<code>POST</code>) and request headers (<code>X-PINGOTHER</code>) are acceptable. In particular, let's look at lines 17-20:</p> + +<pre class="brush: none">Access-Control-Allow-Origin: http://foo.example +Access-Control-Allow-Methods: POST, GET +Access-Control-Allow-Headers: X-PINGOTHER, Content-Type +Access-Control-Max-Age: 86400</pre> + +<p>The server responds with <code>Access-Control-Allow-Methods</code> and says that <code>POST</code> and <code>GET</code> are viable methods to query the resource in question. Note that this header is similar to the {{HTTPHeader("Allow")}} response header, but used strictly within the context of access control.</p> + +<p>The server also sends <code>Access-Control-Allow-Headers</code> with a value of "<code>X-PINGOTHER, Content-Type</code>", confirming that these are permitted headers to be used with the actual request. Like <code>Access-Control-Allow-Methods</code>, <code>Access-Control-Allow-Headers</code> is a comma separated list of acceptable headers.</p> + +<p>Finally, {{HTTPHeader("Access-Control-Max-Age")}} gives the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request. In this case, 86400 seconds is 24 hours. Note that each browser has a <a href="/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age">maximum internal value</a> that takes precedence when the <code>Access-Control-Max-Age</code> is greater.</p> + +<h4 id="Preflighted_requests_and_redirects">Preflighted requests and redirects</h4> + +<p>Not all browsers currently support following redirects after a preflighted request. If a redirect occurs after a preflighted request, some browsers currently will report an error message such as the following.</p> + +<blockquote> +<p>The request was redirected to 'https://example.com/foo', which is disallowed for cross-origin requests that require preflight</p> +</blockquote> + +<blockquote> +<p>Request requires preflight, which is disallowed to follow cross-origin redirect</p> +</blockquote> + +<p>The CORS protocol originally required that behavior but <a href="https://github.com/whatwg/fetch/commit/0d9a4db8bc02251cc9e391543bb3c1322fb882f2">was subsequently changed to no longer require it</a>. However, not all browsers have implemented the change, and so still exhibit the behavior that was originally required.</p> + +<p>So until all browsers catch up with the spec, you may be able to work around this limitation by doing one or both of the following:</p> + +<ul> + <li>change the server-side behavior to avoid the preflight and/or to avoid the redirect—if you have control over the server the request is being made to</li> + <li>change the request such that it is a <a href="#Simple_requests">simple request</a> that doesn’t cause a preflight</li> +</ul> + +<p>But if it’s not possible to make those changes, then another way that may be possible is to this:</p> + +<ol> + <li>Make a <a href="#Simple_requests">simple request</a> (using {{domxref("Response.url")}} for the Fetch API, or {{domxref("XMLHttpRequest.responseURL")}}) to determine what URL the real preflighted request would end up at.</li> + <li>Make another request (the “real” request) using the URL you obtained from <code>Response.url</code> or <code>XMLHttpRequest.responseURL</code> in the first step.</li> +</ol> + +<p>However, if the request is one that triggers a preflight due to the presence of the <code>Authorization</code> header in the request, you won’t be able to work around the limitation using the steps above. And you won’t be able to work around it at all unless you have control over the server the request is being made to.</p> + +<h3 id="Requests_with_credentials">Requests with credentials</h3> + +<p>The most interesting capability exposed by both {{domxref("XMLHttpRequest")}} or <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a> and CORS is the ability to make "credentialed" requests that are aware of <a href="/en-US/docs/Web/HTTP/Cookies">HTTP cookies</a> and HTTP Authentication information. By default, in cross-site <code>XMLHttpRequest</code> or <a href="/en-US/docs/Web/API/Fetch_API">Fetch</a> invocations, browsers will <strong>not</strong> send credentials. A specific flag has to be set on the <code>XMLHttpRequest</code> object or the {{domxref("Request")}} constructor when it is invoked.</p> + +<p>In this example, content originally loaded from <code class="plain">http://foo.example</code> makes a simple GET request to a resource on <code class="plain">http://bar.other</code> which sets Cookies. Content on foo.example might contain JavaScript like this:</p> + +<pre class="brush: js" id="line1">const invocation = new XMLHttpRequest(); +const url = 'http://bar.other/resources/credentialed-content/'; + +function callOtherDomain(){ + if(invocation) { + invocation.open('GET', url, true); + invocation.withCredentials = true; + invocation.onreadystatechange = handler; + invocation.send(); + } +}</pre> + +<p>Line 7 shows the flag on {{domxref("XMLHttpRequest")}} that has to be set in order to make the invocation with Cookies, namely the <code>withCredentials</code> boolean value. By default, the invocation is made without Cookies. Since this is a simple <code>GET</code> request, it is not preflighted, but the browser will <strong>reject</strong> any response that does not have the {{HTTPHeader("Access-Control-Allow-Credentials")}}<code>: true</code> header, and <strong>not</strong> make the response available to the invoking web content.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14291/cred-req.png" style="height: 223px; width: 521px;"></p> + +<p>Here is a sample exchange between client and server:</p> + +<pre class="brush: none">GET /resources/access-control-with-credentials/ HTTP/1.1 +Host: bar.other +User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre +Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 +Accept-Language: en-us,en;q=0.5 +Accept-Encoding: gzip,deflate +Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 +Connection: keep-alive +Referer: http://foo.example/examples/credential.html +Origin: http://foo.example +Cookie: pageAccess=2 + + +HTTP/1.1 200 OK +Date: Mon, 01 Dec 2008 01:34:52 GMT +Server: Apache/2.0.61 (Unix) PHP/4.4.7 mod_ssl/2.0.61 OpenSSL/0.9.7e mod_fastcgi/2.4.2 DAV/2 SVN/1.4.2 +X-Powered-By: PHP/5.2.6 +Access-Control-Allow-Origin: http://foo.example +Access-Control-Allow-Credentials: true +Cache-Control: no-cache +Pragma: no-cache +Set-Cookie: pageAccess=3; expires=Wed, 31-Dec-2008 01:34:53 GMT +Vary: Accept-Encoding, Origin +Content-Encoding: gzip +Content-Length: 106 +Keep-Alive: timeout=2, max=100 +Connection: Keep-Alive +Content-Type: text/plain + + +[text/plain payload] +</pre> + +<p>Although line 11 contains the Cookie destined for the content on <code class="plain">http://bar.other</code>, if bar.other did not respond with an {{HTTPHeader("Access-Control-Allow-Credentials")}}<code>: true</code> (line 19) the response would be ignored and not made available to web content.</p> + +<h4 id="Credentialed_requests_and_wildcards">Credentialed requests and wildcards</h4> + +<p>When responding to a credentialed request, the server <strong>must</strong> specify an origin in the value of the <code>Access-Control-Allow-Origin</code> header, instead of specifying the "<code>*</code>" wildcard.</p> + +<p>Because the request headers in the above example include a <code>Cookie</code> header, the request would fail if the value of the <code>Access-Control-Allow-Origin</code> header were "*". But it does not fail: Because the value of the <code>Access-Control-Allow-Origin</code> header is "<code class="plain">http://foo.example</code>" (an actual origin) rather than the "<code>*</code>" wildcard, the credential-cognizant content is returned to the invoking web content.</p> + +<p>Note that the <code>Set-Cookie</code> response header in the example above also sets a further cookie. In case of failure, an exception—depending on the API used—is raised.</p> + +<h4 id="Third-party_cookies">Third-party cookies</h4> + +<p>Note that cookies set in CORS responses are subject to normal third-party cookie policies. In the example above, the page is loaded from <code>foo.example</code>, but the cookie on line 22 is sent by <code>bar.other</code>, and would thus not be saved if the user has configured their browser to reject all third-party cookies.</p> + +<h2 id="The_HTTP_response_headers">The HTTP response headers</h2> + +<p>This section lists the HTTP response headers that servers send back for access control requests as defined by the Cross-Origin Resource Sharing specification. The previous section gives an overview of these in action.</p> + +<h3 id="Access-Control-Allow-Origin">Access-Control-Allow-Origin</h3> + +<p>A returned resource may have one {{HTTPHeader("Access-Control-Allow-Origin")}} header, with the following syntax:</p> + +<pre class="brush: none">Access-Control-Allow-Origin: <origin> | * +</pre> + +<p><code>Access-Control-Allow-Origin</code> specifies either a single origin, which tells browsers to allow that origin to access the resource; or else — for requests <strong>without</strong> credentials — the "<code>*</code>" wildcard, to tell browsers to allow any origin to access the resource.</p> + +<p>For example, to allow code from the origin <code>http://mozilla.org</code> to access the resource, you can specify:</p> + +<pre class="brush: none">Access-Control-Allow-Origin: http://mozilla.org</pre> + +<p>If the server specifies a single origin rather than the "<code>*</code>" wildcard, then the server should also include <code>Origin</code> in the {{HTTPHeader("Vary")}} response header — to indicate to clients that server responses will differ based on the value of the {{HTTPHeader("Origin")}} request header.</p> + +<h3 id="Access-Control-Expose-Headers">Access-Control-Expose-Headers</h3> + +<p>The {{HTTPHeader("Access-Control-Expose-Headers")}} header lets a server whitelist headers that browsers are allowed to access.</p> + +<pre class="brush: none">Access-Control-Expose-Headers: <field-name>[, <field-name>]* +</pre> + +<p>For example, the following:</p> + +<pre class="brush: none">Access-Control-Expose-Headers: X-My-Custom-Header, X-Another-Custom-Header +</pre> + +<p>…would allow the <code>X-My-Custom-Header</code> and <code>X-Another-Custom-Header</code> headers to be exposed to the browser.</p> + +<h3 id="Access-Control-Max-Age">Access-Control-Max-Age</h3> + +<p>The {{HTTPHeader("Access-Control-Max-Age")}} header indicates how long the results of a preflight request can be cached. For an example of a preflight request, see the above examples.</p> + +<pre class="brush: none">Access-Control-Max-Age: <delta-seconds> +</pre> + +<p>The <code>delta-seconds</code> parameter indicates the number of seconds the results can be cached.</p> + +<h3 id="Access-Control-Allow-Credentials">Access-Control-Allow-Credentials</h3> + +<p>The {{HTTPHeader("Access-Control-Allow-Credentials")}} header Indicates whether or not the response to the request can be exposed when the <code>credentials</code> flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple <code>GET</code> requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser and not returned to web content.</p> + +<pre class="brush: none">Access-Control-Allow-Credentials: true +</pre> + +<p><a class="internal" href="#Requests_with_credentials">Credentialed requests</a> are discussed above.</p> + +<h3 id="Access-Control-Allow-Methods">Access-Control-Allow-Methods</h3> + +<p>The {{HTTPHeader("Access-Control-Allow-Methods")}} header specifies the method or methods allowed when accessing the resource. This is used in response to a preflight request. The conditions under which a request is preflighted are discussed above.</p> + +<pre class="brush: none">Access-Control-Allow-Methods: <method>[, <method>]* +</pre> + +<p>An example of a <a class="internal" href="#Preflighted_requests">preflight request is given above</a>, including an example which sends this header to the browser.</p> + +<h3 id="Access-Control-Allow-Headers">Access-Control-Allow-Headers</h3> + +<p>The {{HTTPHeader("Access-Control-Allow-Headers")}} header is used in response to a <a class="internal" href="#Preflighted_requests">preflight request</a> to indicate which HTTP headers can be used when making the actual request.</p> + +<pre class="brush: none">Access-Control-Allow-Headers: <field-name>[, <field-name>]* +</pre> + +<h2 id="The_HTTP_request_headers">The HTTP request headers</h2> + +<p>This section lists headers that clients may use when issuing HTTP requests in order to make use of the cross-origin sharing feature. Note that these headers are set for you when making invocations to servers. Developers using cross-site {{domxref("XMLHttpRequest")}} capability do not have to set any cross-origin sharing request headers programmatically.</p> + +<h3 id="Origin">Origin</h3> + +<p>The {{HTTPHeader("Origin")}} header indicates the origin of the cross-site access request or preflight request.</p> + +<pre class="brush: none">Origin: <origin> +</pre> + +<p>The origin is a URI indicating the server from which the request initiated. It does not include any path information, but only the server name.</p> + +<div class="note"><strong>Note:</strong> The <code>origin</code> value can be <code>null</code>, or a URI.</div> + +<p>Note that in any access control request, the {{HTTPHeader("Origin")}} header is <strong>always</strong> sent.</p> + +<h3 id="Access-Control-Request-Method">Access-Control-Request-Method</h3> + +<p>The {{HTTPHeader("Access-Control-Request-Method")}} is used when issuing a preflight request to let the server know what HTTP method will be used when the actual request is made.</p> + +<pre class="brush: none">Access-Control-Request-Method: <method> +</pre> + +<p>Examples of this usage can be <a class="internal" href="#Preflighted_requests">found above.</a></p> + +<h3 id="Access-Control-Request-Headers">Access-Control-Request-Headers</h3> + +<p>The {{HTTPHeader("Access-Control-Request-Headers")}} header is used when issuing a preflight request to let the server know what HTTP headers will be used when the actual request is made.</p> + +<pre class="brush: none">Access-Control-Request-Headers: <field-name>[, <field-name>]* +</pre> + +<p>Examples of this usage can be <a class="internal" href="#Preflighted_requests">found above</a>.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Fetch', '#cors-protocol', 'CORS')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td>New definition; supplants <a href="https://www.w3.org/TR/cors/">W3C CORS</a> specification.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("http.headers.Access-Control-Allow-Origin")}}</p> + +<h3 id="Compatibility_notes">Compatibility notes</h3> + +<ul> + <li>Internet Explorer 8 and 9 expose CORS via the <code>XDomainRequest</code> object, but have a full implementation in IE 10.</li> + <li>While Firefox 3.5 introduced support for cross-site <code>XMLHttpRequests</code> and Web Fonts, certain requests were limited until later versions. Specifically, Firefox 7 introduced the ability for cross-site HTTP requests for WebGL Textures, and Firefox 9 added support for Images drawn on a canvas using <code>drawImage()</code>.</li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/HTTP/CORS/Errors">CORS errors</a></li> + <li><a href="https://enable-cors.org/server.html">Enable CORS: I want to add CORS support to my server</a></li> + <li>{{domxref("XMLHttpRequest")}}</li> + <li><a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a></li> + <li><a class="external" href="http://www.kendoui.com/blogs/teamblog/posts/11-10-03/using_cors_with_all_modern_browsers.aspx">Using CORS with All (Modern) Browsers</a></li> + <li><a href="http://www.html5rocks.com/en/tutorials/cors/">Using CORS - HTML5 Rocks</a> + <ul> + </ul> + </li> + <li><a class="external" href="https://arunranga.com/examples/access-control/">Code Samples Showing <code>XMLHttpRequest</code> and Cross-Origin Resource Sharing</a></li> + <li><a href="https://github.com/jackblackevo/cors-jsonp-sample">Client-Side & Server-Side (Java) sample for Cross-Origin Resource Sharing (CORS)</a></li> + <li><a class="internal" href="/en-US/docs/Web/HTTP/Server-Side_Access_Control">Cross-Origin Resource Sharing From a Server-Side Perspective (PHP, etc.)</a></li> + <li><a href="https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141">Stack Overflow answer with “how to” info for dealing with common problems</a>: + <ul> + <li>How to avoid the CORS preflight</li> + <li>How to use a CORS proxy to get around <em>“No Access-Control-Allow-Origin header”</em></li> + <li>How to fix <em>“Access-Control-Allow-Origin header must not be the wildcard”</em></li> + </ul> + </li> +</ul> diff --git a/files/pt-pt/web/http/headers/allow/index.html b/files/pt-pt/web/http/headers/allow/index.html new file mode 100644 index 0000000000..8582cb58f4 --- /dev/null +++ b/files/pt-pt/web/http/headers/allow/index.html @@ -0,0 +1,67 @@ +--- +title: Allow +slug: Web/HTTP/Headers/Allow +tags: + - Cabeçalho de Entidade + - Cabeçalho de HTTP + - HTTP + - Referencia + - cabeçalho +translation_of: Web/HTTP/Headers/Allow +--- +<div>{{HTTPSidebar}}</div> + +<p>O cabeçalho <code><strong>Allow</strong></code> lista os métodos que um recurso suporta.</p> + +<p>Este cabeçalho deve ser enviado se o servidor responder com um código de estado {{HTTPStatus("405")}} <code>Method Not Allowed</code> para indicar que métodos de pedido podem ser utilizados. Um cabeçalho <code>Allowed</code> vazio indica que o recurso não permite métodos de pedido, que podem ocorrer temporariamente para um dado recurso, por exemplo.</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Categoria de cabeçalho</th> + <td>{{Glossary("Entity header")}}</td> + </tr> + <tr> + <th scope="row">{{Glossary("Forbidden header name")}}</th> + <td>não</td> + </tr> + </tbody> +</table> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">Allow: <métodos-de-http> +</pre> + +<h2 id="Diretivos">Diretivos</h2> + +<dl> + <dt><métodos-de-http></dt> + <dd>Uma lista de <a href="/en-US/docs/Web/HTTP/Methods">métodos de pedido HTTP</a> permitidos separados por vírgulas.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="notranslate">Allow: GET, POST, HEAD</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Titulo</th> + </tr> + <tr> + <td>{{RFC("7231", "Allow", "7.4.1")}}</td> + <td>Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content</td> + </tr> + </tbody> +</table> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{HTTPStatus("405")}}</li> + <li>{{HTTPHeader("Server")}}</li> +</ul> diff --git a/files/pt-pt/web/http/headers/index.html b/files/pt-pt/web/http/headers/index.html new file mode 100644 index 0000000000..31ccf98f9f --- /dev/null +++ b/files/pt-pt/web/http/headers/index.html @@ -0,0 +1,360 @@ +--- +title: HTTP headers +slug: Web/HTTP/Headers +tags: + - HTTP + - Headers + - NeedsTranslation + - Networking + - Reference + - TopicStub +translation_of: Web/HTTP/Headers +--- +<div>{{HTTPSidebar}}</div> + +<p>HTTP headers allow the client and the server to pass additional information with the request or the response. A request header consists of its case-insensitive name followed by a colon '<code>:</code>', then by its value (without line breaks). Leading white space before the value is ignored.</p> + +<p>Custom proprietary headers can be added using the 'X-' prefix, but this convention was deprecated in June 2012, because of the inconveniences it caused when non-standard fields became standard in <a href="https://tools.ietf.org/html/rfc6648">RFC 6648</a>; others are listed in an <a class="external" href="http://www.iana.org/assignments/message-headers/perm-headers.html">IANA registry</a>, whose original content was defined in <a class="external" href="http://tools.ietf.org/html/rfc4229">RFC 4229</a>. IANA also maintains a <a class="external" href="http://www.iana.org/assignments/message-headers/prov-headers.html">registry of proposed new HTTP message headers</a>.</p> + +<p>Headers can be grouped according to their contexts:</p> + +<ul> + <li>{{Glossary("General header")}}: Headers applying to both requests and responses but with no relation to the data eventually transmitted in the body.</li> + <li>{{Glossary("Request header")}}: Headers containing more information about the resource to be fetched or about the client itself.</li> + <li>{{Glossary("Response header")}}: Headers with additional information about the response, like its location or about the server itself (name and version etc.).</li> + <li>{{Glossary("Entity header")}}: Headers containing more information about the body of the entity, like its content length or its MIME-type.</li> +</ul> + +<p>Headers can also be grouped according to how proxies handle them:</p> + +<dl> + <dt><a id="e2e" name="e2e"></a>End-to-end headers</dt> + <dd>These headers must be transmitted to the final recipient of the message; that is, the server for a request or the client for a response. Intermediate proxies must retransmit end-to-end headers unmodified and caches must store them.</dd> + <dt><a id="hbh" name="hbh"></a>Hop-by-hop headers</dt> + <dd>These headers are meaningful only for a single transport-level connection and must not be retransmitted by proxies or cached. Such headers are: {{ httpheader("Connection") }}, {{ httpheader("Keep-Alive") }}, {{ httpheader("Proxy-Authenticate") }}, {{ httpheader("Proxy-Authorization") }}, {{ httpheader("TE") }}, {{ httpheader("Trailer") }}, {{ httpheader("Transfer-Encoding") }} and {{ httpheader("Upgrade") }}. Note that only hop-by-hop headers may be set using the {{ httpheader("Connection") }} general header.</dd> +</dl> + +<p>The following list summaries HTTP headers by their usage category. For an alphabetical list, see the navigation on the left side.</p> + +<h2 id="Authentication">Authentication</h2> + +<dl> + <dt>{{HTTPHeader("WWW-Authenticate")}}</dt> + <dd>Defines the authentication method that should be used to gain access to a resource.</dd> + <dt>{{HTTPHeader("Authorization")}}</dt> + <dd>Contains the credentials to authenticate a user agent with a server.</dd> + <dt>{{HTTPHeader("Proxy-Authenticate")}}</dt> + <dd>Defines the authentication method that should be used to gain access to a resource behind a Proxy server.</dd> + <dt>{{HTTPHeader("Proxy-Authorization")}}</dt> + <dd>Contains the credentials to authenticate a user agent with a proxy server.</dd> +</dl> + +<h2 id="Caching">Caching</h2> + +<dl> + <dt>{{HTTPHeader("Age")}}</dt> + <dd>The time in seconds the object has been in a proxy cache.</dd> + <dt>{{HTTPHeader("Cache-Control")}}</dt> + <dd>Specifies directives for caching mechanisms in both, requests and responses.</dd> + <dt>{{HTTPHeader("Expires")}}</dt> + <dd>The date/time after which the response is considered stale.</dd> + <dt>{{HTTPHeader("Pragma")}}</dt> + <dd>Implementation-specific header that may have various effects anywhere along the request-response chain. Used for backwards compatibility with HTTP/1.0 caches where the <code>Cache-Control</code> header is not yet present.</dd> + <dt>{{HTTPHeader("Warning")}}</dt> + <dd>A general warning field containing information about possible problems.</dd> +</dl> + +<h2 id="Client_hints">Client hints</h2> + +<dl> + <dt>{{HTTPHeader("Accept-CH")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Content-DPR")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("DPR")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Downlink")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Save-Data")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Viewport-Width")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Width")}}</dt> + <dd>...</dd> +</dl> + +<dl> + <dt> + <h2 id="Conditionals">Conditionals</h2> + </dt> + <dt>{{HTTPHeader("Last-Modified")}}</dt> + <dd>It is a validator, the last modification date of the resource, used to compare several versions of the same resource. It is less accurate than {{HTTPHeader("ETag")}}, but easier to calculate in some environments. Conditional requests using {{HTTPHeader("If-Modified-Since")}} and {{HTTPHeader("If-Unmodified-Since")}} use this value to change the behavior of the request.</dd> + <dt>{{HTTPHeader("ETag")}}</dt> + <dd>It is a validator, a unique string identifying the version of the resource. Conditional requests using {{HTTPHeader("If-Match")}} and {{HTTPHeader("If-None-Match")}} use this value to change the behavior of the request.</dd> + <dt>{{HTTPHeader("If-Match")}}</dt> + <dd>Makes the request conditional and applies the method only if the stored resource matches one of the given ETags.</dd> + <dt>{{HTTPHeader("If-None-Match")}}</dt> + <dd>Makes the request conditional and applies the method only if the stored resource doesn't match any of the given ETags. This is used to update caches (for safe requests), or to prevent to upload a new resource when one is already existing.</dd> + <dt>{{HTTPHeader("If-Modified-Since")}}</dt> + <dd>Makes the request conditional and expects the entity to be transmitted only if it has been modified after the given date. This is used to transmit data only when the cache is out of date.</dd> + <dt>{{HTTPHeader("If-Unmodified-Since")}}</dt> + <dd>Makes the request conditional and expects the entity to be transmitted only if it has not been modified after the given date. This is used to ensure the coherence of a new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents.</dd> +</dl> + +<h2 id="Connection_management">Connection management</h2> + +<dl> + <dt>{{HTTPHeader("Connection")}}</dt> + <dd>Controls whether or not the network connection stays open after the current transaction finishes.</dd> + <dt>{{HTTPHeader("Keep-Alive")}}</dt> + <dd>Controls how long a persistent connection should stay open.</dd> +</dl> + +<h2 id="Content_negotiation">Content negotiation</h2> + +<dl> + <dt>{{HTTPHeader("Accept")}}</dt> + <dd>Informs the server about the types of data that can be sent back. It is MIME-type.</dd> + <dt>{{HTTPHeader("Accept-Charset")}}</dt> + <dd>Informs the server about which character set the client is able to understand.</dd> + <dt>{{HTTPHeader("Accept-Encoding")}}</dt> + <dd>Informs the server about the encoding algorithm, usually a compression algorithm, that can be used on the resource sent back.</dd> + <dt>{{HTTPHeader("Accept-Language")}}</dt> + <dd>Informs the server about the language the server is expected to send back. This is a hint and is not necessarily under the full control of the user: the server should always pay attention not to override an explicit user choice (like selecting a language in a drop down list).</dd> +</dl> + +<dl> +</dl> + +<h2 id="Controls">Controls</h2> + +<dl> + <dt>{{HTTPHeader("Expect")}}</dt> + <dd>Indicates expectations that need to be fulfilled by the server in order to properly handle the request.</dd> + <dt>{{HTTPHeader("Max-Forwards")}}</dt> + <dd>...</dd> +</dl> + +<h2 id="Cookies">Cookies</h2> + +<dl> + <dt>{{HTTPHeader("Cookie")}}</dt> + <dd>Contains stored <a href="/en-US/docs/Web/HTTP/Cookies">HTTP cookies</a> previously sent by the server with the {{HTTPHeader("Set-Cookie")}} header.</dd> + <dt>{{HTTPHeader("Set-Cookie")}}</dt> + <dd>Send cookies from the server to the user agent.</dd> + <dt>{{HTTPHeader("Cookie2")}} {{obsolete_inline}}</dt> + <dd>Used to contain an HTTP cookie, previously sent by the server with the {{HTTPHeader("Set-Cookie2")}} header, but has been obsoleted by the specification. Use {{HTTPHeader("Cookie")}} instead.</dd> + <dt>{{HTTPHeader("Set-Cookie2")}} {{obsolete_inline}}</dt> + <dd>Used to send cookies from the server to the user agent, but has been obsoleted by the specification. Use {{HTTPHeader("Set-Cookie")}} instead.</dd> + <dt> + <h2 id="CORS">CORS</h2> + </dt> + <dt>{{HTTPHeader("Access-Control-Allow-Origin")}}</dt> + <dd>Indicates whether the response can be shared.</dd> + <dt>{{HTTPHeader("Access-Control-Allow-Credentials")}}</dt> + <dd>Indicates whether or not the response to the request can be exposed when the credentials flag is true.</dd> + <dt>{{HTTPHeader("Access-Control-Allow-Headers")}}</dt> + <dd>Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.</dd> + <dt>{{HTTPHeader("Access-Control-Allow-Methods")}}</dt> + <dd>Specifies the method or methods allowed when accessing the resource in response to a preflight request.</dd> + <dt>{{HTTPHeader("Access-Control-Expose-Headers")}}</dt> + <dd>Indicates which headers can be exposed as part of the response by listing their names.</dd> + <dt>{{HTTPHeader("Access-Control-Max-Age")}}</dt> + <dd>Indicates how long the results of a preflight request can be cached.</dd> + <dt>{{HTTPHeader("Access-Control-Request-Headers")}}</dt> + <dd>Used when issuing a preflight request to let the server know which HTTP headers will be used when the actual request is made.</dd> + <dt>{{HTTPHeader("Access-Control-Request-Method")}}</dt> + <dd>Used when issuing a preflight request to let the server know which <a href="/en-US/docs/Web/HTTP/Methods">HTTP method</a> will be used when the actual request is made.</dd> + <dt>{{HTTPHeader("Origin")}}</dt> + <dd>Indicates where a fetch originates from.</dd> +</dl> + +<h2 id="Do_Not_Track">Do Not Track</h2> + +<dl> + <dt>{{HTTPHeader("DNT")}}</dt> + <dd>Used for expressing the user's tracking preference.</dd> + <dt>{{HTTPHeader("Tk")}}</dt> + <dd>Indicates the tracking status that applied to the corresponding request.</dd> +</dl> + +<h2 id="Downloads">Downloads</h2> + +<dl> + <dt>{{HTTPHeader("Content-Disposition")}}</dt> + <dd>Is a response header if the resource transmitted should be displayed inline (default behavior when the header is not present), or it should be handled like a download and the browser should present a 'Save As' window.</dd> +</dl> + +<h2 id="Message_body_information">Message body information</h2> + +<dl> + <dt>{{HTTPHeader("Content-Length")}}</dt> + <dd>indicates the size of the entity-body, in decimal number of octets, sent to the recipient.</dd> + <dt>{{HTTPHeader("Content-Type")}}</dt> + <dd>Indicates the media type of the resource.</dd> + <dt>{{HTTPHeader("Content-Encoding")}}</dt> + <dd>Used to specify the compression algorithm.</dd> + <dt>{{HTTPHeader("Content-Language")}}</dt> + <dd>Describes the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language.</dd> + <dt>{{HTTPHeader("Content-Location")}}</dt> + <dd>Indicates an alternate location for the returned data.</dd> + <dt> + <h2 id="Proxies">Proxies</h2> + </dt> +</dl> + +<dl> + <dt>{{HTTPHeader("Forwarded")}}</dt> + <dd>Contains information from the client-facing side of proxy servers that is altered or lost when a proxy is involved in the path of the request.</dd> + <dt>{{HTTPHeader("X-Forwarded-For")}} {{non-standard_inline}}</dt> + <dd>Identifies the originating IP addresses of a client connecting to a web server through an HTTP proxy or a load balancer.</dd> + <dt>{{HTTPHeader("X-Forwarded-Host")}} {{non-standard_inline}}</dt> + <dd>Identifies the original host requested that a client used to connect to your proxy or load balancer.</dd> + <dt>{{HTTPHeader("X-Forwarded-Proto")}} {{non-standard_inline}}</dt> + <dd>identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer.</dd> + <dt>{{HTTPHeader("Via")}}</dt> + <dd>Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers.</dd> +</dl> + +<h2 id="Redirects">Redirects</h2> + +<dl> + <dt>{{HTTPHeader("Location")}}</dt> + <dd>Indicates the URL to redirect a page to.</dd> +</dl> + +<h2 id="Request_context">Request context</h2> + +<dl> + <dt>{{HTTPHeader("From")}}</dt> + <dd>Contains an Internet email address for a human user who controls the requesting user agent.</dd> + <dt>{{HTTPHeader("Host")}}</dt> + <dd>Specifies the domain name of the server (for virtual hosting), and (optionally) the TCP port number on which the server is listening.</dd> + <dt>{{HTTPHeader("Referer")}}</dt> + <dd>The address of the previous web page from which a link to the currently requested page was followed.</dd> + <dt>{{HTTPHeader("Referrer-Policy")}}</dt> + <dd>Governs which referrer information sent in the {{HTTPHeader("Referer")}} header should be included with requests made.</dd> + <dt>{{HTTPHeader("User-Agent")}}</dt> + <dd>Contains a characteristic string that allows the network protocol peers to identify the application type, operating system, software vendor or software version of the requesting software user agent. See also the <a href="/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox">Firefox user agent string reference</a>.</dd> +</dl> + +<h2 id="Response_context">Response context</h2> + +<dl> + <dt>{{HTTPHeader("Allow")}}</dt> + <dd>Lists the set of HTTP request methods support by a resource.</dd> + <dt>{{HTTPHeader("Server")}}</dt> + <dd>Contains information about the software used by the origin server to handle the request.</dd> +</dl> + +<h2 id="Range_requests">Range requests</h2> + +<dl> + <dt>{{HTTPHeader("Accept-Ranges")}}</dt> + <dd>Indicates if the server supports range requests and if so, in which unit the range can be expressed.</dd> + <dt>{{HTTPHeader("Range")}}</dt> + <dd>Indicates the part of a document that the server should return.</dd> + <dt>{{HTTPHeader("If-Range")}}</dt> + <dd>Creates a conditional range request that is only fulfilled if the given etag or date matches the remote resource. Used to prevent downloading two ranges from incompatible version of the resource.</dd> + <dt>{{HTTPHeader("Content-Range")}}</dt> + <dd>Indicates where in a full body message a partial message belongs.</dd> +</dl> + +<h2 id="Security">Security</h2> + +<dl> + <dt>{{HTTPHeader("Content-Security-Policy")}} ({{Glossary("CSP")}})</dt> + <dd>Controls resources the user agent is allowed to load for a given page.</dd> + <dt>{{HTTPHeader("Content-Security-Policy-Report-Only")}}</dt> + <dd>Allows web developers to experiment with policies by monitoring (but not enforcing) their effects. These violation reports consist of {{Glossary("JSON")}} documents sent via an HTTP <code>POST</code> request to the specified URI.</dd> + <dt>{{HTTPHeader("Public-Key-Pins")}} ({{Glossary("HPKP")}})</dt> + <dd>Associates a specific cryptographic public key with a certain web server to decrease the risk of {{Glossary("MITM")}} attacks with forged certificates.</dd> + <dt>{{HTTPHeader("Public-Key-Pins-Report-Only")}}</dt> + <dd>Sends reports to the report-uri specified in the header and does still allow clients to connect to the server even if the pinning is violated.</dd> +</dl> + +<dl> + <dt>{{HTTPHeader("Strict-Transport-Security")}} ({{Glossary("HSTS")}})</dt> + <dd>Force communication using HTTPS instead of HTTP.</dd> + <dt>{{HTTPHeader("Upgrade-Insecure-Requests")}}</dt> + <dd>Sends a signal to the server expressing the client’s preference for an encrypted and authenticated response, and that it can successfully handle the {{CSP("upgrade-insecure-requests")}} directive.</dd> +</dl> + +<dl> + <dt>{{HTTPHeader("X-Content-Type-Options")}}</dt> + <dd>Disables MIME sniffing and forces browser to use the type given in {{HTTPHeader("Content-Type")}}.</dd> +</dl> + +<dl> + <dt>{{HTTPHeader("X-Frame-Options")}} (XFO)</dt> + <dd>Indicates whether or not a browser should be allowed to render a page in a {{HTMLElement("frame")}}, {{HTMLElement("iframe")}} or {{HTMLElement("object")}}</dd> + <dt>{{HTTPHeader("X-XSS-Protection")}}</dt> + <dd>Enables cross-site scripting filtering.</dd> +</dl> + +<h2 id="Server-sent_events">Server-sent events</h2> + +<dl> + <dt>{{HTTPHeader("Ping-From")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Ping-To")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Last-Event-ID")}}</dt> + <dd>...</dd> +</dl> + +<h2 id="Transfer_coding">Transfer coding</h2> + +<dl> + <dt>{{HTTPHeader("Transfer-Encoding")}}</dt> + <dd>Specifies the the form of encoding used to safely transfer the entity to the user.</dd> + <dt>{{HTTPHeader("TE")}}</dt> + <dd>Specifies the transfer encodings the user agent is willing to accept.</dd> + <dt>{{HTTPHeader("Trailer")}}</dt> + <dd>Allows the sender to include additional fields at the end of chunked message.</dd> +</dl> + +<h2 id="WebSockets">WebSockets</h2> + +<dl> + <dt>{{HTTPHeader("Sec-WebSocket-Key")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Sec-WebSocket-Extensions")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Sec-WebSocket-Accept")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Sec-WebSocket-Protocol")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Sec-WebSocket-Version")}}</dt> + <dd>...</dd> +</dl> + +<h2 id="Other">Other</h2> + +<dl> + <dt>{{HTTPHeader("Date")}}</dt> + <dd>Contains the date and time at which the message was originated.</dd> + <dt>{{HTTPHeader("Large-Allocation")}}</dt> + <dd>Tells the browser that the page being loaded is going to want to perform a large allocation.</dd> + <dt>{{HTTPHeader("Link")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("Retry-After")}}</dt> + <dd>Indicates how long the user agent should wait before making a follow-up request.</dd> + <dt>{{HTTPHeader("Upgrade")}}</dt> + <dd>This is a Proposed Internet Standard. To view a comprehensive list of all Official and Proposed Internet Standards with detailed information about each, <a href="https://www.rfc-editor.org/standards">visit this Internet Standards reference</a>, which is updated daily. The relevant RFC document for the <a href="https://tools.ietf.org/html/rfc7230#section-6.7">Upgrade header field standard is RFC 7230, section 6.7</a>. The standard establishes rules for upgrading or changing to a different protocol on the current client, server, transport protocol connection. For example, this header standard allows a client to change from HTTP 1.1 to HTTP 2.0, assuming the server decides to acknowledge and implement the Upgrade header field. Niether party is required to accept the terms specified in the Upgrade header field. It can be used in both client and server headers. If the Upgrade header field is specified, then the sender MUST also send the Connection header field with the upgrade option specified. For details on the Connection header field <a href="https://tools.ietf.org/html/rfc7230#section-6.1">please see section 6.1 of the aforementioned RFC</a>.</dd> + <dt>{{HTTPHeader("Vary")}}</dt> + <dd>Determines how to match future request headers to decide whether a cached response can be used rather than requesting a fresh one from the origin server.</dd> + <dt>{{HTTPHeader("X-DNS-Prefetch-Control")}}</dt> + <dd>Controls DNS prefetching, a feature by which browsers proactively perform domain name resolution on both links that the user may choose to follow as well as URLs for items referenced by the document, including images, CSS, JavaScript, and so forth.</dd> + <dt>{{HTTPHeader("X-Requested-With")}}</dt> + <dd>...</dd> + <dt>{{HTTPHeader("X-UA-Compatible")}}</dt> + <dd>...</dd> +</dl> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields">Wikipedia page on List of HTTP headers</a></li> + <li><a href="https://www.iana.org/assignments/message-headers/perm-headers.html">IANA registry</a></li> +</ul> diff --git a/files/pt-pt/web/http/headers/x-content-type-options/index.html b/files/pt-pt/web/http/headers/x-content-type-options/index.html new file mode 100644 index 0000000000..c237f7b7cf --- /dev/null +++ b/files/pt-pt/web/http/headers/x-content-type-options/index.html @@ -0,0 +1,83 @@ +--- +title: X-Content-Type-Options +slug: Web/HTTP/Headers/X-Content-Type-Options +tags: + - Cabeçalho de Resposta + - Cabeçalhos HTTP + - HTTP + - Referencia +translation_of: Web/HTTP/Headers/X-Content-Type-Options +--- +<div>{{HTTPSidebar}}</div> + +<p>Na resposta HTTP o cabeçalho <code><strong>X-Content-Type-Options</strong></code> é um marcador utilizado pelo servidor para indicar the os <a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types">tipos de MIME</a> anunciados nos cabeçalhos {{HTTPHeader("Content-Type")}} não devem ser alterados e seguidos. Isto permite evitar <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#MIME_sniffing">inspecção do tipo de MIME</a>, ou, noutras palavras, é uma de dizer que os webmasters sabem o que estão a fazer.</p> + +<p>Este cabeçalho foi introduzido pela Microsoft no IE 8 como uma maneira de os webmasters bloquearem a inspecção de conteúdo que acontecia e podia transformar tipos MIME não executáveis em tipos de MIME executáveis. Desde então, outros browsers também o introduziram, mesmo que os seus algoritmos de inspecção MIME fossem menos agressivos.</p> + +<p>Testadores de segurança esperam que este cabeçalho esteja definido.</p> + +<p class="note">Nota: <code>nosniff</code> apenas se aplica a "<code>script</code>" e tipos de "<code>style</code>". Aplicando também <code>nosniff</code> a imagens acabou por se tornar <a href="https://github.com/whatwg/fetch/issues/395">incompatível com sites web existentes</a>.</p> + +<table class="properties"> + <tbody> + <tr> + <th scope="row">Tipo de Cabeçalho</th> + <td>{{Glossary("Response header")}}</td> + </tr> + <tr> + <th scope="row">{{Glossary("Forbidden header name")}}</th> + <td>no</td> + </tr> + </tbody> +</table> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">X-Content-Type-Options: nosniff +</pre> + +<h2 id="Directivas">Directivas</h2> + +<dl> + <dt><code>nosniff</code></dt> + <dd>Bloqueia um pedido se o tipo pedido é + <ul> + <li>"<code>style</code>" e o tipo MIME não é "<code>text/css</code>", ou</li> + <li>"<code>script</code>" e o tipo MIME não é do <a href="https://html.spec.whatwg.org/multipage/scripting.html#javascript-mime-type">tipo MIME JavaScript</a>.</li> + </ul> + </dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName("Fetch", "#x-content-type-options-header", "X-Content-Type-Options definition")}}</td> + <td>{{Spec2("Fetch")}}</td> + <td>Definição inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_do_Browser">Compatibilidade do Browser</h2> + +<p class="hidden">A tabela de compatibilidade nesta página é gerada a partir de informação estruturada. Se quiser contribuir para a informação, por favor confira em <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pedido de pull.</p> + +<p>{{Compat("http/headers/x-content-type-options")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{HTTPHeader("Content-Type")}}</li> + <li>A <a href="https://blogs.msdn.microsoft.com/ie/2008/09/02/ie8-security-part-vi-beta-2-update/">definição original</a> de X-Content-Type-Options da Microsoft.</li> + <li>A ferramenta de teste de configuração <a href="https://mozilla.github.io/http-observatory-website/">Mozilla Observatory</a> (incluindo este cabeçalho) de sites web para segurança.</li> + <li> + <p><a href="https://blog.mozilla.org/security/2016/08/26/mitigating-mime-confusion-attacks-in-firefox/">Mitigando Ataques de Confusão MIME no Firefox</a></p> + </li> +</ul> diff --git a/files/pt-pt/web/http/index.html b/files/pt-pt/web/http/index.html new file mode 100644 index 0000000000..f76e190701 --- /dev/null +++ b/files/pt-pt/web/http/index.html @@ -0,0 +1,84 @@ +--- +title: HTTP +slug: Web/HTTP +tags: + - HTTP + - NeedsTranslation + - Reference + - TopicStub + - Web + - 'l10n:priority' +translation_of: Web/HTTP +--- +<div>{{HTTPSidebar}}</div> + +<p class="summary"><span class="seoSummary"><strong><dfn>Hypertext Transfer Protocol (HTTP)</dfn></strong> é um protocolo da <a class="external" href="https://en.wikipedia.org/wiki/Application_Layer">camada de aplicação</a> para a transmissão de documentos de hipermídia, tal com HTML.</span> Ele foi projetado para a comunicação entre navegadores web e servidores web, mas ele também pode ser usado para outros propósitos. HTTP segue o clássico <a class="external" href="https://en.wikipedia.org/wiki/Client%E2%80%93server_model">Modelo cliente-servidor</a>, com um cliente abrindo uma conexão para fazer uma requisição, e então esperando até que ele receba uma resposta. HTTP é um <a href="https://pt.wikipedia.org/wiki/Protocolo_sem_estado">protocolo sem estado</a>, significando que o servidor não manterá qualquer dado (estado) entre duas requisições. Apesar de frequentemente ser baseado na camada TCP/IP, ele pode ser utilizado em qualquer camada de transporte confiável; isto é, um protocolo que não perda menssagens silenciosamente tal como UDP.</p> + +<div class="column-container"> +<div class="column-half"> +<h2 id="Tutorials">Tutorials</h2> + +<p>Learn how to use HTTP with guides and tutorials.</p> + +<dl> + <dt><a href="/en-US/docs/Web/HTTP/Overview">Overview of HTTP</a></dt> + <dd>The basic features of the client-server protocol: what it can do and its intended uses.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Caching">HTTP Cache</a></dt> + <dd>Caching is very important for fast Web sites. This article describes different methods of caching and how to use HTTP Headers to control them.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Cookies">HTTP Cookies</a></dt> + <dd>How cookies work is defined by <a class="external" href="http://tools.ietf.org/html/rfc6265">RFC 6265</a>. When serving an HTTP request, a server can send a <code>Set-Cookie</code> HTTP header with the response. The client then returns the cookie's value with every request to the same server in the form of a <code>Cookie</code> request header. The cookie can also be set to expire on a certain date, or restricted to a specific domain and path.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP Access Control (CORS)</a></dt> + <dd><strong>Cross-site HTTP requests</strong> are HTTP requests for resources from a <strong>different domain</strong> than the domain of the resource making the request. For instance, an HTML page from Domain A (<code>http://domaina.example/</code>) makes a request for an image on Domain B (<code>http://domainb.foo/image.jpg</code>) via the <code>img</code> element. Web pages today very commonly load cross-site resources, including CSS stylesheets, images, scripts, and other resources. CORS allows web developers to control how their site reacts to cross-site requests.</dd> +</dl> + +<dl> + <dt><a href="/en-US/docs/Web/HTTP/Basics_of_HTTP/Evolution_of_HTTP">Evolution of HTTP</a></dt> + <dd>A brief description of the changes between the early versions of HTTP, to the modern HTTP/2 and beyond.</dd> + <dt><a href="https://wiki.mozilla.org/Security/Guidelines/Web_Security">Mozilla web security guidelines</a></dt> + <dd>A collection of tips to help operational teams with creating secure web applications.</dd> +</dl> + +<dl> + <dt><a href="/en-US/docs/Web/HTTP/Messages">HTTP Messages</a></dt> + <dd>Describes the type and structure of the different kind of messages of HTTP/1.x and HTTP/2.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Session">A typical HTTP session</a></dt> + <dd>Shows and explains the flow of a usual HTTP session.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Connection_management_in_HTTP_1.x">Connection management in HTTP/1.x</a></dt> + <dd>Describes the three connection management models available in HTTP/1.x, their strengths, and their weaknesses.</dd> +</dl> +</div> + +<div class="column-half"> +<h2 id="Reference">Reference</h2> + +<p>Browse through detailed HTTP reference documentation.</p> + +<dl> + <dt><a href="/en-US/docs/Web/HTTP/Headers">HTTP Headers</a></dt> + <dd>HTTP message headers are used to describe a resource, or the behavior of the server or the client. Custom proprietary headers can be added using the <code>X-</code> prefix; others in an <a class="external" href="http://www.iana.org/assignments/message-headers/perm-headers.html">IANA registry</a>, whose original content was defined in <a class="external" href="http://tools.ietf.org/html/rfc4229">RFC 4229</a>. IANA also maintains a <a class="external" href="http://www.iana.org/assignments/message-headers/prov-headers.html">registry of proposed new HTTP message headers</a>.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Methods">HTTP Request Methods</a></dt> + <dd>The different operations that can be done with HTTP: {{HTTPMethod("GET")}}, {{HTTPMethod("POST")}}, and also less common requests like {{HTTPMethod("OPTIONS")}}, {{HTTPMethod("DELETE")}}, or {{HTTPMethod("TRACE")}}.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Response_codes">HTTP Status Response Codes</a></dt> + <dd>HTTP response codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: informational responses, successful responses, redirections, client errors, and servers errors.</dd> + <dt><a href="/en-US/docs/Web/HTTP/Headers/Content-Security-Policy">CSP directives</a></dt> + <dd>The {{HTTPHeader("Content-Security-Policy")}} response header fields allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints.</dd> +</dl> + +<h2 id="Tools_resources">Tools & resources</h2> + +<p>Helpful tools and resources for understanding and debugging HTTP.</p> + +<dl> + <dt><a href="/en-US/docs/Tools">Firefox Developer Tools</a></dt> + <dd><a href="/en-US/docs/Tools/Network_Monitor">Network monitor</a></dd> + <dt><a href="https://observatory.mozilla.org/">Mozilla Observatory</a></dt> + <dd> + <p>A project designed to help developers, system administrators, and security professionals configure their sites safely and securely.</p> + </dd> + <dt><a class="external" href="https://redbot.org/">RedBot</a></dt> + <dd>Tools to check your cache-related headers</dd> + <dt><a href="http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/">How Browsers Work</a></dt> + <dd>A very comprehensive article on browser internals and request flow through HTTP protocol. A MUST-READ for any web developer.</dd> +</dl> +</div> +</div> diff --git a/files/pt-pt/web/http/proxy_servers_and_tunneling/index.html b/files/pt-pt/web/http/proxy_servers_and_tunneling/index.html new file mode 100644 index 0000000000..38c03ba2a2 --- /dev/null +++ b/files/pt-pt/web/http/proxy_servers_and_tunneling/index.html @@ -0,0 +1,98 @@ +--- +title: Servidor Proxy e Túneis +slug: Web/HTTP/Proxy_servers_and_tunneling +tags: + - HTTP + - Proxies + - Proxy + - Túnel HTTP +translation_of: Web/HTTP/Proxy_servers_and_tunneling +--- +<div>{{HTTPSidebar}}</div> + +<p class="summary">Ao navegar por diferentes redes da internet, os servidores proxy e os túneis HTTP facilitam o acesso ao conteúdo na Rede Mundial de Computadores (World Wide Web). O proxy pode estar no computador local do usuário, ou em algum lugar entre o computador deste e o servidor de destino na Internet. Esta página é um esquema de conceitos básicos sobre proxies e algumas opções de configuração.</p> + +<p>Há dois tipos de proxies: <strong>proxy de envio </strong> (do inglês "<strong>forward proxies", </strong>ou túnel, ou ainda, gateway) e<strong> proxy reverso</strong> ("<strong>reverse proxies" </strong>usados para proteger o acesso ao servidor de largura de banda, autenticação, decriptação ou caching).</p> + +<h2 id="Proxy_de_Envio">Proxy de Envio</h2> + +<p>Proxy de envio, também chamado gateway ou "proxy" fornece serviços a um cliente ou grupo de clientes. É possível que haja centenas de milhares de proxies de envio livres na Internet. Estes armazenam e enviam serviços de rede (como o DNS, ou páginas da web) para economia e controle da largura de banda usada pelo grupo.</p> + +<p>Proxies de envio também podem ser anónimos e esconder o endereço IP dos usuários que navegam pela Web ou usam outros serviços de Internet. O <a href="https://www.torproject.org/">TOR</a> (The Onion Router), para ser anónimo, roteia tráfego de rede por vários proxies .</p> + +<h2 id="Proxy_reverso">Proxy reverso</h2> + +<p>Como o nome já indica, faz o inverso do proxy de envio: O proxy de envio benefecia a clientes (ou a hosts que o requisitam), já o proxy reverso benefecia a servidores. Proxies de envio podem esconder a identidade de clientes, ao passo que proxies reversos podem esconder a dos servidores. Proxies reversos tem várias funções, dentre os quais:</p> + +<ul> + <li>Load balancing: distribuir a carga por vários servidores web ,</li> + <li>Cache de conteúdo estático: liberta os servidores web por esconder conteúdo estático, como fotos</li> + <li>Compressão: acelera o tempo de carregamento por comprimir e otimizar conteúdos</li> +</ul> + +<h2 id="Envio_de_informação_de_clientes_por_meio_de_proxies">Envio de informação de clientes por meio de proxies</h2> + +<p>Proxies fazem parecer que os pedidos vêm do endereço IP do proxy. Isto pode ser útil se o proxy provê anonimato ao cliente. Porém, noutros casos, perde-se a informação do pedido original. O endereço IP original é usado em verificação de erros, em estatísticas ou ao gerar conteúdo ajustado à localização. Uma forma comum de divulgar esta informação é usando estes cabeçalhos HTTP:</p> + +<p>Cabeçalho padronizado:</p> + +<dl> + <dt>{{HTTPHeader("Forwarded")}}</dt> + <dd>Contêm informação do lado do cliente de proxy, que foi alterada ou perdida se há um proxy no caminho do pedido</dd> +</dl> + +<p>Ou as versões de facto padrão:</p> + +<dl> + <dt>{{HTTPHeader("X-Forwarded-For")}} {{non-standard_inline}}</dt> + <dd>Identifica o endereço IP de origem do cliente que se conectou ao servidor web por meio de um proxy HTTP ou um load balancer</dd> + <dt>{{HTTPHeader("X-Forwarded-Host")}} {{non-standard_inline}}</dt> + <dd>Identifica o Host originalmente requisitado pelo cliente, quando este se conectou ao seu proxy ou load balancer </dd> + <dt>{{HTTPHeader("X-Forwarded-Proto")}} {{non-standard_inline}}</dt> + <dd>Identifica o protocolo (HTTP ou HTTPS) que o cliente usou ao se conectar ao seu proxy ou load balancer</dd> +</dl> + +<p>Pode-se usar o cabeçalho <code>Via</code> para informar, não sobre o cliente conectado, mas sobre o próprio proxy.</p> + +<dl> + <dt>{{HTTPHeader("Via")}}</dt> + <dd>Adicionado por proxies, tanto de envio como reversos, e aparece no cabeçalho do pedido e da resposta.</dd> +</dl> + +<h2 id="Túnel_HTTP">Túnel HTTP </h2> + +<p>O Tunelamento encapsula os dados, permitindo assim que dados de rede privada e protocolos traféguem em redes públicas. Tunelamento HTTP é usar o protocolo de alto nível (HTTP) para transportar outro de nível abaixo (TCP).</p> + +<p>O Protocolo HTTP protocol especifica o método {{HTTPMethod("CONNECT")}}. Este começa comunicações de mão-dupla com o recurso requisitado e pode abrir um túnel. É assim que o cliente de proxy HTTP pode acessar websites a usar SSL (i.e. HTTPS, porta 443). Mas, é digno de nota, que nem todos os servidores proxy tem suporte ao método <code>CONNECT</code> ou limitam-no à porta 443.</p> + +<p>Veja também o artigo <a href="https://en.wikipedia.org/wiki/HTTP_tunnel">HTTP tunnel</a>, na Wikipedia.</p> + +<h2 id="Proxy_Auto-Configuration_PAC">Proxy Auto-Configuration (PAC)</h2> + +<p>O ficheiro <a href="/en-US/docs/Mozilla/Projects/Necko/Proxy_Auto-Configuration_(PAC)_file">Proxy Auto-Configuration (PAC)</a> é uma função de <a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/JavaScript">JavaScript</a> que determina se pedidos de motores de busca (HTTP, HTTPS, e FTP) vão direto ao destino ou são reencaminhadas a um proxy-servidor web. A função JavaScript contida no ficheiro PAC define:</p> + +<p id="Saving_the_Auto-Config_File_Setting_the_MIME_Type">O ficheiro auto-config será salvo com extensão <code>.pac</code>:</p> + +<pre class="syntaxbox notranslate">proxy.pac</pre> + +<p>E o MIME type é configurado para:</p> + +<pre class="syntaxbox notranslate">application/x-ns-proxy-autoconfig</pre> + +<p>O Ficheiro consiste numa função de nome <code>FindProxyForURL</code>. Se o servidor DNS interno está configurado para fonecer nomes à hosts internos, e o objectivo é usar um proxy só para hosts sem nome, então este exemplo deve funcionar:</p> + +<pre class="brush: js notranslate">function FindProxyForURL(url, host) { + if (isResolvable(host)) + return "DIRECT"; + else + return "PROXY proxy.mydomain.com:8080"; +}</pre> + +<p>Veja <a href="/en-US/docs/Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_(PAC)_file">Proxy Auto-Configuration (PAC)</a> para mais exemplos.</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{HTTPMethod("CONNECT")}}</li> + <li><a href="https://pt.wikipedia.org/wiki/Proxy">Proxy na Wikipedia</a></li> +</ul> diff --git a/files/pt-pt/web/http/status/205/index.html b/files/pt-pt/web/http/status/205/index.html new file mode 100644 index 0000000000..abd4774ca7 --- /dev/null +++ b/files/pt-pt/web/http/status/205/index.html @@ -0,0 +1,45 @@ +--- +title: 205 Reset Content +slug: Web/HTTP/Status/205 +tags: + - Códigos de resposta + - Códigos de resposta HTTP + - HTTP + - HTTP Status Code + - Referencia +translation_of: Web/HTTP/Status/205 +--- +<div>{{HTTPSidebar}}</div> + +<p>O código de resposta HTTP <strong><code>205 Reset Content</code></strong> indica ao cliente que deve reinicializar a vista do documento. Assim, por exemplo, deve limpar o conteúdo de um formulário, reiniciar o estado de uma tela ou refrescar o UI.</p> + +<h2 id="Status">Status</h2> + +<pre class="syntaxbox">205 Reset Content</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Title</th> + </tr> + <tr> + <td>{{RFC("7231", "205 Reset Content" , "6.3.6")}}</td> + <td>Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content</td> + </tr> + </tbody> +</table> + +<h2 id="Notas_sobre_compatibilidade">Notas sobre compatibilidade</h2> + +<ul> + <li>O comportamento dos navegadores difere para o caso de esta resposta incluir erradamente um corpo em ligações persistentes. Para mais detalhe, veja <a href="/en-US/docs/Web/HTTP/Status/204">204 No Content</a>.</li> +</ul> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{HTTPStatus(204)}} No Content</li> +</ul> diff --git a/files/pt-pt/web/http/status/405/index.html b/files/pt-pt/web/http/status/405/index.html new file mode 100644 index 0000000000..abe104da6b --- /dev/null +++ b/files/pt-pt/web/http/status/405/index.html @@ -0,0 +1,46 @@ +--- +title: 405 Method Not Allowed +slug: Web/HTTP/Status/405 +tags: + - Código de resposta HTTP + - Erro de cliente + - HTTP + - Referencia + - Status code +translation_of: Web/HTTP/Status/405 +--- +<div>{{HTTPSidebar}}</div> + +<p>O código de resposta HTTP (HyperText Transfer Protocol) <code>405 Method Not Allowed</code> indica que o método do pedido é conhecido pelo servidor, mas não é suportado pelo recurso alvo.</p> + +<p class="newpage">O servidor PRECISA gerar um campo de cabeçalho chamado <code>Allow</code> numa resposta 405 contendo uma lista dos métodos que o recurso alvo atualmente suporta.</p> + +<h2 id="Status">Status</h2> + +<pre class="syntaxbox notranslate">405 Method Not Allowed</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Titulo</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{RFC("7231", "405 Method Not Allowed", "6.5.5")}}</td> + <td>Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content</td> + </tr> + </tbody> +</table> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{HTTPHeader("Allow")}}</li> + <li><em><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noopener">HTTP/1.1: Status Code Definitions</a></em></li> + <li><em><a href="https://kinsta.com/blog/405-method-not-allowed-error/">How to Fix 405 Method Not Allowed</a></em></li> + <li><em><a href="https://docs.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications">Troubleshooting HTTP 405</a></em></li> +</ul> diff --git a/files/pt-pt/web/http/status/502/index.html b/files/pt-pt/web/http/status/502/index.html new file mode 100644 index 0000000000..548e89fd57 --- /dev/null +++ b/files/pt-pt/web/http/status/502/index.html @@ -0,0 +1,51 @@ +--- +title: 502 Bad Gateway +slug: Web/HTTP/Status/502 +tags: + - Erro de servidor + - HTTP + - Status code +translation_of: Web/HTTP/Status/502 +--- +<div>{{HTTPSidebar}}</div> + +<p>O código de resposta HTTP (Protocolo de Transferência de Hipertexto) <code><strong>502 Bad Gateway</strong></code> indica que o servidor, ao agir como portal ou <em>proxy</em>, recebeu uma resposta invalida dum servidor <em>upstream</em> (um servidor mais adiante na cadeia de conexões).</p> + +<div class="note"> +<p><strong>Nota: </strong>Uma {{interwiki("wikipedia", "Gateway", "Gateway")}} pode ser várias coisas numa rede e um erro 502 tipicamente não pode ser resolvido por si, mas requer um conserto no servidor ou nas <em>proxies</em> por qual esta a comunicar.</p> +</div> + +<h2 id="Status">Status</h2> + +<pre class="syntaxbox notranslate">502 Bad Gateway +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Titulo</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{RFC("7231", "502 Bad Gateway", "6.6.3")}}</td> + <td>Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a class="external" href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div> + +<p>{{Compat("http.status.502")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{HTTPStatus(504)}}</li> + <li><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noopener">HTTP/1.1: Status Code Definitions</a></li> +</ul> diff --git a/files/pt-pt/web/http/status/504/index.html b/files/pt-pt/web/http/status/504/index.html new file mode 100644 index 0000000000..ce2ddf7563 --- /dev/null +++ b/files/pt-pt/web/http/status/504/index.html @@ -0,0 +1,50 @@ +--- +title: 504 Gateway Timeout +slug: Web/HTTP/Status/504 +tags: + - Erro de servidor + - HTTP + - Status code +translation_of: Web/HTTP/Status/504 +--- +<div>{{HTTPSidebar}}</div> + +<p>O código de resposta HTTP (Protocolo de Transferência de Hipertexto) <code><strong>504 Gateway Timeout</strong></code> indica que o servidor, ao agir como portal ou <em>proxy</em>, não recebeu uma resposta dum servidor <em>upstream</em> (um servidor mais adiante na cadeia de conexões) no tempo necessário para completar a resposta. </p> + +<div class="note"> +<p><strong>Nota</strong>: Uma {{interwiki("wikipedia", "Gateway", "Gateway")}} pode ser várias coisas numa rede e um erro 504 tipicamente não pode ser resolvido por si, mas requer um conserto no servidor ou nas <em>proxies</em> por qual esta a comunicar.</p> +</div> + +<h2 id="Status">Status</h2> + +<pre class="syntaxbox notranslate">504 Gateway Timeout</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Titulo</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{RFC("7231", "504 Gateway Timeout" , "6.6.5")}}</td> + <td>Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("http.status.504")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="noopener">HTTP/1.1: Status Code Definitions</a></li> + <li>{{HTTPStatus(502)}}</li> +</ul> diff --git a/files/pt-pt/web/http/status/index.html b/files/pt-pt/web/http/status/index.html new file mode 100644 index 0000000000..cc6e9b9e37 --- /dev/null +++ b/files/pt-pt/web/http/status/index.html @@ -0,0 +1,185 @@ +--- +title: HTTP response status codes +slug: Web/HTTP/Status +tags: + - HTTP + - Landing + - NeedsTranslation + - Overview + - Reference + - Status codes + - TopicStub + - Web +translation_of: Web/HTTP/Status +--- +<div>{{HTTPSidebar}}</div> + +<p class="summary"><span class="seoSummary">HTTP response status codes indicate whether a specific <a href="/en-US/docs/Web/HTTP">HTTP</a> request has been successfully completed. Responses are grouped in five classes: informational responses, successful responses, redirects, client errors, and servers errors.</span> Status codes are defined by <a href="https://tools.ietf.org/html/rfc2616#section-10">section 10 of RFC 2616</a>.</p> + +<h2 id="Information_responses">Information responses</h2> + +<dl> + <dt>{{HTTPStatus(100, "100 Continue")}}</dt> + <dd>This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished.</dd> + <dt>{{HTTPStatus(101, "101 Switching Protocol")}}</dt> + <dd>This code is sent in response to an {{HTTPHeader("Upgrade")}} request header by the client, and indicates the protocol the server is switching to.</dd> + <dt>{{HTTPStatus(102, "102 Processing")}} ({{Glossary("WebDAV")}})</dt> + <dd>This code indicates that the server has received and is processing the request, but no response is available yet.</dd> + <dt>{{HTTPStatus(103, "103 Early Hints")}}</dt> + <dd>This status code is primarily intended to be used with the {{HTTPHeader("Link")}} header to allow the user agent to start preloading resources while the server is still preparing a response.</dd> +</dl> + +<h2 id="Successful_responses">Successful responses</h2> + +<dl> + <dt>{{HTTPStatus(200, "200 OK")}}</dt> + <dd>The request has succeeded. The meaning of a success varies depending on the HTTP method:<br> + GET: The resource has been fetched and is transmitted in the message body.<br> + HEAD: The entity headers are in the message body.<br> + PUT or POST: The resource describing the result of the action is transmitted in the message body.<br> + TRACE: The message body contains the request message as received by the server</dd> + <dt>{{HTTPStatus(201, "201 Created")}}</dt> + <dd>The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a POST request, or after some PUT requests.</dd> + <dt>{{HTTPStatus(202, "202 Accepted")}}</dt> + <dd>The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.</dd> + <dt>{{HTTPStatus(203, "203 Non-Authoritative Information")}}</dt> + <dd>This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response.</dd> + <dt>{{HTTPStatus(204, "204 No Content")}}</dt> + <dd>There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones.</dd> + <dt>{{HTTPStatus(205, "205 Reset Content")}}</dt> + <dd>This response code is sent after accomplishing request to tell user agent reset document view which sent this request.</dd> + <dt>{{HTTPStatus(206, "206 Partial Content")}}</dt> + <dd>This response code is used because of range header sent by the client to separate download into multiple streams.</dd> + <dt>{{HTTPStatus(207, "207 Multi-Status")}} ({{Glossary("WebDAV")}})</dt> + <dd>A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate.</dd> + <dt>{{HTTPStatus(208, "208 Multi-Status")}} ({{Glossary("WebDAV")}})</dt> + <dd>Used inside a DAV: propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly.</dd> + <dt>{{HTTPStatus(226, "226 IM Used")}} (<a href="https://tools.ietf.org/html/rfc3229">HTTP Delta encoding</a>)</dt> + <dd>The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.</dd> +</dl> + +<h2 id="Redirection_messages">Redirection messages</h2> + +<dl> + <dt>{{HTTPStatus(300, "300 Multiple Choice")}}</dt> + <dd>The request has more than one possible response. The user-agent or user should choose one of them. There is no standardized way of choosing one of the responses.</dd> + <dt>{{HTTPStatus(301, "301 Moved Permanently")}}</dt> + <dd>This response code means that the URI of the requested resource has been changed permanently. Probably, the new URI would be given in the response.</dd> + <dt>{{HTTPStatus(302, "302 Found")}}</dt> + <dd>This response code means that the URI of requested resource has been changed <em>temporarily</em>. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.</dd> + <dt>{{HTTPStatus(303, "303 See Other")}}</dt> + <dd>The server sent this response to direct the client to get the requested resource at another URI with a GET request.</dd> + <dt>{{HTTPStatus(304, "304 Not Modified")}}</dt> + <dd>This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.</dd> + <dt><code>305 Use Proxy</code> {{deprecated_inline}}</dt> + <dd>Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.</dd> + <dt><code>306 unused</code></dt> + <dd>This response code is no longer used, it is just reserved currently. It was used in a previous version of the HTTP 1.1 specification.</dd> + <dt>{{HTTPStatus(307, "307 Temporary Redirect")}}</dt> + <dd>The server sends this response to direct the client to get the requested resource at another URI with same method that was used in the prior request. This has the same semantics as the <code>302 Found</code> HTTP response code, with the exception that the user agent <em>must not</em> change the HTTP method used: If a <code>POST</code> was used in the first request, a <code>POST</code> must be used in the second request.</dd> + <dt>{{HTTPStatus(308, "308 Permanent Redirect")}}</dt> + <dd>This means that the resource is now permanently located at another URI, specified by the <code>Location:</code> HTTP Response header. This has the same semantics as the <code>301 Moved Permanently</code> HTTP response code, with the exception that the user agent <em>must not</em> change the HTTP method used: If a <code>POST</code> was used in the first request, a <code>POST</code> must be used in the second request.</dd> +</dl> + +<h2 id="Client_error_responses">Client error responses</h2> + +<dl> + <dt>{{HTTPStatus(400, "400 Bad Request")}}</dt> + <dd>This response means that server could not understand the request due to invalid syntax.</dd> + <dt>{{HTTPStatus(401, "401 Unauthorized")}}</dt> + <dd>Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.</dd> + <dt><code>402 Payment Required</code></dt> + <dd>This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently.</dd> + <dt>{{HTTPStatus(403, "403 Forbidden")}}</dt> + <dd>The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server.</dd> + <dt>{{HTTPStatus(404, "404 Not Found")}}</dt> + <dd>The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web.</dd> + <dt>{{HTTPStatus(405, "405 Method Not Allowed")}}</dt> + <dd>The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, <code>GET</code> and <code>HEAD</code>, must never be disabled and should not return this error code.</dd> + <dt>{{HTTPStatus(406, "406 Not Acceptable")}}</dt> + <dd>This response is sent when the web server, after performing <a href="/en-US/docs/HTTP/Content_negotiation#Server-driven_negotiation">server-driven content negotiation</a>, doesn't find any content following the criteria given by the user agent.</dd> + <dt>{{HTTPStatus(407, "407 Proxy Authentication Required")}}</dt> + <dd>This is similar to 401 but authentication is needed to be done by a proxy.</dd> + <dt>{{HTTPStatus(408, "408 Request Timeout")}}</dt> + <dd>This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.</dd> + <dt>{{HTTPStatus(409, "409 Conflict")}}</dt> + <dd>This response is sent when a request conflicts with the current state of the server.</dd> + <dt>{{HTTPStatus(410, "410 Gone")}}</dt> + <dd>This response would be sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code.</dd> + <dt>{{HTTPStatus(411, "411 Length Required")}}</dt> + <dd>Server rejected the request because the <code>Content-Length</code> header field is not defined and the server requires it.</dd> + <dt>{{HTTPStatus(412, "412 Precondition Failed")}}</dt> + <dd>The client has indicated preconditions in its headers which the server does not meet.</dd> + <dt>{{HTTPStatus(413, "413 Payload Too Large")}}</dt> + <dd>Request entity is larger than limits defined by server; the server might close the connection or return an <code>Retry-After</code> header field.</dd> + <dt>{{HTTPStatus(414, "414 URI Too Long")}}</dt> + <dd>The URI requested by the client is longer than the server is willing to interpret.</dd> + <dt>{{HTTPStatus(415, "415 Unsupported Media Type")}}</dt> + <dd>The media format of the requested data is not supported by the server, so the server is rejecting the request.</dd> + <dt>{{HTTPStatus(416, "416 Requested Range Not Satisfiable")}}</dt> + <dd>The range specified by the <code>Range</code> header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.</dd> + <dt>{{HTTPStatus(417, "417 Expectation Failed")}}</dt> + <dd>This response code means the expectation indicated by the <code>Expect</code> request header field can't be met by the server.</dd> + <dt>{{HTTPStatus(418, "418 I'm a teapot")}}</dt> + <dd>The server refuses the attempt to brew coffee with a teapot.</dd> + <dt>{{HTTPStatus(421, "421 Misdirected Request")}}</dt> + <dd>The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.</dd> + <dt>{{HTTPStatus(422, "422 Unprocessable Entity")}} ({{Glossary("WebDAV")}})</dt> + <dd>The request was well-formed but was unable to be followed due to semantic errors.</dd> + <dt>{{HTTPStatus(423, "423 Locked")}} ({{Glossary("WebDAV")}})</dt> + <dd>The resource that is being accessed is locked.</dd> + <dt>{{HTTPStatus(424, "424 Failed Dependency")}} ({{Glossary("WebDAV")}})</dt> + <dd>The request failed due to failure of a previous request.</dd> + <dt>{{HTTPStatus(425, "425 Too Early")}}</dt> + <dd>Indicates that the server is unwilling to risk processing a request that might be replayed.</dd> + <dt>{{HTTPStatus(426, "426 Upgrade Required")}}</dt> + <dd>The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an {{HTTPHeader("Upgrade")}} header in a 426 response to indicate the required protocol(s).</dd> + <dt>{{HTTPStatus(428, "428 Precondition Required")}}</dt> + <dd>The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.</dd> + <dt>{{HTTPStatus(429, "429 Too Many Requests")}}</dt> + <dd>The user has sent too many requests in a given amount of time ("rate limiting").</dd> + <dt>{{HTTPStatus(431, "431 Request Header Fields Too Large")}}</dt> + <dd>The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.</dd> + <dt>{{HTTPStatus(451, "451 Unavailable For Legal Reasons")}}</dt> + <dd>The user requests an illegal resource, such as a web page censored by a government.</dd> +</dl> + +<h2 id="Server_error_responses">Server error responses</h2> + +<dl> + <dt>{{HTTPStatus(500, "500 Internal Server Error")}}</dt> + <dd>The server has encountered a situation it doesn't know how to handle.</dd> + <dt>{{HTTPStatus(501, "501 Not Implemented")}}</dt> + <dd>The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are <code>GET</code> and <code>HEAD</code>.</dd> + <dt>{{HTTPStatus(502, "502 Bad Gateway")}}</dt> + <dd>This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.</dd> + <dt>{{HTTPStatus(503, "503 Service Unavailable")}}</dt> + <dd>The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the <code>Retry-After:</code> HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.</dd> + <dt>{{HTTPStatus(504, "504 Gateway Timeout")}}</dt> + <dd>This error response is given when the server is acting as a gateway and cannot get a response in time.</dd> + <dt>{{HTTPStatus(505, "505 HTTP Version Not Supported")}}</dt> + <dd>The HTTP version used in the request is not supported by the server.</dd> + <dt>{{HTTPStatus(506, "506 Variant Also Negotiates")}}</dt> + <dd>The server has an internal configuration error: transparent content negotiation for the request results in a circular reference.</dd> + <dt>{{HTTPStatus(507, "507 Insufficient Storage")}}</dt> + <dd>The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.</dd> + <dt>{{HTTPStatus(508, "508 Loop Detected")}} ({{Glossary("WebDAV")}})</dt> + <dd>The server detected an infinite loop while processing the request.</dd> + <dt>{{HTTPStatus(510, "510 Not Extended")}}</dt> + <dd>Further extensions to the request are required for the server to fulfill it.</dd> + <dt>{{HTTPStatus(511, "511 Network Authentication Required")}}</dt> + <dd>The 511 status code indicates that the client needs to authenticate to gain network access.</dd> +</dl> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("http.status")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes">List of HTTP status codes on Wikipedia</a></li> + <li><a href="http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml">IANA official registry of HTTP status codes</a></li> +</ul> diff --git a/files/pt-pt/web/index.html b/files/pt-pt/web/index.html new file mode 100644 index 0000000000..7edc7ff11e --- /dev/null +++ b/files/pt-pt/web/index.html @@ -0,0 +1,88 @@ +--- +title: Tecnologia da Web para programadores +slug: Web +tags: + - Landing + - Web +translation_of: Web +--- +<p>A Web aberta apresenta oportunidades incriveis para os programadores. Para tirar o máximo proveito destas tecnologias, precisa de saber como utilizá-las. Em baixo, irá encontrar as hiperligações para a documentação da MDN sobre as tecnologias da Web.</p> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Tecnologias_da_Web">Tecnologias da Web</h2> + +<div class="row topicpage-table"> +<div class="section"> +<h3 id="Basics">Basics</h3> + +<dl> + <dt><a href="/pt-PT/docs/Web/HTML">HTML</a></dt> + <dd>A "Linguagem de Marcação de Hipertexto" é a linguagem utilizada para descrever e definir o conteúdo de uma página da Web num formato bem estruturado.</dd> + <dt><a href="/pt-PT/docs/Web/CSS">CSS</a></dt> + <dd>"Folhas de Estilo em Cascata" é utilizado para descrever a aparência de conteúdo da Web.</dd> +</dl> + +<h3 id="Scripting">Scripting</h3> + +<dl> + <dt><a href="/pt-PT/docs/Web/JavaScript">JavaScript</a></dt> + <dd>JavaScript é uma linguagem de programação que é executada no seu navegador, que é utilizada para criar <em>sites</em> da Web interativos e aplicações para a execução de um navegador seguro.</dd> + <dt><a href="pt-PT/docs/Web/Reference/API">APIs da Web</a></dt> + <dd>Reference material for each of the individual APIs that comprise the Web's powerful scriptability, including the <a href="/pt-PT/docs/DOM">DOM</a> and all of the related APIs and interfaces you can use to build Web content and apps. + <ul> + <li><a href="/pt-PT/docs/Web/API" title="/en-US/docs/Web/API">Web API interface reference</a> — all interfaces, arranged alphabetically.</li> + <li>The <a href="/pt-PT/docs/WebAPI">WebAPI page</a> lists device-access APIs and other APIs useful for applications.</li> + </ul> + </dd> +</dl> + +<h3 id="Gráficos">Gráficos</h3> + +<dl> + <dt><a href="/pt-PT/docs/SVG">SVG</a></dt> + <dd>Scalable Vector Graphics let you describe images as sets of vectors (lines) and shapes in order to allow them to scale smoothly regardless of the size at which they're drawn.</dd> + <dt><a href="/pt-PT/docs/Web/API/WebGL_API" title="/en-US/docs/Web/WebGL">WebGL</a></dt> + <dd>WebGL brings 3D graphics to the Web by introducing an API that closely conforms to OpenGL ES 2.0, which can be used in HTML {{HTMLElement("canvas")}} elements.</dd> +</dl> + +<h3 id="Outros">Outros</h3> + +<dl> + <dt><a href="/pt-PT/docs/Web/MathML">MathML</a></dt> + <dd>Mathematical Markup Language makes it possible to display complex mathematical equations and syntax.</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Documentation" id="Documentação_por_tipo">Documentação por tipo</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/Guide">Guia do Programador da Web</a></dt> + <dd>O "Guia de Programadore da Web" fornece conteúdo útil de instruções para ajudá-lo a realmente utilizar as tecnologias da Web para fazer o que deseja ou precisa.</dd> + <dt><a href="/pt-PT/docs/Web/Tutoriais">Tutoriais para os programadores da Web</a></dt> + <dd>Uma lista de tutoriais para o guiar passo-a-passo pelas APIs de aprendizagem, tecnologias ou áreas de tópicos abrangentes.</dd> + <dt><a href="/pt-PT/docs/Web/Reference">Referências</a></dt> + <dd> + <div class="note">Esta página irá oferecer hiperligações para todas a informação de referência na MDN, mas esta ainda está em desenvolvimento.</div> + </dd> +</dl> + +<h2 id="Outros_tópicos">Outros tópicos</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/Progressive_web_apps">Desenvolver aplicações da Web</a></dt> + <dd>Documentation for Web application developers; Web apps are true write-once, deploy anywhere apps for mobile, desktop, and Firefox OS.</dd> + <dt><a href="/pt-PT/docs/Web/Accessibility">Acessibilidade</a></dt> + <dd>Accessibility in Web development means enabling as many people as possible to use Web sites, even when those people's abilities are limited in some way. Here we provide information on developing Web content to be accessible.</dd> + <dt><a href="/pt-PT/docs/Web/Security">Segurança</a></dt> + <dd> + <p>É essencial garantir que o seu <em>site</em> da Web ou aplicação da Web aberta esteja segura.</p> + </dd> +</dl> +</div> +</div> + +<p><span class="alllinks"><a href="/pt-PT/docs/tag/Web">Ver Tudo...</a></span></p> +</div> +</div> diff --git a/files/pt-pt/web/javascript/estruturas_de_dados/index.html b/files/pt-pt/web/javascript/estruturas_de_dados/index.html new file mode 100644 index 0000000000..8b8578229b --- /dev/null +++ b/files/pt-pt/web/javascript/estruturas_de_dados/index.html @@ -0,0 +1,297 @@ +--- +title: Tipos de dados de JavaScript e estruturas de dados +slug: Web/JavaScript/Estruturas_de_dados +tags: + - JavaScript + - Principiante + - Tipos +translation_of: Web/JavaScript/Data_structures +--- +<div>{{jsSidebar("More")}}</div> + +<p>Programming languages all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in JavaScript and what properties they have; these can be used to build other data structures. When possible, comparisons with other languages are drawn.</p> + +<h2 id="Digitação_dinâmica">Digitação dinâmica</h2> + +<p>JavaScript is a <em>loosely typed</em> or a <em>dynamic</em> language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types:</p> + +<pre class="brush: js">var foo = 42; // foo is now a Number +var foo = 'bar'; // foo is now a String +var foo = true; // foo is now a Boolean +</pre> + +<h2 id="Tipos_de_dados">Tipos de dados</h2> + +<p>The latest ECMAScript standard defines seven data types:</p> + +<ul> + <li>Six data types that are {{Glossary("Primitive", "primitives")}}: + <ul> + <li>{{Glossary("Boolean")}}</li> + <li>{{Glossary("Null")}}</li> + <li>{{Glossary("Undefined")}}</li> + <li>{{Glossary("Number")}}</li> + <li>{{Glossary("String")}}</li> + <li>{{Glossary("Symbol")}} (new in ECMAScript 6)</li> + </ul> + </li> + <li>and {{Glossary("Object")}}</li> +</ul> + +<h2 id="Valores_primitivos">Valores primitivos</h2> + +<p>All types except objects define immutable values (values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values of these types as "primitive values".</p> + +<h3 id="Tipo_booleano">Tipo booleano</h3> + +<p>Boolean represents a logical entity and can have two values: <code>true</code>, and <code>false</code>.</p> + +<h3 id="Tipo_Null">Tipo <em>Null</em></h3> + +<p>The Null type has exactly one value: <code>null</code>. See {{jsxref("null")}} and {{Glossary("Null")}} for more details.</p> + +<h3 id="Tipo_indefinido">Tipo indefinido</h3> + +<p>A variable that has not been assigned a value has the value <code>undefined</code>. See {{jsxref("undefined")}} and {{Glossary("Undefined")}} for more details.</p> + +<h3 id="Tipo_número">Tipo número</h3> + +<p>According to the ECMAScript standard, there is only one number type: the <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format">double-precision 64-bit binary format IEEE 754 value</a> (number between -(2<sup>53</sup> -1) and 2<sup>53</sup> -1). <strong>There is no specific type for integers</strong>. In addition to being able to represent floating-point numbers, the number type has three symbolic values: <code>+Infinity</code>, <code>-Infinity</code>, and <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN"><code>NaN</code></a> (not-a-number).</p> + +<p>To check for the largest available value or smallest available value within <code>+/-Infinity</code>, you can use the constants {{jsxref("Number.MAX_VALUE")}} or {{jsxref("Number.MIN_VALUE")}} and starting with ECMAScript 6, you are also able to check if a number is in the double-precision floating-point number range using {{jsxref("Number.isSafeInteger()")}} as well as {{jsxref("Number.MAX_SAFE_INTEGER")}} and {{jsxref("Number.MIN_SAFE_INTEGER")}}. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value.</p> + +<p>The number type has only one integer that has two representations: 0 is represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost no impact. For example <code>+0 === -0</code> is <code>true</code>. However, you are able to notice this when you divide by zero:</p> + +<pre class="brush: js">> 42 / +0 +Infinity +> 42 / -0 +-Infinity +</pre> + +<p>Although a number often represents only its value, JavaScript provides <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators" title="en/JavaScript/Reference/Operators/Bitwise_Operators">some binary operators</a>. These can be used to represent several Boolean values within a single number using <a class="external" href="http://en.wikipedia.org/wiki/Mask_%28computing%29">bit masking</a>. However, this is usually considered a bad practice, since JavaScript offers other means to represent a set of Booleans (like an array of Booleans or an object with Boolean values assigned to named properties). Bit masking also tends to make code more difficult to read, understand, and maintain. It may be necessary to use such techniques in very constrained environments, like when trying to cope with the storage limitation of local storage or in extreme cases when each bit over the network counts. This technique should only be considered when it is the last measure that can be taken to optimize size.</p> + +<h3 id="Tipo_string">Tipo <em>string</em></h3> + +<p>JavaScript's {{jsxref("Global_Objects/String", "String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.</p> + +<p>Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example:</p> + +<ul> + <li>A substring of the original by picking individual letters or using {{jsxref("String.substr()")}}.</li> + <li>A concatenation of two strings using the concatenation operator (<code>+</code>) or {{jsxref("String.concat()")}}.</li> +</ul> + +<h4 id="Beware_of_stringly-typing_your_code!">Beware of "stringly-typing" your code!</h4> + +<p>It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:</p> + +<ul> + <li>It is easy to build complex strings with concatenation.</li> + <li>Strings are easy to debug (what you see printed is always what is in the string).</li> + <li>Strings are the common denominator of a lot of APIs (<a href="/en-US/docs/Web/API/HTMLInputElement" title="HTMLInputElement">input fields</a>, <a href="/en-US/docs/Storage" title="Storage">local storage</a> values, {{ domxref("XMLHttpRequest") }} responses when using <code>responseText</code>, etc.) and it can be tempting to only work with strings.</li> +</ul> + +<p>With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.</p> + +<p>Use strings for textual data. When representing complex data, parse strings and use the appropriate abstraction.</p> + +<h3 id="Tipo_símbolo">Tipo símbolo</h3> + +<p>Symbols are new to JavaScript in ECMAScript Edition 6. A Symbol is a <strong>unique</strong> and <strong>immutable</strong> primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called atoms. For more details see {{Glossary("Symbol")}} and the {{jsxref("Symbol")}} object wrapper in JavaScript.</p> + +<h2 id="Objetos">Objetos</h2> + +<p>In computer science, an object is a value in memory which is possibly referenced by an {{Glossary("Identifier", "identifier")}}.</p> + +<h3 id="Propriedades">Propriedades</h3> + +<p>In JavaScript, objects can be seen as a collection of properties. With the <a href="/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Object_literals">object literal syntax</a>, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.</p> + +<p>There are two types of object properties which have certain attributes: The data property and the accessor property.</p> + +<h4 id="Data_property">Data property</h4> + +<p>Associates a key with a value and has the following attributes:</p> + +<table class="standard-table"> + <caption>Attributes of a data property</caption> + <tbody> + <tr> + <th>Attribute</th> + <th>Type</th> + <th>Description</th> + <th>Default value</th> + </tr> + <tr> + <td>[[Value]]</td> + <td>Any JavaScript type</td> + <td>The value retrieved by a get access of the property.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Writable]]</td> + <td>Boolean</td> + <td>If <code>false</code>, the property's [[Value]] can't be changed.</td> + <td>false</td> + </tr> + <tr> + <td>[[Enumerable]]</td> + <td>Boolean</td> + <td>If <code>true</code>, the property will be enumerated in <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> loops. See also <a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></td> + <td>false</td> + </tr> + <tr> + <td>[[Configurable]]</td> + <td>Boolean</td> + <td>If <code>false</code>, the property can't be deleted and attributes other than [[Value]] and [[Writable]] can't be changed.</td> + <td>false</td> + </tr> + </tbody> +</table> + +<table class="standard-table"> + <caption>Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)</caption> + <tbody> + <tr> + <th>Attribute</th> + <th>Type</th> + <th>Description</th> + </tr> + <tr> + <td>Read-only</td> + <td>Boolean</td> + <td>Reversed state of the ES5 [[Writable]] attribute.</td> + </tr> + <tr> + <td>DontEnum</td> + <td>Boolean</td> + <td>Reversed state of the ES5 [[Enumerable]] attribute.</td> + </tr> + <tr> + <td>DontDelete</td> + <td>Boolean</td> + <td>Reversed state of the ES5 [[Configurable]] attribute.</td> + </tr> + </tbody> +</table> + +<h4 id="Accessor_property">Accessor property</h4> + +<p>Associates a key with one or two accessor functions (get and set) to retrieve or store a value and has the following attributes:</p> + +<table class="standard-table"> + <caption>Attributes of an accessor property</caption> + <tbody> + <tr> + <th>Attribute</th> + <th>Type</th> + <th>Description</th> + <th>Default value</th> + </tr> + <tr> + <td>[[Get]]</td> + <td>Function object or undefined</td> + <td>The function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed. See also <a href="/en-US/docs/Web/JavaScript/Reference/Operators/get"><code>get</code></a>.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Set]]</td> + <td>Function object or undefined</td> + <td>The function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed. See also <a href="/en-US/docs/Web/JavaScript/Reference/Operators/set"><code>set</code></a>.</td> + <td>undefined</td> + </tr> + <tr> + <td>[[Enumerable]]</td> + <td>Boolean</td> + <td>If <code>true</code>, the property will be enumerated in <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a> loops.</td> + <td>false</td> + </tr> + <tr> + <td>[[Configurable]]</td> + <td>Boolean</td> + <td>If <code>false</code>, the property can't be deleted and can't be changed to a data property.</td> + <td>false</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Note: </strong>Attribute is usually used by JavaScript engine, so you can't directly access it(see more about <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty()</a>).That's why the attribute is put in double square brackets instead of single.</p> +</div> + +<h3 id="Objetos_Normal_e_funções">Objetos "Normal", e funções</h3> + +<p>A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s) and values can be anything. This makes objects a natural fit for <a class="external" href="http://en.wikipedia.org/wiki/Hash_table">hashmaps</a>.</p> + +<p>Functions are regular objects with the additional capability of being callable.</p> + +<h3 id="Dates"><em>Dates</em></h3> + +<p>When representing dates, the best choice is to use the built-in <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code> utility</a> in JavaScript.</p> + +<h3 id="Coleções_indexadas_Arrays_e_Arrays_digitados">Coleções indexadas: <em>Arrays </em>e <em>Arrays </em>digitados</h3> + +<p><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="Array">Arrays</a> are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from <code>Array.prototype</code> which provides to them a handful of convenient methods to manipulate arrays. For example, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" title="en/JavaScript/Reference/Global_Objects/Array/indexOf">indexOf</a></code> (searching a value in the array) or <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Array/push" title="en/JavaScript/Reference/Global_Objects/Array/push">push</a></code> (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.</p> + +<p><a href="/en-US/docs/Web/JavaScript/Typed_arrays">Typed Arrays</a> are new to JavaScript with ECMAScript Edition 6 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:</p> + +<p>{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}</p> + +<h3 id="Keyed_collections_Maps_Sets_WeakMaps_WeakSets">Keyed collections: Maps, Sets, WeakMaps, WeakSets</h3> + +<p>These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.</p> + +<p>One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.</p> + +<p>Usually, to bind data to a DOM node, one could set properties directly on the object or use <code>data-*</code> attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.</p> + +<h3 id="Structured_data_JSON">Structured data: JSON</h3> + +<p>JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.</p> + +<h3 id="More_objects_in_the_standard_library">More objects in the standard library</h3> + +<p>JavaScript has a standard library of built-in objects. Please have a look at the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">reference</a> to find out about more objects.</p> + +<h2 id="Determining_types_using_the_typeof_operator">Determining types using the <code>typeof</code> operator</h2> + +<p>The <code>typeof</code> operator can help you to find the type of your variable. Please read the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof">reference page</a> for more details and edge cases.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-8', 'Types')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a class="link-https" href="https://github.com/nzakas/computer-science-in-javascript/">Nicholas Zakas collection of common data structure and common algorithms in JavaScript.</a></li> + <li><a href="https://github.com/monmohan/DataStructures_In_Javascript" title="https://github.com/monmohan/DataStructures_In_Javascript">Search Tre(i)es implemented in JavaScript</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/gestao_memoria/index.html b/files/pt-pt/web/javascript/gestao_memoria/index.html new file mode 100644 index 0000000000..56bfec0f7f --- /dev/null +++ b/files/pt-pt/web/javascript/gestao_memoria/index.html @@ -0,0 +1,187 @@ +--- +title: Gestão de memória +slug: Web/JavaScript/Gestao_Memoria +tags: + - Desempenho + - JavaScript + - memoria +translation_of: Web/JavaScript/Memory_Management +--- +<div>{{JsSidebar("Advanced")}}</div> + +<h2 id="Introdução">Introdução</h2> + +<p>Linguagens de baixo nível, como o C, têm funções pimitivas de gestão de memória, como por exemplo, <code>malloc()</code> e <code>free()</code>. Por outro lado, os valores em JavaScript são alocados quando coisas (objetos, variáveis de texto, etc.) são criadas e "automaticamente" libertadas da memória quando deixam de ser utilizadas. O último processo é chamado de <em>coleção do lixo</em>. Este "automatismo" é uma fonte de mal entendidos e transmite aos programadores de JavaScript ( e aos de outras linguagens de alto nível ) a impressão de que podem decidir não se preocupar com a gestão da memória. Isto é uma erro.</p> + +<h2 id="Ciclo_da_duração_da_memória">Ciclo da duração da memória</h2> + +<p>Independentemente da linguagem de programação, o ciclo da duração da memória é praticamente sempre o mesmo:</p> + +<ol> + <li>Alocação da memória necessária</li> + <li>Utilização da memória alocada ( leitura, escrita )</li> + <li>Libertar a memória alocada quando já não é necessária</li> +</ol> + +<p>A segunda etapa é explícita em todas as linguagens. A primeira e a última etapa são explícitas em linguagens de baixo nível mas são, na sua maioria, implícitas em linguagens de alto nível como o JavaScript.</p> + +<h3 id="Alocação_no_JavaScript">Alocação no JavaScript</h3> + +<h4 id="Inicialização_do_valor">Inicialização do valor</h4> + +<p>Com o intuito de não incomodar o programador com alocações, o JavaScript fá-lo juntamente com a declaração de valores.</p> + +<pre class="brush: js">var n = 123; // alocação da memória para um número +var s = 'azerty'; // alocação de memória para um texto + +var o = { + a: 1, + b: null +}; // alocação de memória para um objeto e o seu conteúdo + +// (similar ao objeto) alocação de memória para a matriz e +// os seus valores +var a = [1, null, 'abra']; + +function f(a) { + return a + 2; +} // alocação de uma função (que é um objeto que pode ser chamado) + +// Expressões de funções também alocam um objeto +someElement.addEventListener('click', function() { + someElement.style.backgroundColor = 'blue'; +}, false); +</pre> + +<h4 id="Alocação_através_de_chamadas_de_funções">Alocação através de chamadas de funções</h4> + +<p>Algumas chamadas de funções resultam na alocação de um objeto.</p> + +<pre class="brush: js">var d = new Date(); // alocação de um objeto <em>Date</em> + +var e = document.createElement('div'); // alocação de um elemento DOM</pre> + +<p>Alguns métodos alocam novos valores ou objetos:</p> + +<pre class="brush: js">var s = 'azerty'; +var s2 = s.substr(0, 3); // s2 é uma nova variável de texto +// Dado que as variáveis de texto são de valor imutável, +// o JavaScript pode decidir não alocar memória, +// mas apenas armazenar o intervalo [0, 3]. + +var a = ['ouais ouais', 'nan nan']; +var a2 = ['generation', 'nan nan']; +var a3 = a.concat(a2); +// nova matriz de 4 elementos resultando +// da concatenação dos elementos de <em>a</em> e <em>a2</em> +</pre> + +<h3 id="Utilização_de_valores">Utilização de valores</h3> + +<p>Basicamente, a utilização de valores significa a leitura e a escrita na memória alocada. Isto pode ser feito através da leitura ou escrita do valor de uma variável ou uma propriedade de um objeto ou até a passagem de um argumento para uma função.</p> + +<h3 id="Remoção_quando_a_memória_já_não_é_necessária">Remoção quando a memória já não é necessária</h3> + +<p>A maioria dos problemas de gestão de memória aparecem nesta fase. A tarefa mais difícil é descobrir quando "a memória alocada já não é necessária". Em geral, requer que o programador determine quando, no seu código, este pedaço de memória já não é necessário e a liberte.</p> + +<p>Linguagens de alto nível têm embutidas um pedaço de código chamado "coleção de lixo", cuja tarefa é rastrear a alocação e uso da memória, para detetar quando um pedaço de memória já não é necessário e neste caso, automaticamente libertá-la. Este processo é uma aproximação dado que o problema geral de se saber quando um pedaço da memória é necessário, é <a class="external" href="https://pt.wikipedia.org/wiki/Decidibilidade">indecisível</a> ( não pode ser solucionado por um algoritmo ).</p> + +<h2 id="Coleção_de_lixo">Coleção de lixo</h2> + +<p>Como mencionado anteriormente, o problema geral de automaticamente descobrir quando alguma ocupação de memória "já não é necessária", é indecisível. Como consequência, as coleções de lixo implementam uma restrição à solução para o problema em geral. Esta seção explicará as noções necessárias para se compreender os principais algoritmos da coleção de lixo e as suas limitações.</p> + +<h3 id="Referências">Referências</h3> + +<p>A noção principal dos algoritmos de coleção de lixo baseiam-se na noção de <em>referência</em>. Dentro do contexto da gestão de memória, um objeto é dito referenciar outro objeto, se o primeiro tiver acesso ao segundo ( quer implicitamente quer explicitamente ). Por exemplo, um objeto JavaScript tem uma referência ao seu <a href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain">protótipo</a> ( referência implícita ) e aos valores das suas propriedades ( referência explícita ).</p> + +<p>Neste contexto, a noção de "objeto" é expandida a algo mais abrangente que um objeto JavaScript e também contém âmbitos de funções ( ou âmbito léxico global ).</p> + +<h3 id="Contagem_de_referências_na_coleção_de_lixo">Contagem de referências na coleção de lixo</h3> + +<p>Este é o algoritmo mais simples da coleção de lixo. Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto já não é referenciado por nenhum outro objeto". Um objeto é considerado coletável para a coleção de lixo se tiver nenhuma referenciação por parte de outro objeto.</p> + +<h4 id="Exemplo">Exemplo</h4> + +<pre class="brush: js">var o = { + a: { + b: 2 + } +}; +// 2 objetos criados. Um é referenciado por outro como sendo suas propriedades +// O outro é referenciado por virtude ao ser assignado para a variável 'o' +// Obviamente, nenhum podem ser coletado pela coleção de lixo + + +var o2 = o; // A variável 'o2' é a segunda coisa que + // tem uma referência ao objeto +o = 1; // agora, o objeto que era originalmente o 'o' tem uma referência única + // corporificada pela variável 'o2' + +var oa = o2.a; // referência à propriedade 'a' do objeto. + // Este objeto tem agora 2 referências: uma como propriedade, + // a outra como variável 'oa' + +o2 = 'yo'; // O objeto que era o original 'o' tem agora zero + // referências a si próprio. Pode ser coletado para a coleção de lixo + // No entanto, a propriedade 'a' ainda é referenciada pela + // variável 'oa', logo não pode ser libertado + +oa = null; // A propriedade 'a' do objeto original 'o' + // tem zero referências a si próprio. Pode ser coletado para a coleção de lixo. +</pre> + +<h4 id="Limitação_ciclos">Limitação: ciclos</h4> + +<p>Existe uma limitação no que se refere aos ciclos. No exemplo seguinte, dois objetos são criados e referenciam-se mutuamente, criando um ciclo. Estes sairão do âmbito depois de uma chamada a uma função e como tal, são efetivamente inúteis e podem ser libertados. No entanto, o algoritmo de contagem de referências considera que os dois objetos têm pelo menos uma referenciação; nenhum pode ser coletado para a coleção de lixo .</p> + +<pre class="brush: js">function f() { + var o = {}; + var o2 = {}; + o.a = o2; // o referencia o2 + o2.a = o; // o2 referencia o + + return 'azerty'; +} + +f(); +</pre> + +<h4 id="Exemplo_de_aplicação_real">Exemplo de aplicação real</h4> + +<p>O Internet Explorer 6 e 7 são conhecidos por terem um coletor de contagem de referenciações de coleções de lixo para os objetos DOM. Os ciclos são um erro comum que podem gerar percas de memória:</p> + +<pre class="brush: js">var div; +window.onload = function() { + div = document.getElementById('myDivElement'); + div.circularReference = div; + div.lotsOfData = new Array(10000).join('*'); +}; +</pre> + +<p>No exemplo acima, o elemento DOM "myDivElement" tem uma referência circular a si próprio na propriedade "circularReference". Se a propriedade não for explicitamente removida ou anulada, o coletor de contagem de referências da coleção de lixo, irá sempre ter uma referenciação intacta e irá manter o elemento DOM na memória mesmo quando for removido da árvore DOM. Se o elemento DOM contém bastante dados ( ilustrado no exemplo acima com a propriedade "lotsOfData" ), a memória consumida por estes dados nunca será libertada.</p> + +<h3 id="Algoritmo_de_marcação_e_limpeza">Algoritmo de marcação e limpeza</h3> + +<p>Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto é inalcançável".</p> + +<p>Este algoritmo assume o conhecimento de um conjunto de objetos chamados "roots" ( em JavaScript, a <em>root</em> - raiz - é um objeto global ). Periodicamente, a coleção de lixo começará pela raíz e procurará todos os objetos que são referenciados a partir desta; depois todos os que são referenciados a partir dos seguintes, etc.. Começando pela raiz, o coletor de lixo irá localizar objetos inalcançáveis; coletando-os.</p> + +<p>Este algoritmo é melhor do que o anterior dado que "um objeto tem zero referenciações" leva a um objeto inalcançável. O contrário não é verdade como vimos nos ciclos.</p> + +<p>Desde 2012, todos os modernos navegadores de Internet contêm um coletor de marcação e limpeza. Todos os melhoramentos feitos na área da coleção de lixo no JavaScript ( generalização / incrementação / concorrência / coleção de lixo paralela ) nos últimos anos são implemetações de melhoramento deste algoritmo, mas não melhoramentos do algoritmo de coleção de lixo em si nem a sua redução à definição de que quando "um objeto já não é necessário".</p> + +<h4 id="Os_ciclos_já_não_são_um_problema.">Os ciclos já não são um problema.</h4> + +<p>No primeiro exemplo acima, depois do retorno da chamada à função, 2 objetos já não são referenciados por algo alcançável no objeto global. Consequentemente, irão ser localizados pelo coletor da coleção de lixo.</p> + +<h4 id="Limitações_os_objetos_necessitam_de_ser_explicitamente_inalcançáveis">Limitações: os objetos necessitam de ser explicitamente inalcançáveis</h4> + +<p>Apesar disto estar marcado como uma limitação, é um caso que raramente ocorre na prática pelo que é por isto que ninguém se preocupa muito com a coleção de lixo.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a class="external" href="http://www.ibm.com/developerworks/web/library/wa-memleak/">Aritgo da IBM sobre "Padrões de percas de memória no JavaScript" (2007)</a></li> + <li><a class="external" href="http://msdn.microsoft.com/en-us/magazine/ff728624.aspx">Artigo da Kangax sobre como registar um apontador de evento e evitar percas de memória (2010)</a></li> + <li><a href="https://developer.mozilla.org/pt-PT/docs/Mozilla/Performance" title="https://developer.mozilla.org/en-US/docs/Mozilla/Performance">Desempenho</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html b/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html new file mode 100644 index 0000000000..01de143289 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html @@ -0,0 +1,735 @@ +--- +title: Detalhes do modelo de objeto +slug: Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto +tags: + - Guia(2) + - Intermediário + - JavaScript + - Objeto +translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> + +<div class="note"> +<p>The content of this article is under discussion. Please provide feedback and help us to make this page better: {{bug(1201380)}}.</p> +</div> + +<p class="summary">JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This chapter attempts to clarify the situation.</p> + +<p>This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.</p> + +<h2 id="Linguagens_com_base_em_classe_versus_protótipo">Linguagens com base em classe versus protótipo</h2> + +<p>Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.</p> + +<ul> + <li>A <em>class</em> defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the <code>Employee</code> class could represent the set of all employees.</li> + <li>An <em>instance</em>, on the other hand, is the instantiation of a class; that is, one of its members. For example, <code>Victoria</code> could be an instance of the <code>Employee</code> class, representing a particular individual as an employee. An instance has exactly the same properties of its parent class (no more, no less).</li> +</ul> + +<p>A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a <em>prototypical object</em>, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the <em>prototype</em> for another object, allowing the second object to share the first object's properties.</p> + +<h3 id="Definição_de_uma_classe">Definição de uma classe</h3> + +<p>In class-based languages, you define a class in a separate <em>class definition</em>. In that definition you can specify special methods, called <em>constructors</em>, to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the <code>new</code> operator in association with the constructor method to create class instances.</p> + +<p>JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the <code>new</code> operator with a constructor function to create a new object.</p> + +<h3 id="Subclasses_e_sucessão">Subclasses e sucessão</h3> + +<p>In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a <em>subclass</em> of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the <code>Employee</code> class includes only the <code>name</code> and <code>dept</code> properties, and <code>Manager</code> is a subclass of <code>Employee</code> that adds the <code>reports</code> property. In this case, an instance of the <code>Manager</code> class would have all three properties: <code>name</code>, <code>dept</code>, and <code>reports</code>.</p> + +<p>JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the <code>Employee</code> — <code>Manager</code> example, but you use slightly different terminology. First you define the <code>Employee</code> constructor function, specifying the <code>name</code> and <code>dept</code> properties. Next, you define the <code>Manager</code> constructor function, calling the <code>Empl</code><code>oyee</code> constructor and specifying the <code>reports</code> property. Finally, you assign a new object derived from <code>Employee.prototype</code> as the <code>prototype</code> for the <code>Manager</code> constructor function. Then, when you create a new <code>Manager</code>, it inherits the <code>name</code> and <code>dept</code> properties from the <code>Employee</code> object.</p> + +<h3 id="Adição_e_remoção_de_propriedades">Adição e remoção de propriedades</h3> + +<p>In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at run time. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at run time you can add or remove properties of any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.</p> + +<h3 id="Resumo_das_diferenças">Resumo das diferenças</h3> + +<p>The following table gives a short summary of some of these differences. The rest of this chapter describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.</p> + +<table class="standard-table"> + <caption>Comparison of class-based (Java) and prototype-based (JavaScript) object systems</caption> + <thead> + <tr> + <th scope="col">Com base em Classe (Java)</th> + <th scope="col">Com base em Protótipo (JavaScript)</th> + </tr> + </thead> + <tbody> + <tr> + <td>Class and instance are distinct entities.</td> + <td>All objects can inherit from another object.</td> + </tr> + <tr> + <td>Define a class with a class definition; instantiate a class with constructor methods.</td> + <td>Define and create a set of objects with constructor functions.</td> + </tr> + <tr> + <td>Create a single object with the <code>new</code> operator.</td> + <td>Same.</td> + </tr> + <tr> + <td>Construct an object hierarchy by using class definitions to define subclasses of existing classes.</td> + <td>Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.</td> + </tr> + <tr> + <td>Inherit properties by following the class chain.</td> + <td>Inherit properties by following the prototype chain.</td> + </tr> + <tr> + <td>Class definition specifies <em>all</em> properties of all instances of a class. Cannot add properties dynamically at run time.</td> + <td>Constructor function or prototype specifies an <em>initial set</em> of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.</td> + </tr> + </tbody> +</table> + +<h2 id="The_employee_example">The employee example</h2> + +<p>The remainder of this chapter uses the employee hierarchy shown in the following figure.</p> + +<div style="display: table-row;"> +<div style="display: table-cell; width: 350px; text-align: center; vertical-align: middle; padding: 10px;"> +<p>A simple object hierarchy with the following objects:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/3060/figure8.1.png"></p> +</div> + +<div style="display: table-cell; vertical-align: middle; padding: 10px;"> +<ul> + <li><code>Employee</code> has the properties <code>name</code> (whose value defaults to the empty string) and <code>dept</code> (whose value defaults to "general").</li> + <li><code>Manager</code> is based on <code>Employee</code>. It adds the <code>reports</code> property (whose value defaults to an empty array, intended to have an array of <code>Employee</code> objects as its value).</li> + <li><code>WorkerBee</code> is also based on <code>Employee</code>. It adds the <code>projects</code> property (whose value defaults to an empty array, intended to have an array of strings as its value).</li> + <li><code>SalesPerson</code> is based on <code>WorkerBee</code>. It adds the <code>quota</code> property (whose value defaults to 100). It also overrides the <code>dept</code> property with the value "sales", indicating that all salespersons are in the same department.</li> + <li><code>Engineer</code> is based on <code>WorkerBee</code>. It adds the <code>machine</code> property (whose value defaults to the empty string) and also overrides the <code>dept</code> property with the value "engineering".</li> +</ul> +</div> +</div> + +<h2 id="Criação_de_hierarquia">Criação de hierarquia</h2> + +<p>There are several ways to define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application.</p> + +<p>This section shows how to use very simple (and comparatively inflexible) definitions to demonstrate how to get the inheritance to work. In these definitions, you cannot specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time.</p> + +<p>In a real application, you would probably define constructors that allow you to provide property values at object creation time (see <a href="#More_flexible_constructors">More flexible constructors</a> for information). For now, these simple definitions demonstrate how the inheritance occurs.</p> + +<p>The following Java and JavaScript <code>Employee</code> definitions are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript (this is due to Java being a <a href="http://en.wikipedia.org/wiki/Strong_and_weak_typing">strongly typed language</a> while JavaScript is a weakly typed language).</p> + +<div class="twocolumns"> +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">function Employee() { + this.name = ""; + this.dept = "general"; +} +</pre> + +<h4 id="Java">Java</h4> + +<pre class="brush: java">public class Employee { + public String name = ""; + public String dept = "general"; +} +</pre> +</div> + +<p>The <code>Manager</code> and <code>WorkerBee</code> definitions show the difference in how to specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the <code>prototype</code> property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_2">JavaScript</h4> + +<pre class="brush: js">function Manager() { + Employee.call(this); + this.reports = []; +} +Manager.prototype = Object.create(Employee.prototype); + +function WorkerBee() { + Employee.call(this); + this.projects = []; +} +WorkerBee.prototype = Object.create(Employee.prototype); +</pre> + +<h4 id="Java_2">Java</h4> + +<pre class="brush: java">public class Manager extends Employee { + public Employee[] reports = new Employee[0]; +} + + + +public class WorkerBee extends Employee { + public String[] projects = new String[0]; +} + + +</pre> +</div> + +<p>The <code>Engineer</code> and <code>SalesPerson</code> definitions create objects that descend from <code>WorkerBee</code> and hence from <code>Employee</code>. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the <code>dept</code> property with new values specific to these objects.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_3">JavaScript</h4> + +<pre class="brush: js">function SalesPerson() { + WorkerBee.call(this); + this.dept = "sales"; + this.quota = 100; +} +SalesPerson.prototype = Object.create(WorkerBee.prototype); + +function Engineer() { + WorkerBee.call(this); + this.dept = "engineering"; + this.machine = ""; +} +Engineer.prototype = Object.create(WorkerBee.prototype); +</pre> + +<h4 id="Java_3">Java</h4> + +<pre class="brush: java">public class SalesPerson extends WorkerBee { + public double quota; + public dept = "sales"; + public quota = 100.0; +} + + +public class Engineer extends WorkerBee { + public String machine; + public dept = "engineering"; + public machine = ""; +} + +</pre> +</div> + +<p>Using these definitions, you can create instances of these objects that get the default values for their properties. The next figure illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.</p> + +<div class="note"> +<p><strong>Nota:</strong> The term <em><em>instance</em></em> has a specific technical meaning in class-based languages. In these languages, an instance is an individual instantiation of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that <code><code>jane</code></code> is an instance of <code><code>Engineer</code></code>. Similarly, although the terms <em><em>parent</em>, <em>child</em>, <em>ancestor</em></em>, and <em><em>descendant</em></em> do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.</p> +</div> + +<h3 id="Criação_de_objetos_com_definições_simples">Criação de objetos com definições simples</h3> + +<div class="twocolumns"> +<h4 id="Hierarquia_do_objeto">Hierarquia do objeto</h4> + +<p>The following hierarchy is created using the code on the right side.</p> + +<p><img src="https://mdn.mozillademos.org/files/10412/=figure8.3.png"></p> + +<p> </p> + +<h4 id="individual_objects">individual objects</h4> + +<pre class="brush: js">var jim = new Employee; +// jim.name is '' +// jim.dept is 'general' + +var sally = new Manager; +// sally.name is '' +// sally.dept is 'general' +// sally.reports is [] + +var mark = new WorkerBee; +// mark.name is '' +// mark.dept is 'general' +// mark.projects is [] + +var fred = new SalesPerson; +// fred.name is '' +// fred.dept is 'sales' +// fred.projects is [] +// fred.quota is 100 + +var jane = new Engineer; +// jane.name is '' +// jane.dept is 'engineering' +// jane.projects is [] +// jane.machine is '' +</pre> +</div> + +<h2 id="Propriedades_do_objeto">Propriedades do objeto</h2> + +<p>This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at run time.</p> + +<h3 id="Propriedades_de_sucessão">Propriedades de sucessão</h3> + +<p>Suppose you create the <code>mark</code> object as a <code>WorkerBee</code> with the following statement:</p> + +<pre class="brush: js">var mark = new WorkerBee; +</pre> + +<p>When JavaScript sees the <code>new</code> operator, it creates a new generic object and passes this new object as the value of the <code>this</code> keyword to the <code>WorkerBee</code> constructor function. The constructor function explicitly sets the value of the <code>projects</code> property, and implicitly sets the value of the internal <code>__proto__</code> property to the value of <code>WorkerBee.prototype</code>. (That property name has two underscore characters at the front and two at the end.) The <code>__proto__</code> property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable <code>mark</code> to that object.</p> + +<p>This process does not explicitly put values in the <code>mark</code> object (<em>local</em> values) for the properties that <code>mark</code> inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value is not there locally, JavaScript checks the prototype chain (using the <code>__proto__</code> property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object does not have the property. In this way, the <code>mark</code> object has the following properties and values:</p> + +<pre class="brush: js">mark.name = ""; +mark.dept = "general"; +mark.projects = []; +</pre> + +<p>The <code>mark</code> object inherits values for the <code>name</code> and <code>dept</code> properties from the prototypical object in <code>mark.__proto__</code>. It is assigned a local value for the <code>projects</code> property by the <code>WorkerBee</code> constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in <a href="#Property_inheritance_revisited">Property inheritance revisited</a>.</p> + +<p>Because these constructors do not let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from <code>WorkerBee</code>. You can, of course, change the values of any of these properties. So, you could give specific information for <code>mark</code> as follows:</p> + +<pre class="brush: js">mark.name = "Doe, Mark"; +mark.dept = "admin"; +mark.projects = ["navigator"];</pre> + +<h3 id="Adição_de_propriedades">Adição de propriedades</h3> + +<p>In JavaScript, you can add properties to any object at run time. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you assign a value to the object, as follows:</p> + +<pre class="brush: js">mark.bonus = 3000; +</pre> + +<p>Now, the <code>mark</code> object has a <code>bonus</code> property, but no other <code>WorkerBee</code> has this property.</p> + +<p>If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a <code>specialty</code> property to all employees with the following statement:</p> + +<pre class="brush: js">Employee.prototype.specialty = "none"; +</pre> + +<p>As soon as JavaScript executes this statement, the <code>mark</code> object also has the <code>specialty</code> property with the value of <code>"none"</code>. The following figure shows the effect of adding this property to the <code>Employee</code> prototype and then overriding it for the <code>Engineer</code> prototype.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4422/=figure8.4.png" style="height: 519px; width: 833px;"><br> + <small><strong>Adding properties</strong></small></p> + +<h2 id="Mais_construtores_flexíveis">Mais construtores flexíveis</h2> + +<p>The constructor functions shown so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. The following figure shows one way to do this.</p> + +<p><img alt="" class="internal" id="figure8.5" src="/@api/deki/files/4423/=figure8.5.png" style="height: 481px; width: 1012px;"><br> + <small><strong>Specifying properties in a constructor, take 1</strong></small></p> + +<p>The following table shows the Java and JavaScript definitions for these objects.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_4">JavaScript</h4> + +<h4 id="Java_4">Java</h4> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; +} +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class Employee { + public String name; + public String dept; + public Employee () { + this("", "general"); + } + public Employee (String name) { + this(name, "general"); + } + public Employee (String name, String dept) { + this.name = name; + this.dept = dept; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function WorkerBee (projs) { + + this.projects = projs || []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class WorkerBee extends Employee { + public String[] projects; + public WorkerBee () { + this(new String[0]); + } + public WorkerBee (String[] projs) { + projects = projs; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js"> +function Engineer (mach) { + this.dept = "engineering"; + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class Engineer extends WorkerBee { + public String machine; + public Engineer () { + dept = "engineering"; + machine = ""; + } + public Engineer (String mach) { + dept = "engineering"; + machine = mach; + } +} +</pre> +</div> + +<p>These JavaScript definitions use a special idiom for setting default values:</p> + +<pre class="brush: js">this.name = name || ""; +</pre> + +<p>The JavaScript logical OR operator (<code>||</code>) evaluates its first argument. If that argument converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if <code>name</code> has a useful value for the <code>name</code> property. If it does, it sets <code>this.name</code> to that value. Otherwise, it sets <code>this.name</code> to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.</p> + +<div class="note"> +<p><strong>Note:</strong> This may not work as expected if the constructor function is called with arguments which convert to <code><code>false</code></code> (like <code>0</code> (zero) and empty string (<code><code>""</code></code>). In this case the default value will be chosen.</p> +</div> + +<p>With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. You can use the following statement to create a new <code>Engineer</code>:</p> + +<pre class="brush: js">var jane = new Engineer("belau"); +</pre> + +<p><code>Jane</code>'s properties are now:</p> + +<pre class="brush: js">jane.name == ""; +jane.dept == "engineering"; +jane.projects == []; +jane.machine == "belau" +</pre> + +<p>Notice that with these definitions, you cannot specify an initial value for an inherited property such as <code>name</code>. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.</p> + +<p>So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. The following figure shows these new definitions.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4430/=figure8.6.png" style="height: 534px; width: 1063px;"><br> + <small><strong>Specifying properties in a constructor, take 2</strong></small></p> + +<p>Let's look at one of these definitions in detail. Here's the new definition for the <code>Engineer</code> constructor:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +</pre> + +<p>Suppose you create a new <code>Engineer</code> object as follows:</p> + +<pre class="brush: js">var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +</pre> + +<p>JavaScript follows these steps:</p> + +<ol> + <li>The <code>new</code> operator creates a generic object and sets its <code>__proto__</code> property to <code>Engineer.prototype</code>.</li> + <li>The <code>new</code> operator passes the new object to the <code>Engineer</code> constructor as the value of the <code>this</code> keyword.</li> + <li>The constructor creates a new property called <code>base</code> for that object and assigns the value of the <code>WorkerBee</code> constructor to the <code>base</code> property. This makes the <code>WorkerBee</code> constructor a method of the <code>Engineer</code> object.The name of the<code> base</code> property is not special. You can use any legal property name; <code>base</code> is simply evocative of its purpose.</li> + <li> + <p>The constructor calls the <code>base</code> method, passing as its arguments two of the arguments passed to the constructor (<code>"Doe, Jane"</code> and <code>["navigator", "javascript"]</code>) and also the string <code>"engineering"</code>. Explicitly using <code>"engineering"</code> in the constructor indicates that all <code>Engineer</code> objects have the same value for the inherited <code>dept</code> property, and this value overrides the value inherited from <code>Employee</code>.</p> + </li> + <li>Because <code>base</code> is a method of <code>Engineer</code>, within the call to <code>base</code>, JavaScript binds the <code>this</code> keyword to the object created in Step 1. Thus, the <code>WorkerBee</code> function in turn passes the <code>"Doe, Jane"</code> and <code>"engineering"</code> arguments to the <code>Employee</code> constructor function. Upon return from the <code>Employee</code> constructor function, the <code>WorkerBee</code> function uses the remaining argument to set the <code>projects</code> property.</li> + <li>Upon return from the <code>base</code> method, the <code>Engineer</code> constructor initializes the object's <code>machine</code> property to <code>"belau"</code>.</li> + <li>Upon return from the constructor, JavaScript assigns the new object to the <code>jane</code> variable.</li> +</ol> + +<p>You might think that, having called the <code>WorkerBee</code> constructor from inside the <code>Engineer</code> constructor, you have set up inheritance appropriately for <code>Engineer</code> objects. This is not the case. Calling the <code>WorkerBee</code> constructor ensures that an <code>Engineer</code> object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the <code>Employee</code> or <code>WorkerBee</code> prototypes, those properties are not inherited by the <code>Engineer</code> object. For example, assume you have the following statements:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +Employee.prototype.specialty = "none"; +</pre> + +<p>The <code>jane</code> object does not inherit the <code>specialty</code> property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; +var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +Employee.prototype.specialty = "none"; +</pre> + +<p>Now the value of the <code>jane</code> object's <code>specialty</code> property is "none".</p> + +<p>Another way of inheriting is by using the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global Objects/Function/call">call()</a></code> / <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="en-US/docs/JavaScript/Reference/Global Objects/Function/apply"><code>apply()</code></a> methods. Below are equivalent:</p> + +<div class="twocolumns"> +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +</pre> + +<pre class="brush: js">function Engineer (name, projs, mach) { + WorkerBee.call(this, name, "engineering", projs); + this.machine = mach || ""; +} +</pre> +</div> + +<p>Using the javascript <code>call()</code> method makes a cleaner implementation because the <code>base</code> is not needed anymore.</p> + +<h2 id="Sucessão_de_propriedade_revisitada">Sucessão de propriedade revisitada</h2> + +<p>The preceding sections described how JavaScript constructors and prototypes provide hierarchies and inheritance. This section discusses some subtleties that were not necessarily apparent in the earlier discussions.</p> + +<h3 id="Valores_locais_versus_sucedidos">Valores locais versus sucedidos</h3> + +<p>When you access an object property, JavaScript performs these steps, as described earlier in this chapter:</p> + +<ol> + <li>Check to see if the value exists locally. If it does, return that value.</li> + <li>If there is not a local value, check the prototype chain (using the <code>__proto__</code> property).</li> + <li>If an object in the prototype chain has a value for the specified property, return that value.</li> + <li>If no such property is found, the object does not have the property.</li> +</ol> + +<p>The outcome of these steps depends on how you define things along the way. The original example had these definitions:</p> + +<pre class="brush: js">function Employee () { + this.name = ""; + this.dept = "general"; +} + +function WorkerBee () { + this.projects = []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p>With these definitions, suppose you create <code>amy</code> as an instance of <code>WorkerBee</code> with the following statement:</p> + +<pre class="brush: js">var amy = new WorkerBee; +</pre> + +<p>The <code>amy</code> object has one local property, <code>projects</code>. The values for the <code>name</code> and <code>dept</code> properties are not local to <code>amy</code> and so derive from the <code>amy</code> object's <code>__proto__</code> property. Thus, <code>amy</code> has these property values:</p> + +<pre class="brush: js">amy.name == ""; +amy.dept == "general"; +amy.projects == []; +</pre> + +<p>Now suppose you change the value of the <code>name</code> property in the prototype associated with <code>Employee</code>:</p> + +<pre class="brush: js">Employee.prototype.name = "Unknown" +</pre> + +<p>At first glance, you might expect that new value to propagate down to all the instances of <code>Employee</code>. However, it does not.</p> + +<p>When you create <em>any</em> instance of the <code>Employee</code> object, that instance gets a local value for the <code>name</code> property (the empty string). This means that when you set the <code>WorkerBee</code> prototype by creating a new <code>Employee</code> object, <code>WorkerBee.prototype</code> has a local value for the <code>name</code> property. Therefore, when JavaScript looks up the <code>name</code> property of the <code>amy</code> object (an instance of <code>WorkerBee</code>), JavaScript finds the local value for that property in <code>WorkerBee.prototype</code>. It therefore does not look further up the chain to <code>Employee.prototype</code>.</p> + +<p>If you want to change the value of an object property at run time and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the preceding code to the following:</p> + +<pre class="brush: js">function Employee () { + this.dept = "general"; +} +Employee.prototype.name = ""; + +function WorkerBee () { + this.projects = []; +} +WorkerBee.prototype = new Employee; + +var amy = new WorkerBee; + +Employee.prototype.name = "Unknown"; +</pre> + +<p>In this case, the <code>name</code> property of <code>amy</code> becomes "Unknown".</p> + +<p>As these examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself.</p> + +<h3 id="Determining_instance_relationships">Determining instance relationships</h3> + +<p>Property lookup in JavaScript looks within an object's own properties and, if the property name is not found, it looks within the special object property <code>__proto__</code>. This continues recursively; the process is called "lookup in the prototype chain".</p> + +<p>The special property <code>__proto__</code> is set when an object is constructed; it is set to the value of the constructor's <code>prototype</code> property. So the expression <code>new Foo()</code> creates an object with <code>__proto__ == <code class="moz-txt-verticalline">Foo.prototype</code></code>. Consequently, changes to the properties of <code class="moz-txt-verticalline">Foo.prototype</code> alters the property lookup for all objects that were created by <code>new Foo()</code>.</p> + +<p>Every object has a <code>__proto__</code> object property (except <code>Object</code>); every function has a <code>prototype</code> object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's <code>__proto__</code> to a function's <code>prototype</code> object. JavaScript provides a shortcut: the <code>instanceof</code> operator tests an object against a function and returns true if the object inherits from the function prototype. For example,</p> + +<pre class="brush: js">var f = new Foo(); +var isTrue = (f instanceof Foo);</pre> + +<p>For a more detailed example, suppose you have the same set of definitions shown in <a href="#Inheriting_properties">Inheriting properties</a>. Create an <code>Engineer</code> object as follows:</p> + +<pre class="brush: js">var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji"); +</pre> + +<p>With this object, the following statements are all true:</p> + +<pre class="brush: js">chris.__proto__ == Engineer.prototype; +chris.__proto__.__proto__ == WorkerBee.prototype; +chris.__proto__.__proto__.__proto__ == Employee.prototype; +chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype; +chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null; +</pre> + +<p>Given this, you could write an <code>instanceOf</code> function as follows:</p> + +<pre class="brush: js">function instanceOf(object, constructor) { + object = object.__proto__; + while (object != null) { + if (object == constructor.prototype) + return true; + if (typeof object == 'xml') { + return constructor.prototype == XML.prototype; + } + object = object.__proto__; + } + return false; +} +</pre> + +<div class="note"><strong>Note:</strong> The implementation above checks the type of the object against "xml" in order to work around a quirk of how XML objects are represented in recent versions of JavaScript. See {{ bug(634150) }} if you want the nitty-gritty details.</div> + +<p>Using the instanceOf function defined above, these expressions are true:</p> + +<pre class="brush: js">instanceOf (chris, Engineer) +instanceOf (chris, WorkerBee) +instanceOf (chris, Employee) +instanceOf (chris, Object) +</pre> + +<p>But the following expression is false:</p> + +<pre class="brush: js">instanceOf (chris, SalesPerson) +</pre> + +<h3 id="Informação_global_nos_construtores">Informação global nos construtores</h3> + +<p>When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use the following definition for <code>Employee</code>:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + this.id = idCounter++; +} +</pre> + +<p>With this definition, when you create a new <code>Employee</code>, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, <code>victoria.id</code> is 1 and <code>harry.id</code> is 2:</p> + +<pre class="brush: js">var victoria = new Employee("Pigbert, Victoria", "pubs") +var harry = new Employee("Tschopik, Harry", "sales") +</pre> + +<p>At first glance that seems fine. However, <code>idCounter</code> gets incremented every time an <code>Employee</code> object is created, for whatever purpose. If you create the entire <code>Employee</code> hierarchy shown in this chapter, the <code>Employee</code> constructor is called every time you set up a prototype. Suppose you have the following code:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + this.id = idCounter++; +} + +function Manager (name, dept, reports) {...} +Manager.prototype = new Employee; + +function WorkerBee (name, dept, projs) {...} +WorkerBee.prototype = new Employee; + +function Engineer (name, projs, mach) {...} +Engineer.prototype = new WorkerBee; + +function SalesPerson (name, projs, quota) {...} +SalesPerson.prototype = new WorkerBee; + +var mac = new Engineer("Wood, Mac"); +</pre> + +<p>Further assume that the definitions omitted here have the <code>base</code> property and call the constructor above them in the prototype chain. In this case, by the time the <code>mac</code> object is created, <code>mac.id</code> is 5.</p> + +<p>Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using the following constructor:</p> + +<pre class="brush: js">function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + if (name) + this.id = idCounter++; +} +</pre> + +<p>When you create an instance of <code>Employee</code> to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an <code>Employee</code> to get an assigned id, you must specify a name for the employee. In this example, <code>mac.id</code> would be 1.</p> + +<h3 id="No_multiple_inheritance">No multiple inheritance</h3> + +<p>Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.</p> + +<p>Inheritance of property values occurs at run time by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.</p> + +<p>In JavaScript, you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:</p> + +<pre class="brush: js">function Hobbyist (hobby) { + this.hobby = hobby || "scuba"; +} + +function Engineer (name, projs, mach, hobby) { + this.base1 = WorkerBee; + this.base1(name, "engineering", projs); + this.base2 = Hobbyist; + this.base2(hobby); + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; + +var dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo") +</pre> + +<p>Further assume that the definition of <code>WorkerBee</code> is as used earlier in this chapter. In this case, the <code>dennis</code> object has these properties:</p> + +<pre class="brush: js">dennis.name == "Doe, Dennis" +dennis.dept == "engineering" +dennis.projects == ["collabra"] +dennis.machine == "hugo" +dennis.hobby == "scuba" +</pre> + +<p>So <code>dennis</code> does get the <code>hobby</code> property from the <code>Hobbyist</code> constructor. However, assume you then add a property to the <code>Hobbyist</code> constructor's prototype:</p> + +<pre class="brush: js">Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"] +</pre> + +<p>The <code>dennis</code> object does not inherit this new property.</p> + +<div>{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> diff --git a/files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html b/files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html new file mode 100644 index 0000000000..d0c815aac5 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html @@ -0,0 +1,832 @@ +--- +title: Expressoes e Operadores +slug: Web/JavaScript/Guia/Expressoes_e_Operadores +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}</div> +<p><span id="result_box" lang="pt"><span class="hps">Este capítulo descreve</span> <span class="hps">expressões e operadores JavaScript</span><span>, incluindo </span></span>atribuição<span id="result_box" lang="pt"><span>, comparação,</span> <span class="hps">aritmética,</span> <span class="hps">bit a bit</span><span>, lógico, string</span><span>, e</span> <span class="hps">operadores especiais.</span></span></p> + +<h2 id="Expressões">Expressões</h2> + +<p>Uma <em>expressão</em> é qualquer unidade de código válida que resolve um valor.</p> + +<p><span id="result_box" lang="pt"><span class="alt-edited hps">Conceitualmente</span><span>, há dois</span> <span class="hps">tipos de expressões</span><span>: aqueles</span> <span class="hps">que</span> <span class="hps">atribui um valor</span> <span class="hps">para</span> <span class="hps">uma variável, e</span> <span class="hps">aqueles</span> <span class="hps">que</span> <span class="hps">simplesmente tem</span> <span class="hps">um valor.</span> <span class="hps">Por exemplo,</span> <span class="hps">a expressão</span> <code><span class="hps">x = 7</span></code> <span class="hps">é uma expressão que</span> <span class="hps">atribui</span> a x <span class="hps">o valor </span><span class="hps">sete.</span> <span class="hps">Esta expressão</span> <span class="hps">avalia</span><span>-se</span> <span class="hps">a sete.</span> <span class="hps">Tais expressões</span> <span class="alt-edited hps">usam <em>operadores de atribuição</em></span><span>.</span> <span class="hps">Por outro lado</span><span>, a expressão de</span> <code><span class="hps">3 + 4</span></code> <span class="hps">simplesmente avalia</span> <span class="hps">a sete</span><span>; ele</span> <span class="hps">não realiza</span> <span class="hps">uma atribuição.</span> <span class="hps">Os</span> <span class="hps">operadores usados</span> <span class="hps">em tais expressões</span> <span class="hps">são referidos</span> <span class="hps">simplesmente como</span> <span class="hps"><em>operadores</em>.</span></span></p> + +<p><span class="short_text" id="result_box" lang="pt"><span class="hps">JavaScript</span> <span class="hps">tem os seguintes tipos</span> <span class="hps">de expressões:</span></span></p> + +<ul> + <li><span id="result_box" lang="pt"><span class="hps">Aritmética:</span> <span class="hps">resulta em um número</span><span>, por exemplo</span> <span class="hps">3,14159.</span></span> (Generally uses {{ web.link("#Arithmetic_operators", "arithmetic operators") }}.)</li> + <li><span id="result_box" lang="pt"><span class="hps">String:</span> <span class="hps">avalia</span> <span class="hps">em</span> <span class="hps">uma cadeia de caracteres</span><span>, por exemplo,</span> <span class="hps">"Fred</span><span>" ou</span> <span class="hps">"234"</span></span>. (Generally uses {{ web.link("#String_operators", "string operators") }}.)</li> + <li>Logical: resulta em verdadeira (true em inglês) ou falsa (false em inglês). (Often involves {{ web.link("#Logical_operators", "logical operators") }}.)</li> + <li>Object: resulta como um objeto. (See {{ web.link("#Special_operators", "special operators") }} for various ones that evaluate to objects.)</li> +</ul> + +<h2 id="Operadores">Operadores</h2> + +<p><span id="result_box" lang="pt"><span class="hps">JavaScript</span> <span class="hps">tem os seguintes tipos</span> <span class="hps">de operadores.</span> <span class="hps">Esta seção</span> <span class="hps">descreve os operadores</span> <span class="hps">e contém informações sobre</span> <span class="hps">a precedência do operador</span><span>.</span></span></p> + +<ul> + <li>{{ web.link("#Assignment_operators", "Assignment operators") }}</li> + <li>{{ web.link("#Comparison_operators", "Comparison operators") }}</li> + <li>{{ web.link("#Arithmetic_operators", "Arithmetic operators") }}</li> + <li>{{ web.link("#Bitwise_operators", "Bitwise operators") }}</li> + <li>{{ web.link("#Logical_operators", "Logical operators") }}</li> + <li>{{ web.link("#String_operators", "String operators") }}</li> + <li>{{ web.link("#Special_operators", "Special operators") }}</li> +</ul> + +<p>JavaScript has both <em>binary</em> and <em>unary</em> operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:</p> + +<pre><em>operand1</em> <em>operator</em> <em>operand2</em> +</pre> + +<p>For example, <code>3+4</code> or <code>x*y</code>.</p> + +<p>A unary operator requires a single operand, either before or after the operator:</p> + +<pre><em>operator</em> <em>operand</em> +</pre> + +<p>or</p> + +<pre><em>operand</em> <em>operator</em> +</pre> + +<p>For example, <code>x++</code> or <code>++x</code>.</p> + +<h3 id="Assignment_operators">Assignment operators</h3> + +<p>An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x.</p> + +<p>The other assignment operators are shorthand for standard operations, as shown in the following table.</p> + +<table class="standard-table"> + <caption>Table 3.1 Assignment operators</caption> + <thead> + <tr> + <th scope="col">Shorthand operator</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>x += y</code></td> + <td><code>x = x + y</code></td> + </tr> + <tr> + <td><code>x -= y</code></td> + <td><code>x = x - y</code></td> + </tr> + <tr> + <td><code>x *= y</code></td> + <td><code>x = x * y</code></td> + </tr> + <tr> + <td><code>x /= y</code></td> + <td><code>x = x / y</code></td> + </tr> + <tr> + <td><code>x %= y</code></td> + <td><code>x = x % y</code></td> + </tr> + <tr> + <td><code>x <<= y</code></td> + <td><code>x = x << y</code></td> + </tr> + <tr> + <td><code>x >>= y</code></td> + <td><code>x = x >> y</code></td> + </tr> + <tr> + <td><code>x >>>= y</code></td> + <td><code>x = x >>> y</code></td> + </tr> + <tr> + <td><code>x &= y</code></td> + <td><code>x = x & y</code></td> + </tr> + <tr> + <td><code>x ^= y</code></td> + <td><code>x = x ^ y</code></td> + </tr> + <tr> + <td><code>x |= y</code></td> + <td><code>x = x | y</code></td> + </tr> + </tbody> +</table> + +<h3 id="Comparison_operators">Comparison operators</h3> + +<p><span class="comment">This seems to me kind of poorly explained, mostly the difference betwen "==" and "==="...</span> A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. (The sole exceptions to this rule are <code>===</code> and <code>!==</code>, which perform "strict" equality and inequality and which do not attempt to convert the operands to compatible types before checking equality.) This generally results in a numerical comparison being performed. The following table describes the comparison operators, assuming the following code:</p> + +<pre class="brush: js">var var1 = 3, var2 = 4; +</pre> + +<table class="standard-table"> + <caption>Table 3.2 Comparison operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Description</th> + <th scope="col">Examples returning true</th> + </tr> + </thead> + <tbody> + <tr> + <td>Equal (<code>==</code>)</td> + <td>Returns true if the operands are equal.</td> + <td><code>3 == var1</code> + <p><code>"3" == var1</code></p> + <code>3 == '3'</code></td> + </tr> + <tr> + <td>Not equal (<code>!=</code>)</td> + <td>Returns true if the operands are not equal.</td> + <td><code>var1 != 4<br> + var2 != "3"</code></td> + </tr> + <tr> + <td>Strict equal (<code>===</code>)</td> + <td>Returns true if the operands are equal and of the same type.</td> + <td><code>3 === var1</code></td> + </tr> + <tr> + <td>Strict not equal (<code>!==</code>)</td> + <td>Returns true if the operands are not equal and/or not of the same type.</td> + <td><code>var1 !== "3"<br> + 3 !== '3'</code></td> + </tr> + <tr> + <td>Greater than (<code>></code>)</td> + <td>Returns true if the left operand is greater than the right operand.</td> + <td><code>var2 > var1<br> + "12" > 2</code></td> + </tr> + <tr> + <td>Greater than or equal (<code>>=</code>)</td> + <td>Returns true if the left operand is greater than or equal to the right operand.</td> + <td><code>var2 >= var1<br> + var1 >= 3</code></td> + </tr> + <tr> + <td>Less than (<code><</code>)</td> + <td>Returns true if the left operand is less than the right operand.</td> + <td><code>var1 < var2<br> + "12" < "2"</code></td> + </tr> + <tr> + <td>Less than or equal (<code><=</code>)</td> + <td>Returns true if the left operand is less than or equal to the right operand.</td> + <td><code>var1 <= var2<br> + var2 <= 5</code></td> + </tr> + </tbody> +</table> + +<h3 id="Arithmetic_operators">Arithmetic operators</h3> + +<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces <a href="/en-US/docs/JavaScript/Reference/Global_Objects/NaN" title="en-US/docs/JavaScript/Reference/Global_Properties/NaN"><code>NaN</code></a>). For example:</p> + +<pre class="brush: js">console.log(1 / 2); /* prints 0.5 */ +console.log(1 / 2 == 1.0 / 2.0); /* also this is true */ +</pre> + +<p>In addition, JavaScript provides the arithmetic operators listed in the following table.</p> + +<table class="fullwidth-table"> + <caption>Table 3.3 Arithmetic operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Description</th> + <th scope="col">Example</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>%</code><br> + (Modulus)</td> + <td>Binary operator. Returns the integer remainder of dividing the two operands.</td> + <td>12 % 5 returns 2.</td> + </tr> + <tr> + <td><code>++</code><br> + (Increment)</td> + <td>Unary operator. Adds one to its operand. If used as a prefix operator (<code>++x</code>), returns the value of its operand after adding one; if used as a postfix operator (<code>x++</code>), returns the value of its operand before adding one.</td> + <td>If <code>x</code> is 3, then <code>++x</code> sets <code>x</code> to 4 and returns 4, whereas <code>x++</code> returns 3 and, only then, sets <code>x</code> to 4.</td> + </tr> + <tr> + <td><code>--</code><br> + (Decrement)</td> + <td>Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator.</td> + <td>If <code>x</code> is 3, then <code>--x</code> sets <code>x</code> to 2 and returns 2, whereas <code>x--</code> returns 3 and, only then, sets <code>x</code> to 2.</td> + </tr> + <tr> + <td><code>-</code><br> + (Unary negation)</td> + <td>Unary operator. Returns the negation of its operand.</td> + <td>If <code>x</code> is 3, then <code>-x</code> returns -3.</td> + </tr> + </tbody> +</table> + +<h3 id="Bitwise_operators">Bitwise operators</h3> + +<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.</p> + +<p>The following table summarizes JavaScript's bitwise operators.</p> + +<table class="standard-table"> + <caption>Table 3.4 Bitwise operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Usage</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td>Bitwise AND</td> + <td><code>a & b</code></td> + <td>Returns a one in each bit position for which the corresponding bits of both operands are ones.</td> + </tr> + <tr> + <td>Bitwise OR</td> + <td><code>a | b</code></td> + <td>Returns a one in each bit position for which the corresponding bits of either or both operands are ones.</td> + </tr> + <tr> + <td>Bitwise XOR</td> + <td><code>a ^ b</code></td> + <td>Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.</td> + </tr> + <tr> + <td>Bitwise NOT</td> + <td><code>~ a</code></td> + <td>Inverts the bits of its operand.</td> + </tr> + <tr> + <td>Left shift</td> + <td><code>a << b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the left, shifting in zeros from the right.</td> + </tr> + <tr> + <td>Sign-propagating right shift</td> + <td><code>a >> b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the right, discarding bits shifted off.</td> + </tr> + <tr> + <td>Zero-fill right shift</td> + <td><code>a >>> b</code></td> + <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the right, discarding bits shifted off, and shifting in zeros from the left.</td> + </tr> + </tbody> +</table> + +<h4 id="Bitwise_Logical_Operators" name="Bitwise_Logical_Operators">Bitwise logical operators</h4> + +<p>Conceptually, the bitwise logical operators work as follows:</p> + +<ul> + <li>The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).</li> + <li>Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.</li> + <li>The operator is applied to each pair of bits, and the result is constructed bitwise.</li> +</ul> + +<p>For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:</p> + +<table class="standard-table"> + <caption>Table 3.5 Bitwise operator examples</caption> + <thead> + <tr> + <th scope="col">Expression</th> + <th scope="col">Result</th> + <th scope="col">Binary Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>15 & 9</code></td> + <td><code>9</code></td> + <td><code>1111 & 1001 = 1001</code></td> + </tr> + <tr> + <td><code>15 | 9</code></td> + <td><code>15</code></td> + <td><code>1111 | 1001 = 1111</code></td> + </tr> + <tr> + <td><code>15 ^ 9</code></td> + <td><code>6</code></td> + <td><code>1111 ^ 1001 = 0110</code></td> + </tr> + <tr> + <td><code>~15</code></td> + <td><code>0</code></td> + <td><code>~1111 = 0000</code></td> + </tr> + <tr> + <td><code>~9</code></td> + <td><code>6</code></td> + <td><code>~1001 = 0110</code></td> + </tr> + </tbody> +</table> + +<p> </p> + +<h4 id="Bitwise_Shift_Operators" name="Bitwise_Shift_Operators">Bitwise shift operators</h4> + +<p>The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.</p> + +<p>Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.</p> + +<p>The shift operators are listed in the following table.</p> + +<table class="fullwidth-table"> + <caption>Table 3.6 Bitwise shift operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Description</th> + <th scope="col">Example</th> + </tr> + </thead> + <tbody> + <tr> + <td><code><<</code><br> + (Left shift)</td> + <td>This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.</td> + <td><code>9<<2</code> yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.</td> + </tr> + <tr> + <td><code>>></code><br> + (Sign-propagating right shift)</td> + <td>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.</td> + <td><code>9>>2</code> yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, <code>-9>>2</code> yields -3, because the sign is preserved.</td> + </tr> + <tr> + <td><code>>>></code><br> + (Zero-fill right shift)</td> + <td>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.</td> + <td><code>19>>>2</code> yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.</td> + </tr> + </tbody> +</table> + +<h3 id="Logical_operators">Logical operators</h3> + +<p>Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.</p> + +<table class="fullwidth-table"> + <caption>Table 3.6 Logical operators</caption> + <thead> + <tr> + <th scope="col">Operator</th> + <th scope="col">Usage</th> + <th scope="col">Description</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>&&</code></td> + <td><code>expr1 && expr2</code></td> + <td>(Logical AND) Returns <code>expr1</code> if it can be converted to false; otherwise, returns <code>expr2</code>. Thus, when used with Boolean values, <code>&&</code> returns true if both operands are true; otherwise, returns false.</td> + </tr> + <tr> + <td><code>||</code></td> + <td><code>expr1 || expr2</code></td> + <td>(Logical OR) Returns <code>expr1</code> if it can be converted to true; otherwise, returns <code>expr2</code>. Thus, when used with Boolean values, <code>||</code> returns true if either operand is true; if both are false, returns false.</td> + </tr> + <tr> + <td><code>!</code></td> + <td><code>!expr</code></td> + <td>(Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.</td> + </tr> + </tbody> +</table> + +<p>Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.</p> + +<p>The following code shows examples of the && (logical AND) operator.</p> + +<pre class="brush: js">var a1 = true && true; // t && t returns true +var a2 = true && false; // t && f returns false +var a3 = false && true; // f && t returns false +var a4 = false && (3 == 4); // f && f returns false +var a5 = "Cat" && "Dog"; // t && t returns Dog +var a6 = false && "Cat"; // f && t returns false +var a7 = "Cat" && false; // t && f returns false +</pre> + +<p>The following code shows examples of the || (logical OR) operator.</p> + +<pre class="brush: js">var o1 = true || true; // t || t returns true +var o2 = false || true; // f || t returns true +var o3 = true || false; // t || f returns true +var o4 = false || (3 == 4); // f || f returns false +var o5 = "Cat" || "Dog"; // t || t returns Cat +var o6 = false || "Cat"; // f || t returns Cat +var o7 = "Cat" || false; // t || f returns Cat +</pre> + +<p>The following code shows examples of the ! (logical NOT) operator.</p> + +<pre class="brush: js">var n1 = !true; // !t returns false +var n2 = !false; // !f returns true +var n3 = !"Cat"; // !t returns false +</pre> + +<h4 id="Short-Circuit_Evaluation" name="Short-Circuit_Evaluation">Short-circuit evaluation</h4> + +<p>As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:</p> + +<ul> + <li><code>false</code> && <em>anything</em> is short-circuit evaluated to false.</li> + <li><code>true</code> || <em>anything</em> is short-circuit evaluated to true.</li> +</ul> + +<p>The rules of logic guarantee that these evaluations are always correct. Note that the <em>anything</em> part of the above expressions is not evaluated, so any side effects of doing so do not take effect.</p> + +<h3 id="String_operators">String operators</h3> + +<p>In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, <code>"my " + "string"</code> returns the string <code>"my string"</code>.</p> + +<p>The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable <code>mystring</code> has the value "alpha", then the expression <code>mystring += "bet"</code> evaluates to "alphabet" and assigns this value to <code>mystring</code>.</p> + +<h3 id="Special_operators">Special operators</h3> + +<p>JavaScript provides the following special operators:</p> + +<ul> + <li>{{ web.link("#Conditional_operator", "Conditional operator") }}</li> + <li>{{ web.link("#Comma_operator", "Comma operator") }}</li> + <li><code>{{ web.link("#delete", "delete") }}</code></li> + <li><code>{{ web.link("#in", "in") }}</code></li> + <li><code>{{ web.link("#instanceof", "instanceof") }}</code></li> + <li><code>{{ web.link("#new", "new") }}</code></li> + <li><code>{{ web.link("#this", "this") }}</code></li> + <li><code>{{ web.link("#typeof", "typeof") }}</code></li> + <li><code>{{ web.link("#void", "void") }}</code></li> +</ul> + +<h4 id="conditional_operator" name="conditional_operator">Conditional operator</h4> + +<p>The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:</p> + +<pre><em>condition</em> ? <em>val1</em> : <em>val2</em> +</pre> + +<p>If <code>condition</code> is true, the operator has the value of <code>val1</code>. Otherwise it has the value of <code>val2</code>. You can use the conditional operator anywhere you would use a standard operator.</p> + +<p>For example,</p> + +<pre class="brush: js">var status = (age >= 18) ? "adult" : "minor"; +</pre> + +<p>This statement assigns the value "adult" to the variable <code>status</code> if <code>age</code> is eighteen or more. Otherwise, it assigns the value "minor" to <code>status</code>.</p> + +<h4 id="comma_operator" name="comma_operator">Comma operator</h4> + +<p>The comma operator (<code>,</code>) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a <code>for</code> loop, to allow multiple variables to be updated each time through the loop.</p> + +<p>For example, if <code>a</code> is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:</p> + +<pre class="brush: js">for (var i = 0, j = 9; i <= 9; i++, j--) + document.writeln("a[" + i + "][" + j + "]= " + a[i][j]); +</pre> + +<h4 id="delete" name="delete"><code>delete</code></h4> + +<p>The <code>delete</code> operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:</p> + +<pre class="brush: js">delete objectName; +delete objectName.property; +delete objectName[index]; +delete property; // legal only within a with statement +</pre> + +<p>where <code>objectName</code> is the name of an object, <code>property</code> is an existing property, and <code>index</code> is an integer representing the location of an element in an array.</p> + +<p>The fourth form is legal only within a <code>with</code> statement, to delete a property from an object.</p> + +<p>You can use the <code>delete</code> operator to delete variables declared implicitly but not those declared with the <code>var</code> statement.</p> + +<p>If the <code>delete</code> operator succeeds, it sets the property or element to <code>undefined</code>. The <code>delete</code> operator returns true if the operation is possible; it returns false if the operation is not possible.</p> + +<pre class="brush: js">x = 42; +var y = 43; +myobj = new Number(); +myobj.h = 4; // create property h +delete x; // returns true (can delete if declared implicitly) +delete y; // returns false (cannot delete if declared with var) +delete Math.PI; // returns false (cannot delete predefined properties) +delete myobj.h; // returns true (can delete user-defined properties) +delete myobj; // returns true (can delete if declared implicitly) +</pre> + +<h5 id="Deleting_array_elements">Deleting array elements</h5> + +<p>When you delete an array element, the array length is not affected. For example, if you delete <code>a[3]</code>, <code>a[4]</code> is still <code>a[4]</code> and <code>a[3]</code> is undefined.</p> + +<p>When the <code>delete</code> operator removes an array element, that element is no longer in the array. In the following example, <code>trees[3]</code> is removed with <code>delete</code>. However, <code>trees[3]</code> is still addressable and returns <code>undefined</code>.</p> + +<pre class="brush: js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +delete trees[3]; +if (3 in trees) { + // this does not get executed +} +</pre> + +<p>If you want an array element to exist but have an undefined value, use the <code>undefined</code> keyword instead of the <code>delete</code> operator. In the following example, <code>trees[3]</code> is assigned the value <code>undefined</code>, but the array element still exists:</p> + +<pre class="brush: js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +trees[3] = undefined; +if (3 in trees) { + // this gets executed +} +</pre> + +<h4 id="in" name="in"><code>in</code></h4> + +<p>The <code>in</code> operator returns true if the specified property is in the specified object. The syntax is:</p> + +<pre class="brush: js">propNameOrNumber in objectName +</pre> + +<p>where <code>propNameOrNumber</code> is a string or numeric expression representing a property name or array index, and <code>objectName</code> is the name of an object.</p> + +<p>The following examples show some uses of the <code>in</code> operator.</p> + +<pre class="brush: js">// Arrays +var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +0 in trees; // returns true +3 in trees; // returns true +6 in trees; // returns false +"bay" in trees; // returns false (you must specify the index number, + // not the value at that index) +"length" in trees; // returns true (length is an Array property) + +// Predefined objects +"PI" in Math; // returns true +var myString = new String("coral"); +"length" in myString; // returns true + +// Custom objects +var mycar = {make: "Honda", model: "Accord", year: 1998}; +"make" in mycar; // returns true +"model" in mycar; // returns true +</pre> + +<h4 id="instanceof" name="instanceof"><code>instanceof</code></h4> + +<p>The <code>instanceof</code> operator returns true if the specified object is of the specified object type. The syntax is:</p> + +<pre class="brush: js">objectName instanceof objectType +</pre> + +<p>where <code>objectName</code> is the name of the object to compare to <code>objectType</code>, and <code>objectType</code> is an object type, such as <code>Date</code> or <code>Array</code>.</p> + +<p>Use <code>instanceof</code> when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.</p> + +<p>For example, the following code uses <code>instanceof</code> to determine whether <code>theDay</code> is a <code>Date</code> object. Because <code>theDay</code> is a <code>Date</code> object, the statements in the <code>if</code> statement execute.</p> + +<pre class="brush: js">var theDay = new Date(1995, 12, 17); +if (theDay instanceof Date) { + // statements to execute +} +</pre> + +<h4 id="new" name="new"><code>new</code></h4> + +<p>You can use the <code>new</code> operator to create an instance of a user-defined object type or of one of the predefined object types <code>Array</code>, <code>Boolean</code>, <code>Date</code>, <code>Function</code>, <code>Image</code>, <code>Number</code>, <code>Object</code>, <code>Option</code>, <code>RegExp</code>, or <code>String</code>. On the server, you can also use it with <code>DbPool</code>, <code>Lock</code>, <code>File</code>, or <code>SendMail</code>. Use <code>new</code> as follows:</p> + +<pre class="brush: js">var objectName = new objectType([param1, param2, ..., paramN]); +</pre> + +<p>You can also create objects using object initializers, as described in {{ web.link("Working_with_objects#Using_object_initializers", "using object initializers") }}.</p> + +<p>See the <a href="/en-US/docs/JavaScript/Reference/Operators/new" title="en-US/docs/JavaScript/Reference/Operators/Special_Operators/new_Operator"><code>new</code> operator</a> page in the Core JavaScript Reference for more information.</p> + +<h4 id="this" name="this"><code>this</code></h4> + +<p>Use the <code>this</code> keyword to refer to the current object. In general, <code>this</code> refers to the calling object in a method. Use <code>this</code> as follows:</p> + +<pre class="brush: js">this["propertyName"] +</pre> + +<pre class="brush: js">this.propertyName +</pre> + +<p><strong>Example 1.</strong><br> + Suppose a function called <code>validate</code> validates an object's <code>value</code> property, given the object and the high and low values:</p> + +<pre class="brush: js">function validate(obj, lowval, hival){ + if ((obj.value < lowval) || (obj.value > hival)) + alert("Invalid Value!"); +} +</pre> + +<p>You could call <code>validate</code> in each form element's <code>onChange</code> event handler, using <code>this</code> to pass it the form element, as in the following example:</p> + +<pre class="brush: html"><B>Enter a number between 18 and 99:</B> +<INPUT TYPE="text" NAME="age" SIZE=3 + onChange="validate(this, 18, 99);"> +</pre> + +<p><strong>Example 2.</strong><br> + When combined with the <code>form</code> property, <code>this</code> can refer to the current object's parent form. In the following example, the form <code>myForm</code> contains a <code>Text</code> object and a button. When the user clicks the button, the value of the <code>Text</code> object is set to the form's name. The button's <code>onClick</code> event handler uses <code>this.form</code> to refer to the parent form, <code>myForm</code>.</p> + +<pre class="brush: html"><FORM NAME="myForm"> +Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> +<P> +<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" + onClick="this.form.text1.value = this.form.name;"> +</FORM> +</pre> + +<h4 id="typeof" name="typeof"><code>typeof</code></h4> + +<p>The <code>typeof</code> operator is used in either of the following ways:</p> + +<ol> + <li> + <pre class="brush: js">typeof operand +</pre> + </li> + <li> + <pre class="brush: js">typeof (operand) +</pre> + </li> +</ol> + +<p>The <code>typeof</code> operator returns a string indicating the type of the unevaluated operand. <code>operand</code> is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.</p> + +<p>Suppose you define the following variables:</p> + +<pre class="brush: js">var myFun = new Function("5 + 2"); +var shape = "round"; +var size = 1; +var today = new Date(); +</pre> + +<p>The <code>typeof</code> operator returns the following results for these variables:</p> + +<pre class="brush: js">typeof myFun; // returns "function" +typeof shape; // returns "string" +typeof size; // returns "number" +typeof today; // returns "object" +typeof dontExist; // returns "undefined" +</pre> + +<p>For the keywords <code>true</code> and <code>null</code>, the <code>typeof</code> operator returns the following results:</p> + +<pre class="brush: js">typeof true; // returns "boolean" +typeof null; // returns "object" +</pre> + +<p>For a number or string, the <code>typeof</code> operator returns the following results:</p> + +<pre class="brush: js">typeof 62; // returns "number" +typeof 'Hello world'; // returns "string" +</pre> + +<p>For property values, the <code>typeof</code> operator returns the type of value the property contains:</p> + +<pre class="brush: js">typeof document.lastModified; // returns "string" +typeof window.length; // returns "number" +typeof Math.LN2; // returns "number" +</pre> + +<p>For methods and functions, the <code>typeof</code> operator returns results as follows:</p> + +<pre class="brush: js">typeof blur; // returns "function" +typeof eval; // returns "function" +typeof parseInt; // returns "function" +typeof shape.split; // returns "function" +</pre> + +<p>For predefined objects, the <code>typeof</code> operator returns results as follows:</p> + +<pre class="brush: js">typeof Date; // returns "function" +typeof Function; // returns "function" +typeof Math; // returns "object" +typeof Option; // returns "function" +typeof String; // returns "function" +</pre> + +<h4 id="void" name="void"><code>void</code></h4> + +<p>The <code>void</code> operator is used in either of the following ways:</p> + +<ol> + <li> + <pre class="brush: js">void (expression) +</pre> + </li> + <li> + <pre class="brush: js">void expression +</pre> + </li> +</ol> + +<p>The <code>void</code> operator specifies an expression to be evaluated without returning a value. <code>expression</code> is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.</p> + +<p>You can use the <code>void</code> operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.</p> + +<p>The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, <code>void(0)</code> evaluates to undefined, which has no effect in JavaScript.</p> + +<pre class="brush: html"><A HREF="javascript:void(0)">Click here to do nothing</A> +</pre> + +<p>The following code creates a hypertext link that submits a form when the user clicks it.</p> + +<pre class="brush: html"><A HREF="javascript:void(document.form.submit())"> +Click here to submit</A></pre> + +<h3 id="Operator_precedence">Operator precedence</h3> + +<p>The <em>precedence</em> of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.</p> + +<p>The following table describes the precedence of operators, from highest to lowest.</p> + +<p><small><em>In accordance with <a href="/en-US/docs/Talk:JavaScript/Guide/Obsolete_Pages/Operators#Precedence_Tablerators#Precedence_Table" title="Talk:JavaScript/Guide/Obsolete_Pages/Operators#Precedence_Table">relevant discussion</a>, this table was reversed to list operators in <strong>decreasing</strong> order of priority.</em></small></p> + +<table class="standard-table"> + <caption>Table 3.7 Operator precedence</caption> + <thead> + <tr> + <th scope="col">Operator type</th> + <th scope="col">Individual operators</th> + </tr> + </thead> + <tbody> + <tr> + <td>member</td> + <td><code>. []</code></td> + </tr> + <tr> + <td>call / create instance</td> + <td><code>() new</code></td> + </tr> + <tr> + <td>negation/increment</td> + <td><code>! ~ - + ++ -- typeof void delete</code></td> + </tr> + <tr> + <td>multiply/divide</td> + <td><code>* / %</code></td> + </tr> + <tr> + <td>addition/subtraction</td> + <td><code>+ -</code></td> + </tr> + <tr> + <td>bitwise shift</td> + <td><code><< >> >>></code></td> + </tr> + <tr> + <td>relational</td> + <td><code>< <= > >= in instanceof</code></td> + </tr> + <tr> + <td>equality</td> + <td><code>== != === !==</code></td> + </tr> + <tr> + <td>bitwise-and</td> + <td><code>&</code></td> + </tr> + <tr> + <td>bitwise-xor</td> + <td><code>^</code></td> + </tr> + <tr> + <td>bitwise-or</td> + <td><code>|</code></td> + </tr> + <tr> + <td>logical-and</td> + <td><code>&&</code></td> + </tr> + <tr> + <td>logical-or</td> + <td><code>||</code></td> + </tr> + <tr> + <td>conditional</td> + <td><code>?:</code></td> + </tr> + <tr> + <td>assignment</td> + <td><code>= += -= *= /= %= <<= >>= >>>= &= ^= |=</code></td> + </tr> + <tr> + <td>comma</td> + <td><code>,</code></td> + </tr> + </tbody> +</table> + +<p>A more detailed version of this table, complete with links to additional details about each operator, may be found in <a href="/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence#Table" title="en-US/docs/JavaScript/Reference/Operators/Operator_Precedence#Table">JavaScript Reference</a>.</p> diff --git a/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html b/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html new file mode 100644 index 0000000000..109bd99fe4 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html @@ -0,0 +1,641 @@ +--- +title: Gramática e tipos +slug: Web/JavaScript/Guia/Gramática_e_tipos +tags: + - Guia(2) + - JavaScript +translation_of: Web/JavaScript/Guide/Grammar_and_types +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</div> + +<p class="summary">Este capítulo discute a gramática básica do JavaScript, declarações de variáveis, tipos de dados e literais.</p> + +<h2 id="Básicos">Básicos</h2> + +<p>JavaScript borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python.</p> + +<p>JavaScript is <strong>case-sensitive</strong> and uses the <strong>Unicode</strong> character set.</p> + +<p>In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by a semicolon (;). Spaces, tabs and newline characters are called whitespace. The source text of JavaScript scripts gets scanned from left to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or whitespace. ECMAScript also defines certain keywords and literals and has rules for automatic insertion of semicolons (<a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">ASI</a>) to end statements. However, it is recommended to always add semicolons to end your statements; it will avoid side effects. For more information, see the detailed reference about JavaScript's <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">lexical grammar</a>.</p> + +<h2 id="Comentários">Comentários</h2> + +<p>The syntax of <strong>comments</strong> is the same as in C++ and in many other languages:</p> + +<pre class="brush: js">// a one line comment + +/* this is a longer, + multi-line comment + */ + +/* You can't, however, /* nest comments */ SyntaxError */</pre> + +<h2 id="Declarações">Declarações</h2> + +<p>There are three kinds of declarations in JavaScript.</p> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Declares a variable, optionally initializing it to a value.</dd> + <dt>{{experimental_inline}} {{jsxref("Statements/let", "let")}}</dt> + <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> + <dt>{{experimental_inline}} {{jsxref("Statements/const", "const")}}</dt> + <dd>Declares a read-only named constant.</dd> +</dl> + +<h3 id="Variáveis">Variáveis</h3> + +<p>You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.</p> + +<p>A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).</p> + +<p>You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a> as characters in identifiers.</p> + +<p>Some examples of legal names are <code>Number_hits</code>, <code>temp99</code>, and <code>_name</code>.</p> + +<h3 id="Declararação_de_variáveis">Declararação de variáveis</h3> + +<p>You can declare a variable in three ways:</p> + +<ul> + <li>With the keyword {{jsxref("Statements/var", "var")}}. For example, <code>var x = 42</code>. This syntax can be used to declare both local and global variables.</li> + <li>By simply assigning it a value. For example, <code>x = 42</code>. This always declares a global variable. It generates a strict JavaScript warning. You shouldn't use this variant.</li> + <li>With the keyword {{jsxref("Statements/let", "let")}}. For example, <code>let y = 13</code>. This syntax can be used to declare a block scope local variable. See <a href="#Variable_scope">Variable scope</a> below.</li> +</ul> + +<h3 id="Avaliação_de_variáveis">Avaliação de variáveis</h3> + +<p>A variable declared using the <code>var</code> statement with no initial value specified has the value {{jsxref("undefined")}}.</p> + +<p>An attempt to access an undeclared variable or an attempt to access an identifier declared with let statement before initialization will result in a {{jsxref("ReferenceError")}} exception being thrown:</p> + +<pre class="brush: js">var a; +console.log("The value of a is " + a); // logs "The value of a is undefined" +console.log("The value of b is " + b); // throws ReferenceError exception + +console.log("The value of x is " + x); // throws ReferenceError exception +let x; </pre> + +<p>You can use <code>undefined</code> to determine whether a variable has a value. In the following code, the variable <code>input</code> is not assigned a value, and the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else" title="en-US/docs/JavaScript/Reference/Statements/if...else">if</a></code> statement evaluates to <code>true</code>.</p> + +<pre class="brush: js">var input; +if(input === undefined){ + doThis(); +} else { + doThat(); +} +</pre> + +<p>The <code>undefined</code> value behaves as <code>false</code> when used in a boolean context. For example, the following code executes the function <code>myFunction</code> because the <code>myArray</code> element is undefined:</p> + +<pre class="brush: js">var myArray = []; +if (!myArray[0]) myFunction(); +</pre> + +<p>The <code>undefined</code> value converts to <code>NaN</code> when used in numeric context.</p> + +<pre class="brush: js">var a; +a + 2; // Evaluates to NaN</pre> + +<p>When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:</p> + +<pre class="brush: js">var n = null; +console.log(n * 32); // Will log 0 to the console +</pre> + +<h3 id="Variable_scope">Variable scope</h3> + +<p>When you declare a variable outside of any function, it is called a <em>global</em> variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a <em>local</em> variable, because it is available only within that function.</p> + +<p>JavaScript before ECMAScript 2015 does not have <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement" title="en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement">block statement</a> scope; rather, a variable declared within a block is local to the <em>function (or global scope)</em> that the block resides within. For example the following code will log <code>5</code>, because the scope of <code>x</code> is the function (or global context) within which <code>x</code> is declared, not the block, which in this case is an <code>if</code> statement.</p> + +<pre class="brush: js">if (true) { + var x = 5; +} +console.log(x); // 5 +</pre> + +<p>This behavior changes, when using the <code>let</code> declaration introduced in ECMAScript 2015.</p> + +<pre class="brush: js">if (true) { + let y = 5; +} +console.log(y); // ReferenceError: y is not defined +</pre> + +<h3 id="Variable_hoisting">Variable hoisting</h3> + +<p>Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as <strong>hoisting</strong>; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that are hoisted will return a value of <code>undefined</code>. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.</p> + +<pre class="brush: js">/** + * Example 1 + */ +console.log(x === undefined); // true +var x = 3; + +/** + * Example 2 + */ +// will return a value of undefined +var myvar = "my value"; + +(function() { + console.log(myvar); // undefined + var myvar = "local value"; +})(); +</pre> + +<p>The above examples will be interpreted the same as:</p> + +<pre class="brush: js">/** + * Example 1 + */ +var x; +console.log(x === undefined); // true +x = 3; + +/** + * Example 2 + */ +var myvar = "my value"; + +(function() { + var myvar; + console.log(myvar); // undefined + myvar = "local value"; +})(); +</pre> + +<p>Because of hoisting, all <code>var</code> statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.</p> + +<p>In ECMAScript 2015, <code>let (const)</code> <strong>will not hoist</strong> the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/ReferenceError" title="TypeError">ReferenceError</a>.</code> The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.</p> + +<pre class="brush: js">console.log(x); // <code>ReferenceError</code> +let x = 3;</pre> + +<h3 id="Variáveis_gGlobais">Variáveis gGlobais</h3> + +<p>Global variables are in fact properties of the <em>global object</em>. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the <code>window.<em>variable</em></code> syntax.</p> + +<p>Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called <code>phoneNumber</code> is declared in a document, you can refer to this variable from an iframe as <code>parent.phoneNumber</code>.</p> + +<h3 id="Constantes">Constantes</h3> + +<p>You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.</p> + +<pre class="brush: js">const PI = 3.14; +</pre> + +<p>A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.</p> + +<p>The scope rules for constants are the same as those for <code>let</code> block scope variables. If the <code>const</code> keyword is omitted, the identifier is assumed to represent a variable.</p> + +<p>You cannot declare a constant with the same name as a function or variable in the same scope. For example:</p> + +<pre class="brush: js">// THIS WILL CAUSE AN ERROR +function f() {}; +const f = 5; + +// THIS WILL CAUSE AN ERROR ALSO +function f() { + const g = 5; + var g; + + //statements +} +</pre> + +<p>However, object attributes are not protected, so the following statement is executed without problems.</p> + +<pre class="brush: js"><code>const MY_OBJECT = {"key": "value"}; +MY_OBJECT.key = "otherValue";</code></pre> + +<h2 id="Estruturas_e_tipode_dados">Estruturas e tipode dados</h2> + +<h3 id="tipos_de_dados">tipos de dados</h3> + +<p>The latest ECMAScript standard defines seven data types:</p> + +<ul> + <li>Six data types that are {{Glossary("Primitive", "primitives")}}: + <ul> + <li>{{Glossary("Boolean")}}. <code>true</code> and <code>false</code>.</li> + <li>{{Glossary("null")}}. A special keyword denoting a null value. Because JavaScript is case-sensitive, <code>null</code> is not the same as <code>Null</code>, <code>NULL</code>, or any other variant.</li> + <li>{{Glossary("undefined")}}. A top-level property whose value is undefined.</li> + <li>{{Glossary("Number")}}. <code>42</code> or <code>3.14159</code>.</li> + <li>{{Glossary("String")}}. "Howdy"</li> + <li>{{Glossary("Symbol")}} (new in ECMAScript 2015). A data type whose instances are unique and immutable.</li> + </ul> + </li> + <li>and {{Glossary("Object")}}</li> +</ul> + +<p>Although these data types are a relatively small amount, they enable you to perform useful functions with your applications. {{jsxref("Object", "Objects")}} and {{jsxref("Function", "functions")}} are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.</p> + +<h3 id="Conversão_de_tipo_de_dados">Conversão de tipo de dados</h3> + +<p>JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:</p> + +<pre class="brush: js">var answer = 42; +</pre> + +<p>And later, you could assign the same variable a string value, for example:</p> + +<pre class="brush: js">answer = "Thanks for all the fish..."; +</pre> + +<p>Because JavaScript is dynamically typed, this assignment does not cause an error message.</p> + +<p>In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:</p> + +<pre class="brush: js">x = "The answer is " + 42 // "The answer is 42" +y = 42 + " is the answer" // "42 is the answer" +</pre> + +<p>In statements involving other operators, JavaScript does not convert numeric values to strings. For example:</p> + +<pre class="brush: js">"37" - 7 // 30 +"37" + 7 // "377" +</pre> + +<h3 id="Conversão_de_strings_para_números">Conversão de strings para números</h3> + +<p>In the case that a value representing a number is in memory as a string, there are methods for conversion.</p> + +<ul> + <li id="parseInt()_and_parseFloat()">{{jsxref("parseInt", "parseInt()")}}</li> + <li>{{jsxref("parseFloat", "parseFloat()")}}</li> +</ul> + +<p><code>parseInt</code> will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for <code>parseInt</code> is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.</p> + +<p>An alternative method of retrieving a number from a string is with the <code>+</code> (unary plus) operator:</p> + +<pre class="brush: js">"1.1" + "1.1" = "1.11.1" +(+"1.1") + (+"1.1") = 2.2 +// Note: the parentheses are added for clarity, not required.</pre> + +<h2 id="Literais">Literais</h2> + +<p>You use literals to represent values in JavaScript. These are fixed values, not variables, that you <em>literally</em> provide in your script. This section describes the following types of literals:</p> + +<ul> + <li>{{anch("Array literals")}}</li> + <li>{{anch("Boolean literals")}}</li> + <li>{{anch("Floating-point literals")}}</li> + <li>{{anch("Integers")}}</li> + <li>{{anch("Object literals")}}</li> + <li>{{anch("RegExp literals")}}</li> + <li>{{anch("String literals")}}</li> +</ul> + +<h3 id="Literais_de_tabela">Literais de tabela</h3> + +<p>An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets (<code>[]</code>). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.</p> + +<p>The following example creates the <code>coffees</code> array with three elements and a length of three:</p> + +<pre class="brush: js">var coffees = ["French Roast", "Colombian", "Kona"]; +</pre> + +<div class="note"> +<p><strong>Note :</strong> An array literal is a type of object initializer. See <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers" title="en-US/docs/JavaScript/Guide/Working with Objects#Using Object Initializers">Using Object Initializers</a>.</p> +</div> + +<p>If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.</p> + +<p>Array literals are also <code>Array</code> objects. See {{jsxref("Array")}} and <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> for details on <code>Array</code> objects.</p> + +<h4 id="Extra_commas_in_array_literals">Extra commas in array literals</h4> + +<p>You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with <code>undefined</code> for the unspecified elements. The following example creates the <code>fish</code> array:</p> + +<pre class="brush: js">var fish = ["Lion", , "Angel"]; +</pre> + +<p>This array has two elements with values and one empty element (<code>fish[0]</code> is "Lion", <code>fish[1]</code> is <code>undefined</code>, and <code>fish[2]</code> is "Angel").</p> + +<p>If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no <code>myList[3]</code>. All other commas in the list indicate a new element.</p> + +<div class="note"> +<p><strong>Nota :</strong> Trailing commas can create errors in older browser versions and it is a best practice to remove them.</p> +</div> + +<pre class="brush: js">var myList = ['home', , 'school', ]; +</pre> + +<p>In the following example, the length of the array is four, and <code>myList[0]</code> and <code>myList[2]</code> are missing.</p> + +<pre class="brush: js">var myList = [ , 'home', , 'school']; +</pre> + +<p>In the following example, the length of the array is four, and <code>myList[1]</code> and <code>myList[3]</code> are missing. Only the last comma is ignored.</p> + +<pre class="brush: js">var myList = ['home', , 'school', , ]; +</pre> + +<p>Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as <code>undefined</code> will increase your code's clarity and maintainability.</p> + +<h3 id="Lietrais_boolianas">Lietrais boolianas</h3> + +<p>The Boolean type has two literal values: <code>true</code> and <code>false</code>.</p> + +<p>Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See {{jsxref("Boolean")}} for more information.</p> + +<h3 id="Íntegros">Íntegros</h3> + +<p>Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).</p> + +<ul> + <li>Decimal integer literal consists of a sequence of digits without a leading 0 (zero).</li> + <li>Leading 0 (zero) on an integer literal, or leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.</li> + <li>Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.</li> + <li> + <p>Leading 0b (or 0B) indicates binary. Binary integers can include digits only 0 and 1.</p> + </li> +</ul> + +<p>Some examples of integer literals are:</p> + +<pre class="eval">0, 117 and -345 (decimal, base 10) +015, 0001 and -0o77 (octal, base 8) +0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16) +0b11, 0b0011 and -0b11 (binary, base 2) +</pre> + +<p>For more information, see <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">Numeric literals in the Lexical grammar reference</a>.</p> + +<h3 id="Literais_de_ponto_flutuante">Literais de ponto flutuante</h3> + +<p>A floating-point literal can have the following parts:</p> + +<ul> + <li>A decimal integer which can be signed (preceded by "+" or "-"),</li> + <li>A decimal point ("."),</li> + <li>A fraction (another decimal number),</li> + <li>An exponent.</li> +</ul> + +<p>The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").</p> + +<p>More succinctly, the syntax is:</p> + +<pre class="eval">[(+|-)][digits][.digits][(E|e)[(+|-)]digits] +</pre> + +<p>For example:</p> + +<pre class="eval">3.1415926 +-.123456789 +-3.1E+12 +.1e-23 +</pre> + +<h3 id="Literais_de_objeto">Literais de objeto</h3> + +<p>An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (<code>{}</code>). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.</p> + +<p>The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>, and assigns to it a new string, "<code>Saturn</code>"; the second element, the <code>getCar</code> property, is immediately assigned the result of invoking the function <code>(carTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>sales</code>).</p> + +<pre class="brush: js">var sales = "Toyota"; + +function carTypes(name) { + if (name === "Honda") { + return name; + } else { + return "Sorry, we don't sell " + name + "."; + } +} + +var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales }; + +console.log(car.myCar); // Saturn +console.log(car.getCar); // Honda +console.log(car.special); // Toyota +</pre> + +<p>Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.</p> + +<pre class="brush: js">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; + +console.log(car.manyCars.b); // Jeep +console.log(car[7]); // Mazda +</pre> + +<p>Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript {{Glossary("Identifier","identifier")}} or number, it must be enclosed in quotes. Property names that are not valid identifiers also cannot be accessed as a dot (<code>.</code>) property, but can be accessed and set with the array-like notation("<code>[]</code>").</p> + +<pre class="brush: js">var unusualPropertyNames = { + "": "An empty string", + "!": "Bang!" +} +console.log(unusualPropertyNames.""); // SyntaxError: Unexpected string +console.log(unusualPropertyNames[""]); // An empty string +console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token ! +console.log(unusualPropertyNames["!"]); // Bang!</pre> + +<p>In ES2015, object literals are extended to support setting the prototype at construction, shorthand for <code>foo: foo</code> assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.</p> + +<pre class="brush: js">var obj = { + // __proto__ + __proto__: theProtoObj, + // Shorthand for ‘handler: handler’ + handler, + // Methods + toString() { + // Super calls + return "d " + super.toString(); + }, + // Computed (dynamic) property names + [ 'prop_' + (() => 42)() ]: 42 +};</pre> + +<p>Por favor, note:</p> + +<pre class="brush: js">var foo = {a: "alpha", 2: "two"}; +console.log(foo.a); // alpha +console.log(foo[2]); // two +//console.log(foo.2); // Error: missing ) after argument list +//console.log(foo[a]); // Error: a is not defined +console.log(foo["a"]); // alpha +console.log(foo["2"]); // two +</pre> + +<h3 id="RegExp_literals">RegExp literals</h3> + +<p>A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.</p> + +<pre class="brush: js">var re = /ab+c/;</pre> + +<h3 id="Lietrais_de_string">Lietrais de string</h3> + +<p>A string literal is zero or more characters enclosed in double (<code>"</code>) or single (<code>'</code>) quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:</p> + +<pre class="brush: js">"foo" +'bar' +"1234" +"one line \n another line" +"John's cat" +</pre> + +<p>You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the <code>String.length</code> property with a string literal:</p> + +<pre class="brush: js">console.log("John's cat".length) +// Will print the number of symbols in the string including whitespace. +// In this case, 10. +</pre> + +<p>In ES2015, template literals are also available. Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.</p> + +<pre class="brush: js">// Basic literal string creation +`In JavaScript '\n' is a line-feed.` + +// Multiline strings +`In JavaScript this is + not legal.` + +// String interpolation +var name = "Bob", time = "today"; +`Hello ${name}, how are you ${time}?` + +// Construct an HTTP request prefix is used to interpret the replacements and construction +POST`http://foo.org/bar?a=${a}&b=${b} + Content-Type: application/json + X-Credentials: ${credentials} + { "foo": ${foo}, + "bar": ${bar}}`(myOnReadyStateChangeHandler);</pre> + +<p>You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on <code>String</code> objects.</p> + +<h4 id="Using_special_characters_in_strings">Using special characters in strings</h4> + +<p>In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p> + +<pre class="brush: js">"one line \n another line" +</pre> + +<p>The following table lists the special characters that you can use in JavaScript strings.</p> + +<table class="standard-table"> + <caption>Table: JavaScript special characters</caption> + <thead> + <tr> + <th scope="col">Cárater</th> + <th scope="col">Significado</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>Null Byte</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>Backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Form feed</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>New line</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Carriage return</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Vertical tab</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Apostrophe or single quote</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Double quote</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Backslash character</td> + </tr> + <tr> + <td><code>\<em>XXX</em></code></td> + <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\x<em>XX</em></code></td> + <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\u<em>XXXX</em></code></td> + <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a>.</td> + </tr> + <tr> + <td><code>\u<em>{XXXXX}</em></code></td> + <td>Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.</td> + </tr> + </tbody> +</table> + +<h4 id="Escaping_characters">Escaping characters</h4> + +<p>For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p> + +<p>You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p> + +<pre class="brush: js">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; +console.log(quote); +</pre> + +<p>The result of this would be:</p> + +<pre class="eval">He read "The Cremation of Sam McGee" by R.W. Service. +</pre> + +<p>To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p> + +<pre class="brush: js">var home = "c:\\temp"; +</pre> + +<p>You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.</p> + +<pre class="brush: js">var str = "this string \ +is broken \ +across multiple\ +lines." +console.log(str); // this string is broken across multiplelines. +</pre> + +<p>Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line:</p> + +<pre class="brush: js">var poem = +"Roses are red,\n\ +Violets are blue.\n\ +Sugar is sweet,\n\ +and so is foo." +</pre> + +<h2 id="Mais_informação">Mais informação</h2> + +<p>This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:</p> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Control flow and error handling</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a></li> +</ul> + +<p>In the next chapter, we will have a look at control flow constructs and error handling.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</p> diff --git a/files/pt-pt/web/javascript/guia/index.html b/files/pt-pt/web/javascript/guia/index.html new file mode 100644 index 0000000000..aec08fb7ad --- /dev/null +++ b/files/pt-pt/web/javascript/guia/index.html @@ -0,0 +1,123 @@ +--- +title: Guia de JavaScript +slug: Web/JavaScript/Guia +tags: + - Guía + - JavaScript + - 'l10n:prioridade' +translation_of: Web/JavaScript/Guide +--- +<div>{{jsSidebar("JavaScript Guide")}}</div> + +<p class="summary">The JavaScript Guide shows you how to use <a href="/en-US/docs/Web/JavaScript">JavaScript</a> and gives an overview of the language. If you want to get started with JavaScript or programming in general, consult the articles in the <a href="/en-US/Learn">learning area</a>. If you need exhaustive information about a language feature, have a look at the <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a>.</p> + +<h2 id="Capítulos">Capítulos</h2> + +<p>This Guide is divided into several chapters:</p> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Introduction">Introdução</a></span> + + <p><a href="/pt-PT/docs/Web/JavaScript/Guia/Introdução">About this guide</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#What_is_JavaScript">About JavaScript</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_Java">JavaScript and Java</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_the_ECMAScript_Specification">ECMAScript</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Getting_started_with_JavaScript">Tools</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Hello_world">Hello World</a></p> + </li> + <li><span><a href="/pt-PT/docs/Web/JavaScript/Guia/Gramática_e_tipos">Gramática e tipos</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Basics">Basic syntax & comments</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations">Declarations</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope">Variable scope</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting">Variable hoisting</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types">Data structures and types</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Literals">Literals</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Controlo de fluxo e manipulação de erros</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#if...else_statement">if...else</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#switch_statement">switch</a></code><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Exception_handling_statements"><code>try</code>/<code>catch</code>/<code>throw</code></a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Utilizing_Error_objects">Error objects</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Promises">Promises</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops e iteração</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement">for</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#while_statement">while</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#do...while_statement">do...while</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#break_statement">break</a>/<a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#continue_statement">continue</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement">for..in</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for..of</a></code></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Funções</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Defining_functions">Defining functions</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions">Calling functions</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope">Function scope</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Closures">Closures</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Using_the_arguments_object">Arguments</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_parameters">parameters</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Arrow_functions">Arrow functions</a></p> + </li> + <li><span><a href="/pt-PT/docs/Web/JavaScript/Guia/Guia_expressões_e_operadores">Expressões e operadores</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment_operators">Assignment</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison_operators">Comparisons</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators">Arithmetic operators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">Bitwise</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators">logical operators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Conditional_(ternary)_operator">Conditional (ternary) operator</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates">Números e datas</a></span><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers"> Number literals</a> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Number_object"><code>Number</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Math_object"><code>Math</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Date_object"><code>Date</code> object</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting">Formatação de texto</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#String_literals">String literals</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#String_objects"><code>String</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#Multi-line_template_literals">Template literals</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#Internationalization">Internationalization</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Coleções indexadas</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_object">Arrays</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Typed_Arrays">Typed arrays</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections">Coleções Keyed</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#Map_object">Map</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakMap_object">WeakMap</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#Set_object">Set</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakSet_object">WeakSet</a></code></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects">Trabalhar com objetos</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties">Objets e propriedades</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">Criação de objetos</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_methods">Definição de métodos</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Getter and setter</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">Detalhes do modelo de objeto</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Class-based_vs._prototype-based_languages">Prototype-based OOP</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Creating_the_hierarchy">Creating object hierarchies</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Property_inheritance_revisited">Inheritance</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterators e geradores</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators">Iterators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables">Iterables</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators">Generators</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming">Metadados de programação</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Proxies">Proxy</a></code><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Handlers_and_traps">Handlers and traps</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Revocable_Proxy">Revocable Proxy</a><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Reflection">Reflect</a></code></p> + </li> +</ul> + +<p>{{Next("Web/JavaScript/Guide/Introduction")}}</p> diff --git a/files/pt-pt/web/javascript/guia/introdução/index.html b/files/pt-pt/web/javascript/guia/introdução/index.html new file mode 100644 index 0000000000..f77bb74379 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/introdução/index.html @@ -0,0 +1,137 @@ +--- +title: Introdução +slug: Web/JavaScript/Guia/Introdução +tags: + - Guía + - JavaScript +translation_of: Web/JavaScript/Guide/Introduction +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</div> + +<p class="summary">Este capítulo apresenta a linguagem JavaScript e discuste alguns dos seus conceitos fundamentais.</p> + +<h2 id="O_que_você_já_deveria_saber">O que você já deveria saber</h2> + +<p>Este guia assume que você possuí os seguintes conhecimentos:</p> + +<ul> + <li>Um conhecimento geral sobre Internet e o World Wide Web ({{Glossary("WWW")}}).</li> + <li>Bom conhecimento sobre como desenvolver em HyperText Markup Language ({{Glossary("HTML")}}).</li> + <li>Alguma experiência com programação. Caso seja iniciante nesse mundo, experimente seguir algum dos links com tutoriais que estão presentes na página principal sobre <a href="/pt-PT/docs/Web/JavaScript/Guia">JavaScript</a>.</li> +</ul> + +<h2 id="Onde_encontrar_informação_sobre_JavaScript">Onde encontrar informação sobre JavaScript?</h2> + +<p>A documentação de JavaScript no MDN incluí o seguinte:</p> + +<ul> + <li><a href="/pt-PT/docs/Learn">Aprender a Web</a> fornece informação para iniciantes e introduz os conceitos básicos sobre programação e Internet.</li> + <li><a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a> (este guia) fornece uma visão geral sobre a linguagem JavaScript e os seus objetos.</li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference">Referência de JavaScript</a> fornece conteúdos de referência detalhada para JavaScript.</li> +</ul> + +<p>Se for iniciante em JavaScript, comece lendo alguns dos artigos na <a href="/pt-PT/docs/Learn">área de aprendizagem</a> e o <a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a>. Assim que compreender os fundamentos da linguagem, pode consultar a <a href="/pt-PT/docs/Web/JavaScript/Reference">Referência de JavaScript</a> para obter mais detalhes sobre objetos individuais e declarações.</p> + +<h2 id="O_que_é_JavaScript">O que é JavaScript?</h2> + +<p>JavaScript é uma linguagem de script orientada a objetos e que funciona entre plataformas. É uma linguagem pequena e simples. Ela pode ser rodada num ambiente anfitrião (por exemplo, o browser), o código JavaScript pode estar ligado a objetos do ambiente e fornece controle programático sobre os mesmos.</p> + +<p>O JavaScript contém uma biblioteca padrão de objetos, tais como <code>Array</code>, <code>Date</code>, <code>Math</code>, e um conjunto fundamental de elementos da linguagem tais como operadores, estruturas de controle, e statements. Os elementos básicos do JavaScript podem ser extendidos com objetos adicionais para uma variedade de propósitos, por exemplo:</p> + +<ul> + <li>JavaScript a correr no cliente extende a linguagem básica pois fornece objetos para controlar o browser e o seu Document Object Model (DOM). Por exemplo, extenções de cliente permitem a uma aplicação adicionar elementos num formulário HTML e responder a eventos do utilizador tais como cliques, input adicionado, e navegação na página.</li> + <li>JavaScript a correr no <span style="background-color: #f3a8a3;">servidor </span>extende a linguagem básica ao fornecer objetos relevantes para que isso aconteça. Por exemplo, extenções do lado do servidor permitem que uma aplicação comunique com uma base de dados, garante continuidade de informação entre invocações da aplicação, ou executa manipulações de ficheiros no servidor.</li> +</ul> + +<h2 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript e Java</h2> + +<p>JavaScript e Java são linguagens similares em alguns aspetos mas fundamentalmente diferentes noutros. A linguagem JavaScript assemelha-se ao Java mas não tem o static typing nem a validação strong type. O JavaScsript segue a sintaxe de expressões do Java, convenções de nomenclatura e os construtores básicos de controlo de fluxo. Esta última foi a razão pelo qual a linguagem foi renomeada de LiveScript para JavaScript.</p> + +<p>In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.</p> + +<p>JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.</p> + +<p>Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.</p> + +<p>In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.</p> + +<table class="standard-table"> + <caption>JavaScript comparado com Java</caption> + <thead> + <tr> + <th scope="col">JavaScript</th> + <th scope="col">Java</th> + </tr> + </thead> + <tbody> + <tr> + <td>Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically.</td> + <td>Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.</td> + </tr> + <tr> + <td>Variable data types are not declared (dynamic typing).</td> + <td>Variable data types must be declared (static typing).</td> + </tr> + <tr> + <td>Cannot automatically write to hard disk.</td> + <td>Can automatically write to hard disk.</td> + </tr> + </tbody> +</table> + +<p>For more information on the differences between JavaScript and Java, see the chapter <a href="/pt-PT/docs/Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto">Details of the object model</a>.</p> + +<h2 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript e a especificação ECMAScript</h2> + +<p>JavaScript is standardized at <a class="external" href="http://www.ecma-international.org/">Ecma International</a> — the European association for standardizing information and communication systems (ECMA was formerly an acronym for the European Computer Manufacturers Association) to deliver a standardized, international programming language based on JavaScript. This standardized version of JavaScript, called ECMAScript, behaves the same way in all applications that support the standard. Companies can use the open standard language to develop their implementation of JavaScript. The ECMAScript standard is documented in the ECMA-262 specification. See <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">New in JavaScript</a> to learn more about different versions of JavaScript and ECMAScript specification editions.</p> + +<p>The ECMA-262 standard is also approved by the <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization) as ISO-16262. You can also find the specification on <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a>. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a> and/or <a href="https://whatwg.org">WHATWG (Web Hypertext Application Technology Working Group)</a>. The DOM defines the way in which HTML document objects are exposed to your script. To get a better idea about the different technologies that are used when programming with JavaScript, consult the article <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> + +<h3 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">Documentação JavaScript versus especificação ECMAScript</h3> + +<p>The ECMAScript specification is a set of requirements for implementing ECMAScript; it is useful if you want to implement standards-compliant language features in your ECMAScript implementation or engine (such as SpiderMonkey in Firefox, or v8 in Chrome).</p> + +<p>The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.</p> + +<p>The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.</p> + +<p>The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.</p> + +<h2 id="Começar_com_JavaScript">Começar com JavaScript</h2> + +<p>Getting started with JavaScript is easy: all you need is a modern Web browser. This guide includes some JavaScript features which are only currently available in the latest versions of Firefox, so using the most recent version of Firefox is recommended.</p> + +<p>There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.</p> + +<h3 id="A_Consola_da_Web">A Consola da Web</h3> + +<p>A <a href="/pt-PT/docs/Tools/Consola_da_Web">Consola da Web</a> shows you information about the currently loaded Web page, and also includes a <a href="/en-US/docs/Tools/Web_Console#The_command_line_interpreter">command line</a> that you can use to execute JavaScript expressions in the current page.</p> + +<p>To open the Web Console (Ctrl+Shift+K), select "Web Console" from the "Developer" menu, which is under the "Tools" menu in Firefox. It appears at the bottom of the browser window. Along the bottom of the console is a command line that you can use to enter JavaScript, and the output appears in the pane above:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7363/web-console-commandline.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h3 id="Scratchpad">Scratchpad</h3> + +<p>The Web Console is great for executing single lines of JavaScript, but although you can execute multiple lines, it's not very convenient for that, and you can't save your code samples using the Web Console. So for more complex examples <a href="/en-US/docs/Tools/Scratchpad">Scratchpad</a> is a better tool.</p> + +<p>To open Scratchpad (Shift+F4), select "Scratchpad" from the "Developer" menu, which is under the menu in Firefox. It opens in a separate window and is an editor that you can use to write and execute JavaScript in the browser. You can also save scripts to disk and load them from disk.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7365/scratchpad.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h3 id="Olá_mundo">Olá mundo</h3> + +<p>To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:</p> + +<pre class="brush: js">function greetMe(yourName) { + alert("Hello " + yourName); +} + +greetMe("World"); +</pre> + +<p>Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!</p> + +<p>In the following pages, this guide will introduce you to the JavaScript syntax and language features, so that you will be able to write more complex applications.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</p> diff --git a/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html b/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html new file mode 100644 index 0000000000..549ecbe331 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html @@ -0,0 +1,47 @@ +--- +title: Introdução ao JavaScript +slug: Web/JavaScript/Guia/Introdução_ao_JavaScript +--- +<p>Este capítulo introduz o JavaScript e discute alguns de seus conceitos fundamentais.</p> +<h3 id="What_is_JavaScript.3F" name="What_is_JavaScript.3F">O que é o JavaScript?</h3> +<p>O JavaScript é uma linguagem de script multiplataforma, orientada a objetos. O JavaScript é uma linguagem pequena e leve; não é útil como uma linguagem de uso isolado, mas é projetada para fácil integração em outros produtos e aplicações, tais como navegadores web. Dentro de um ambiente de hospedagem, o JavaScript pode ser conectado aos objetos de seu ambiente para proporcionar um controle programático sobre elas.</p> +<p>O núcleo do JavaScript contém um núcleo de objetos, como <code>Array</code>, <code>Date</code>, e <code>Math</code>, e um núcleo de elementos de linguagem como operadores, estruturas de controle, e declarações. O núcleo do JavaScript pode ser extendido para uma variedade de propósitos complementando-o com objetos adicionais; por exemplo:</p> +<ul> <li><em>O lado do cliente no JavaScript</em> extende o núcleo da linguagem fornecendo objetos para controlar um navegador (Navigator ou outro navegador web) e seu Document Object Model (DOM). Por exemplo, extensões para o lado do cliente permitem a uma aplicação colocar elementos em um formulário HTML e responder a eventos de usuários como cliques de mouse, entrada de dados e navegação na página.</li> <li><em>O lado do servidor no JavaScript</em> extende o núcleo da linguagem fornecendo objetos relevantes à execução de JavaScript no servidor. Por exemplo, extensões do lado do servidor permitem a uma aplicação comunicar-se com um banco de dados relacional, proporcionar continuidade de informação de uma invocação da aplicação para outra, ou executar manipulações de arquivos em um servidor.</li> +</ul> +<p>Através da funcionalidade JavaScript's LiveConnect, pode-se permitir que códigos em Java e em JavaScript comuniquem-se. É possível instanciar objetos Java e acessar seus métodos e campos públicos a partir do JavaScript. A partir do Java, por sua vez, pode-se acessar objetos, propriedades e métodos do JavaScript.</p> +<p>O Netscape inventou o JavaScript e o JavaScript foi inicialmente usado em navegadores Netscape.</p> +<h3 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript e Java</h3> +<p>O JavaScript e o Java são similares em algumas coisas, mas fundamentalmente diferentes em outras. A linguagem JavaScript assemelha-se ao Java, mas não possui a checagem de tipos forte e digitação estática do Java. O JavaScript suport a maioria das sintaxes de expressões em Java e um construtor básico de controles de fluxo.</p> +<p>Em contraste com o sistema em tempo de compilação do Java, de classes construídas por declarações, o JavaScript suporta um sistema de tempo de execução baseado em um pequeno número de tipos de dados representando números, booleanos, e valores de strings. O JavaScript possui um modelo de objetos baseado em protótipos, ao invés do mais comum, modelo de objetos baseado em classes. O modelo baseado em protótipos provê a herança dinâmica; isto é, o que é herdado pode variar para objetos individuais. O JavaScript também suporta funções sem requisições especiais de declaração. Funções podem ser propriedades de objetos, executando métodos fracamente tipados.</p> +<p>O JavaScript é uma linguagem com forma bastante livre comparada ao Java. Você não precisa declarar todas as variáveis, classes e métodos. Você não precisa se preocupar se os métodos são públicos, privados ou protegidos, e você não precisa implementar interfaces. Tipos de variáveis, parâmetros e retornos de funções não são explicitados.</p> +<p>O Java é uma linguagem de programação baseada em classes e projetava para rápida execução e tipagem segura. Tipagem segura significa, por exemplo, que você não pode converter um inteiro do Java para uma referência de um objeto ou acessar a memória privada, corrompendo bytecodes do Java. O modelo baseado em classes do Java significa que o programa consiste exclusivamente de classes e seus métodos. A herança das classes no Java e a tipagem forte, geralmente requerem objetos com hierarquias firmemente acopladas. Estes requisitos fazem do Java uma linguagem de programação mais complexa que a autoria do JavaScript.</p> +<p>Em contraste, o JavaScript descende em espírito de uma linha menor, linguagens tipadas dinamicamente, tais como HyperTalk e dBASE. Estas linguagens de stript oferecem ferramentas de programação para um público muito maior, devido a simplicidade de sua sintaxe, funcionalidades especializadas integradas e requisitos mínimos para criação de objetos.</p> +<table class="standard-table"> <caption>Tabela 1.1 JavaScript em comparação ao Java</caption> <thead> <tr> <th scope="col">JavaScript</th> <th scope="col">Java</th> </tr> </thead> <tbody> <tr> <td>Orientação a objetos. Sem distinção entre tipos de objetos. A herança ocorre através do mecanismo de protótipos e os métodos e propriedades podem ser adicionados a qualquer objeto dinamicamente.</td> <td>Baseada em classes. Objetos são divididos em classes e instâncias com toda a herança através da hierarquia da classe. Classes e instâncias não podem ter métodos e propriedades adicionados dinamicamente.</td> </tr> <tr> <td>Tipos de dados variáveis não são declarados (tipagem dinâmica).</td> <td>Tipos de dados variáveis precisam ser declarados (tipagem estática).</td> </tr> <tr> <td>Não pode escrever automaticamente no disco rígido.</td> <td>Não pode escrever automaticamente no disco rígido.</td> </tr> </tbody> +</table> +<p>Para mais informações sobre as diferenças entre o JavaScript e o Java, veja o capítulo <a href="/en/JavaScript/Guide/Details_of_the_Object_Model" title="en/JavaScript/Guide/Details of the Object Model">Details of the Object Model</a>.</p><h3 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript e a especificação ECMAScript</h3> +<p>O Netscape inventou o JavaScript e o JavaScript foi primeiramente usado nos navegadores Netscape. Entretanto, a Netscape está trabalhando com a <a class="external" href="http://www.ecma-international.org/">Ecma International</a> — a associação européia para padronizão de informação e sistemas de comunicação (formalmente conhecida como ECMA - European Computer Manufacturers Association, em português: Associação de Fabricantes de Computadores Europeus) — para entregar uma linguagem de programação internacional padronizada, baseada no JavaScript. Esta versão padronizada do JavaScript, chamada de ECMAScript, comporta-se da mesma maneira em todas as aplicações que suportem o padrão. Empresas podem usar a linguagem padrão aberta para desenvolver sua implementação do JavaScript. O ECMAScript padrão é documentado na especificação ECMA-262.</p> +<p>O padrão ECMA-262 é também aprovado pela <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization, em português: Organização Internacional para Padronização) como ISO-16262. Você pode encontrar uma <a class="external" href="http://www.mozilla.org/js/language/E262-3.pdf">versão PDF do ECMA-262</a> (en) no site da Mozilla. Você pode também encontrar a especificação em <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a> (en). A especificação do ECMAScript não descreve o Document Object Model (DOM), o qual é padronizado pelo <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a>. O DOM define a maneira com a qual os objetos do documento HTML são expostos ao seu script.</p> +<h4 id="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions" name="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions">Relação entre as versões do JavaScript e as edições do ECMAScript</h4> +<p>O Netscape trabalhou próximo a Ecma International para produzir a Especificação ECMAScript (ECMA-262). A tabela seguinte descreve a relação entre as versões do JavaScript e as edições do ECMAScript.</p> +<table class="standard-table"> <caption>Tabela 1.2 Versões do JavaScript e edições do ECMAScript</caption> <thead> <tr> <th scope="row">Versão do JavaScript</th> <th scope="col">Relação com a edição do ECMAScript</th> </tr> </thead> <tbody> <tr> <td>JavaScript 1.1</td> <td>O ECMA-262, Edição 1 é baseado no JavaScript 1.1.</td> </tr> <tr> <td>JavaScript 1.2</td> <td>O ECMA-262 não estava completo quando o JavaScript 1.2 foi lançado. O JavaScript 1.2 não é totalmente compatível com o ECMA-262, Edição 1, pelas seguintes razões: <ul> <li>O Netscape desenvolveu características adicionais no JavaScript 1.2 que não foram consideradas no ECMA-262.</li> <li>O ECMA-262 adiciona duas novas características: internacionalização usando Unicode e comportamento uniforme em todas as plataformas. Muitas características do JavaScript 1.2, tais com o objeto <code>Date</code>, eram dependentes de plataforma e usavam um comportamento específico da plataforma.</li> </ul> </td> </tr> <tr> <td> <p>JavaScript 1.3</p> </td> <td> <p>O JavaScript 1.3 é totalmente compatível com o ECMA-262, Edição 1.</p> <p>O JavaScript 1.3 corrigiu as inconsistências que o JavaScript 1.2 tinha com o ECMA-262, mantendo todas as características adicionais do JavaScript 1.2 com a exceção de == e !=, os quais foram mudados conforme o ECMA-262.</p> </td> </tr> <tr> <td> <p>JavaScript 1.4</p> </td> <td> <p>O JavaScript 1.4 é totalmente comatível com o ECMA-262, Edição 1.</p> <p>A terceira versão da especificação ECMAScript não estava finalizada quando o JavaScript 1.4 foi lançado.</p> </td> </tr> <tr> <td>JavaScript 1.5</td> <td>O JavaScript 1.5 é totalmente compatível com o ECMA-262, Edição 3.</td> </tr> </tbody> +</table> +<div class="note"><strong>Nota</strong>: O ECMA-262, Edição 2 consistiu de mudanças editoriais pequenas e correções de bugs da especificação da Edição 1. O grupo de trabalho TC39 da Ecma International está atualmente trabalhando no ECMAScript Edição 4, o qual corresponderá a um lançamento futuro do JavaScript, o JavaScript 2.0.</div> +<p>A <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência de JavaScript</a> (en) indica quais características da linguagem estão em conformidade com o ECMAScript.</p> +<p>O JavaScript sempre permite incluir características que não fazem parte da Especificação do ECMAScript; O JavaScript é compatível com o ECMASCript; mesmo provendo características adicionais.</p><h4 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">Documentação do JavaScript versus a especificação do ECMAScript</h4> +<p>A especificação do ECMAScript é um conjunto de requisitos para a implementação do ECMAScript; ela é útil caso deseje-se determinar, se uma característica do JavaScript é suportada em outras implementações do ECMAScript. Caso planeje-se escrever código JavaScript usando somente características suportadas pelo ECMAScript, então é interessante checar a especificação ECMAScript.</p> +<p>O documento ECMAScript não pretende ajudar programadores de scripts; para informações sobre escrita de scripts, deve-se usar a documentação do JavaScript.</p><h4 id="JavaScript_and_ECMAScript_Terminology" name="JavaScript_and_ECMAScript_Terminology">Terminologia do JavaScript e do ECMAScript</h4> +<p>A especificação do ECMAScript utiliza a terminologia e sintaxe que pode ser desconhecida para um programador JavaScript. Embora a descrição da linguagem possa diferir, a linguagem em si, é a mesma. O JavaScript suporta todas as funcionalidades descritas na especificação ECMAScript.</p> +<p>A documentação do JavaScript descreve aspectos da linguagem que são apropriados para um programador JavaScript. Por exemplo:</p> +<ul> <li>O Objeto Global não é discutido na documentação do JavaScript porque ele não é usado diretamente. Os métodos e propriedades do Objeto Global, os quais são usados, são discutidos na documentação do JavaScript, mas são chamados de funções e propriedades de nível superior.</li> <li>O construtor sem parâmetros (zero argumentos) com os objetos <code>Number</code> e <code>String</code> não é discutido na documentação do JavaScript, pois o gerado é pouco usado. Um construtor de <code>Number</code> sem nenhum argumento, retorna +0, e um construtor de <code>String</code> sem argumentos, retorna "" (uma string vazia).</li> +</ul> +<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters"); +wiki.languages({ + "en": "en/JavaScript/Guide/JavaScript_Overview", + "es": "es/Gu\u00eda_JavaScript_1.5/Concepto_de_JavaScript", + "fr": "fr/Guide_JavaScript_1.5/Aper\u00e7u_de_JavaScript", + "ja": "ja/Core_JavaScript_1.5_Guide/JavaScript_Overview", + "ko": "ko/Core_JavaScript_1.5_Guide/JavaScript_Overview", + "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Przegl\u0105d_JavaScriptu", + "zh-cn": "cn/Core_JavaScript_1.5_Guide/JavaScript\u603b\u89c8", + "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要" +});</pre> diff --git a/files/pt-pt/web/javascript/guia/sobre/index.html b/files/pt-pt/web/javascript/guia/sobre/index.html new file mode 100644 index 0000000000..6957645a40 --- /dev/null +++ b/files/pt-pt/web/javascript/guia/sobre/index.html @@ -0,0 +1,166 @@ +--- +title: Sobre este guia +slug: Web/JavaScript/Guia/Sobre +--- +<p>JavaScript é uma linguagem de scripts multiplataforma, baseada em objetos. Este guia explica tudo que é necessário saber sobre como utilizar o JavaScript.</p> + +<h2 id="Novas_caraterísticas_em_versões_do_JavaScript">Novas caraterísticas em versões do JavaScript</h2> + +<pre class="script" style="font-size: 16px;">/* Nota: Para adicionar um link na descrição de uma nova versão do JavaScript, +adicione o número da variável versionList abaixo. A página ligada deve +residir em /en/JavaScript/New_in_JavaScript/N, onde N é o número da versão. */ + +var versionList = ["1.5", "1.6", "1.7", "1.8", "1.8.1", "1.8.5"]; +var s = ""; +<ul> + foreach (var i in versionList){ + let s = "/en/JavaScript/New_in_JavaScript/" .. i; + <li>web.link(s, wiki.getPage(s).title)</li>; + } +</ul>;</pre> + +<h2 id="O_que_já_é_necessário_saber">O que já é necessário saber</h2> + +<p>Este guia assume que já possui os seguintes conhecimentos como base:</p> + +<ul> + <li>Um entendimento geral da Internet e da World Wide Web (WWW).</li> + <li>Bom conhecimento de trabalho com HyperText Markup Language (<a href="/en/HTML" title="en/HTML">HTML</a>).</li> +</ul> + +<p>Alguma experiência de programação com uma linguagem como C ou Visual Basic é útil, mas não necessária.</p> + +<h2 id="Versões_do_JavaScript">Versões do JavaScript</h2> + +<table class="standard-table"> + <caption>Tabela 1 Versões do JavaScript e do Navigator</caption> + <thead> + <tr> + <th scope="col">versão JavaScript</th> + <th scope="col">versão Navigator</th> + </tr> + </thead> + <tbody> + <tr> + <td>JavaScript 1.0</td> + <td>Navigator 2.0</td> + </tr> + <tr> + <td>JavaScript 1.1</td> + <td>Navigator 3.0</td> + </tr> + <tr> + <td>JavaScript 1.2</td> + <td>Navigator 4.0-4.05</td> + </tr> + <tr> + <td>JavaScript 1.3</td> + <td>Navigator 4.06-4.7x</td> + </tr> + <tr> + <td>JavaScript 1.4</td> + <td> </td> + </tr> + <tr> + <td>JavaScript 1.5</td> + <td>Navigator 6.0<br> + Mozilla (navegador open source)</td> + </tr> + <tr> + <td>JavaScript 1.6</td> + <td><a href="/en/Firefox_1.5_for_developers" title="en/Firefox_1.5_for_developers">Firefox 1.5</a>, outros produtos baseados no Mozilla 1.8</td> + </tr> + <tr> + <td>JavaScript 1.7</td> + <td><a href="/en/Firefox_2_for_developers" title="en/Firefox_2_for_developers">Firefox 2</a>, outros produtos baseados no Mozilla 1.8.1</td> + </tr> + <tr> + <td>JavaScript 1.8</td> + <td><a href="/en/Firefox_3_for_developers" title="en/Firefox_3_for_developers">Firefox 3</a>, outros produtos baseados no Gecko 1.9</td> + </tr> + </tbody> +</table> + +<p>Cada versão do Netscape Enterprise Server também suporta diferentes versões do JavaScript. Para ajudar na escrita de scripts compatíveis com múltiplas versões do Enterprise Server, este manual usa uma abreviação para indicar a versão do servidor na qual cada característica foi implementada.</p> + +<table class="standard-table"> + <caption>Tabela 2 Abreviações das versões do Netscape Enterprise Server</caption> + <thead> + <tr> + <th scope="col">Abreviação</th> + <th scope="col">versão Enterprise Server</th> + </tr> + </thead> + <tbody> + <tr> + <td>NES 2.0</td> + <td>Netscape Enterprise Server 2.0</td> + </tr> + <tr> + <td>NES 3.0</td> + <td>Netscape Enterprise Server 3.0</td> + </tr> + </tbody> +</table> + +<h2 id="Onde_encontrar_informações_sobre_JavaScript">Onde encontrar informações sobre JavaScript</h2> + +<p>A documentação do JavaScript inclui os seguintes livros:</p> + +<ul> + <li><a href="/en/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">Guia de JavaScript</a> (este guia) fornece informações sobre a linguagem JavaScript e seus objetos.</li> + <li><a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência JavaScript</a> fornece material de referência para a linguagem JavaScript.</li> +</ul> + +<p>Se você é novo no JavaScript, comece com o <a href="/en/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">Guia de JavaScript</a>. Uma vez que você tenha uma boa compreensão dos fundamentos, você pode usar a <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência JavaScript</a> para obter mais detalhes sobre objetos e declarações.</p> + +<h2 id="Dicas_para_aprender_JavaScript">Dicas para aprender JavaScript</h2> + +<p>Começar com o JavaScript é fácil: é necessário apenas um navegador web moderno. Este guia inclui algumas características do JavaScript que estão atualmente disponíveis nas últimas versões do Firefox (e outros navegadores baseados no Gecko), é recomendado, portanto, o uso da versão mais recente do Firefox.</p> + +<h3 id="Um_interpretador_interativo">Um interpretador interativo</h3> + +<p>Uma linha de comando interativa com JavaScript é inestimável para o aprendizado da linguagem, pois permite experimentar código de forma interativa sem ter que salvar um arquivo e recarregar a página. O Console de erros do Firefox, acessível através do menu de Ferramentas, fornece uma maneira simples de testar JavaScript interativamente: Basta entrar uma linha de código e clicar no botão "Executar".</p> + +<p><img alt="Image:ErrorConsole.png" class="internal" src="/@api/deki/files/192/=ErrorConsole.png"></p> + +<h3 id="Firebug">Firebug</h3> + +<p>Uma linha de comando interativa mais avançada está disponível com o uso do<a class="external" href="http://www.getfirebug.com/"> Firebug</a>, uma extensão de terceiros para o Firefox. O Firebug também fornece um inspetor DOM avançado, um depurador de JavaScript, uma ferramenta de análise e vários outros utilitários.</p> + +<p><img alt="Image:Firebug.png" class="internal" src="/@api/deki/files/204/=Firebug.png"></p> + +<p>Um dos mais úteis benefícios proporcionados pelo Firebug é <code>console.log()</code>, uma função que imprime seus argumentos no console do Firebug. Diferentemente de outras linguagens de programação, o JavaScript não possui um conceito de impressão para a saída padrão. O <code>console.log()</code> fornece uma alternativa útil, tornando mais fácil ver o que seu programa está fazendo.</p> + +<p>Muitos dos exemplos neste guia usam <code>alert()</code> para exibir mensagens conforme são executados. Tendo o Firebug instalado, pode ser usando <code>console.log()</code> ao invés de <code>alert()</code> ao rodar estes exemplos.</p> + +<h2 id="Convenções_de_documento">Convenções de documento</h2> + +<p>Aplicações JavaScript rodam em muitos sistemas operacionais; a informação neste livro aplica-se a todas as versões. Os caminhos de arquivos e diretórios são dados no formato Windows (com contrabarras separando os nomes dos diretórios). Para versões Unix, os caminhos são os mesmo, exceto por serem usadas barras ao invés de contrabarras para separar os diretórios.</p> + +<p>Este guia usa localizador padrão de recursos (<em>uniform resource locators</em> (URL)) da seguinte forma:</p> + +<p><code>http://<em>server</em>.<em>domain</em>/<em>path</em>/<em>file</em>.html</code></p> + +<p>Nestas URL, <em>server</em> representa o nome do servidor no qual a aplicação é rodada, tal como <code>research1</code> ou <code>www</code>; <em>domain</em> representa seu domínio de internet, como <code>netscape.com</code> ou <code>uiuc.edu</code>; <em>path</em> representa a estrutura do diretório no servidor; e <em>file</em><code>.html</code> representa o nome de um arquivo individual. No geral, itens em itálico em são <em>placeholders</em> e itens em fonte monoespaçada normal são literais. Se o servidor possuir <em>Secure Sockets Layer</em> (SSL) habilitado, pode ser usado <code>https</code> ao invés de <code>http</code> na URL.</p> + +<p>Este guia utiliza as seguintes convenções de fontes:</p> + +<ul> + <li><code>A fonte mono espaçada</code> é utilziada para amostras de código e listagens de código, API e elementos da linguagem (como nomes de métodos e propriedades), nome de arquivos, caminhos, diretórios, tags HTML, e qualquer texto que possa ser digitado na tela. (<code><em>A fonte monoespaçada itálica</em></code> é usada para <em>placeholders </em>embutidos no código.)</li> + <li><em>O tipo itálico</em> é usado para títulos de livros, ênfase, variáveis e <em>placeholders</em>, e palavras usadas em sentido literal.</li> + <li><strong>O tipo negrito</strong> é usado para termos de glossário.</li> +</ul> + +<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters"); +wiki.languages({ + "en": "en/JavaScript/Guide/About", + "es": "es/Gu\u00eda_JavaScript_1.5/Acerca_de_esta_gu\u00eda", + "fr": "fr/Guide_JavaScript_1.5/\u00c0_propos", + "ja": "ja/Core_JavaScript_1.5_Guide/About", + "ko": "ko/Core_JavaScript_1.5_Guide/About", + "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/O_tym_przewodniku", + "zh-cn": "cn/Core_JavaScript_1.5_Guide/\u5173\u4e8e", + "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/關於" +}) +</pre> diff --git a/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html b/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html new file mode 100644 index 0000000000..c2cbc7f3db --- /dev/null +++ b/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html @@ -0,0 +1,547 @@ +--- +title: 'Valores, Variáveis e Literais' +slug: 'Web/JavaScript/Guia/Valores,_Variáveis_e_Literais' +--- +<p>Este capítulo discute valores reconhecidos pelo JavaScript e descreve a construção de blocos fundamentais de expressões em JavaScript: variáveis, constantes e literais.</p> + +<h2 id="Valores">Valores</h2> + +<p>O JavaScript reconhece os seguintes tipos de valores:</p> + +<ul> + <li><a href="/en/JavaScript/Reference/Global_Objects/Number" title="en/JavaScript/Reference/Global Objects/Number">Números</a> (en), como 42 ou 3,14159</li> + <li>Valores <a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/JavaScript/Reference/Global Objects/Boolean">lógicos (Booleanos)</a> (en), <code>true</code> ou <code>false</code></li> + <li><a href="/en/JavaScript/Reference/Global_Objects/String" title="en/JavaScript/Reference/Global Objects/String">Strings</a> (en), tais como "Howdy!"</li> + <li><code>null</code>, um palavra chave especial denotando um valor nulo; <code>null</code> também é um valor primitivo. Como JavaScript é sensível a maiúsculas, <code>null</code> não é a mesma coisa que <code>Null</code>, <code>NULL</code>, ou qualquer outra variante</li> + <li><code><a href="/en/JavaScript/Reference/Global_Objects/undefined" title="en/JavaScript/Reference/Global Objects/undefined">undefined</a></code> (en), uma propriedade de alto nível a qual possui o valor indefinido; <code>undefined</code> também é um valor primitivo.</li> +</ul> + +<p>Este conjunto de tipos de valores relativamente pequeno, permite realizar funções úteis com suas aplicações. Não há distinção explícita entre números inteiros e reais. Nem existe um tipo de dados de datas explícito em JavaScript. Entretanto, é possível utilizar o objeto <code><a href="/en/JavaScript/Reference/Global_Objects/Date" title="en/JavaScript/Reference/Global Objects/Date">Date</a></code> (en) e seus métodos para lidar com datas.</p> + +<p><a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global Objects/Object">Objetos</a> (en) e <a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/JavaScript/Reference/Global Objects/Function">funções</a> (en) são os outros elementos fundamentias da linguagem. Pode-se pensar em objetos como nomes nos quais podem ser guardados valores, e funções como procedimentos que sua aplicação pode executar.</p> + +<h3 id="Conversão_de_tipos_de_dados">Conversão de tipos de dados</h3> + +<p>O JavaScript é uma linguagem de tipagem dinâmica. Isto significa que não é necessário especificar o tipo de dado de uma variável quando ela for declarada, e tipos de dados são automaticamento convertidos conforme necessário durante a execução do script. Então, por exemplo, pode-se definir uma variável como:</p> + +<pre>var resposta = 42; +</pre> + +<p>E depois, pode-se atribuir para a mesma variável um valor de string, por exemplo:</p> + +<pre class="deki-transform">resposta = "Obrigado pelos peixes..."; +</pre> + +<p>Como o JavaScript possui tipagem dinâmica, esta atribuição não gera uma mensagem de erro.</p> + +<p>Em expressões envolvendo valores numéricos e strings com o operador +, o JavaScript converte valores numérios para string. Por exemplo, considere as seguintes declarações:</p> + +<pre class="eval deki-transform">x = "A resposta é " + 42 // retorna "A resposta é 42" +y = 42 + " é a resposta" // retorna "42 é a resposta" +</pre> + +<p>Em declarações envolvendo outros operadores, o JavaScript não converte valores numérico para strings. Por exemplo:</p> + +<pre class="eval deki-transform">"37" - 7 // retorna 30 +"37" + 7 // retorna "377"</pre> + +<h2 id="Variáveis">Variáveis</h2> + +<p>Variáveis são usadas como nomes simbólicos para valores em sua aplicação. Os nomes das variáveis, chamadas <em>identificadores</em>, de acordo com certas regras.</p> + +<p>Um identificador JavaScript deve começar com uma letra, sublinhado (_), ou cifrão ($); caracteres subsequentes podem também ser dígitos (0-9). Como o JavaScript é sensível a maiúsculas, as letras incluem os caracteres de "A" até "Z" (maiúsculas) e os caracteres de "a" até "z" (minúsculas).</p> + +<p>A partir do JavaScript 1.5 é possível usar letras em ISO 8859-1 ou Unicode tais como å e ü nos identificadores. Também é possível usar as <a href="#Sequências de escape em Unicode">Sequências de escape em Unicode</a> \uXXXX como caracteres nos identificadores.</p> + +<p>Alguns exemplos de nomes possíveis são: <code>Number_hits</code>, <code>temp99</code> e <code>_name</code>.</p> + +<h3 id="Declaração_de_variáveis">Declaração de variáveis</h3> + +<p>Você pode declarar uma variável de duas maneiras:</p> + +<ul> + <li>Com a palavra chave <a href="/en/JavaScript/Reference/Statements/var" title="en/JavaScript/Reference/Statements/var">var</a>. Por exemplo, <code>var x = 42</code>. Esta sintaxe pode ser usada para declarar tanto variáveis <a href="#Variable_Scope">locais quanto globais</a> (en).</li> + <li>Simplesmente atribuindo um valor a ela. Por exemplo, <code>x = 42</code>. Isto sempre declara uma <a href="#Global_Variables">variável global</a> (en) e gera um aviso estrito do JavaScript. Esta variante não deve ser usada.</li> +</ul> + +<h3 id="Avaliação_de_variáveis">Avaliação de variáveis</h3> + +<p>Uma variável declarada usando-se a declaração <code>var</code> sem possuir um valor inicial especificado possui o valor <code><a href="/en/JavaScript/Reference/Global_Objects/undefined" title="en/JavaScript/Reference/Global Objects/undefined">undefined</a></code>.</p> + +<p>Uma tentativa de acesso a uma variável não declarada resultará no lançamento de uma exceção <code>ReferenceError</code>:</p> + +<pre class="eval deki-transform">var a; +print("O valor de a é " + a); // imprime "O valor de a é undefined" +print("O valor de b é " + b); // lança a exceção ReferenceError +</pre> + +<p>Você pode usar <code>undefined</code> para determinar quando uma variável possui um valor. No código a seguir, a variável <code>input</code> não possui um valor atribuido e a declaração <code><a href="/en/JavaScript/Reference/Statements/if...else" title="en/Core_JavaScript_1.5_Reference/Statements/if...else">if</a></code> é avaliada como <code>true</code>.</p> + +<pre class="eval deki-transform">var input; +if(input === undefined){ + doThis(); +} else { + doThat(); +} +</pre> + +<p><span class="comment">O valor</span> <code>undefined</code> comporta-se como <code>false</code> quando usado em um contexto booleano. Por exemplo, o código a seguir executa a função <code>myFunction</code> porque o elemento <code>myArray</code> não está definido:</p> + +<pre class="eval deki-transform">var myArray = new Array(); +if (!myArray[0]) myFunction(); +</pre> + +<p>Quando você avalia uma variável nula, o valor nulo comporta-se como um 0 no contexto numérico e como falso em contextos booleanos. Por exemplo</p> + +<pre class="eval deki-transform">var n = null; +print(n * 32); // imprime 0 +</pre> + +<h3 id="Escopo_de_variáveis">Escopo de variáveis</h3> + +<p>Quando uma variável é declarada de fora de qualquer função, ele é chamada de variável <em>global</em>, pois ela está disponível para qualquer outro código no documento atual. Quando você declara uma variável dentro de uma função, ela é chamada de variável <em>local</em>, pois ela está disponível somente dentro dessa função.</p> + +<p>O JavaScript não possui um escopo de <a href="/en/JavaScript/Guide/Statements#Block_Statement" title="en/JavaScript/Guide/Statements#Block Statement">declaração de blocos</a> (en); ao contrário, será local para o código interno ao bloco. Por exemplo, o código a seguir imprimirá <code>0</code> ao invés de lançar a exceção <span><span class="comment">ReferenceError se</span></span> <code>condition</code> é <code>false</code>:</p> + +<pre class="eval deki-transform">if (condition) { + var x = 5; +} +print(x ? x : 0); +</pre> + +<p>Outra coisa não usual sobre variáveis em JavaScript é que é possível referir-se a uma variável declarada depois, sem receber uma exceção. Este conceito é conhecido como <em>hoisting</em>; as variáveis no JavaScript são levadas para o topo da função ou da declaração. Entretanto, as variáveis não inicializadas retornarão um valor <code>undefined</code>.</p> + +<pre class="eval deki-transform">print(x === undefined); // prints "true" +var x = 3; + +//will return a value of undefined +var myvar = "my value"; + +(function() { + alert(myvar);//undefined + var myvar = "local value" +})(); +</pre> + +<h3 id="Variáveis_globais">Variáveis globais</h3> + +<p><span class="comment">necessário links para as páginas discutindo cadeias no âmbito do objeto global</span> Variáveis globais são, na verdade, propriedade de um <em>objeto global</em>. Em páginas web o objeto global é <code><a href="/en/DOM/window" title="en/DOM/window">window</a></code>, então você pode configurar e acessar variáveis globais usando a sintaxe<code> window.<em>variable</em></code>.</p> + +<p>Consequentemente, você pode acessar variáveis globais declaradas em uma janela ou quadro de alguma outra janela ou quadro, especificando o nome do mesmo. Por exemplo, se uma variável chamada <code>phoneNumber</code> é declarada em um documento <code>FRAMESET</code>, você pode referir-se a esta variável a partir de um frame herdeiro como <code>parent.phoneNumber</code>.</p> + +<h3 id="Veja_também">Veja também</h3> + +<p><a href="/en/Sharp_variables_in_JavaScript" title="en/Sharp_variables_in_JavaScript">Sharp variables in JavaScript</a> (en)</p> + +<h2 id="Constantes">Constantes</h2> + +<p>Você pode criar elementos "somente leitura", nomeados constantes com a palavra chave <code><a href="/en/JavaScript/Reference/Statements/const" title="en/Core_JavaScript_1.5_Reference/Statements/const">const</a></code>. A sintaxe de um identificador constante é a mesma para um identificador de variáveis: deve começar com uma letra ou sublinhado e pode conter caracteres alfabéticos, numéricos ou sublinhado.</p> + +<pre class="eval deki-transform">const prefix = '212'; +</pre> + +<p>Uma constante não pode ter seu valor mudado através de uma atribuição ou ser declarada novamente enquanto o script estiver rodando.</p> + +<p>As regras de escopo para constantes são as mesmas que as das variáveis, exceto que a palavra chave <code>const</code> é sempre necessária, mesmo para constantes globais. Se uma palavra chave é omitida, o identificador é assumido como uma variável.</p> + +<p>Você não pode declarar uma constante com o mesmo nome de uma função ou variável no mesmo escopo. Por exemplo:</p> + +<pre class="eval deki-transform">// ISTO CAUSARA UM ERRO +function f() {}; +const f = 5; + +// ISTO TAMBEM CAUSARA UM ERRO +function f() { + const g = 5; + var g; + + // declaracoes +} +</pre> + +<h2 id="Literais">Literais</h2> + +<p>Você usa literais para representar valores em JavaScript. Estes valores são fixos, não variáveis, que você fornece <em>literalmente</em> no seu script. Esta seção descreve os seguintes tipos de literais:</p> + +<ul> + <li><a href="#Ordenação de literais">Ordenação de literais</a></li> + <li><a href="#Booleanos literais">Booleanos literais</a></li> + <li><a href="#Pontos flutuantes literais">Pontos flutuantes literais</a></li> + <li><a href="#Inteiros">Inteiros</a></li> + <li><a href="#Objetos literais">Objetos literais</a></li> + <li><a href="#Strings literais">Strings literais</a></li> +</ul> + +<h3 id="Ordenação_de_literais"><a id="Ordenação de literais" name="Ordenação de literais">Ordenação de literais</a></h3> + +<p>Um literal ordenado é uma lista de zero ou mais expressões, cada qual representando um elemento ordenado, armazenado em colchetes ([]). Quando você cria uma ordenação usando um literal ordenado, ele é inicializado com os valores especificados como seus elementos e seu comprimento configurado para o número de argumentos especificados.</p> + +<p>O exemplo a seguir cria uma ordenação <code>coffees</code> com três elementos e o comprimento de três:</p> + +<pre class="eval deki-transform">var coffees = ["French Roast", "Colombian", "Kona"]; +</pre> + +<p><strong>Nota</strong> Uma ordenação literal é um tipo de inicializador de objeto. Veja<a href="/en/JavaScript/Guide/Working_with_Objects#Using_Object_Initializers" title="en/JavaScript/Guide/Working with Objects#Using Object Initializers"> Using Object Initializers</a> (en).</p> + +<p>Se uma ordenação é criada usando um literal em um alto nível de script, o JavaScript interpreta a ordenação cada vez que uma expressão contendo a ordenação literal é avaliada. Adicionalmente, um literal usado em uma função é criado cada vez que a função é chamada.</p> + +<p>Ordenações literais são também objetos <code>Array</code>. Veja <a href="/en/JavaScript/Guide/Predefined_Core_Objects#Array_Object" title="en/JavaScript/Guide/Predefined Core Objects#Array Object">Array Object</a> (en) para detalhes sobre objetos <code>Array</code>.</p> + +<h4 id="Vírgulas_extras_em_literais_ordenados">Vírgulas extras em literais ordenados</h4> + +<p>Não é necessário especificar todos os elementos de um literal ordenado. Se forem colocadas duas vírgulas em uma coluna, a ordenação é criada com espaços para elementos não especificados. O exemplo seguinte mostra a ordenação <code>fish</code>:</p> + +<pre class="eval deki-transform">var fish = ["Lion", , "Angel"]; +</pre> + +<p>Esta ordenação possui dois elementos com valores e um elemento vazio (<code>fish[0]</code> é "Lion", <code>fish[1]</code> é <code>undefined</code> e <code>fish[2]</code> é "Angel").</p> + +<p>Caso seja inserida uma última vírgula ao fim da lista de elementos, a vírgula é ignorada. No exemplo a seguir, o comprimento da ordenação é três. Não há <code>myList[3]</code>. Todas as outras vírgulas da lista indicam um novo elemento.</p> + +<pre class="eval deki-transform">var myList = ['home', , 'school', ]; +</pre> + +<p>No exemplo a seguir, o comprimento da ordenação é quatro, e <code>myList[0]</code> e <code>myList[2]</code> estão faltando.</p> + +<pre class="eval deki-transform">var myList = [ , 'home', , 'school']; +</pre> + +<p>No exemplo seguinte, o comprimento da ordenação é quatro, e <code>myList[1]</code> e <code>myList[3]</code> estão faltando. Somente a última vírgula é ignorada.</p> + +<pre class="eval deki-transform">var myList = ['home', , 'school', , ]; +</pre> + +<h3 id="Booleanos_literais"><a id="Booleanos literais" name="Booleanos literais">Booleanos literais</a></h3> + +<p>O tipo Booleano possui dois valores literais: <code>true</code> e <code>false</code>.</p> + +<p>Não confunda-os com os valores Booleanos primitivos <code>true</code> e <code>false</code> com os valores verdadeiro e falso do objeto Booleano. O objeto Booleano é um invólucro ao redor do tipo de dado Booleano. Veja <a href="/en/JavaScript/Guide/Predefined_Core_Objects#Boolean_Object" title="en/JavaScript/Guide/Predefined Core Objects#Boolean Object">Boolean Object</a> (en) para mais informações.</p> + +<h3 id="Inteiros_2"><a id="Inteiros" name="Inteiros">Inteiros</a></h3> + +<p>Inteiros podem ser expressos na base decimal (base 10), hexadecimal (base 16) e octal (base 8). Um inteiro decimal literal consiste em uma sequência de dígitos sem um 0 (zero) no início. Um 0 (zero) no início de um inteiro literal indica que se trata de um octal; um 0x (ou 0X) indica hexadecimal. Inteiros hexadecimais podem incluir dígitos (0-9) e as letras de a-f e A-F. Inteiros octais podem incluir somente dígitos 0-7.</p> + +<p>Inteiros octais literais são obsoletos e foram removidos do padrão ECMA-262, Edição 3. O JavaScript 1.5 ainda os suporta para compatibilidade com versões anteriores.</p> + +<p>Alguns exemplo de inteiros literais são:</p> + +<pre class="eval">0, 117 e -345 (decimal, base 10) +015, 0001 e -077 (octal, base 8) +0x1123, 0x00111 e -0xF1A7 (hexadecimal, "hex" ou base 16) +</pre> + +<h3 id="Pontos_flutuantes_literais"><a id="Pontos flutuantes literais" name="Pontos flutuantes literais">Pontos flutuantes literais</a></h3> + +<p>Um literal de ponto flutuante pode possuir as seguintes partes:</p> + +<ul> + <li>Um inteiro decimal, o qual pode ser assinado (precedido por "+" ou "-"),</li> + <li>Um ponto decimal ("."),</li> + <li>Uma fração (outro número decimal),</li> + <li>Um expoente.</li> +</ul> + +<p>A parte do expoente é um "e" ou "E" seguido por um inteiro, o qual pode ser assinado (precedido por "+" ou "-"). Um literal de ponto flutuante deve ter ao menos um dígito e um ponto decimal ou "e" (ou "E").</p> + +<p>Alguns exemplos de pontos flutuantes literais são 3.1415, -3.1E12, .1e12, and 2E-12.</p> + +<p>Mais claramente, a sintaxe é:</p> + +<pre class="eval">[digitos][.digitos][(E|e)[(+|-)]digitos] +</pre> + +<p>Por exemplo:</p> + +<pre class="eval">3.14 +2345.789 +.3333333333333333333 +</pre> + +<h3 id="Objetos_literais"><a id="Objetos literais" name="Objetos literais">Objetos literais</a></h3> + +<p>An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.</p> + +<p>The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>; the second element, the <code>getCar</code> property, invokes a function <code>(CarTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>Sales</code>).</p> + +<pre class="eval deki-transform">var Sales = "Toyota"; + +function CarTypes(name) { + if (name == "Honda") + return name; + else + return "Sorry, we don't sell " + name + "."; +} + +var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales }; + +document.write(car.myCar); // Saturn +document.write(car.getCar); // Honda +document.write(car.special); // Toyota +</pre> + +<p>Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.</p> + +<pre class="eval deki-transform">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; + +document.write(car.manyCars.b); // Jeep +document.write(car[7]); // Mazda +</pre> + +<p>Please note:</p> + +<pre class="eval deki-transform">var foo = {a: "alpha", 2: "two"}; +document.write(foo.a); // alpha +document.write(foo[2]); // two +//document.write(foo.2); // Error: missing ) after argument list +//document.write(foo[a]); // Error: a is not defined +document.write(foo["a"]); // alpha +document.write(foo["2"]); // two +</pre> + +<h3 id="Strings_literais"><a id="Strings literais" name="Strings literais">Strings literais</a></h3> + +<p>A string literal is zero or more characters enclosed in double (<code>"</code>) or single (<code>'</code>) quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:</p> + +<ul> + <li><code>"foo"</code></li> + <li><code>'bar'</code></li> + <li><code>"1234"</code></li> + <li><code>"one line \n another line"</code></li> + <li><code>"John's cat"</code></li> +</ul> + +<p>You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the <code>String.length</code> property with a string literal:</p> + +<pre class="deki-transform">"John's cat".length +</pre> + +<p>You should use string literals unless you specifically need to use a String object. See <a href="/en/JavaScript/Guide/Predefined_Core_Objects#String_Object" title="en/JavaScript/Guide/Predefined Core Objects#String Object">String Object</a> for details on <code>String</code> objects.</p> + +<h4 id="Usando_caracteres_especiais_em_strings">Usando caracteres especiais em strings</h4> + +<p>In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p> + +<pre class="eval deki-transform">"one line \n another line" +</pre> + +<p>The following table lists the special characters that you can use in JavaScript strings.</p> + +<table class="standard-table"> + <caption>Table 2.1 JavaScript special characters</caption> + <thead> + <tr> + <th scope="col">Character</th> + <th scope="col">Meaning</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\b</code></td> + <td>Backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Form feed</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>New line</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Carriage return</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Vertical tab</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Apostrophe or single quote</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Double quote</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Backslash character (\).</td> + </tr> + <tr> + <td><code>\<em>XXX</em></code></td> + <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td> + </tr> + <tr> + <td><code>\x<em>XX</em></code></td> + <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td> + </tr> + <tr> + <td><code>\u<em>XXXX</em></code></td> + <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See <a href="#Sequências de escape em Unicode">Unicode Escape Sequences</a>.</td> + </tr> + </tbody> +</table> + +<h4 id="Caracteres_de_escape">Caracteres de escape</h4> + +<p>For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p> + +<p>You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p> + +<pre class="eval deki-transform">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; +document.write(quote); +</pre> + +<p>The result of this would be:</p> + +<pre class="eval">He read "The Cremation of Sam McGee" by R.W. Service. +</pre> + +<p>To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p> + +<pre class="eval deki-transform">var home = "c:\\temp"; +</pre> + +<p>You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.</p> + +<pre>var str = "this string \ +is broken \ +across multiple\ +lines."</pre> + +<p>Although JavaScript does not have "heredoc" syntax, you can get close by adding a linebreak escape and an escaped linebreak at the end of each line:</p> + +<pre>var poem = +"Roses are red,\n\ +Violets are blue.\n\ +I'm schizophrenic,\n\ +And so am I." +</pre> + +<h2 id="Unicode">Unicode</h2> + +<p>Unicode is a universal character-coding standard for the interchange and display of principal written languages. It covers the languages of the Americas, Europe, Middle East, Africa, India, Asia, and Pacifica, as well as historic scripts and technical symbols. Unicode allows for the exchange, processing, and display of multilingual texts, as well as the use of common technical and mathematical symbols. It hopes to resolve internationalization problems of multilingual computing, such as different national character standards. Not all modern or archaic scripts, however, are currently supported.</p> + +<p>The Unicode character set can be used for all known encoding. Unicode is modeled after the ASCII (American Standard Code for Information Interchange) character set. It uses a numerical value and name for each character. The character encoding specifies the identity of the character and its numeric value (code position), as well as the representation of this value in bits. The 16-bit numeric value (code value) is defined by a hexadecimal number and a prefix U, for example, U+0041 represents A. The unique name for this value is LATIN CAPITAL LETTER A.</p> + +<p><strong>Unicode is not supported in versions of JavaScript prior to 1.3.</strong></p> + +<h3 id="Compatibilidade_do_Unicode_com_ASCII_e_ISO">Compatibilidade do Unicode com ASCII e ISO</h3> + +<p>Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646.</p> + +<p>Several encoding standards (including UTF-8, UTF-16 and ISO UCS-2) are used to physically represent Unicode as actual bits.</p> + +<p>The UTF-8 encoding of Unicode is compatible with ASCII characters and is supported by many programs. The first 128 Unicode characters correspond to the ASCII characters and have the same byte value. The Unicode characters U+0020 through U+007E are equivalent to the ASCII characters 0x20 through 0x7E. Unlike ASCII, which supports the Latin alphabet and uses a 7-bit character set, UTF-8 uses between one and four octets for each character ("octet" meaning a byte, or 8 bits.) This allows for several million characters. An alternative encoding standard, UTF-16, uses two octets to represent Unicode characters. An escape sequence allows UTF-16 to represent the whole Unicode range by using four octets. The ISO UCS-2 (Universal Character Set) uses two octets.</p> + +<p>JavaScript and Navigator support for UTF-8/Unicode means you can use non-Latin, international, and localized characters, plus special technical symbols in JavaScript programs. Unicode provides a standard way to encode multilingual text. Since the UTF-8 encoding of Unicode is compatible with ASCII, programs can use ASCII characters. You can use non-ASCII Unicode characters in the comments, string literals, identifiers, and regular expressions of JavaScript.</p> + +<h3 id="Sequências_de_escape_em_Unicode"><a id="Sequências de escape em Unicode" name="Sequências de escape em Unicode">Sequências de escape em Unicode</a></h3> + +<p>You can use the Unicode escape sequence in string literals, regular expressions, and identifiers. The escape sequence consists of six ASCII characters: \u and a four-digit hexadecimal number. For example, \u00A9 represents the copyright symbol. Every Unicode escape sequence in JavaScript is interpreted as one character.</p> + +<p>The following code returns the copyright symbol and the string "Netscape Communications".</p> + +<pre class="deki-transform">var x = "\u00A9 Netscape Communications";</pre> + +<p>The following table lists frequently used special characters and their Unicode value.</p> + +<table class="standard-table"> + <caption>Table 2.2 Unicode values for special characters</caption> + <thead> + <tr> + <th scope="col">Category</th> + <th scope="col">Unicode value</th> + <th scope="col">Name</th> + <th scope="col">Format name</th> + </tr> + </thead> + <tbody> + <tr> + <td rowspan="4">White space values<br> + <br> + <br> + </td> + <td>\u0009</td> + <td>Tab</td> + <td><TAB></td> + </tr> + <tr> + <td>\u000B</td> + <td>Vertical Tab</td> + <td><VT></td> + </tr> + <tr> + <td>\u000C</td> + <td>Form Feed</td> + <td><FF></td> + </tr> + <tr> + <td>\u0020</td> + <td>Space</td> + <td><SP></td> + </tr> + <tr> + <td rowspan="2">Line terminator values<br> + </td> + <td>\u000A</td> + <td>Line Feed</td> + <td><LF></td> + </tr> + <tr> + <td>\u000D</td> + <td>Carriage Return</td> + <td><CR></td> + </tr> + <tr> + <td rowspan="5">Additional Unicode escape sequence values<br> + <br> + <br> + <br> + </td> + <td>\u0008</td> + <td>Backspace</td> + <td><BS></td> + </tr> + <tr> + <td>\u0009</td> + <td>Horizontal Tab</td> + <td><HT></td> + </tr> + <tr> + <td>\u0022</td> + <td>Double Quote</td> + <td>"</td> + </tr> + <tr> + <td>\u0027</td> + <td>Single Quote</td> + <td>'</td> + </tr> + <tr> + <td>\u005C</td> + <td>Backslash</td> + <td>\</td> + </tr> + </tbody> +</table> + +<p>The JavaScript use of the Unicode escape sequence is different from Java. In JavaScript, the escape sequence is never interpreted as a special character first. For example, a line terminator escape sequence inside a string does not terminate the string before it is interpreted by the function. JavaScript ignores any escape sequence if it is used in comments. In Java, if an escape sequence is used in a single comment line, it is interpreted as an Unicode character. For a string literal, the Java compiler interprets the escape sequences first. For example, if a line terminator escape character (e.g., \u000A) is used in Java, it terminates the string literal. In Java, this leads to an error, because line terminators are not allowed in string literals. You must use \n for a line feed in a string literal. In JavaScript, the escape sequence works the same way as \n.</p> + +<h3 id="Caracteres_Unicode_em_arquivos_JavaScript">Caracteres Unicode em arquivos JavaScript</h3> + +<p>Earlier versions of <a href="/en/Gecko" title="en/Gecko">Gecko</a> assumed the Latin-1 character encoding for JavaScript files loaded from XUL. Starting with Gecko 1.8, the character encoding is inferred from the XUL file's encoding. Please see <a href="/en/International_characters_in_XUL_JavaScript" title="en/International_characters_in_XUL_JavaScript">International characters in XUL JavaScript</a> for more information.</p> + +<h3 id="Exibindo_caracteres_com_Unicode">Exibindo caracteres com Unicode</h3> + +<p>You can use Unicode to display the characters in different languages or technical symbols. For characters to be displayed properly, a client such as Mozilla Firefox or Netscape needs to support Unicode. Moreover, an appropriate Unicode font must be available to the client, and the client platform must support Unicode. Often, Unicode fonts do not display all the Unicode characters. Some platforms, such as Windows 95, provide partial support for Unicode.</p> + +<p>To receive non-ASCII character input, the client needs to send the input as Unicode. Using a standard enhanced keyboard, the client cannot easily input the additional characters supported by Unicode. Sometimes, the only way to input Unicode characters is by using Unicode escape sequences.</p> + +<p>For more information on Unicode, see the <a class="external" href="http://www.unicode.org/">Unicode Home Page</a> and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.</p> + +<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters");</pre> diff --git a/files/pt-pt/web/javascript/index.html b/files/pt-pt/web/javascript/index.html new file mode 100644 index 0000000000..96b6b4b28b --- /dev/null +++ b/files/pt-pt/web/javascript/index.html @@ -0,0 +1,140 @@ +--- +title: JavaScript +slug: Web/JavaScript +tags: + - Aprender + - JavaScript + - Landing + - Página Landing + - 'l10n:priority' +translation_of: Web/JavaScript +--- +<div>{{JsSidebar}}</div> + +<div> +<p class="summary"><strong>JavaScript</strong> (<strong>JS</strong>) é uma linguagem de programação compilada simples, interpretada ou "<em>just-in-time"</em> com {{Glossary("First-class Function", "funções de primeira classe")}}. Embora seja mais conhecida coma a linguagem de <em>scripting</em> para as páginas da Web, também é utilizada em <a class="external" href="https://en.wikipedia.org/wiki/JavaScript#Uses_outside_Web_pages">muitos ambientes além de navegadores</a> (inglês), tais como <a class="external" href="/en-US/docs/Glossary/Node.js">Node.js</a>, <a href="https://couchdb.apache.org/">Apache CouchDB</a> e <a href="http://www.adobe.com/devnet/acrobat/javascript.html">Adobe Acrobat</a>. JavaScript é uma linguagem dinâmica, {{Glossary("Prototype-based programming", "baseada em protótipos")}} e que suporta os paradigmas de programação orientada a objetos, imperativa e declarativa (incluindo programação funcional). Leia mais <a href="/pt-PT/docs/Web/JavaScript/Sobre_JavaScript">sobre o JavaScript</a>.</p> + +<p>Esta secção do <em>site </em>é dedicada à própria linguagem JavaScript, e não a partes específicas das páginas da Internet ou outros ambientes. Para informação sobre {{Glossary("API","APIs")}} específicas para as páginas da Web, por favor, consulte <a href="/pt-PT/docs/Web/API">APIs da Web </a>e <a href="/pt-PT/docs/DOM/DOM_Reference" title="https://developer.mozilla.org/en/DOM">DOM</a>.</p> + +<p>O padrão para JavaScript é <a href="/en-US/docs/Web/JavaScript/Language_Resources">ECMAScript</a>. Em 2012, todos os <a href="https://kangax.github.io/compat-table/es5/">navegadores modernos</a> são totalmente compatíveis com a versão ECMAScript 5.1. Navegadores mais antigos suportam pelo menos ECMAScript 3. No dia 17 de junho de 2015, <a href="https://www.ecma-international.org">ECMA International</a> publicou a sexta versão principal de ECMAScript, cujo nome oficial é ECMAScript 2015, e inicialmente era chamada ECMAScript 6 ou ES6. Desde então, as normas de ECMAScript são lançadas anualmente. Esta documentação refere-se à última proposta, que atualmente é <a href="https://tc39.github.io/ecma262/">ECMAScript 2018</a>.</p> + +<p>Não faça confusão entre JavaScript e <a href="https://pt.wikipedia.org/wiki/Java_(linguagem_de_programa%C3%A7%C3%A3o)">a linguagem de programação Java</a>. Tanto "Java" como "JavaScript" são marcas ou marcas registadas da Oracle nos E.U.A. e outros países. Contudo, estas linguagens de programação têm muitas diferenças na sua sintaxe, semânticas e utilização.</p> + +<div class="column-container"> +<div class="column-half"> +<h2 id="Tutoriais">Tutoriais</h2> + +<p>Aprender a programar em JavaScript com guias e tutorials.</p> + +<h3 id="Para_principiantes_absolutos">Para principiantes absolutos</h3> + +<p>Dirija-se ao nosso <a href="/en-US/docs/Learn/JavaScript">tópico sobre JavaScript</a> se quer aprender esta linguagem mas não tem experiência alguma em programação. Seguem-se os módulos disponíveis:</p> + +<dl> + <dt><a href="/pt-PT/docs/Learn/JavaScript/Primeiros_passos">JavaScript - primeiros passos</a></dt> + <dd>Responde a questões fundamentais como "o que é JavaScript?", "que aspeto tem a linguagem?", e "o que pode fazer?", além de discutir funcionalidades chave JavaScript como variáveis, strings, números e arrays.</dd> + <dt><a href="/pt-PT/docs/Learn/JavaScript/Elementos_constituintes">JavaScript - elementos constituintes</a></dt> + <dd>Continua a abordagem às principais funcionalidades de JavaScript, tendo como foco os blocos de código utilizados mais habitualmente, tais como instruções condicionais, ciclos, funções e eventos.</dd> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects">Introducing JavaScript objects</a></dt> + <dd>The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you.</dd> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous">Asynchronous JavaScript</a></dt> + <dd>Discusses asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.</dd> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs">Client-side web APIs</a></dt> + <dd>Explores what APIs are, and how to use some of the most common APIs you'll come across often in your development work.</dd> +</dl> + +<h3 id="Guia_de_JavaScript">Guia de JavaScript</h3> + +<dl> + <dt><a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a></dt> + <dd>Um guia muito detalhado de JavaScript, apropriado para pessoas com experiência em JavaScript ou noutra linguagem.</dd> +</dl> + +<h3 id="Intermediário">Intermediário</h3> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript">Reintrodução ao JavaScript</a></dt> + <dd>Uma visão geral para quem acha que conhece o JavaScript.</dd> +</dl> + +<dl> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">Estrutura de Dados no JavaScript</a></dt> + <dd>Uma visão geral das estruturas de dados disponíveis no JavaScript.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">Equality comparisons and sameness</a></dt> + <dd>JavaScript provides three different value-comparison operations: strict equality using <code>===</code>, loose equality using <code>==</code>, and the {{jsxref("Global_Objects/Object/is", "Object.is()")}} method.</dd> + <dt><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">Closures</a></dt> + <dd> + <p>A closure is the combination of a function and the lexical environment within which that function was declared.</p> + </dd> +</dl> + +<h3 id="Avançado">Avançado</h3> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a></dt> + <dd>Explanation of the widely misunderstood and under-estimated prototype-based inheritance.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></dt> + <dd>Strict mode defines that you can not use any variable before initializing it. It is a restricted variant of ECMAScript 5, for faster performance and easier debugging.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></dt> + <dd>JavaScript typed arrays provide a mechanism for accessing raw binary data.</dd> + <dt><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management">Memory Management</a></dt> + <dd>Memory life cycle and garbage collection in JavaScript.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/EventLoop">Concurrency model and Event Loop</a></dt> + <dd>JavaScript has a concurrency model based on an "event loop".</dd> +</dl> +</div> + +<div class="column-half"> +<h2 id="Referência">Referência</h2> + +<p>Explore a documentação completa de <a href="/pt-PT/docs/Web/JavaScript/Reference">refrência de JavaScript</a>.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">Standard objects</a></dt> + <dd>Get to know standard built-in objects {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, and others.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Expressions and operators</a></dt> + <dd>Learn more about the behavior of JavaScript's operators {{jsxref("Operators/instanceof", "instanceof")}}, {{jsxref("Operators/typeof", "typeof")}}, {{jsxref("Operators/new", "new")}}, {{jsxref("Operators/this", "this")}}, the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a>, and more.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Statements">Statements and declarations</a></dt> + <dd>Learn how {{jsxref("Statements/do...while", "do-while")}}, {{jsxref("Statements/for...in", "for-in")}}, {{jsxref("Statements/for...of", "for-of")}}, {{jsxref("Statements/try...catch", "try-catch")}}, {{jsxref("Statements/let", "let")}}, {{jsxref("Statements/var", "var")}}, {{jsxref("Statements/const", "const")}}, {{jsxref("Statements/if...else", "if-else")}}, {{jsxref("Statements/switch", "switch")}}, and more JavaScript statements and keywords work.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Funções</a></dt> + <dd>Aprenda como trabalhar com funções do JavaScript para desenvolver suas aplicações.</dd> +</dl> + +<h2 id="Ferramentas_e_recursos">Ferramentas e recursos</h2> + +<p>Ferramentas úteis para escrever e depurar o seu código <strong>JavaScript</strong>.</p> + +<dl> + <dt><a href="/pt-PT/docs/Tools">Ferramentas de Desenvolvimento do Firefox</a></dt> + <dd><a href="/pt-PT/docs/Tools/Scratchpad">Scratchpad</a>, <a href="/pt-PT/docs/Tools/Consola_da_Web">Consola da Web</a>, <a href="/pt-PT/docs/Tools/Desempenho">JavaScript Profiler</a>, <a href="/en-US/docs/Tools/Debugger">Debugger</a>, e muito mais.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Shells">JavaScript Shells</a></dt> + <dd>A JavaScript shell allows you to quickly test snippets of JavaScript code.</dd> + <dt><a href="https://learnjavascript.online/">Learn JavaScript</a></dt> + <dd>An excellent resource for aspiring web developers — Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.</dd> + <dt><a href="https://togetherjs.com/">TogetherJS</a></dt> + <dd>Collaboration made easy. By adding TogetherJS to your site, your users can help each other out on a website in real time!</dd> + <dt><a href="https://stackoverflow.com/questions/tagged/javascript">Stack Overflow</a></dt> + <dd>Dúvidas no Stack Overflow marcadas com "JavaScript".</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">JavaScript versions and release notes</a></dt> + <dd>Browse JavaScript's feature history and implementation status.</dd> + <dt><a href="https://jsfiddle.net/">JSFiddle</a></dt> + <dd>Edit JavaScript, CSS, HTML and get live results. Use external resources and collaborate with your team online.</dd> + <dt></dt> + <dt><a href="https://plnkr.co/">Plunker</a></dt> + <dd>Plunker is an online community for creating, collaborating on and sharing your web development ideas. Edit your JavaScript, CSS, HTML files and get live results and file structure.</dd> + <dt><a href="https://jsbin.com/">JSBin</a></dt> + <dd> + <p>JS Bin is an open source collaborative web development debugging tool.</p> + </dd> + <dt><a href="https://codepen.io/">Codepen</a></dt> + <dd> + <p>Codepen is another collaborative web development tool used as a live result playground.</p> + </dd> + <dt><a href="https://stackblitz.com/">StackBlitz</a></dt> + <dd> + <p>StackBlitz is another online playground/debugging tool, which can host and deploy full stack applications using React, Angular, etc.</p> + </dd> +</dl> +</div> +</div> +</div> diff --git a/files/pt-pt/web/javascript/novidades_no_javascript/index.html b/files/pt-pt/web/javascript/novidades_no_javascript/index.html new file mode 100644 index 0000000000..42d40e9929 --- /dev/null +++ b/files/pt-pt/web/javascript/novidades_no_javascript/index.html @@ -0,0 +1,80 @@ +--- +title: Novidades no JavaScript +slug: Web/JavaScript/Novidades_no_JavaScript +tags: + - NeedsTranslation + - TopicStub +translation_of: Archive/Web/JavaScript/New_in_JavaScript +--- +<div>{{jsSidebar("New_in_JS")}}</div> + +<p>This chapter contains information about JavaScript's version history and implementation status for Mozilla/SpiderMonkey-based JavaScript applications, such as Firefox.</p> + +<h2 id="ECMAScript_versions">ECMAScript versions</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Language_Resources">Language resources</a></dt> + <dd>Learn more about the ECMAScript standards on which the JavaScript language is based on.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla">ECMAScript 5 support</a></dt> + <dd>Implementation status for the current standard ECMA-262 Edition 5.1 in Mozilla-based engines and products.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla">ECMAScript 6 support</a></dt> + <dd>Implementation status for the draft ECMA-262 Edition 6 in Mozilla-based engines and products.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_7_support_in_Mozilla">ECMAScript 7 support</a></dt> + <dd>Implementation status for the upcoming ECMA-262 Edition 7 in Mozilla-based engines and products.</dd> +</dl> + +<h2 id="JavaScript_release_notes">JavaScript release notes</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/Firefox_JavaScript_changelog">Firefox JavaScript changelog</a></dt> + <dd>See this changelog for JavaScript features implemented in Firefox 5 and later.</dd> + <dt>Chrome JavaScript changelog</dt> + <dd>(TODO). See this changelog for JavaScript features implemented in Chrome releases.</dd> +</dl> + +<h2 id="JavaScript_versions">JavaScript versions</h2> + +<p><strong>Deprecated</strong> ({{deprecated_inline()}}). The explicit versioning and opt-in of language features was Mozilla-specific and <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=867609">is in process of being removed</a>. Firefox 4 was the last version which referred to an JavaScript version (1.8.5). With new ECMA standards, JavaScript language features are now often mentioned with their initial definition in ECMA-262 Editions such as Edition 6 (ES6).</p> + +<p>JavaScript was released as version 1.0 in March 1996 in Netscape Navigator 2.0 and Internet Explorer 2.0.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.1">JavaScript 1.1</a></dt> + <dd>Version shipped in Netscape Navigator 3.0. Released on August 19, 1996.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.2">JavaScript 1.2</a></dt> + <dd>Version shipped in Netscape Navigator 4.0-4.05. Released on June 11, 1997.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.3">JavaScript 1.3</a></dt> + <dd>Version shipped in Netscape Navigator 4.06-4.7x. Released on October 19, 1998.<br> + Standardization work to be compliant with ECMA-262 1st and 2nd Edition.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.4">JavaScript 1.4</a></dt> + <dd>Version shipped in Netscape's server side JavaScript. Released in 1999.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.5">JavaScript 1.5</a></dt> + <dd>Version shipped in Netscape Navigator 6.0 and Firefox 1.0. Release on November 14, 2000.<br> + Standardization work to be compliant with ECMA-262 3rd Edition.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.6">JavaScript 1.6</a></dt> + <dd>Version shipped in Firefox 1.5. Released in November 2005.<br> + Includes ECMAScript for XML (E4X), new <code>Array</code> methods plus <code>String</code> and <code>Array</code> generics.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JavaScript 1.7</a></dt> + <dd>Version shipped in Firefox 2. Released in October 2006.<br> + Includes generators, iterators, array comprehensions, <code>let</code> expressions, and destructuring assignment.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8">JavaScript 1.8</a></dt> + <dd>Version shipped in Firefox 3. Released in June 2008.<br> + Includes expression closures, generator expressions and <code>Array.reduce()</code></dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8.1">JavaScript 1.8.1</a></dt> + <dd>Version shipped in Firefox 3.5. Released on <span class="st">June 30, 2009.<br> + Includes the TraceMonkey JIT and supports native JSON.</span></dd> + <dt>JavaScript 1.8.2</dt> + <dd>Version shipped in Firefox 3.6. Released June 22, 2009.<br> + Includes only minor changes.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.8.5">JavaScript 1.8.5</a></dt> + <dd>Version shipped in Firefox 4. Released July 27, 2010.<br> + Includes many new features for ECMA-262 Edition 5 compliance.<br> + This is the last JavaScript version.</dd> +</dl> + +<h2 id="Features_still_requiring_version_opt-in">Features still requiring version opt-in</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let"><code>let</code> statement</a></dt> + <dd>The <code>let</code> statement requires the JavaScript version 1.7 (or higher) opt-in. See {{bug(932517)}} and {{bug(932513)}}.</dd> +</dl> diff --git a/files/pt-pt/web/javascript/novidades_no_javascript/novidades_no_javascript_1.8/index.html b/files/pt-pt/web/javascript/novidades_no_javascript/novidades_no_javascript_1.8/index.html new file mode 100644 index 0000000000..4791e4d0e9 --- /dev/null +++ b/files/pt-pt/web/javascript/novidades_no_javascript/novidades_no_javascript_1.8/index.html @@ -0,0 +1,136 @@ +--- +title: Novidades no Javascript 1.8 +slug: Web/JavaScript/Novidades_no_JavaScript/Novidades_no_Javascript_1.8 +tags: + - JavaScript + - Todas_as_Categorias +translation_of: Archive/Web/JavaScript/New_in_JavaScript/1.8 +--- +<p>{{jsSidebar("New_in_JS")}}</p> + +<p>O JavaScript 1.8 está programado para ser lançado como parte do Gecko 1.9 (que será incorporado ao <a href="/pt/Firefox_3_para_desenvolvedores" title="pt/Firefox_3_para_desenvolvedores">Firefox 3</a>). Esta é uma atualização menos substancial que o <a href="/en/New_in_JavaScript_1.7">JavaScript 1.7</a>, mas tem algumas atualizações para acompanhar o progresso rumo ao ECMAScript 4/JavaScript 2. Esta liberação incluirá todas as novas características especificadas no <a href="/en/New_in_JavaScript_1.6">JavaScript 1.6</a> e <a href="/en/New_in_JavaScript_1.7">JavaScript 1.7</a>.</p> + +<p>Veja o {{ Bug(380236) }} para acompanhar o progresso do desenvolvimento do JavaScript 1.8.</p> + +<h2 id="Usando_JavaScript_1.8" name="Usando_JavaScript_1.8">Usando JavaScript 1.8</h2> + +<p>A fim de usar algumas das novas características do JavaScript 1.8 no HTML, use:</p> + +<pre class="eval"> <script type="application/javascript;version=1.8"> ... seu código ... </script> +</pre> + +<p>Quando usando o <a href="/en/Introduction_to_the_JavaScript_shell">JavaScript shell</a>, componentes XPCOM ou elementos XUL <code><script></code>, a versão mais recente do Javascript (1.8 no Mozilla 1.9) é usada automaticamente ({{ Bug(381031) }}, {{ Bug(385159) }}).</p> + +<p>Os recursos que requerem o uso das novas palavras-chave "yield" e "let" requerem que você especifique a versão 1.7 ou mais recente, porque o código existente pode usar estas palavras-chave como variáveis ou nomes de função. Os recursos que não introduzem novas palavras-chave (como o gerador de expressões) podem ser usados sem que seja necessário especificar a versão do JavaScript.</p> + +<h2 id="Fechamentos_de_express.C3.B5es" name="Fechamentos_de_express.C3.B5es">Fechamentos de expressões</h2> + +<p>Esta adição nada mais é que uma abreviação para escrever funções simples, dando à linguagem algo similar a uma típica <a class="external" href="http://en.wikipedia.org/wiki/Lambda_calculus#Lambda_calculus_and_programming_languages">notação lambda</a>.</p> + +<p>JavaScript 1.7 e mais antigos:</p> + +<pre class="eval"> function(x) { return x * x; } +</pre> + +<p>JavaScript 1.8:</p> + +<pre class="eval"> function(x) x * x +</pre> + +<p>Esta sintaxe permite que você deixe de fora as chaves e a declaração 'return' — fazendo-as implícitas. Não há benefício adicionado ao se escrever código desta maneira, à exceção de ser sintaticamente mais curto.</p> + +<p><strong>Exemplos:</strong></p> + +<p>Uma abreviação para ligar ouvintes de evento:</p> + +<pre class="eval"> document.addEventListener("click", function() false, true); +</pre> + +<p>Usando esta notação com alguma das funções de array do JavaScript 1.6:</p> + +<pre class="eval"> elems.some(function(elem) elem.type == "text"); +</pre> + +<h2 id="Gerador_de_express.C3.B5es" name="Gerador_de_express.C3.B5es">Gerador de expressões</h2> + +<p>Esta adição permite que você crie geradores de maneira simples (que foram introduzidos no JavaScript 1.7). Tipicamente você teria que criar uma função personalizada contendo a palavra-chave yield, mas esta adição permite que você use uma sintaxe semelhante à compreensão de arrays para criar uma instrução geradora idêntica.</p> + +<p>No JavaScript 1.7, você poderia escrever algo como o seguinte, a fim de criar um gerador personalizado para um objeto:</p> + +<pre class="eval"> function add3(obj) { + for ( let i in obj ) + yield i + 3; + } + + let it = add3(someObj); + try { + while (true) { + document.write(it.next() + "<br>\n"); + } + } catch (err if err instanceof StopIteration) { + document.write("End of record.<br>\n"); + } +</pre> + +<p>No JavaScript 1.8, você pode contornar a criação de uma função de gerador personalizada usando um gerador de expressões em vez disso:</p> + +<pre class="eval"> let it = (i + 3 for (i in someObj)); + try { + while (true) { + document.write(it.next() + "<br>\n"); + } + } catch (err if err instanceof StopIteration) { + document.write("End of record.<br>\n"); + } +</pre> + +<p>Geradores de expressões também podem ser passados como valores a uma função. Isto é particularmente notável de modo que geradores não serão executados antes que seja absolutamente necessário (diferente de típicas situações de compreensão de array, onde os arrays são construídos antes do tempo). Um exemplo da diferença pode ser visto aqui:</p> + +<p>Usando a compreensão de array do JavaScript 1.7</p> + +<pre class="eval"> handleResults([ i for ( i in obj ) if ( i > 3 ) ]); + + function handleResults( results ) { + for ( let i in results ) + // ... + } +</pre> + +<p>Usando o gerador de expressões do JavaScript 1.8</p> + +<pre class="eval"> handleResults( i for ( i in obj ) if ( i > 3 ) ); + + function handleResults( results ) { + for ( let i in results ) + // ... + } +</pre> + +<p>A diferença significativa entre os dois exemplos, começando pelo que usa o gerador de expressões, é que você poderia usar somente o <em>loop</em> uma vez sobre a estrutura 'obj', ao invés de uma vez compreender o array e novamente iterar com ele.</p> + +<h2 id="Mais_extras_do_Array" name="Mais_extras_do_Array">Mais extras do Array</h2> + +<p>Existem dois novos métodos iterativos de <code><a href="/en/Core_JavaScript_1.5_Reference/Global_Objects/Array">Array</a></code> incluídos no JavaScript 1.8, especificamente:</p> + +<ul> + <li><code><a href="/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce">reduce()</a></code> - executa uma função em cada item no <em>array</em> e coleta os resultados de chamadas anteriores.</li> + <li><code><a href="/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight">reduceRight()</a></code> - executa uma função em cada item no <em>array</em> e coleta os resultados de chamadas anteriores, mas em reverso.</li> +</ul> + +<h2 id="Mudan.C3.A7as_na_desestrutura.C3.A7.C3.A3o_for..in" name="Mudan.C3.A7as_na_desestrutura.C3.A7.C3.A3o_for..in">Mudanças na desestruturação for..in</h2> + +<p>Menção em <a href="/en/New_in_JavaScript_1.7#Looping_across_objects">en:New_in_JavaScript_1.7#Looping_across_objects</a> ({{ Bug(366941) }}).</p> + +<h2 id="Mudan.C3.A7as_iminentes" name="Mudan.C3.A7as_iminentes">Mudanças iminentes</h2> + +<p>As mudanças esperadas para a chegada no JavaScript 1.8 incluem:</p> + +<ul> + <li>Codificação e decodificação JSON.</li> + <li>Sintaxe <em>slice</em>.</li> + <li>Desestruturação generalizada <code>for...in</code> (isso significa algo diferente de <a href="#Chances_in_destrugturing_for..in">#Chances in destrugturing for..in</a>? --<a href="/User:Nickolay">Nickolay</a> 10:52, 9 de setembro de 2007 (PDT)).</li> +</ul> + +<p><span class="comment">Categorias</span></p> + +<p><span class="comment">Interwiki Language Links</span></p> diff --git a/files/pt-pt/web/javascript/o_que_é_o_javascript/index.html b/files/pt-pt/web/javascript/o_que_é_o_javascript/index.html new file mode 100644 index 0000000000..4145f9dc58 --- /dev/null +++ b/files/pt-pt/web/javascript/o_que_é_o_javascript/index.html @@ -0,0 +1,13 @@ +--- +title: O que é o JavaScript +slug: Web/JavaScript/O_que_é_o_JavaScript +--- +<p>O JavaScript é uma linguagem de programação do lado <b>cliente</b>, ou seja, é processada pelo próprio navegador. +Com o JavaScript podemos criar efeitos especiais para nossas páginas na Web, além +de podermos proporcionar uma maior interatividade com nossos usuários. +O JavaScript é uma linguagem orientada a objetos, ou seja, ela trata todos os elementos da página +como objetos distintos, fascilitando a tarefa da programação. +</p><p>Resumindo, o JavaScript é uma poderosa linguagem que deve ser dominada por quem deseja criar páginas Web dinamicas e interativas. +</p><p><br> +--<a>rafael.marcondes92@gmail.com</a> 12:39, 14 Julho 2008 (PDT) +</p> diff --git a/files/pt-pt/web/javascript/reference/classes/index.html b/files/pt-pt/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..03ff413025 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/classes/index.html @@ -0,0 +1,437 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Construtores + - ECMAScript 2015 + - Herança + - Intermedio + - JavaScript +translation_of: Web/JavaScript/Reference/Classes +--- +<div>{{JsSidebar("Classes")}}</div> + +<p>Classes JavaScript , introduzidas no ECMAScript de 2015, são principalemente syntactical sugar sobre a herança baseada em prototipagem do JavaScript. A sintaxe de classe <strong>não </strong>introduz no JavaScript nenhum novo modelo de herança do paradigma das linguagens orientado a objetos .</p> + +<h2 id="Definição_de_classes">Definição de classes</h2> + +<p>As classes são na realidade "<a href="/en-US/docs/Web/JavaScript/Reference/Functions">funções</a> especiais", e, tal como você pode definir o <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">expressões de funções</a> e <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">declarações de funções</a>, a sintaxe de classe tem dois componentes: <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">expressões de classes</a> e a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">declaração da classe</a>.</p> + +<h3 id="Declaração_de_classes">Declaração de classes</h3> + +<p>Uma forma de definir uma classe é usar uma <strong>declaração de classe</strong>. Para declarar uma classe, utiliza-se a palavra reservada <code>class</code> seguida do nome da classe ("Rectangle" no seguinte exemplo).</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<h4 id="Hoisting">Hoisting</h4> + +<p>Uma diferença importante entre a <strong>declaração de funções</strong> e a <strong>declaração de classes</strong> é que a declaração de funções são {{Glossary("Hoisting", "hoisted")}} e a declaração de classes não. É preciso primeiro declarar a classe e só depois aceder-lhe, caso contrário, como no código que se segue, será lançada uma {{jsxref("ReferenceError")}}:</p> + +<pre class="brush: js example-bad">var p = new Rectangle(); // ReferenceError + +class Rectangle {} +</pre> + +<h3 id="Expressão_de_Classe">Expressão de Classe</h3> + +<p>A <strong>expressão de classe</strong> é outra forma de definir uma classe. As expressões de classes podem ter nome o ser anónimas. O nome dado a uma expressão de classe é local ao corpo da classe. (ainda assim pode ser obtido através do propriedade <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name">.name</a> da classe (não da instância) )</p> + +<pre class="brush: js">// unnamed +var Rectangle = class { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; + +// named +var Rectangle = class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}; +</pre> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> <strong>Expressões </strong>de classes também padecem da mesma situação de hoisting mencionada para as <strong>declarações </strong>de classes.</p> +</div> + +<h2 id="Definição_de_corpo_de_classe_e_de_método">Definição de corpo de classe e de método</h2> + +<p>O corpo da classe é a parte que está entre as chavetas <code>{}</code>. É aqui que são definidos os membros da classe, tais como, métodos e construtores.</p> + +<h3 id="Strict_mode_-_modo_estrito">Strict mode - modo estrito</h3> + +<p>Os corpos da <em>declaração de classes </em>e da <em>expressão de classes </em>são executados em <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> i.e. construtor, métodos estáticos e de prototipo, funções getter e setter são executadas em modo estrito.</p> + +<h3 id="Construtor_(constructor)">Construtor (<em>constructor</em>)</h3> + +<p>O método <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor</a></code> é um método especial para criar e inicializar um objto criado de uma <code>class</code>. Numa classe, apenas pode existir um método especial com o nome "constructor". Se a classe tiver mais do que uma occorrência de um método <code>constructor</code> será lançada uma {{jsxref("SyntaxError")}}.</p> + +<p>Um construtor pode utlizar a palavra reservada <code>super</code> para invocar o construtor da classe pai.</p> + +<h3 id="Métodos_de_Prototype">Métodos de Prototype </h3> + +<p>Ver também <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">definição de métodos</a>.</p> + +<pre class="brush: js">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } + // Getter + get area() { + return this.calcArea(); + } + // Method + calcArea() { + return this.height * this.width; + } +} + +const square = new Rectangle(10, 10); + +console.log(square.area); // 100</pre> + +<h3 id="Métodos_estáticos">Métodos estáticos</h3> + +<p>A palavra reservada <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> define um método como estático para uma classe. Os métodos estáticos são chamados sem <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)" title='An example of class instance is "var john = new Person();"'>instanciarem </a>as suas classes e <strong>não podem </strong>ser chamados a partir de instâncias da classe. Os métodos estáticos são frequentemente utilizados para criar funções utilitárias para uma aplicação.</p> + +<pre class="brush: js">class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } + + static distance(a, b) { + const dx = a.x - b.x; + const dy = a.y - b.y; + + return Math.hypot(dx, dy); + } +} + +const p1 = new Point(5, 5); +const p2 = new Point(10, 10); + +console.log(Point.distance(p1, p2)); // 7.0710678118654755</pre> + +<h3 id="Boxing_com_métodos_estáticos_e_de_protótipo">Boxing com métodos estáticos e de protótipo </h3> + +<p>Quando um método estático é chamado sem um objeto correspondente ao "this", o valor do "this" é então <code>undefined</code> dentro do método chamado. O comportamento será o mesmo, mesmo que a diretiva <code>"use strict"</code> não esteja presente, isto porque o código contido no limite sintático do corpo da <code>class</code> é sempre executado em modo estrito.</p> + +<pre class="brush: js">class Animal { + speak() { + return this; + } + static eat() { + return this; + } +} + +let obj = new Animal(); +obj.speak(); // Animal {} +let speak = obj.speak; +speak(); // undefined + +Animal.eat() // class Animal +let eat = Animal.eat; +eat(); // undefined</pre> + +<p> </p> + +<p>Se o texto acima for escrito usando a sintaxe tradicional baseada em função, o autooboxing ocorrerá nas chamadas de método no modo não estrito com base no valor inicial do <em>this</em>. Se o valor inicial for <code>undefined</code>, isso será definido para o objeto global.</p> + +<p>Autoboxing não acontecerá no modo estrito, o valor do <em>this </em>permanece como passado ao método.</p> + +<p> </p> + +<pre><code>function Animal() { } + +Animal.prototype.speak = function() { + return this; +} + +Animal.eat = function() { + return this; +} + +let obj = new Animal(); +let speak = obj.speak; +speak(); // global object + +let eat = Animal.eat; +eat(); // global object</code></pre> + +<h3 id="Propriedades_de_instância">Propriedades de instância</h3> + +<p>Propriedades de instância devem ser definidas dentro de métodos da classe:</p> + +<pre><code>class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</code></pre> + +<p>Propriedades estáticas da classe e propriedades de dados do protótipo devem ser definidas fora da declaração do ClassBody:</p> + +<pre><code>Rectangle.staticWidth = 20; +Rectangle.prototype.prototypeWidth = 25;</code></pre> + +<h3 id="Declaração_de_campos_(Field)">Declaração de campos (<em>Field</em>)</h3> + +<div class="blockIndicator warning"> +<p>Declarações de campo públicos e privados são uma <a href="https://github.com/tc39/proposal-class-fields">funcionalidade experimental (stage 3)</a> proposta no <a href="https://tc39.github.io/beta/">TC39</a>, o comité de padrões JavaScript. O suporte nos navegadores é limitado, mas a funcionalidade pode ser usada por meio de uma etapa de <em>build</em> com sistemas como o <a href="https://babeljs.io/">Babel</a>.</p> +</div> + +<h4 id="Declaração_de_campos_(field_)_públicos">Declaração de campos (<em>field </em>) públicos</h4> + +<p>Com a sintaxe de declaração de campo JavaScript, o exemplo acima pode ser escrito como:</p> + +<pre><code>class Rectangle { + height = 0; + width; + constructor(height, width) { + this.height = height; + this.width = width; + } +}</code></pre> + +<p> </p> + +<p>Ao declarar campos antecipadamente, as definições de classe se tornam mais autodocumentadas e os campos estão sempre presentes.</p> + +<p>Como visto acima, os campos podem ser declarados com ou sem um valor padrão.</p> + +<p> </p> + +<h4 id="Declaração_de_campos_(field)_privados">Declaração de campos (<em>field</em>) privados </h4> + +<p>Usando campos privados, a definição pode ser refinada como abaixo.</p> + +<pre><code>class Rectangle { + #height = 0; + #width; + constructor(height, width) { + this.#height = height; + this.#width = width; + } +}</code></pre> + +<p> </p> + +<p>É um erro referenciar campos privados de fora da classe. eles só podem ser lidos ou escritos dentro do corpo da classe. Ao definir coisas que não são visíveis fora da classe, você garante que os utilizadores das suas classes não dependeram de estruturas internas, que podem mudar a versão para a versão.</p> + +<div class="blockIndicator note"> +<p>Campos privados só podem ser declarados antecipadamente numa declaração de campo.</p> +</div> + +<p>Os campos privados não podem ser criados posteriormente através da sua afetação, como se pode fazer com as propriedades normais.</p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<h2 id="Derivação_de_classes_com_extends">Derivação de classes com <code>extends</code></h2> + +<p>A palavra reservada <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> é utilizada na <em>declaração de classes </em>ou na <em>expressão de classes</em> para criar uma classe filha ou derivada de outra .</p> + +<pre class="brush: js">class Animal { + constructor(name) { + this.name = name; + } + + speak() { + console.log(this.name + ' makes a noise.'); + } +} + +class Dog extends Animal { + speak() { + console.log(this.name + ' barks.'); + } +} + +var d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. +</pre> + +<p>Se houver um construtor presente numa classe derivada, este precisa de chamar super() antes de utilizar o "this".</p> + +<p>A tradicionais "classes" function-based podem também ser extendidas:</p> + +<pre class="brush: js">function Animal (name) { + this.name = name; +} + +Animal.prototype.speak = function () { + console.log(this.name + ' makes a noise.'); +} + +class Dog extends Animal { + speak() { + console.log(this.name + ' barks.'); + } +} + +var d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. +</pre> + +<p>É de notar que uma classe não pode estender um objeto regular (non-constructible). Alternativamente, para se criar herança a partir de um objeto regular, deve ser usado {{jsxref("Object.setPrototypeOf()")}}:</p> + +<pre class="brush: js">var Animal = { + speak() { + console.log(this.name + ' makes a noise.'); + } +}; + +class Dog { + constructor(name) { + this.name = name; + } +} + +// If you do not do this you will get a TypeError when you invoke speak +Object.setPrototypeOf(Dog.prototype, Animal); + +var d = new Dog('Mitzie'); +d.speak(); // Mitzie makes a noise. +</pre> + +<h2 id="Espécies">Espécies</h2> + +<p>Se quiser devolver um objeto do tipo {{jsxref("Array")}} na sua classe derivada <code>MyArray</code>. O padrão espécies permite-lhe redefinir o construtor por omissão.</p> + +<p>Por exemplo, na utilização de um método como o {{jsxref("Array.map", "map()")}}, o qual devolve o construtor por omissão, querer-se-á que estes métodos devolvam um objeto pai do tipo <code>Array</code>, em vez de um objeto <code>MyArray</code>. O símbolo {{jsxref("Symbol.species")}} permite fazer isto:</p> + +<pre class="brush: js">class MyArray extends Array { + // Overwrite species to the parent Array constructor + static get [Symbol.species]() { return Array; } +} + +var a = new MyArray(1,2,3); +var mapped = a.map(x => x * x); + +console.log(mapped instanceof MyArray); // false +console.log(mapped instanceof Array); // true +</pre> + +<h2 id="Chamadas_à_super_classe_com_super">Chamadas à super classe com <code>super</code></h2> + +<p>A palavra reservada <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code> é utilizada para chamar funções no objeto pai do objeto.</p> + +<pre class="brush: js">class Cat { + constructor(name) { + this.name = name; + } + + speak() { + console.log(this.name + ' makes a noise.'); + } +} + +class Lion extends Cat { + speak() { + super.speak(); + console.log(this.name + ' roars.'); + } +} + +var l = new Lion('Fuzzy'); +l.speak(); +// Fuzzy makes a noise. +// Fuzzy roars. + +</pre> + +<h2 id="Mix-ins">Mix-ins</h2> + +<p>A subclasses abstratas ou <em>mix-ins</em> são templates para classes. Uma classe ECMAScript apenas pode ter uma única superclasse, Portanto, múltiplas heranças de classes de ferramentas, por exemplo, não são possíveis. A funcionalidade deve ser fornecida pela superclasse.</p> + +<p>Uma função com uma superclasse como entrada e uma subclasse estendendo aquela superclasse como saída pode ser usada para implementar mix-ins no ECMAScript.:</p> + +<pre class="brush: js">var calculatorMixin = Base => class extends Base { + calc() { } +}; + +var randomizerMixin = Base => class extends Base { + randomize() { } +}; +</pre> + +<p>Uma classe que usa esses mix-ins pode ser escrita assim:</p> + +<pre class="brush: js">class Foo { } +class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Definição inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2016')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2017')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_no_Browser">Compatibilidade no Browser </h2> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se você quiser contribuir com os dados, consulte: <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pull request.</div> + +<p>{{Compat("javascript.classes")}}</p> + +<h2 id="Executar_no_Scratchpad">Executar no Scratchpad</h2> + +<p>Uma classe não pode ser redefinida. Se estiver a escrever código no Scratchpad (Firefox menu Tools > Web Developer > Scratchpad) e se 'executar' a definição de uma classe com o mesmo nome duas vezes, irá receber um obscuro SyntaxError: redeclaration of let <class-name>.</p> + +<p>Para voltar a executar uma definição, utilise o menu Scratchpad's Execute > Reload and Run.<br> + Vote, por favor, no bug <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1428672">#1428672</a>.</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/classes/static/index.html b/files/pt-pt/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..9cb5c48367 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/classes/static/index.html @@ -0,0 +1,131 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +translation_of: Web/JavaScript/Reference/Classes/static +--- +<div>{{jsSidebar("Classes")}}</div> + +<p>A palavra-chave <code><strong>static</strong></code> define um método estático para uma classe.</p> + +<div>{{EmbedInteractiveExample("pages/js/classes-static.html")}}</div> + + + +<h2 id="Síntaxe">Síntaxe</h2> + +<pre class="syntaxbox">static <em>nomeDoMetodo</em>() { ... }</pre> + +<h2 id="Descrição">Descrição</h2> + +<p>Métodos estáticos são chamados diretamente na classe mas não em instâncias da mesma. Estes são regularmente utilizados para criar funções utilitárias.</p> + +<h2 id="Como_chamar_métodos_estáticos">Como chamar métodos estáticos</h2> + +<h3 id="Noutro_método_estático">Noutro método estático</h3> + +<p>Para chamar um método estático dentro de outro que pertença à mesma classe, pode-se usar a palavra-chave <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>.</p> + +<pre class="brush: js">class StaticMethodCall { + static staticMethod() { + return 'Metodo estatico foi invocado'; + } + static anotherStaticMethod() { + return this.staticMethod() + ' dentro de outro'; + } +} +StaticMethodCall.staticMethod(); +// 'Metodo estatico foi invocado' + +StaticMethodCall.anotherStaticMethod(); +// 'Metodo estatico foi invocado dentro de outro'</pre> + +<h3 id="No_construtor_de_classe_e_noutros_métodos">No construtor de classe e noutros métodos</h3> + +<p>Métodos estáticos não são acessíveis através da palavra-chave <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> quando dentro de métodos não-estáticos. É preciso chamá-los ou através do nome da própria classe: <code>CLASSNAME.STATIC_METHOD_NAME()</code> ou como propriedade do construtor da classe: <code>this.constructor.STATIC_METHOD_NAME()</code>.</p> + +<pre class="brush: js">class StaticMethodCall { + constructor() { + console.log(StaticMethodCall.staticMethod()); + // 'metodo estatico foi invocado.' + + console.log(this.constructor.staticMethod()); + // 'metodo estatico foi invocado.' + } + + static staticMethod() { + return 'metodo estatico foi invocado.'; + } +}</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Os seguintes exemplos demonstram:</p> + +<ol> + <li>Como implementar um método estático numa classe.</li> + <li>Que se podem criar sub-classes a partir de uma classe com um membro estático (e usá-los).</li> + <li>Como se pode chamar um método estático (com contra-exemplos).</li> +</ol> + +<pre class="brush: js">class Triple { + static triple(n) { + if (n === undefined) { + n = 1; + } + return n * 3; + } +} + +class BiggerTriple extends Triple { + static triple(n) { + return super.triple(n) * super.triple(n); + } +} + +console.log(Triple.triple()); // 3 +console.log(Triple.triple(6)); // 18 + +var tp = new Triple(); + +console.log(BiggerTriple.triple(3)); +// 81 (não foi afetado pela instanciação do pai) + +console.log(tp.triple()); +// 'tp.triple is not a function'. (não é função) +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Definições de Classe')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Definição inicial.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Definições de Classe')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_browsers">Compatibilidade de browsers</h2> + + + +<p>{{Compat("javascript.classes.static")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">expressão <code>class</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">declaração <code>class</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/errors/declaração_função_sem_nome/index.html b/files/pt-pt/web/javascript/reference/errors/declaração_função_sem_nome/index.html new file mode 100644 index 0000000000..a747257379 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/declaração_função_sem_nome/index.html @@ -0,0 +1,113 @@ +--- +title: 'Erro de sintaxe: declaração de função precisa de um nome' +slug: Web/JavaScript/Reference/Errors/declaração_função_sem_nome +translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Mensagem">Mensagem</h2> + +<pre class="syntaxbox">Syntax Error: Expected identifier (Edge) +SyntaxError: function statement requires a name [Firefox] +SyntaxError: Unexpected token ( [Chrome] +</pre> + +<h2 id="Tipo_de_erro">Tipo de erro</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="O_que_correu_mal">O que correu mal?</h2> + +<p>Existe uma <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">declaração de função</a> no código que precisa de um nome. Você deve verficiar como as funções são definidas e se é necessário indicar um nome para a função</p> + +<p><span class="tlid-translation translation"><span title="">Existe uma </span></span><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">declaração de função</a><span class="tlid-translation translation"><span title=""> no código que requer um nome.</span> <span title="">Você precisará verificar como as funções são definidas e se você precisa fornecer um nome para a função, ou se a função em questão precisa ser uma expressão de função, um {{Glossary ("IIFE")}}, ou se o</span> <span title="">código da função esta colocado corretamente neste contexto.</span></span></p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Declarações_vs_Expressões">Declarações vs Expressões</h3> + +<p>Uma <em><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">declaração de função</a></em> precisa de um nome, o código seguinte não funciona:</p> + +<pre class="brush: js example-bad">function () { + return 'Hello world'; +} +// SyntaxError: function statement requires a name +</pre> + +<p>É possível usar uma <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">expressão de função</a> (atribuição) como alternativa:</p> + +<pre class="brush: js example-good">var greet = function() { + return 'Hello world'; +};</pre> + +<p><span class="tlid-translation translation"><span title="">Ou, a sua função é talvez destinada a ser uma IIFE (Expressão de Função Invocada Imediatamente), que é uma função que é executada assim que é definida.</span> Serão precisos<span title=""> mais alguns parêntises neste caso:</span></span></p> + +<pre class="brush: js example-good">(function () { + +})();</pre> + +<h3 id="Funções_com_nome">Funções com nome</h3> + +<p>Se você está a usar uma função com <a href="/en-US/docs/Web/JavaScript/Reference/Statements/label">identificador</a>, <span class="tlid-translation translation"><span title="">ainda precisará fornecer um nome de função após a palavra-chave da função.</span> O código seguinte<span title=""> não funciona:</span></span></p> + +<pre class="brush: js example-bad">function Greeter() { + german: function () { + return "Moin"; + } +} +// SyntaxError: function statement requires a name +</pre> + +<p>O código seguinte irá funcionar por exemplo:</p> + +<pre class="brush: js example-good">function Greeter() { + german: function g() { + return "Moin"; + } +}</pre> + +<h3 id="Métodos_de_objectos">Métodos de objectos</h3> + +<p><span class="tlid-translation translation"><span title="">Se você pretendia criar um método de um objeto, você precisará criar um objeto.</span> <span title="">A sintaxe a seguir sem um nome após a palavra-chave </span></span><code>function</code><span class="tlid-translation translation"><span title=""> é válida.</span></span></p> + +<pre class="brush: js example-good">var greeter = { + german: function () { + return "Moin"; + } +};</pre> + +<h3 id="Sintaxe_de_Callback">Sintaxe de Callback</h3> + +<p>Além disso, verifique a sintaxe ao usar callbacks. Parêntisis e virgurlas podem facilmente se tornar complicados.</p> + +<pre class="brush: js example-bad">promise.then( + function() { + console.log("success"); + }); + function() { + console.log("error"); +} +// SyntaxError: function statement requires a name +</pre> + +<p>:</p> + +<pre class="brush: json example-good">promise.then( + function() { + console.log("success"); + }, + function() { + console.log("error"); + } +); +</pre> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions in the JavaScript Guide</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a></li> + <li><a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression">IIFE</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/label">label</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/errors/index.html b/files/pt-pt/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +<p>{{jsSidebar("Errors")}}</p> + +<p>Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a <code>name</code> and a <code>message</code>.</p> + +<p>Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.</p> + +<h2 id="List_of_errors">List of errors</h2> + +<p>In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!</p> + +<p>{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a>: Beginner's introductory tutorial on fixing JavaScript errors.</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/errors/not_a_function/index.html b/files/pt-pt/web/javascript/reference/errors/not_a_function/index.html new file mode 100644 index 0000000000..e17857e074 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/not_a_function/index.html @@ -0,0 +1,172 @@ +--- +title: 'TypeError: "x" is not a function' +slug: Web/JavaScript/Reference/Errors/Not_a_function +tags: + - Erro + - Erros + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Not_a_function +--- +<div>{{jsSidebar("Errors")}}</div> + +<p>A exeção de JavaScript "is not a function" ocorre quando há uma tentativa de chamar um valor a partir de uma função, mas o valor não é uma função.</p> + +<h2 id="Mensagem">Mensagem</h2> + +<pre class="syntaxbox notranslate">TypeError: Object doesn't support property or method {x} (Edge) +TypeError: "x" is not a function +</pre> + +<h2 id="Tipo_de_erro">Tipo de erro</h2> + +<p>{{jsxref("TypeError")}}</p> + +<h2 id="O_que_deu_errado">O que deu errado?</h2> + +<p>Tentou chamar um valor a partir de uma função, mas o valor não é uma função. Isto acontece quando algum código espera que se forneça uma função, mas isso não acontece.</p> + +<p>Talvez haja um erro no nome da função? Pode ser que o objeto a que está a chamar o método não tenha esta função? Por exemplo, um <code>Object</code> não tem função de <code>map</code>, mas o <code>Array</code> tem.</p> + +<p>Há muitas funções que necessitam de uma função como parâmetro (<em>callback</em>). Terá de fornecer uma função para que estes métodos funcionem corretamente:</p> + +<ul> + <li>Quando se trabalha com objetos {{jsxref("Array")}} ou {{jsxref("TypedArray")}}: + <ul> + <li>{{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}}, {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Array.prototype.map()")}}, {{jsxref("Array.prototype.filter()")}}, {{jsxref("Array.prototype.reduce()")}}, {{jsxref("Array.prototype.reduceRight()")}}, {{jsxref("Array.prototype.find()")}}</li> + </ul> + </li> + <li>Quando se trabalha com objetos {{jsxref("Map")}} e {{jsxref("Set")}}: + <ul> + <li>{{jsxref("Map.prototype.forEach()")}} e {{jsxref("Set.prototype.forEach()")}}</li> + </ul> + </li> +</ul> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Um_erro_no_nome_da_função">Um erro no nome da função</h3> + +<p>Neste caso existe um erro no nome função:</p> + +<pre class="brush: js example-bad notranslate">let x = document.getElementByID('foo'); +// TypeError: document.getElementByID is not a function +</pre> + +<p>O nome correto da função é <code>getElementByI<strong>d</strong></code>:</p> + +<pre class="brush: js example-good notranslate">let x = document.getElementById('foo'); +</pre> + +<h3 id="Função_é_chamada_no_objeto_errado">Função é chamada no objeto errado</h3> + +<p>Para certos métodos, é necessário fornecer uma função (<em>callback</em>) e funcionará apenas em objetos específicos. Neste exemplo, é utilizado o {{jsxref("Array.prototype.map()")}}, que funcionará apenas com objetos {{jsxref("Array")}}.</p> + +<pre class="brush: js example-bad notranslate">let obj = {a: 13, b: 37, c: 42}; + +obj.map(function(num) { + return num * 2; +}); + +// TypeError: obj.map is not a function</pre> + +<p>Use antes uma matriz:</p> + +<pre class="brush: js example-good notranslate">let numbers = [1, 4, 9]; + +numbers.map(function(num) { + return num * 2; +}); + +// Array [2, 8, 18] +</pre> + +<h3 id="Function_shares_a_name_with_a_pre-existing_property">Function shares a name with a pre-existing property</h3> + +<p>Por vezes, ao criar uma classe, pode ter uma propriedade e uma função com o mesmo nome. Ao chamar a função, o compilador pensa que a função deixa de existir.</p> + +<pre class="brush: js example-bad notranslate">var Dog = function () { + this.age = 11; + this.color = "black"; + this.name = "Ralph"; + return this; +} + +Dog.prototype.name = function(name) { + this.name = name; + return this; +} + + +var myNewDog = new Dog(); +myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function +</pre> + +<p>Use um nome diferente para a propriedade:</p> + +<pre class="brush: js example-good notranslate">var Dog = function () { + this.age = 11; + this.color = "black"; + this.dogName = "Ralph"; //Using this.dogName instead of .name + return this; +} + +Dog.prototype.name = function(name) { + this.dogName = name; + return this; +} + + +var myNewDog = new Dog(); +myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' } +</pre> + +<h3 id="Usar_parênteses_para_multiplicação">Usar parênteses para multiplicação</h3> + +<p>Em matemática, pode escrever 2 × (3 + 5) como 2*(3 + 5) ou somente 2(3 + 5).</p> + +<p>Usar a última forma dá um erro:</p> + +<pre class="js example-bad notranslate">const sixteen = 2(3 + 5); +alert('2 x (3 + 5) is ' + String(sixteen)); +//Uncaught TypeError: 2 is not a function</pre> + +<p>Pode corrigir o erro com a operadora <code>*</code>:</p> + +<pre class="js example-good notranslate">const sixteen = 2 * (3 + 5); +alert('2 x (3 + 5) is ' + String(sixteen)); +//2 x (3 + 5) is 16 +</pre> + +<h3 id="Importar_o_modulo_exportado_corretamente">Importar o modulo exportado corretamente</h3> + +<p>Certifique-se que está a importar o módulo corretamente.</p> + +<p>Um exemplo de uma biblioteca <em>helper</em> (<code>helpers.js</code>)</p> + +<pre class="brush: js notranslate">let helpers = function () { }; + +helpers.groupBy = function (objectArray, property) { + return objectArray.reduce(function (acc, obj) { + var key = obj[property]; + if (!acc[key]) { + acc[key] = []; + } + acc[key].push(obj); + return acc; + }, +{}); +} + +export default helpers; +</pre> + +<p>A utilização correta de importação (para <code>App.js</code>) é:</p> + +<pre class="notranslate">import helpers from './helpers'</pre> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Funcoes">Funções</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html b/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html new file mode 100644 index 0000000000..f3d1de92c8 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html @@ -0,0 +1,77 @@ +--- +title: 'Aviso: código inacessível depois de declaração de retorno' +slug: Web/JavaScript/Reference/Errors/Stmt_after_return +tags: + - Aviso + - JavaScript +translation_of: Web/JavaScript/Reference/Errors/Stmt_after_return +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Mensagem">Mensagem</h2> + +<pre class="syntaxbox">Warning: unreachable code after return statement (Firefox) +</pre> + +<h2 id="Tipo_de_ErroEdit">Tipo de Erro<a class="button section-edit only-icon" href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Errors/Stmt_after_return$edit#Tipo_de_Erro" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<p>Aviso</p> + +<h2 id="O_que_correu_malEdit">O que correu mal?<a class="button section-edit only-icon" href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Errors/Stmt_after_return$edit#O_que_deu_errado" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<p><em>Unreachable code after return statement</em> pode ocorrer nas seguintes situações:</p> + +<ul> + <li>Quando é utilizada uma expressão depois de uma declaração <a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/return" title="A declaração return finaliza a execução de uma função e especifica os valores que devem ser retonados para onde a função foi chamada."><code>return</code></a> , ou</li> + <li>quando é utilizada uma declaração <em>return</em> sem ponto e vírgula, mas incluindo uma declaração diretamente depois.</li> +</ul> + +<p>Quando existe uma expressão depois de uma declaração <code>return</code> válida, é dado um aviso para indicar que o código depois da declaração <code>return</code> é inacessível, o que significa que o mesmo nunca pode ser executado.</p> + +<p>Porquê é que eu deveria ter ponto e vírgula depois de declarações <code>return</code>? No caso de declarações <code>return</code> sem ponto e vírgula, não é claro se o programador pretendia devolver a declaração na linha seguinte, ou para parar a execução e o retorno. O aviso indica que existe ambiguidade no modo como a declaração <code>return</code> foi escrita.</p> + +<p>Os avisos não serão apresentados para declarações <em>return</em> sem ponto-e-vírgula nas seguintes situações:</p> + +<ul> + <li>{{jsxref("Statements/throw", "throw")}}</li> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/var", "var")}}</li> + <li>{{jsxref("Statements/function", "function")}}</li> +</ul> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Casos_inválidos">Casos inválidos</h3> + +<pre class="brush: js example-bad">function f() { + var x = 3; + x += 4; + return x; // retorna a função de imediato + x -= 3; // logo, esta linha não será executada; é inacessivel +} + +function f() { + return // é tratado como um `return;` + 3 + 4; // logo, a função é retornada, porém esta linha não será alcançada +} +</pre> + +<h3 id="Casos_válidos">Casos válidos</h3> + +<pre class="brush: js example-good">function f() { + var x = 3; + x += 4; + x -= 3; + return x; // OK: return depois de todas as declarações +} + +function f() { + return 3 + 4 // OK: um return sem ponto e vírgula com uma expressão na mesma linha +} +</pre> + +<h2 id="Consulte_tambémEdit">Consulte também<a class="button section-edit only-icon" href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Errors/Stmt_after_return$edit#Ver_também" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<ul> + <li>{{jsxref("Statements/return", "Automatic Semicolon Insertion", "#Automatic_Semicolon_Insertion", 1)}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html b/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html new file mode 100644 index 0000000000..55103f82a7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html @@ -0,0 +1,50 @@ +--- +title: 'SyntaxError: Unexpected token' +slug: Web/JavaScript/Reference/Errors/Unexpected_token +tags: + - Erro de Sintaxe + - Erros + - JavaScript +translation_of: Web/JavaScript/Reference/Errors/Unexpected_token +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Mensagem">Mensagem</h2> + +<pre class="syntaxbox">SyntaxError: expected expression, got "x" +SyntaxError: expected property name, got "x" +SyntaxError: expected target, got "x" +SyntaxError: expected rest argument name, got "x" +SyntaxError: expected closing parenthesis, got "x" +SyntaxError: expected '=>' after argument list, got "x" +</pre> + +<h2 id="Tipo_de_erro">Tipo de erro</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="O_que_aconteceu_de_errado">O que aconteceu de errado?</h2> + +<p>É esperado um contrutor de linguagem específico, mas foi entregue outra coisa qualquer. Isto poderá ser simplesmente um erro de escrita.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Expressão_esperada">Expressão esperada</h3> + +<p>Por exemplo, quando são chamadas funções, as vírgulas imediatamente antes de fechar a função não são permitidas. JavaScript vai esperar outro argumento, que pode na verdade ser qualquer expressão.</p> + +<pre class="brush: js example-bad">Math.max(2, 42,); +// SyntaxError: expected expression, got ')' +</pre> + +<p>Para corrigir o problema, retirava-se a virgula ou adicionavam-se mais argumentos:</p> + +<pre class="brush: js example-good">Math.max(2, 42); +Math.max(2, 42, 13 + 37); +</pre> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Math.max()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/bloco/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/bloco/index.html new file mode 100644 index 0000000000..a3104dbeae --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/bloco/index.html @@ -0,0 +1,116 @@ +--- +title: Bloco (block) +slug: Web/JavaScript/Reference/Extratos_e_declarações/bloco +tags: + - Declaração + - Funcionalidade de Linguagem + - JavaScript + - Referencia +translation_of: Web/JavaScript/Reference/Statements/block +--- +<div>Bloco {{jsSidebar("Statements")}}</div> + +<p>Uma <strong>declaralção bloco </strong>(ou <strong>declaração composto</strong> em outras linguagens) é utilizada para agrupar zero ou mais declarações. O bloco é delimitado por um par de chavetas (“chavetas { }”) e opcionalmente poderá ser {{jsxref("Statements/label", "labelled", "", 1)}}:</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-block.html", "taller")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<h3 id="Declaração_de_Bloco">Declaração de Bloco</h3> + +<pre class="syntaxbox">{ + <em>StatementList</em> +} +</pre> + +<h3 id="Declaração_de_Bloco_Etiquetado">Declaração de Bloco Etiquetado</h3> + +<pre class="syntaxbox"><em>LabelIdentifier</em>: { + <em>StatementList</em> +} +</pre> + +<dl> + <dt><code>StatementList</code></dt> + <dd>Statements grouped within the block statement.</dd> + <dt><code>LabelIdentifier</code></dt> + <dd>An optional {{jsxref("Statements/label", "label", "", 1)}} for visual identification or as a target for {{jsxref("Statements/break", "break")}}.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>The block statement is often called <strong>compound statement</strong> in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an <a href="/en-US/docs/Web/JavaScript/Reference/Statements/Empty">empty statement</a>, where you provide no statement, although one is required.</p> + +<p>Blocks are commonly used in association with {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}} statements.</p> + +<h3 id="Block_Scoping_Rules">Block Scoping Rules</h3> + +<h4 id="With_var_or_function_declaration_in_non-strict_mode">With <code>var</code> or function declaration in non-strict mode</h4> + +<p>Variables declared with <code>var</code> or created by <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function declarations</a> in non-strict mode <strong>do not</strong> have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. For example:</p> + +<pre class="brush: js example-bad">var x = 1; +{ + var x = 2; +} +console.log(x); // logs 2 +</pre> + +<p>This logs 2 because the <code>var x</code> statement within the block is in the same scope as the <code>var x</code> statement before the block.</p> + +<p>In non-strict code, function declarations inside blocks behave strangely. Do not use them.</p> + +<h4 id="With_let_const_or_function_declaration_in_strict_mode">With <code>let</code>, <code>const</code> or function declaration in strict mode</h4> + +<p>By contrast, identifiers declared with {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const", "const")}} <strong>do have </strong>block scope:</p> + +<pre class="brush: js">let x = 1; +{ + let x = 2; +} +console.log(x); // logs 1</pre> + +<p>The <code>x = 2</code> is limited in scope to the block in which it was defined.</p> + +<p>The same is true of <code>const</code>:</p> + +<pre class="brush: js">const c = 1; +{ + const c = 2; +} +console.log(c); // logs 1 and does not throw SyntaxError...</pre> + +<p>Note that the block-scoped <code>const c = 2</code> <em>does not</em> throw a <code>SyntaxError: Identifier 'c' has already been declared</code> because it can be declared uniquely within the block.</p> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-block', 'Block statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements.block")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/if...else", "if...else")}}</li> + <li>{{jsxref("Statements/let", "let")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/for/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/for/index.html new file mode 100644 index 0000000000..ac7586e98b --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/for/index.html @@ -0,0 +1,145 @@ +--- +title: for +slug: Web/JavaScript/Reference/Extratos_e_declarações/for +tags: + - Declaração + - Funcionalidade de Linguagem + - JavaScript + - Loop + - Referencia + - Repetição + - for +translation_of: Web/JavaScript/Reference/Statements/for +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>A <strong>declaração "for"</strong> cria uma repetição (<em>loop</em>) que consiste de três expressões opcionais, entre parênteses e separados por ponto e vírgula, seguido de uma declaração (normalmente <a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/bloco">bdeclaraçãod e bloco (<em>block</em>)</a>) para ser executada na repetição.</p> + +<div>{{EmbedInteractiveExample("pages/js/statement-for.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">for ([<em>initialization</em>]; [<em>condition</em>]; [<em>final-expression</em>]) + <em>statement</em></pre> + +<dl> + <dt><code>initialization</code></dt> + <dd>An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with <code>var</code> or <code>let</code> keywords. Variables declared with <code>var</code> are not local to the loop, i.e. they are in the same scope the <code>for</code> loop is in. Variables declared with let are local to the statement.</dd> + <dd>The result of this expression is discarded.</dd> + <dt><code>condition</code></dt> + <dd>An expression to be evaluated before each loop iteration. If this expression evaluates to true, <code>statement</code> is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the <code>for</code> construct.</dd> + <dt><code>final-expression</code></dt> + <dd>An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of <code>condition</code>. Generally used to update or increment the counter variable.</dd> + <dt><code>statement</code></dt> + <dd>A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement (<code>{ ... }</code>) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (<code>;</code>).</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Using_for">Using <code>for</code></h3> + +<p>The following <code>for</code> statement starts by declaring the variable <code>i</code> and initializing it to <code>0</code>. It checks that <code>i</code> is less than nine, performs the two succeeding statements, and increments <code>i</code> by 1 after each pass through the loop.</p> + +<pre class="brush: js">for (let i = 0; i < 9; i++) { + console.log(i); + // more statements +} +</pre> + +<h3 id="Optional_for_expressions">Optional <code>for</code> expressions</h3> + +<p>All three expressions in the head of the <code>for</code> loop are optional.</p> + +<p>For example, in the <em>initialization</em> block it is not required to initialize variables:</p> + +<pre class="brush: js">var i = 0; +for (; i < 9; i++) { + console.log(i); + // more statements +} +</pre> + +<p>Like the <em>initialization</em> block, the <em>condition</em> block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.</p> + +<pre class="brush: js">for (let i = 0;; i++) { + console.log(i); + if (i > 3) break; + // more statements +}</pre> + +<p>You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.</p> + +<pre class="brush: js">var i = 0; + +for (;;) { + if (i > 3) break; + console.log(i); + i++; +} +</pre> + +<h3 id="Using_for_without_a_statement">Using <code>for</code> without a statement</h3> + +<p>The following <code>for</code> cycle calculates the offset position of a node in the <em>final-expression</em> section, and therefore it does not require the use of a <code>statement</code> section, a semicolon is used instead.</p> + +<pre class="brush: js">function showOffsetPos(sId) { + + var nLeft = 0, nTop = 0; + + for ( + + var oItNode = document.getElementById(sId); /* initialization */ + + oItNode; /* condition */ + + nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */ + + ); /* semicolon */ + + console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;'); + +} + +/* Example call: */ + +showOffsetPos('content'); + +// Output: +// "Offset position of "content" element: +// left: 0px; +// top: 153px;"</pre> + +<div class="note"><strong>Note:</strong> This is one of the few cases in JavaScript where <strong>the semicolon is mandatory</strong>. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements.for")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{jsxref("Statements/empty", "empty statement", "", 0)}}</li> + <li>{{jsxref("Statements/break", "break")}}</li> + <li>{{jsxref("Statements/continue", "continue")}}</li> + <li>{{jsxref("Statements/while", "while")}}</li> + <li>{{jsxref("Statements/do...while", "do...while")}}</li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Statements/for...of", "for...of")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/index.html new file mode 100644 index 0000000000..af841906a1 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/index.html @@ -0,0 +1,150 @@ +--- +title: Declarações e instruções +slug: Web/JavaScript/Reference/Extratos_e_declarações +tags: + - JavaScript + - Referencia + - declarações + - instruções +translation_of: Web/JavaScript/Reference/Statements +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.</p> + +<h2 id="Declarações_e_instruções_por_categoria">Declarações e instruções por categoria</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Controlo_de_Fluxo">Controlo de Fluxo</h3> + +<dl> + <dt>{{jsxref("Statements/block", "Block")}}</dt> + <dd>A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.</dd> + <dt>{{jsxref("Statements/break", "break")}}</dt> + <dd>Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.</dd> + <dt>{{jsxref("Statements/continue", "continue")}}</dt> + <dd>Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.</dd> + <dt>{{jsxref("Statements/Empty", "Empty")}}</dt> + <dd>An empty statement is used to provide no statement, although the JavaScript syntax would expect one.</dd> + <dt>{{jsxref("Statements/if...else", "if...else")}}</dt> + <dd>Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.</dd> + <dt>{{jsxref("Statements/switch", "switch")}}</dt> + <dd>Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.</dd> + <dt>{{jsxref("Statements/throw", "throw")}}</dt> + <dd>Throws a user-defined exception.</dd> + <dt>{{jsxref("Statements/try...catch", "try...catch")}}</dt> + <dd>Marks a block of statements to try, and specifies a response, should an exception be thrown.</dd> +</dl> + +<h3 id="Declarações">Declarações</h3> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Declares a variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/let", "let")}}</dt> + <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> + <dt>{{jsxref("Statements/const", "const")}}</dt> + <dd>Declares a read-only named constant.</dd> +</dl> + +<h3 id="Funções_e_classes">Funções e classes</h3> + +<dl> + <dt>{{jsxref("Statements/function", "function")}}</dt> + <dd>Declara as funções com parâmetros especificados.</dd> + <dt>{{jsxref("Statements/function*", "function*")}}</dt> + <dd>Generators functions enable writing <a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">iterators</a> more easily.</dd> + <dt>{{jsxref("Statements/async_function", "async function")}}</dt> + <dd>Declares an async function with the specified parameters.</dd> + <dt>{{jsxref("Statements/return", "return")}}</dt> + <dd>Specifies the value to be returned by a function.</dd> + <dt>{{jsxref("Statements/class", "class")}}</dt> + <dd>Declara uma Classe.</dd> +</dl> + +<h3 id="Iterações">Iterações</h3> + +<dl> + <dt>{{jsxref("Statements/do...while", "do...while")}}</dt> + <dd>Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.</dd> + <dt>{{jsxref("Statements/for", "for")}}</dt> + <dd>Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.</dd> + <dt>{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}</dt> + <dd>Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.</dd> + <dt>{{jsxref("Statements/for...in", "for...in")}}</dt> + <dd>Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.</dd> + <dt>{{jsxref("Statements/for...of", "for...of")}}</dt> + <dd>Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, <a href="/en-US/docs/JavaScript/Guide/Iterators_and_Generators">iterators and generators</a>), invoking a custom iteration hook with statements to be executed for the value of each distinct property.</dd> + <dt>{{jsxref("Statements/while", "while")}}</dt> + <dd>Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.</dd> +</dl> + +<h3 id="Outros">Outros</h3> + +<dl> + <dt>{{jsxref("Statements/debugger", "debugger")}}</dt> + <dd>Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.</dd> + <dt>{{jsxref("Statements/export", "export")}}</dt> + <dd>Used to export functions to make them available for imports in external modules, another scripts.</dd> + <dt>{{jsxref("Statements/import", "import")}}</dt> + <dd>Used to import functions exported from an external module, another script.</dd> + <dt><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta">import.meta</a></code></dt> + <dd>A meta-property exposing context-specific metadata to a JavaScript module.</dd> + <dt>{{jsxref("Statements/label", "label")}}</dt> + <dd>Provides a statement with an identifier that you can refer to using a <code>break</code> or <code>continue</code> statement.</dd> +</dl> + +<dl> + <dt>{{deprecated_inline}} {{jsxref("Statements/with", "with")}}</dt> + <dd>Extends the scope chain for a statement.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES3', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES3')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12', 'Statements')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: function*, let, for...of, yield, class</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements")}}</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores">Operadores</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/return/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/return/index.html new file mode 100644 index 0000000000..6cec134992 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/return/index.html @@ -0,0 +1,148 @@ +--- +title: return +slug: Web/JavaScript/Reference/Extratos_e_declarações/return +tags: + - Declaração + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/return +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>The <strong><code>return</code> statement</strong> ends function execution and specifies a value to be returned to the function caller.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">return [[expression]]; </pre> + +<dl> + <dt><code>expression</code></dt> + <dd>The expression whose value is to be returned. If omitted, <code>undefined</code> is returned instead.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>When a <code>return</code> statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, <code>x</code>, where <code>x</code> is a number.</p> + +<pre class="brush: js">function square(x) { + return x * x; +} +var demo = square(3); +// demo will equal 9 +</pre> + +<p>If the value is omitted, <code>undefined</code> is returned instead.</p> + +<p>The following return statements all break the function execution:</p> + +<pre class="brush: js">return; +return true; +return false; +return x; +return x + y / 3; +</pre> + +<h3 id="Inserção_Automática_de_Ponto_e_Vírgula">Inserção Automática de Ponto e Vírgula</h3> + +<p>The <code>return</code> statement is affected by <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a>. No line terminator is allowed between the <code>return</code> keyword and the expression.</p> + +<pre class="brush: js">return +a + b; +</pre> + +<p>is transformed by ASI into:</p> + +<pre>return; +a + b; +</pre> + +<p>The console will warn "unreachable code after return statement".</p> + +<div class="note">Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Interromper_uma_função">Interromper uma função</h3> + +<p>A function immediately stops at the point where <code>return</code> is called.</p> + +<pre class="brush: js">function counter() { + for (var count = 1; ; count++) { // infinite loop + console.log(count + 'A'); // until 5 + if (count === 5) { + return; + } + console.log(count + 'B'); // until 4 + } + console.log(count + 'C'); // never appears +} + +counter(); + +// Output: +// 1A +// 1B +// 2A +// 2B +// 3A +// 3B +// 4A +// 4B +// 5A +</pre> + +<h3 id="Devolver_uma_função">Devolver uma função</h3> + +<p>See also the article about <a href="/en-US/docs/Web/JavaScript/Closures">Closures</a>.</p> + +<pre class="brush: js">function magic(x) { + return function calc(x) { return x * 42; }; +} + +var answer = magic(); +answer(1337); // 56154 +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements.return")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope" title="En/Core_JavaScript_1.5_Reference/Functions">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Closures">Closures</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/extratos_e_declarações/throw/index.html b/files/pt-pt/web/javascript/reference/extratos_e_declarações/throw/index.html new file mode 100644 index 0000000000..9e7a8bf54e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/extratos_e_declarações/throw/index.html @@ -0,0 +1,271 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Extratos_e_declarações/throw +tags: + - Comando + - Declaração + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/throw +--- +<div>{{jsSidebar("Statements")}}</div> + +<p>A <strong>declaração <code>throw</code> </strong>lança uma exeção definida pelo utilizador. A execução da função atual irá parar (os comandos depois de <code>throw</code> não serão executados), <span id="result_box" lang="pt"><span>e o controle será passado para o primeiro bloco <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">catch</a></code> no conjunto de chamadas. Se não existir nenhum bloco <code>catch</code> entre as funções de <em>caller</em>, o programa irá terminar.</span></span></p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">expressão throw; </pre> + +<dl> + <dt><code>expressão</code></dt> + <dd>A expressão para <em>throw</em>.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Use the <code>throw</code> statement to throw an exception. When you throw an exception, <code>expression</code> specifies the value of the exception. Each of the following throws an exception:</p> + +<pre class="brush: js">throw 'Error2'; // generates an exception with a string value +throw 42; // generates an exception with the value 42 +throw true; // generates an exception with the value true</pre> + +<p>Also note that the <code>throw</code> statement is affected by <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a> as no line terminator between the <code>throw</code> keyword and the expression is allowed.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Throw_um_objeto">Throw um objeto</h3> + +<p>You can specify an object when you throw an exception. You can then reference the object's properties in the <code>catch</code> block. The following example creates an object of type <code>UserException</code> and uses it in a <code>throw</code> statement.</p> + +<pre class="brush: js">function UserException(message) { + this.message = message; + this.name = 'UserException'; +} +function getMonthName(mo) { + mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec) + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', + 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + if (months[mo] !== undefined) { + return months[mo]; + } else { + throw new UserException('InvalidMonthNo'); + } +} + +try { + // statements to try + var myMonth = 15; // 15 is out of bound to raise the exception + var monthName = getMonthName(myMonth); +} catch (e) { + monthName = 'unknown'; + console.log(e.message, e.name); // pass exception object to err handler +} +</pre> + +<h3 id="Outro_exemplo_de_throwing_um_objeto">Outro exemplo de <em>throwing</em> um objeto</h3> + +<p>The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type <code>ZipCodeFormatException</code>.</p> + +<pre class="brush: js">/* + * Creates a ZipCode object. + * + * Accepted formats for a zip code are: + * 12345 + * 12345-6789 + * 123456789 + * 12345 6789 + * + * If the argument passed to the ZipCode constructor does not + * conform to one of these patterns, an exception is thrown. + */ + +function ZipCode(zip) { + zip = new String(zip); + pattern = /[0-9]{5}([- ]?[0-9]{4})?/; + if (pattern.test(zip)) { + // zip code value will be the first match in the string + this.value = zip.match(pattern)[0]; + this.valueOf = function() { + return this.value + }; + this.toString = function() { + return String(this.value) + }; + } else { + throw new ZipCodeFormatException(zip); + } +} + +function ZipCodeFormatException(value) { + this.value = value; + this.message = 'does not conform to the expected format for a zip code'; + this.toString = function() { + return this.value + this.message; + }; +} + +/* + * This could be in a script that validates address data + * for US addresses. + */ + +const ZIPCODE_INVALID = -1; +const ZIPCODE_UNKNOWN_ERROR = -2; + +function verifyZipCode(z) { + try { + z = new ZipCode(z); + } catch (e) { + if (e instanceof ZipCodeFormatException) { + return ZIPCODE_INVALID; + } else { + return ZIPCODE_UNKNOWN_ERROR; + } + } + return z; +} + +a = verifyZipCode(95060); // returns 95060 +b = verifyZipCode(9560); // returns -1 +c = verifyZipCode('a'); // returns -1 +d = verifyZipCode('95060'); // returns 95060 +e = verifyZipCode('95060 1234'); // returns 95060 1234 +</pre> + +<h3 id="Rethrow_uma_exceção"><em>Rethrow</em> uma exceção</h3> + +<p>You can use <code>throw</code> to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.</p> + +<pre class="brush: js">try { + throw n; // throws an exception with a numeric value +} catch (e) { + if (e <= 50) { + // statements to handle exceptions 1-50 + } else { + // cannot handle this exception, so rethrow + throw e; + } +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition. Implemented in JavaScript 1.4</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.statements.throw")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/try...catch"><code>try...catch</code></a></li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html b/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html new file mode 100644 index 0000000000..9d0ae63c62 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html @@ -0,0 +1,289 @@ +--- +title: Funcionalidades obsoletas +slug: Web/JavaScript/Reference/Funcionalidades_obsoletas +tags: + - JavaScript + - Obsoleto +translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features +--- +<div>{{JsSidebar("More")}}</div> + +<p>Esta página lista as funcionalidades de JavaScript que estão obsoletas (ou seja, ainda disponíveis, mas planeadas para remoção) e obsoletas (isto é, não são mais utilizáveis).</p> + +<h2 id="Funcionalidades_obsoletas">Funcionalidades obsoletas</h2> + +<p>Estas funcionalidades obsoletas ainda podem ser utilziadas, mas devem ser utilizadas com cuidado, pois espera-se que estas sejam removidas inteiramente no futuro. Deverá trabalhar para remover a utilização das mesmas do seu código..</p> + +<h3 id="Propriedades_de_RegExp">Propriedades de RegExp</h3> + +<p>The following properties are deprecated. This does not affect their use in {{jsxref("String.replace", "replacement strings", "", 1)}}:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>Propriedades</th> + <th>Descrição</th> + </tr> + <tr> + <td>{{jsxref("RegExp.n", "$1-$9")}}</td> + <td> + <p>Parenthesized substring matches, if any.<br> + <strong>Warning:</strong> Using these properties can result in problems, since browser extensions can modify them. Avoid them!</p> + </td> + </tr> + <tr> + <td>{{jsxref("RegExp.input", "$_")}}</td> + <td>See <code>input</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.multiline", "$*")}}</td> + <td>See <code>multiline</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastMatch", "$&")}}</td> + <td>See <code>lastMatch</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastParen", "$+")}}</td> + <td>See <code>lastParen</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.leftContext", "$`")}}</td> + <td>See <code>leftContext</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.rightContext", "$'")}}</td> + <td>See <code>rightContext</code>.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.input", "input")}}</td> + <td>The string against which a regular expression is matched.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastMatch", "lastMatch")}}</td> + <td>The last matched characters.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastParen", "lastParen")}}</td> + <td>The last parenthesized substring match, if any.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.leftContext", "leftContext")}}</td> + <td>The substring preceding the most recent match.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.rightContext", "rightContext")}}</td> + <td>The substring following the most recent match.</td> + </tr> + </tbody> +</table> + +<p>The following are now properties of <code>RegExp</code> instances, no longer of the <code>RegExp</code> object:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>Propriedades</th> + <th>Descrição</th> + </tr> + <tr> + <td>{{jsxref("RegExp.global", "global")}}</td> + <td>Whether or not to test the regular expression against all possible matches in a string, or only against the first.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.ignoreCase", "ignoreCase")}}</td> + <td>Whether or not to ignore case while attempting a match in a string.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.lastIndex", "lastIndex")}}</td> + <td>The index at which to start the next match.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.multiline", "multiline")}}</td> + <td>Whether or not to search in strings across multiple lines.</td> + </tr> + <tr> + <td>{{jsxref("RegExp.source", "source")}}</td> + <td>The text of the pattern.</td> + </tr> + </tbody> +</table> + +<h3 id="Métodos_de_egExp">Métodos de egExp</h3> + +<ul> + <li>The {{jsxref("RegExp.compile", "compile()")}} method is deprecated.</li> + <li>The <code>valueOf</code> method is no longer specialized for <code>RegExp</code>. Use {{jsxref("Object.valueOf()")}}.</li> +</ul> + +<h3 id="Propriedades_de_Function">Propriedades de <em>Function</em></h3> + +<ul> + <li>The {{jsxref("Global_Objects/Function/caller", "caller")}} and {{jsxref("Global_Objects/Function/arguments", "arguments")}} properties are deprecated, because they leak the function caller. Instead of the arguments property, you should use the {{jsxref("Functions/arguments", "arguments")}} object inside function closures.</li> +</ul> + +<h3 id="Gerador_de_Legacy">Gerador de <em>Legacy</em></h3> + +<ul> + <li>{{jsxref("Statements/Legacy_generator_function", "Legacy generator function statement")}} and {{jsxref("Operators/Legacy_generator_function", "Legacy generator function expression")}} are deprecated. Use {{jsxref("Statements/function*", "function* statement")}} and {{jsxref("Operators/function*", "function* expression")}} instead.</li> + <li>{{jsxref("Operators/Array_comprehensions", "JS1.7/JS1.8 Array comprehension", "#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions")}} and {{jsxref("Operators/Generator_comprehensions", "JS1.7/JS1.8 Generator comprehension", "#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions")}} are deprecated.</li> +</ul> + +<h3 id="Iterator"><em>Iterator</em></h3> + +<ul> + <li>{{jsxref("Global_Objects/StopIteration", "StopIteration")}} is deprecated.</li> + <li>{{jsxref("Global_Objects/Iterator", "Iterator")}} is deprecated.</li> +</ul> + +<h3 id="Métodos_de_Object">Métodos de <em>Object</em></h3> + +<ul> + <li>{{jsxref("Object.watch", "watch")}} and {{jsxref("Object.unwatch", "unwatch")}} are deprecated. Use {{jsxref("Proxy")}} instead.</li> + <li><code>__iterator__</code> is deprecated.</li> + <li>{{jsxref("Object.noSuchMethod", "__noSuchMethod__")}} is deprecated. Use {{jsxref("Proxy")}} instead.</li> +</ul> + +<h3 id="Métodos_de_Date">Métodos de <em>Date</em></h3> + +<ul> + <li>{{jsxref("Global_Objects/Date/getYear", "getYear")}} and {{jsxref("Global_Objects/Date/setYear", "setYear")}} are affected by the Year-2000-Problem and have been subsumed by {{jsxref("Global_Objects/Date/getFullYear", "getFullYear")}} and {{jsxref("Global_Objects/Date/setFullYear", "setFullYear")}}.</li> + <li>You should use {{jsxref("Global_Objects/Date/toISOString", "toISOString")}} instead of the deprecated {{jsxref("Global_Objects/Date/toGMTString", "toGMTString")}} method in new code.</li> + <li>{{jsxref("Global_Objects/Date/toLocaleFormat", "toLocaleFormat")}} is deprecated.</li> +</ul> + +<h3 id="Functions"><em>Functions</em></h3> + +<ul> + <li>{{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}} are deprecated. Use regular {{jsxref("Operators/function", "functions")}} or {{jsxref("Functions/Arrow_functions", "arrow functions", "", 1)}} instead.</li> +</ul> + +<h3 id="Proxy"><em>Proxy</em></h3> + +<ul> + <li><a href="/en-US/docs/Archive/Web/Old_Proxy_API">Proxy.create</a> and <a href="/en-US/docs/Archive/Web/Old_Proxy_API">Proxy.createFunction</a> are deprecated. Use {{jsxref("Proxy")}} instead.</li> + <li>The following traps are obsolete: + <ul> + <li><code>hasOwn</code> ({{bug(980565)}}, Firefox 33).</li> + <li><code>getEnumerablePropertyKeys</code> ({{bug(783829)}}, Firefox 37)</li> + <li><code>getOwnPropertyNames</code> ({{bug(1007334)}}, Firefox 33)</li> + <li><code>keys</code> ({{bug(1007334)}}, Firefox 33)</li> + </ul> + </li> +</ul> + +<h3 id="Sequências_de_Escape">Sequências de <em>Escape</em></h3> + +<ul> + <li>Octal escape sequences (\ followed by one, two, or three octal digits) are deprecated in string and regular expression literals.</li> + <li>The {{jsxref("Global_Objects/escape", "escape")}} and {{jsxref("Global_Objects/unescape", "unescape")}} functions are deprecated. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}}, {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}}, {{jsxref("Global_Objects/decodeURI", "decodeURI")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} to encode and decode escape sequences for special characters.</li> +</ul> + +<h3 id="Métodos_de_String">Métodos de <em>String</em></h3> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/tag/HTML%20wrapper%20methods">HTML wrapper methods</a> like {{jsxref("String.prototype.fontsize")}} and {{jsxref("String.prototype.big")}}.</li> + <li>{{jsxref("String.prototype.quote")}} is removed from Firefox 37.</li> + <li>non standard <code>flags</code> parameter in {{jsxref("String.prototype.search")}}, {{jsxref("String.prototype.match")}}, and {{jsxref("String.prototype.replace")}} are deprecated.</li> +</ul> + +<h2 id="Funcionalidades_removidas">Funcionalidades removidas</h2> + +<p>Estas funcionalidades obsoletas foram totalmente removidas do JavaScript e não podem mais ser utilizadas a partir da versão indicada do JavaScript.</p> + +<h3 id="Object"><em>Object</em></h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Property</th> + <th>Description</th> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/count", "__count__")}}</td> + <td>Returns the number of enumerable properties directly on a user-defined object.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/Parent", "__parent__")}}</td> + <td>Points to an object's context.</td> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}</td> + <td>Evaluates a string of JavaScript code in the context of the specified object.</td> + </tr> + <tr> + <td>{{jsxref("Object.observe()")}}</td> + <td>Asynchronously observing the changes to an object.</td> + </tr> + <tr> + <td>{{jsxref("Object.unobserve()")}}</td> + <td>Remove observers.</td> + </tr> + <tr> + <td>{{jsxref("Object.getNotifier()")}}</td> + <td>Creates an object that allows to synthetically trigger a change.</td> + </tr> + </tbody> +</table> + +<h3 id="Function"><em>Function</em></h3> + +<table class="standard-table"> + <tbody> + <tr> + <th>Property</th> + <th>Description</th> + </tr> + <tr> + <td>{{jsxref("Global_Objects/Function/arity", "arity")}}</td> + <td>Number of formal arguments.</td> + </tr> + </tbody> +</table> + +<h3 id="Array"><em>Array</em></h3> + +<table class="standard-table"> + <tbody> + <tr> + <td>Property</td> + <td>Description</td> + </tr> + <tr> + <td>{{jsxref("Array.observe()")}}</td> + <td>Asynchronously observing changes to Arrays.</td> + </tr> + <tr> + <td>{{jsxref("Array.unobserve()")}}</td> + <td>Remove observers.</td> + </tr> + </tbody> +</table> + +<h3 id="Number"><em>Number</em></h3> + +<ul> + <li>{{jsxref("Number.toInteger()")}}</li> +</ul> + +<h3 id="ParallelArray"><em>ParallelArray</em></h3> + +<ul> + <li>{{jsxref("ParallelArray")}}</li> +</ul> + +<h3 id="Statements"><em>Statements</em></h3> + +<ul> + <li>{{jsxref("Statements/for_each...in", "for each...in")}} is deprecated. Use {{jsxref("Statements/for...of", "for...of")}} instead.</li> + <li>Destructuring {{jsxref("Statements/for...in", "for...in")}} is deprecated. Use {{jsxref("Statements/for...of", "for...of")}} instead.</li> + <li>let blocks and let expressions are obsolete.</li> +</ul> + +<h3 id="E4X">E4X</h3> + +<p>See <a href="/en-US/docs/Archive/Web/E4X">E4X</a> for more information.</p> + +<h3 id="Variáveis_Sharp">Variáveis <em>Sharp</em></h3> + +<p>Consulte <a href="/en-US/docs/Archive/Web/Sharp_variables_in_JavaScript">Sharp variables in JavaScript</a> para mais informação.</p> diff --git a/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html b/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html new file mode 100644 index 0000000000..c7ac84a4b9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html @@ -0,0 +1,228 @@ +--- +title: O objeto arguments +slug: Web/JavaScript/Reference/Funcoes/arguments +tags: + - Class + - Funções + - JavaScript + - Referencia + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +<p>{{JSSidebar("Functions")}}</p> + +<p><strong><code>arguments</code></strong> é um objeto semelhante a uma "<code>Matiz</code>" acessível dentro de <em>functions </em>que contém os valores dos argumentos passados para essa função.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> If you're writing ES6 compatible code, then <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a> should be preferred.</p> +</div> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> “Array-like” means that <code>arguments</code> has a <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/length">length</a></code> property and properties indexed from zero, but it doesn't have {{JSxRef("Array")}}'s built-in methods like <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach</a></code> and <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a></code>. See <a href="#Description">§Description</a> for details.</p> +</div> + +<div>{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">arguments</pre> + +<h2 id="Descrição">Descrição</h2> + +<p>The <code>arguments</code> object is a local variable available within all non-<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow</a> functions. You can refer to a function's arguments inside that function by using its <code>arguments</code> object. It has entries for each argument the function was called with, with the first entry's index at 0.</p> + +<p>For example, if a function is passed 3 arguments, you can access them as follows:</p> + +<pre class="brush: js">arguments[0] // first argument +arguments[1] // second argument +arguments[2] // third argument +</pre> + +<p>Each argument can also be set or reassigned:</p> + +<pre class="brush: js">arguments[1] = 'new value'; +</pre> + +<p>The <code>arguments</code> object is not an {{JSxRef("Array")}}. It is similar, but does not have any <code>Array</code> properties except <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments/length">length</a></code>. For example, it does not have the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">pop</a></code> method. However, it can be converted to a real <code>Array</code>:</p> + +<pre class="brush: js">var args = Array.prototype.slice.call(arguments); +// Using an array literal is shorter than above but allocates an empty array +var args = [].slice.call(arguments); +</pre> + +<p>As you can do with any Array-like object, you can use ES2015's {{JSxRef("Array.from()")}} method or <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread operator</a> to convert <code>arguments</code> to a real Array:</p> + +<pre>let args = Array.from(arguments); +// or +let args = [...arguments];</pre> + +<p>The <code>arguments</code> object is useful for functions called with more arguments than they are formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments, such as <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min">Math.min()</a></code>. This example function accepts any number of string arguments and returns the longest one:</p> + +<pre class="brush: js">function longestString() { + var longest = ''; + for (var i=0; i < arguments.length; i++) { + if (arguments[i].length > longest.length) { + longest = arguments[i]; + } + } + return longest; +} +</pre> + +<p>You can use <code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code> to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/length">length</a></code> property.</p> + +<h3 id="Utilizar_typeof_com_Arguments">Utilizar <code>typeof</code> com <em>Arguments</em></h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></code> operator returns <code>'object'</code> when used with <code>arguments</code></p> + +<pre class="brush: js">console.log(typeof arguments); // 'object' </pre> + +<p>The type of individual arguments can be determined by indexing <code>arguments</code>:</p> + +<pre>console.log(typeof arguments[0]); // returns the type of the first argument</pre> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt></dt> + <dt>{{jsxref("Functions/arguments/callee", "arguments.callee")}}</dt> + <dd>Reference to the currently executing function that the arguments belong to.</dd> + <dt>{{jsxref("Functions/arguments/length", "arguments.length")}}</dt> + <dd>The number of arguments that were passed to the function.</dd> + <dt>{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}</dt> + <dd>Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in <code>arguments</code>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Definir_uma_function_que_concatena_várias_strings">Definir uma <em>function</em> que concatena várias <em>strings</em></h3> + +<p>This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.</p> + +<pre class="brush:js">function myConcat(separator) { + var args = Array.prototype.slice.call(arguments, 1); + return args.join(separator); +}</pre> + +<p>You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:</p> + +<pre class="brush:js">// returns "red, orange, blue" +myConcat(', ', 'red', 'orange', 'blue'); + +// returns "elephant; giraffe; lion; cheetah" +myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah'); + +// returns "sage. basil. oregano. pepper. parsley" +myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');</pre> + +<h3 id="Definir_uma_function_que_cria_listas_HTML">Definir uma <em>function</em> que cria listas HTML</h3> + +<p>This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "<code>u</code>" if the list is to be unordered (bulleted), or "<code>o</code>" if the list is to be ordered (numbered). The function is defined as follows:</p> + +<pre class="brush:js">function list(type) { + var html = '<' + type + 'l><li>'; + var args = Array.prototype.slice.call(arguments, 1); + html += args.join('</li><li>'); + html += '</li></' + type + 'l>'; // end list + + return html; +}</pre> + +<p>You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:</p> + +<pre class="brush:js">var listHTML = list('u', 'One', 'Two', 'Three'); + +/* listHTML is: +"<ul><li>One</li><li>Two</li><li>Three</li></ul>" +*/</pre> + +<h3 id="Parâmetros_Rest_predefinição_e_desestruturados">Parâmetros Rest, predefinição, e desestruturados</h3> + +<p>The <code>arguments</code> object can be used in conjunction with <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest</a>, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default</a>, and <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructured</a> parameters.</p> + +<pre class="brush: js">function foo(...args) { + return args; +} +foo(1, 2, 3); // [1,2,3] +</pre> + +<p>While the presence of rest, default, or destructured parameters does not alter the <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode#Making_eval_and_arguments_simpler">behavior of the <code>arguments</code> object in strict mode code</a>, there is a subtle difference for non-strict code.</p> + +<p>In strict-mode code, the <code>arguments</code> object behaves the same whether or not a function is passed rest, default, or destructured parameters. That is, assigning new values to variables in the body of the function will not affect the <code>arguments</code> object. Nor will assigning new variables to the <code>arguments</code> object affect the value of variables.</p> + +<div class="blockIndicator note"> +<p><strong>Nota:</strong> You cannot write a <code>"use strict";</code> directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params">a syntax error</a>.</p> +</div> + +<p>Non-strict functions that are passed only simple parameters (that is, not rest, default, or restructured parameters) will sync the value of variables new values in the body of the function with the <code>arguments</code> object, and vice versa:</p> + +<pre class="brush: js">function func(a) { + arguments[0] = 99; // updating arguments[0] also updates a + console.log(a); +} +func(10); // 99 +</pre> + +<p>And also:</p> + +<pre class="brush: js">function func(a) { + a = 99; // updating a also updates arguments[0] + console.log(arguments[0]); +} +func(10); // 99 +</pre> + +<p>Conversely, non-strict functions that <strong>are</strong> passed rest, default, or destructured parameters <strong>will not</strong> sync new values assigned to argument variables in the function body with the <code>arguments</code> object. Instead, the <code>arguments</code> object in non-strict functions with complex parameters <strong>will always</strong> reflect the values passed to the function when the function was called (this is the same behavior as exhibited by all strict-mode functions, regardless of the type of variables they are passed):</p> + +<pre class="brush: js">function func(a = 55) { + arguments[0] = 99; // updating arguments[0] does not also update a + console.log(a); +} +func(10); // 10</pre> + +<p>E também:</p> + +<pre class="brush: js">function func(a = 55) { + a = 99; // updating a does not also update arguments[0] + console.log(arguments[0]); +} +func(10); // 10 +</pre> + +<p>E também:</p> + +<pre class="brush: js">// An untracked default parameter +function func(a = 55) { + console.log(arguments[0]); +} +func(); // undefined</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibildiade_de_navegador">Compatibildiade de navegador</h2> + + + +<p>{{Compat("javascript.functions.arguments")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{JSxRef("Function")}}</li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Funcoes/parametros_rest">Parâmetros Rest</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html b/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html new file mode 100644 index 0000000000..aa7b7b3121 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html @@ -0,0 +1,399 @@ +--- +title: Expressões da função "Seta" +slug: Web/JavaScript/Reference/Funcoes/Funcoes_seta +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Uma <strong>expressão da função seta</strong> é uma alternativa sintaticamente compacta a uma expressão de <a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores/função">expressão de função</a> regular, embora sem as suas próprias associações às palavras-chave <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a></code>, ou <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></code>. As expressões de função (<em>function</em>) de seta são inadequadas como métodos, e não podem ser utilziadas como construtores.</p> + +<div>{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<h3 id="Basic_syntax">Basic syntax</h3> + +<pre class="syntaxbox">(param1, param2, …, paramN) => { statements } +(param1, param2, …, paramN) => expression +// equivalent to: => { return expression; } + +// Parentheses are optional when there's only one parameter name: +(singleParam) => { statements } +singleParam => { statements } + +// The parameter list for a function with no parameters should be written with a pair of parentheses. +() => { statements } +</pre> + +<h3 id="Advanced_syntax">Advanced syntax</h3> + +<pre class="syntaxbox">// Parenthesize the body of a function to return an object literal expression: +params => ({foo: bar}) + +// <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Rest_parameters">Rest parameters</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a> are supported +(param1, param2, ...rest) => { statements } +(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { +statements } + +// <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring</a> within the parameter list is also supported +var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; +f(); // 6 +</pre> + +<h2 id="Descrição">Descrição</h2> + +<p>See also <a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a>.</p> + +<p>Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the <code>this</code> keyword.</p> + +<h3 id="Funções_curtas">Funções curtas</h3> + +<pre class="brush: js">var elements = [ + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium' +]; + +// This statement returns the array: [8, 6, 7, 9] +elements.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(function(element) { + return element.length; +}); + +// The regular function above can be written as the arrow function below +elements.map((element) => { + return element.length; +}); // [8, 6, 7, 9] + +// When there is only one parameter, we can remove the surrounding parentheses +elements.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(element => { + return element.length; +}); // [8, 6, 7, 9] + +// When the only statement in an arrow function is `return`, we can remove `return` and remove +// the surrounding curly brackets +elements.map(element => element.length); // [8, 6, 7, 9] + +// In this case, because we only need the length property, we can use destructuring parameter: +// Notice that the `length` corresponds to the property we want to get whereas the +// obviously non-special `lengthFooBArX` is just the name of a variable which can be changed +// to any valid variable name you want +elements.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9] + +// This destructuring parameter assignment can also be written as seen below. However, note that in +// this example we are not assigning `length` value to the made up property. Instead, the literal name +// itself of the variable `length` is used as the property we want to retrieve from the object. +elements.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(({ length }) => length); // [8, 6, 7, 9] +</pre> + +<h3 id="No_separate_this">No separate <code>this</code></h3> + +<p>Before arrow functions, every new function defined its own <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> value based on how the function was called:</p> + +<ul> + <li>A new object in the case of a constructor.</li> + <li><code>undefined</code> in <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> function calls.</li> + <li>The base object if the function was called as an "object method".</li> + <li>etc.</li> +</ul> + +<p>This proved to be less than ideal with an object-oriented style of programming.</p> + +<pre class="brush: js">function Person() { + // The Person() constructor defines `this` as an instance of itself. + this.age = 0; + + setInterval(function growUp() { + // In non-strict mode, the growUp() function defines `this` + // as the global object (because it's where growUp() is executed.), + // which is different from the `this` + // defined by the Person() constructor. + this.age++; + }, 1000); +} + +var p = new Person();</pre> + +<p>In ECMAScript 3/5, the <code>this</code> issue was fixable by assigning the value in <code>this</code> to a variable that could be closed over.</p> + +<pre class="brush: js">function Person() { + var that = this; + that.age = 0; + + setInterval(function growUp() { + // The callback refers to the `that` variable of which + // the value is the expected object. + that.age++; + }, 1000); +}</pre> + +<p>Alternatively, a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">bound function</a> could be created so that a preassigned <code>this</code> value would be passed to the bound target function (the <code>growUp()</code> function in the example above).</p> + +<p>An arrow function does not have its own <code>this</code>. The <code>this</code> value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for <code>this</code> which is not present in current scope, an arrow function ends up finding the <code>this</code> from its enclosing scope.</p> + +<p>Thus, in the following code, the <code>this</code> within the function that is passed to <code>setInterval</code> has the same value as the <code>this</code> in the lexically enclosing function:</p> + +<pre class="brush: js">function Person(){ + this.age = 0; + + setInterval(() => { + this.age++; // |this| properly refers to the Person object + }, 1000); +} + +var p = new Person();</pre> + +<h4 id="Relation_with_strict_mode">Relation with strict mode</h4> + +<p>Given that <code>this</code> comes from the surrounding lexical context, <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> rules with regard to <code>this</code> are ignored.</p> + +<pre class="brush: js">var f = () => { 'use strict'; return this; }; +f() === window; // or the global object</pre> + +<p>All other strict mode rules apply normally.</p> + +<h4 id="Invoked_through_call_or_apply">Invoked through call or apply</h4> + +<p>Since arrow functions do not have their own <code>this</code>, the methods <code>call()</code> and <code>apply()</code> can only pass in parameters. Any <code>this</code> argument is ignored.</p> + +<pre class="brush: js">var adder = { + base: 1, + + add: function(a) { + var f = v => v + this.base; + return f(a); + }, + + addThruCall: function(a) { + var f = v => v + this.base; + var b = { + base: 2 + }; + + return f.call(b, a); + } +}; + +console.log(adder.add(1)); // This would log 2 +console.log(adder.addThruCall(1)); // This would log 2 still</pre> + +<h3 id="No_binding_of_arguments">No binding of <code>arguments</code></h3> + +<p>Arrow functions do not have their own <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code> object</a>. Thus, in this example, <code>arguments</code> is simply a reference to the arguments of the enclosing scope:</p> + +<pre class="brush: js">var arguments = [1, 2, 3]; +var arr = () => arguments[0]; + +arr(); // 1 + +function foo(n) { + var f = () => arguments[0] + n; // <em>foo</em>'s implicit arguments binding. arguments[0] is n + return f(); +} + +foo(3); // 6</pre> + +<p>In most cases, using <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a> is a good alternative to using an <code>arguments</code> object.</p> + +<pre class="brush: js">function foo(n) { + var f = (...args) => args[0] + n; + return f(10); +} + +foo(1); // 11</pre> + +<h3 id="Arrow_functions_used_as_methods">Arrow functions used as methods</h3> + +<p>As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:</p> + +<pre class="brush: js">'use strict'; + +var obj = { // does not create a new scope + i: 10, + b: () => console.log(this.i, this), + c: function() { + console.log(this.i, this); + } +} + +obj.b(); // prints undefined, Window {...} (or the global object) +obj.c(); // prints 10, Object {...}</pre> + +<p>Arrow functions do not have their own <code>this</code>. Another example involving {{jsxref("Object.defineProperty()")}}:</p> + +<pre class="brush: js">'use strict'; + +var obj = { + a: 10 +}; + +Object.defineProperty(obj, 'b', { + get: () => { + console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object) + return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined' + } +}); +</pre> + +<h3 id="Use_of_the_new_operator">Use of the <code>new</code> operator</h3> + +<p>Arrow functions cannot be used as constructors and will throw an error when used with <code>new</code>.</p> + +<pre class="brush: js">var Foo = () => {}; +var foo = new Foo(); // TypeError: Foo is not a constructor</pre> + +<h3 id="Use_of_prototype_property">Use of <code>prototype</code> property</h3> + +<p>Arrow functions do not have a <code>prototype</code> property.</p> + +<pre class="brush: js">var Foo = () => {}; +console.log(Foo.prototype); // undefined +</pre> + +<h3 id="Use_of_the_yield_keyword">Use of the <code>yield</code> keyword</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code> keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.</p> + +<h2 id="Function_body">Function body</h2> + +<p>Arrow functions can have either a "concise body" or the usual "block body".</p> + +<p>In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit <code>return</code> statement.</p> + +<pre class="brush: js">var func = x => x * x; +// concise body syntax, implied "return" + +var func = (x, y) => { return x + y; }; +// with block body, explicit "return" needed +</pre> + +<h2 id="Returning_object_literals">Returning object literals</h2> + +<p>Keep in mind that returning object literals using the concise body syntax <code>params => {object:literal}</code> will not work as expected.</p> + +<pre class="brush: js">var func = () => { foo: 1 }; +// Calling func() returns undefined! + +var func = () => { foo: function() {} }; +// SyntaxError: function statement requires a name</pre> + +<p>This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. <code>foo</code> is treated like a label, not a key in an object literal).</p> + +<p>You must wrap the object literal in parentheses:</p> + +<pre class="brush: js">var func = () => ({ foo: 1 });</pre> + +<h2 id="Line_breaks">Line breaks</h2> + +<p>An arrow function cannot contain a line break between its parameters and its arrow.</p> + +<pre class="brush: js">var func = (a, b, c) + => 1; +// SyntaxError: expected expression, got '=>'</pre> + +<p>However, this can be amended by putting the line break after the arrow or using parentheses/braces as seen below to ensure that the code stays pretty and fluffy. You can also put line breaks between arguments.</p> + +<pre class="brush: js">var func = (a, b, c) => + 1; + +var func = (a, b, c) => ( + 1 +); + +var func = (a, b, c) => { + return 1 +}; + +var func = ( + a, + b, + c +) => 1; + +// no SyntaxError thrown</pre> + +<h2 id="Parsing_order">Parsing order</h2> + +<p>Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a> compared to regular functions.</p> + +<pre class="brush: js">let callback; + +callback = callback || function() {}; // ok + +callback = callback || () => {}; +// SyntaxError: invalid arrow-function arguments + +callback = callback || (() => {}); // ok +</pre> + +<h2 id="More_examples">More examples</h2> + +<pre class="brush: js">// An empty arrow function returns undefined +let empty = () => {}; + +(() => 'foobar')(); +// Returns "foobar" +// (this is an <a href="/en-US/docs/Glossary/IIFE">Immediately Invoked Function Expression</a>) + +var simple = a => a > 15 ? 15 : a; +simple(16); // 15 +simple(10); // 10 + +let max = (a, b) => a > b ? a : b; + +// Easy array filtering, mapping, ... + +var arr = [5, 6, 13, 0, 1, 18, 23]; + +var sum = arr.reduce((a, b) => a + b); +// 66 + +var even = arr.filter(v => v % 2 == 0); +// [6, 0, 18] + +var double = arr.map(v => v * 2); +// [10, 12, 26, 0, 2, 36, 46] + +// More concise promise chains +promise.then(a => { + // ... +}).then(b => { + // ... +}); + +// Parameterless arrow functions that are visually easier to parse +setTimeout( () => { + console.log('I happen sooner'); + setTimeout( () => { + // deeper code + console.log('I happen later'); + }, 1); +}, 1); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.functions.arrow_functions")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/funcoes/index.html b/files/pt-pt/web/javascript/reference/funcoes/index.html new file mode 100644 index 0000000000..02b35fc7bd --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcoes/index.html @@ -0,0 +1,594 @@ +--- +title: Funções +slug: Web/JavaScript/Reference/Funcoes +tags: + - Constructor + - Função + - Funções + - JavaScript + - Parâmetro + - parâmetros +translation_of: Web/JavaScript/Reference/Functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the <em>function body</em>. Values can be <em>passed</em> to a function, and the function will <em>return</em> a value.</p> + +<p>In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a></code> objects.</p> + +<p>For more examples and explanations, see also the <a href="/en-US/docs/Web/JavaScript/Guide/Functions">JavaScript guide about functions</a>.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Every function in JavaScript is a <code>Function</code> object. See {{jsxref("Function")}} for information on properties and methods of <code>Function</code> objects.</p> + +<p>To return a value other than the default, a function must have a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a></code> statement that specifies the value to return. A function without a return statement will return a default value. In the case of a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> called with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code> keyword, the default value is the value of its <code>this</code> parameter. For all other functions, the default return value is {{jsxref("undefined")}}.</p> + +<p>The parameters of a function call are the function's <em>arguments</em>. Arguments are passed to functions <em>by value</em>. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:</p> + +<pre class="brush: js">/* Declare the function 'myFunc' */ +function myFunc(theObject) { + theObject.brand = "Toyota"; +} + +/* + * Declare variable 'mycar'; + * create and initialize a new Object; + * assign reference to it to 'mycar' + */ +var mycar = { + brand: "Honda", + model: "Accord", + year: 1998 +}; + +/* Logs 'Honda' */ +console.log(mycar.brand); + +/* Pass object reference to the function */ +myFunc(mycar); + +/* + * Logs 'Toyota' as the value of the 'brand' property + * of the object, as changed to by the function. + */ +console.log(mycar.brand); +</pre> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> keyword</a> does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body.</p> + +<h2 id="Definindo_funções">Definindo funções</h2> + +<p>There are several ways to define functions:</p> + +<h3 id="The_function_declaration_(function_statement)">The function declaration (<code>function</code> statement)</h3> + +<p>There is a special syntax for declaring functions (see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> for details):</p> + +<pre class="syntaxbox">function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_function_expression_(function_expression)">The function expression (<code>function</code> expression)</h3> + +<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not <em>hoisted</em> onto the beginning of the scope, therefore they cannot be used before they appear in the code.</p> + +<pre class="syntaxbox">function [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<p>Here is an example of an <strong>anonymous</strong> function expression (the <code>name</code> is not used):</p> + +<pre class="brush: js">var myFunction = function() { + statements +}</pre> + +<p>It is also possible to provide a name inside the definition in order to create a <strong>named</strong> function expression:</p> + +<pre class="brush: js">var myFunction = function namedFunction(){ + statements +} +</pre> + +<p>One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.</p> + +<p>As we can see, both examples do not start with the <code>function</code> keyword. Statements involving functions which do not start with <code>function</code> are function expressions.</p> + +<p>When functions are used only once, a common pattern is an <strong>IIFE (<em>Immediately Invokable Function Expression</em>)</strong>.</p> + +<pre class="brush: js">(function() { + statements +})();</pre> + +<p>IIFE are function expressions that are invoked as soon as the function is declared.</p> + +<h3 id="The_generator_function_declaration_(function*_statement)">The generator function declaration (<code>function*</code> statement)</h3> + +<p>There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):</p> + +<pre class="syntaxbox">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_generator_function_expression_(function*_expression)">The generator function expression (<code>function*</code> expression)</h3> + +<p>A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):</p> + +<pre class="syntaxbox">function* [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_arrow_function_expression_(>)">The arrow function expression (=>)</h3> + +<p>An arrow function expression has a shorter syntax and lexically binds its <code>this</code> value (see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> for details):</p> + +<pre class="syntaxbox">([param[, param]]) => { + statements +} + +param => expression +</pre> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument. Zero arguments need to be indicated with <code>()</code>. For only one argument, the parentheses are not required. (like <code>foo => 1</code>)</dd> + <dt><code>statements or expression</code></dt> + <dd>Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.</dd> +</dl> + +<h3 id="The_Function_constructor">The <code>Function</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>Function</code> constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.</p> +</div> + +<p>As all other objects, {{jsxref("Function")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new Function (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function body.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h3 id="The_GeneratorFunction_constructor">The <code>GeneratorFunction</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> <code>GeneratorFunction</code> is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>GeneratorFunction</code> constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.</p> +</div> + +<p>As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new GeneratorFunction (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Parâmetros_de_função">Parâmetros de função</h2> + +<h3 id="Parâmetros_predefinidos">Parâmetros predefinidos</h3> + +<p>Default function parameters allow formal parameters to be initialized with default values if no value or <code>undefined</code> is passed. For more details, see<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters"> default parameters</a>.</p> + +<h3 id="Parâmetros_Rest">Parâmetros <em>Rest</em></h3> + +<p>The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p> + +<h2 id="O_objeto_arguments">O objeto <em><code>arguments</code></em></h2> + +<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>.</p> + +<ul> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments">arguments</a></code>: An array-like object containing the arguments passed to the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a></code> {{Deprecated_inline}}: The currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a></code> {{Obsolete_inline}} : The function that invoked the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code>: The number of arguments passed to the function.</li> +</ul> + +<h2 id="Definindo_funções_de_método">Definindo funções de método</h2> + +<h3 id="Getter_and_setter_functions">Getter and setter functions</h3> + +<p>You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></dt> + <dd> + <p>Binds an object property to a function that will be called when that property is looked up.</p> + </dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></dt> + <dd>Binds an object property to a function to be called when there is an attempt to set that property.</dd> +</dl> + +<h3 id="Method_definition_syntax">Method definition syntax</h3> + +<p>Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a> for more information.</p> + +<pre class="brush: js">var obj = { + foo() {}, + bar() {} +};</pre> + +<h2 id="Constructor_vs._declaration_vs._expression">Constructor vs. declaration vs. expression</h2> + +<p>Compare the following:</p> + +<p>A function defined with the <code>Function</code> <em>constructor</em> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = new Function('x', 'y', 'return x * y');</pre> + +<p>A <em>function declaration</em> of a function named <code>multiply</code>:</p> + +<pre class="brush: js">function multiply(x, y) { + return x * y; +} // there is no semicolon here +</pre> + +<p>A <em>function expression</em> of an anonymous function assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function(x, y) { + return x * y; +}; +</pre> + +<p>A <em>function expression</em> of a function named <code>func_name</code> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function func_name(x, y) { + return x * y; +}; +</pre> + +<h3 id="Differences">Differences</h3> + +<p>All do approximately the same thing, with a few subtle differences:</p> + +<p>There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example:</p> + +<pre class="brush: js">var y = function x() {}; +alert(x); // throws an error +</pre> + +<p>The function name also appears when the function is serialized via <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p> + +<p>On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.</p> + +<p>As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:</p> + +<p>A function defined by '<code>new Function'</code> does not have a function name. However, in the <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs:</p> + +<pre class="brush: js">function anonymous() { +} +</pre> + +<p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p> + +<pre class="brush: js">var foo = new Function("alert(anonymous);"); +foo(); +</pre> + +<p>Unlike functions defined by function expressions or by the <code>Function</code> constructor, a function defined by a function declaration can be used before the function declaration itself. For example:</p> + +<pre class="brush: js">foo(); // alerts FOO! +function foo() { + alert('FOO!'); +} +</pre> + +<p>A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</p> + +<pre class="brush: js">/* + * Declare and initialize a variable 'p' (global) + * and a function 'myFunc' (to change the scope) inside which + * declare a varible with same name 'p' (current) and + * define three functions using three different ways:- + * 1. function declaration + * 2. function expression + * 3. function constructor + * each of which will log 'p' + */ +var p = 5; +function myFunc() { + var p = 9; + + function decl() { + console.log(p); + } + var expr = function() { + console.log(p); + }; + var cons = new Function('\tconsole.log(p);'); + + decl(); + expr(); + cons(); +} +myFunc(); + +/* + * Logs:- + * 9 - for 'decl' by function declaration (current scope) + * 9 - for 'expr' by function expression (current scope) + * 5 - for 'cons' by Function constructor (global scope) + */ +</pre> + +<p>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should generally be avoided whenever possible.</p> + +<p>It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a <code>Function constructor</code> 's string aren't parsed repeatedly. For example:</p> + +<pre class="brush: js">var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); +foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.</pre> + +<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p> + +<ul> + <li>becomes part of an expression</li> + <li>is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:</li> +</ul> + +<pre class="brush: js">var x = 0; // source element +if (x === 0) { // source element + x = 10; // not a source element + function boo() {} // not a source element +} +function foo() { // source element + var y = 20; // source element + function bar() {} // source element + while (y === 10) { // source element + function blah() {} // not a source element + y++; // not a source element + } +} +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">// function declaration +function foo() {} + +// function expression +(function bar() {}) + +// function expression +x = function hello() {} + + +if (x) { + // function expression + function world() {} +} + + +// function declaration +function a() { + // function declaration + function b() {} + if (0) { + // function expression + function c() {} + } +} +</pre> + +<h2 id="Block-level_functions">Block-level functions</h2> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.</p> + +<pre class="brush: js">'use strict'; + +function f() { + return 1; +} + +{ + function f() { + return 2; + } +} + +f() === 1; // true + +// f() === 2 in non-strict mode +</pre> + +<h3 id="Block-level_functions_in_non-strict_code">Block-level functions in non-strict code</h3> + +<p>In a word: Don't.</p> + +<p>In non-strict code, function declarations inside blocks behave strangely. For example:</p> + +<pre class="brush: js">if (shouldDefineZero) { + function zero() { // DANGER: compatibility risk + console.log("This is zero."); + } +} +</pre> + +<p>ES2015 says that if <code>shouldDefineZero</code> is false, then <code>zero</code> should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define <code>zero</code> whether the block executed or not.</p> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, all browsers that support ES2015 handle this the same way: <code>zero</code> is defined only if <code>shouldDefineZero</code> is true, and only in the scope of the <code>if</code>-block.</p> + +<p>A safer way to define functions conditionally is to assign a function expression to a variable:</p> + +<pre class="brush: js">var zero; +if (shouldDefineZero) { + zero = function() { + console.log("This is zero."); + }; +} +</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Returning_a_formatted_number">Returning a formatted number</h3> + +<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p> + +<pre class="brush: js">// This function returns a string padded with leading zeros +function padZeros(num, totalLen) { + var numStr = num.toString(); // Initialize return value as string + var numZeros = totalLen - numStr.length; // Calculate no. of zeros + for (var i = 1; i <= numZeros; i++) { + numStr = "0" + numStr; + } + return numStr; +} +</pre> + +<p>The following statements call the padZeros function.</p> + +<pre class="brush: js">var result; +result = padZeros(42,4); // returns "0042" +result = padZeros(42,2); // returns "42" +result = padZeros(5,4); // returns "0005" +</pre> + +<h3 id="Determining_whether_a_function_exists">Determining whether a function exists</h3> + +<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is performed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p> + +<pre class="brush: js"> if ('function' === typeof window.noFunc) { + // use noFunc() + } else { + // do something else + } +</pre> + +<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Arrow functions, Generator functions, default parameters, rest parameters.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.functions")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Functions/Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions/Default_parameters", "Default parameters")}}</li> + <li>{{jsxref("Functions/rest_parameters", "Rest parameters")}}</li> + <li>{{jsxref("Functions/arguments", "Arguments object")}}</li> + <li>{{jsxref("Functions/get", "getter")}}</li> + <li>{{jsxref("Functions/set", "setter")}}</li> + <li>{{jsxref("Functions/Method_definitions", "Method definitions")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">Functions and function scope</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html b/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html new file mode 100644 index 0000000000..a21cb25ed6 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html @@ -0,0 +1,234 @@ +--- +title: Parâmetros Rest +slug: Web/JavaScript/Reference/Funcoes/parametros_rest +tags: + - Funcionalidade Linguagem + - Funções + - JavaScript + - Parametros Rest + - Rest +translation_of: Web/JavaScript/Reference/Functions/rest_parameters +--- +<div>Parâmetrois {{jsSidebar("Functions")}}</div> + +<p><span class="seoSummary">A sintaxe do <strong>parâmetro "rest"</strong> permite-nos representar um número indefinido de argumentos</span><span class="seoSummary">como um <em>array</em>.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">function f(<var>a</var>, <var>b</var>, ...<var>theArgs</var>) { + // ... +}</pre> + +<h2 id="Descrição">Descrição</h2> + +<p>A function's last parameter can be prefixed with <code>...</code> which will cause all remaining (user supplied) arguments to be placed within a "standard" Javascript array.</p> + +<p>Only the last parameter can be a "rest parameter".</p> + +<pre class="brush: js">function myFun(<var>a</var>, <var>b</var>, ...<var>manyMoreArgs</var>) { + console.log("a", a) + console.log("b", b) + console.log("manyMoreArgs", manyMoreArgs) +} + +myFun("one", "two", "three", "four", "five", "six") + +// Console Output: +// a, one +// b, two +// manyMoreArgs, [three, four, five, six] +</pre> + +<h3 id="Difference_between_rest_parameters_and_the_arguments_object">Difference between rest parameters and the <code>arguments</code> object</h3> + +<p>There are three main differences between rest parameters and the {{jsxref("Functions/arguments", "arguments")}} object:</p> + +<ul> + <li>rest parameters are only the ones that haven't been given a separate name (i.e. formally defined in function expression), while the <code>arguments</code> object contains <em>all</em> arguments passed to the function;</li> + <li>the <code>arguments</code> object is not a real array, while rest parameters are {{jsxref("Global_Objects/Array", "Array")}} instances, meaning methods like {{jsxref("Array.sort", "sort")}}, {{jsxref("Array.map", "map")}}, {{jsxref("Array.forEach", "forEach")}} or {{jsxref("Array/pop", "pop")}} can be applied on it directly;</li> + <li>the <code>arguments</code> object has additional functionality specific to itself (like the <code>callee</code> property).</li> +</ul> + +<h3 id="From_arguments_to_an_array">From arguments to an array</h3> + +<p>Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments</p> + +<pre class="brush: js">// Before rest parameters, "arguments" could be converted to a normal array using: + +function f(a, b) { + + let normalArray = Array.prototype.slice.call(arguments) + // -- or -- + let normalArray = [].slice.call(arguments) + // -- or -- + let normalArray = Array.from(arguments) + + let first = normalArray.shift() // OK, gives the first argument + let first = arguments.shift() // ERROR (arguments is not a normal array) +} + +// Now, you can easily gain access to a normal array using a rest parameter + +function f(...args) { + let normalArray = args + let first = normalArray.shift() // OK, gives the first argument +} +</pre> + +<h3 id="Destructuring_rest_parameters">Destructuring rest parameters</h3> + +<p>Rest parameters can be destructured Arrays only (though objects will soon be supported). That means that their data can be unpacked into distinct variables. (See <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring assignment</a>.)</p> + +<pre class="brush: js">function f(...[a, b, c]) { + return a + b + c; +} + +f(1) // NaN (b and c are undefined) +f(1, 2, 3) // 6 +f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured) +</pre> + +<div class="blockIndicator note"> +<h4 id="Fixme">Fixme</h4> + +<p><s>Doing this is possible, but (afaik) there's no use-case, so it's just confusing the junior audience. The following code does exactly the same. There should at least be a note, that in theory you can do something like this, but there is no point in doing so.</s> The example is contrived, but imagine that [a, b, c] were the return value of some function. Then the utility is clear.</p> + +<p><s>Also, since <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">Function arguments</a> will never have named parameters (this is not Python), the statement "objects will soon be supported" is wrong. </s> The preceding example may be mixing up destructuring with rest parameters. Please see the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">page on destructuring assignment</a> for an example with object destructuring applied in the parameters area.</p> + +<pre class="brush: js">function f(a, b, c) { + return a + b + c +} + +f(1) // NaN (b and c are undefined) +f(1, 2, 3) // 6 +f(1, 2, 3, 4) // 6 (the fourth parameter is not ...) +</pre> +</div> + +<h2 id="Exemplos">Exemplos</h2> + +<p>In this example, the first argument is mapped to <code>a</code> and the second to <code>b</code>, so these named arguments are used like normal.</p> + +<p>However, the third argument, <code>manyMoreArgs</code>, will be an array that contains the 3<sup>rd</sup>, 4<sup>th</sup>, 5<sup>th</sup>, 6<sup>th</sup> ... <var>n</var><sup>th</sup> — as many arguments that the user includes.</p> + +<pre class="brush: js">function myFun(a, b, ...manyMoreArgs) { + console.log("a", a) + console.log("b", b) + console.log("manyMoreArgs", manyMoreArgs) +} + +myFun("one", "two", "three", "four", "five", "six") + +// a, one +// b, two +// manyMoreArgs, [three, four, five, six] +</pre> + +<p>Below... even though there is just one value, the last argument still gets put into an array.</p> + +<pre class="brush: js">// using the same function definition from example above + +myFun("one", "two", "three") + +// a, one +// b, two +// manyMoreArgs, [three]</pre> + +<p>Below, the third argument isn't provided, but <code>manyMoreArgs</code> is still an array (albeit an empty one).</p> + +<pre class="brush: js">// using the same function definition from example above + +myFun("one", "two") + +// a, one +// b, two +// manyMoreArgs, []</pre> + +<p>Since <code>theArgs</code> is an array, a count of its elements is given by the <code>length</code> property:</p> + +<pre class="brush: js">function fun1(...theArgs) { + console.log(theArgs.length) +} + +fun1() // 0 +fun1(5) // 1 +fun1(5, 6, 7) // 3 +</pre> + +<p>In the next example, a rest parameter is used to collect all parameters after the first into an array. Each one of them is then multiplied by the first parameter, and the array is returned:</p> + +<pre class="brush: js">function multiply(multiplier, ...theArgs) { + return theArgs.map(function(element) { + return multiplier * element + }) +} + +let arr = multiply(2, 1, 2, 3) +console.log(arr) // [2, 4, 6] +</pre> + +<p><code>Array</code> methods can be used on rest parameters, but not on the <code>arguments</code> object:</p> + +<pre class="brush: js">function sortRestArgs(...theArgs) { + let sortedArgs = theArgs.sort() + return sortedArgs +} + +console.log(sortRestArgs(5, 3, 7, 1)) // 1, 3, 5, 7 + +function sortArguments() { + let sortedArgs = arguments.sort() + return sortedArgs // this will never happen +} + + +console.log(sortArguments(5, 3, 7, 1)) +// throws a TypeError (arguments.sort is not a function) +</pre> + +<p>To use <code>Array</code> methods on the <code>arguments</code> object, it must be converted to a real array first.</p> + +<pre class="brush: js">function sortArguments() { + let args = Array.from(arguments) + let sortedArgs = args.sort() + return sortedArgs +} +console.log(sortArguments(5, 3, 7, 1)) // 1, 3, 5, 7 +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibildiade_de_navegador">Compatibildiade de navegador</h2> + + + +<p>{{Compat("javascript.functions.rest_parameters")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator" title="spread operator">Spread syntax</a> (also ‘<code>...</code>’)</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments" title="arguments">Arguments object</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" title="Array">Array</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions" title="Functions and function scope">Functions</a></li> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:rest_parameters">Original proposal at ecmascript.org</a></li> + <li><a class="external" href="http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/">JavaScript arguments object and beyond</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring assignment</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..237818a04c --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,205 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - JavaScript + - Prototipo + - Referencia + - Vector + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>concat()</strong></code> é usado para concatenar dois ou mais vectores. Este método não altera os vectores existentes, devolvendo ao invés um novo vector.</p> + +<pre class="brush: js">var vec1 = ['a', 'b', 'c']; +var vec2 = ['d', 'e', 'f']; + +var vec3 = vec1.concat(vec2); + +// vec3 é um novo vector [ "a", "b", "c", "d", "e", "f" ]</pre> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">var <var>novo_vector</var> = <var>velho_vector</var>.concat(<var>valor1</var>[, <var>valor2</var>[, ...[, <var>valorN</var>]]])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>valor<em>N</em></code></dt> + <dd>Vectores e/ou valores a concatenar num novo vector. Veja a descrição detalhada abaixo.</dd> +</dl> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>Uma nova instância de {{jsxref("Array")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>concat</code> cria um novo vector constituído pelos elementos no vector em que foi chamado, seguidos por ordem por, cada argumento, os elementos desse argumento (se o argumento é um vector), ou o argumento em si (se o argumento não é um vector). Não entra recursivamente em vectores inclusos.</p> + +<p>O método <code>concat</code> não altera <code>this</code> ou qualquer dos vectores fornecidos como argumentos, devolve sim uma cópia superficial (shallow copy) que contém cópias dos mesmos elementos combinados dos vectores originais. Os elementos dos vectores originais são copiados para o novo vector da seguinte forma:</p> + +<ul> + <li>Object references (and not the actual object): <code>concat</code> copies object references into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays. This includes elements of array arguments that are also arrays.</li> + <li>Strings, numbers and booleans (not {{jsxref("Global_Objects/String", "String")}}, {{jsxref("Global_Objects/Number", "Number")}}, and {{jsxref("Global_Objects/Boolean", "Boolean")}} objects): <code>concat</code> copies the values of strings and numbers into the new array.</li> +</ul> + +<div class="note"> +<p><strong>Note:</strong> Concatenating array(s)/value(s) will leave the originals untouched. Furthermore, any operation on the new array(only if the element is not object reference) will have no effect on the original arrays, and vice versa.</p> +</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Concatenar_dois_vectores">Concatenar dois vectores</h3> + +<p>O código que se segue concatena dois vectores:</p> + +<pre class="brush: js">var alfa = ['a', 'b', 'c']; +var numerico = [1, 2, 3]; + +alfa.concat(numerico); +// resulta em ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Concatenar_três_vectores">Concatenar três vectores</h3> + +<p>O código que se segue concatena três vectores:</p> + +<pre class="brush: js">var num1 = [1, 2, 3], + num2 = [4, 5, 6], + num3 = [7, 8, 9]; + +var nums = num1.concat(num2, num3); + +console.log(nums); +// resulta em [1, 2, 3, 4, 5, 6, 7, 8, 9] +</pre> + +<h3 id="Concatenar_valores_para_um_vector">Concatenar valores para um vector</h3> + +<p>O código que se segue concatena três valores a um vector:</p> + +<pre class="brush: js">var alfa = ['a', 'b', 'c']; + +var alfaNumerico = alfa.concat(1, [2, 3]); + +console.log(alphaNumeric); +// resulta em ['a', 'b', 'c', 1, 2, 3] +</pre> + +<h3 id="Concatenar_vectores_inclusos">Concatenar vectores inclusos</h3> + +<p>O código que se segue concatena vectores inclusos e demonstra retenção de referências:</p> + +<pre class="brush: js">var num1 = [[1]]; +var num2 = [2, [3]]; + +var nums = num1.concat(num2); + +console.log(nums); +// resulta em [[1], 2, [3]] + +// modificar o primeiro elemento de num1 +num1[0].push(4); + +console.log(nums); +// resulta em [[1, 4], 2, [3]] +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definição inicial. Implementado no JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.push", "push")}} / {{jsxref("Array.pop", "pop")}} — adicionar/eliminar elementos no fim do vector</li> + <li>{{jsxref("Array.unshift", "unshift")}} / {{jsxref("Array.shift", "shift")}} — adicionar/eliminar elementos no início do vector</li> + <li>{{jsxref("Array.splice", "splice")}} — adicionar e/ou eliminar elementos no local especificado do vector</li> + <li>{{jsxref("String.prototype.concat()")}}</li> + <li>{{jsxref("Symbol.isConcatSpreadable")}} – control flattening.</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..3eedeb54a9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,210 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>find()</strong></code> retorna o <strong>valor</strong> do primeiro elemento do array que satisfaça a função de teste fornecida. Caso contrário o valor {{jsxref("undefined")}} é retornado.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-find.html")}}</div> + + + +<p>Ver também o método {{jsxref("Array.findIndex", "findIndex()")}} , o qual retorna o <strong>index</strong> de um elemento encontrado num array, em alternativa do seu valor.</p> + +<p>É possível obter a posição de um elemento ou verificar a sua existência num array, através da função {{jsxref("Array.prototype.indexOf()")}} ou {{jsxref("Array.prototype.includes()")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>arr</var>.find(<var>callback</var>[, <var>thisArg</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Função a executar em cada elemento do array, utilizando três argumentos: + <dl> + <dt><code>element</code></dt> + <dd>O elemento a ser processado no array.</dd> + <dt><code>index</code>{{optional_inline}}</dt> + <dd>O index do elemento a ser processado no array.</dd> + <dt><code>array</code>{{optional_inline}}</dt> + <dd>O array no qual o método <code>find</code> foi chamado.</dd> + </dl> + </dd> + <dt><code>thisArg</code> <code>{{Optional_inline}}</code></dt> + <dd>Objeto para usar como <code>this</code> ao executar a <code>callback</code>.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Um valor do array caso um elemento passe no teste; caso contrário, {{jsxref("undefined")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método<code>find</code> executa a <code>callback</code> uma vez para cada index do array até ser encontrado um no qual a <code>callback</code> retorna o valor true. Caso um elemento seja encontrado, o método <code>find</code> retorna imediatamente o seu valor. Caso contrário, o método <code>find</code> retorna {{jsxref("undefined")}}. A função de <code>callback</code> é invocada para cada index do array do <code>0</code> ao <code>length - 1</code> e é invocada para todos os indexes, não apenas nos que tem valor. Isto pode significar que é menos eficiente para o um array com muitos elementos sem valor (sparse array) do que outros métodos que visitam apenas os elementos com valor.</p> + +<p>A função de <code>callback</code> é invocada com 3 parâmetros: o valor do elemento, o index do elemento, e o Array no qual é executado.</p> + +<p>Se o parâmetro <code>thisArg</code> for disponibilizado ao método <code>find</code>, este será usado como <code>this</code> para cada invocação da <code>callback</code>. Caso contrário, será usado o valor {{jsxref("undefined")}}.</p> + +<p>O método <code>find</code> não altera o array no qual é invocado.</p> + +<p>A quantidade de elementos processados pelo método <code>find</code> é definida antes da invocação da <code>callback</code>. Os elementos adicionados ao array após o método <code>find</code> ter iniciado não serão visitados pela <code>callback</code>. Se um elemento existente e não visitado, for alterado pela <code>callback</code>, o seu valor que foi passado para a <code>callback</code> será o valor a ser avaliado pelo método <code>find</code>; Os elementos eliminados após o inicio do método find também serão visitados.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Encontrar_um_objeto_num_array_através_de_uma_das_suas_propriedades">Encontrar um objeto num array através de uma das suas propriedades</h3> + +<pre class="brush: js">var inventory = [ + {name: 'apples', quantity: 2}, + {name: 'bananas', quantity: 0}, + {name: 'cherries', quantity: 5} +]; + +function isCherries(fruit) { + return fruit.name === 'cherries'; +} + +console.log(inventory.find(isCherries)); +// { name: 'cherries', quantity: 5 }</pre> + +<h3 id="Encontrar_um_número_primo_num_array">Encontrar um número primo num array</h3> + +<p>O seguinte exemplo encontra um elemento no array que seja um número primo (caso não exista, retorna {{jsxref("undefined")}} ).</p> + +<pre class="brush: js">function isPrime(element, index, array) { + var start = 2; + while (start <= Math.sqrt(element)) { + if (element % start++ < 1) { + return false; + } + } + return element > 1; +} + +console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found +console.log([4, 5, 8, 12].find(isPrime)); // 5 +</pre> + +<p>O seguinte exemplo, apresenta como os elementos não existentes e eliminados são visitados e o seu valor passado para a callback será o seu valor quando visitado.</p> + +<pre class="brush: js">// Declare array with no element at index 2, 3 and 4 +var a = [0,1,,,,5,6]; + +// Shows all indexes, not just those that have been assigned values +a.find(function(value, index) { + console.log('Visited index ' + index + ' with value ' + value); +}); + +// Shows all indexes, including deleted +a.find(function(value, index) { + + // Delete element 5 on first iteration + if (index == 0) { + console.log('Deleting a[5] with value ' + a[5]); + delete a[5]; + } + // Element 5 is still visited even though deleted + console.log('Visited index ' + index + ' with value ' + value); +}); + +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Este método foi adicionado ao <em>ECMAScript 2015 Language Specification </em>e pode não estar disponível em todas as implementações de JavaScript. É possível desenvolver o polyfill do método find com o seguinte código:</p> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.find +if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { + value: function(predicate) { + // 1. Let O be ? ToObject(this value). + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If IsCallable(predicate) is false, throw a TypeError exception. + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + + // 4. If thisArg was supplied, let T be thisArg; else let T be undefined. + var thisArg = arguments[1]; + + // 5. Let k be 0. + var k = 0; + + // 6. Repeat, while k < len + while (k < len) { + // a. Let Pk be ! ToString(k). + // b. Let kValue be ? Get(O, Pk). + // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)). + // d. If testResult is true, return kValue. + var kValue = o[k]; + if (predicate.call(thisArg, kValue, k, o)) { + return kValue; + } + // e. Increase k by 1. + k++; + } + + // 7. Return undefined. + return undefined; + } + }); +} +</pre> + +<p>É melhor não utilizar o polyfill <code>Array.prototype</code> para motores JavaScript obsoletos que não suportem métodos <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, uma vez que, não é possível torna-los não-enumeráveis.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_Browsers">Compatibilidade de Browsers</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.find")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Array.prototype.findIndex()")}} – procurar e obter um index</li> + <li>{{jsxref("Array.prototype.includes()")}} – testar se existe um valor num array</li> + <li>{{jsxref("Array.prototype.filter()")}} – encontrar todos os elementos</li> + <li>{{jsxref("Array.prototype.every()")}} – testar se todos os elementos cumprem o requisito</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..77e1bcc9d9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,328 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>forEach()</strong></code> executa a função que foi fornecida uma vez para cada elemento do vetor (array).</p> + +<div>{{EmbedInteractiveExample("pages/js/array-foreach.html")}}</div> + +<p class="hidden">A origem deste exemplo interactivo está armazenado num repositório do GitHub. Se queres contribuir para o projecto dos exemplos interactivos, por favor clona <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> e manda-nos um pull request.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>vet</var>.forEach(function <var>callback(presenteValor[, indice[, vetor]]) { + //o teu iterador +}</var>[, <var>argThis</var>]);</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>callback</code></dt> + <dd>Função a executar para cada elemento, levando três argumentos: + <dl> + <dt><code>presenteValor</code></dt> + <dd>Valor do presente elemento a ser processado do vetor (array).</dd> + <dt><code>indice</code>{{optional_inline}}</dt> + <dd>Índice do presente elemento a ser processado do vetor (array).</dd> + <dt><code>vet</code>{{optional_inline}}</dt> + <dd>O vetor (array) a que o <code>forEach()</code> está a ser aplicado.</dd> + </dl> + </dd> + <dt><code>argThis</code> {{Optional_inline}}</dt> + <dd> + <p>Valor a usar como <code><strong>this</strong></code> (ou seja o <code>Object</code> de referência) quando é executado o <code>callback</code>.</p> + </dd> +</dl> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>forEach()</code> executa o <code>callback</code> fornecido uma vez para cada elemento presente no vetor (array) por ordem ascendente. Não é invocado para indices de propriedades que foram apagadas ou que não foram inicializadas (ou seja em sparse arrays).</p> + +<p><code>callback</code> é invocado com <strong>três argumentos</strong>:</p> + +<ul> + <li>o <strong>valor do elemento</strong></li> + <li>o <strong>índice do elemento</strong></li> + <li>o <strong>vetor (array) que está a ser percorrido</strong></li> +</ul> + +<p>If a <code>thisArg</code> parameter is provided to <code>forEach()</code>, it will be used as callback's <code>this</code> value. Otherwise, the value {{jsxref("undefined")}} will be used as its <code>this</code> value. The <code>this</code> value ultimately observable by <code>callback</code> is determined according to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">the usual rules for determining the <code>this</code> seen by a function</a>.</p> + +<p>The range of elements processed by <code>forEach()</code> is set before the first invocation of <code>callback</code>. Elements that are appended to the array after the call to <code>forEach()</code> begins will not be visited by <code>callback</code>. If the values of existing elements of the array are changed, the value passed to <code>callback</code> will be the value at the time <code>forEach()</code> visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using {{jsxref("Array.prototype.shift()", "shift()")}}) during the iteration, later elements will be skipped - see example below.</p> + +<p><code>forEach()</code> executes the <code>callback</code> function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.</p> + +<p><code>forEach()</code> does not mutate the array on which it is called (although <code>callback</code>, if invoked, may do so).</p> + +<div class="note"> +<p>There is no way to stop or break a <code>forEach()</code> loop other than by throwing an exception. If you need such behavior, the <code>forEach()</code> method is the wrong tool.</p> + +<p>Early termination may be accomplished with:</p> + +<ul> + <li>A simple loop</li> + <li>A <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a> loop</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> + +<p>The other Array methods: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.</p> +</div> + +<h2 id="Examples">Examples</h2> + +<h3 id="Converting_a_for_loop_to_forEach">Converting a for loop to forEach</h3> + +<p>before</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +for (let i=0; i<items.length; i++) { + copy.push(items[i]) +} +</pre> + +<p>after</p> + +<pre class="brush:js">const items = ['item1', 'item2', 'item3']; +const copy = []; + +items.forEach(function(item){ + copy.push(item) +}); + +</pre> + +<p> </p> + +<h3 id="Printing_the_contents_of_an_Array_Object">Printing the contents of an Array Object</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">var userInfo = [{ + name: "Mayank", + age: 30 +}, { + name: Meha, + age: 26 +}]; + +userInfo.forEach(function(employee) { + console.log(employee.name) +}); +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<h3 id="Printing_the_contents_of_an_array">Printing the contents of an array</h3> + +<p>The following code logs a line for each element in an array:</p> + +<pre class="brush:js">function logArrayElements(element, index, array) { + console.log('a[' + index + '] = ' + element); +} + +// Notice that index 2 is skipped since there is no item at +// that position in the array. +[2, 5, , 9].forEach(logArrayElements); +// logs: +// a[0] = 2 +// a[1] = 5 +// a[3] = 9 +</pre> + +<h3 id="Using_thisArg">Using <code>thisArg</code></h3> + +<p>The following (contrived) example updates an object's properties from each entry in the array:</p> + +<pre class="brush:js">function Counter() { + this.sum = 0; + this.count = 0; +} +Counter.prototype.add = function(array) { + array.forEach(function(entry) { + this.sum += entry; + ++this.count; + }, this); + // ^---- Note +}; + +const obj = new Counter(); +obj.add([2, 5, 9]); +obj.count; +// 3 +obj.sum; +// 16 +</pre> + +<p>Since the <code>thisArg</code> parameter (<code>this</code>) is provided to <code>forEach()</code>, it is passed to <code>callback</code> each time it's invoked, for use as its <code>this</code> value.</p> + +<div class="note"> +<p>If passing the function argument using an <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a> the <code>thisArg</code> parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.</p> +</div> + +<h3 id="An_object_copy_function">An object copy function</h3> + +<p>The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how <code>Array.prototype.forEach()</code> works by using ECMAScript 5 <code>Object.*</code> meta property functions.</p> + +<pre class="brush: js">function copy(obj) { + const copy = Object.create(Object.getPrototypeOf(obj)); + const propNames = Object.getOwnPropertyNames(obj); + + propNames.forEach(function(name) { + const desc = Object.getOwnPropertyDescriptor(obj, name); + Object.defineProperty(copy, name, desc); + }); + + return copy; +} + +const obj1 = { a: 1, b: 2 }; +const obj2 = copy(obj1); // obj2 looks like obj1 now +</pre> + +<h3 id="If_the_array_is_modified_during_iteration_other_elements_might_be_skipped.">If the array is modified during iteration, other elements might be skipped.</h3> + +<p>The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. <code>forEach()</code> does not make a copy of the array before iterating.</p> + +<pre class="brush:js">var words = ['one', 'two', 'three', 'four']; +words.forEach(function(word) { + console.log(word); + if (word === 'two') { + words.shift(); + } +}); +// one +// two +// four +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>forEach()</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>forEach()</code> in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that <code>callback.call()</code> evaluates to the original value of {{jsxref("Function.prototype.call()")}}.</p> + +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.18 +// Reference: http://es5.github.io/#x15.4.4.18 +if (!Array.prototype.forEach) { + + Array.prototype.forEach = function(callback/*, thisArg*/) { + + var T, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling toObject() passing the + // |this| value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get() internal + // method of O with the argument "length". + // 3. Let len be toUint32(lenValue). + var len = O.length >>> 0; + + // 4. If isCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let + // T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let k be 0. + k = 0; + + // 7. Repeat while k < len. + while (k < len) { + + var kValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator. + // b. Let kPresent be the result of calling the HasProperty + // internal method of O with argument Pk. + // This step can be combined with c. + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Call the Call internal method of callback with T as + // the this value and argument list containing kValue, k, and O. + callback.call(T, kValue, k, O); + } + // d. Increase k by 1. + k++; + } + // 8. return undefined. + }; +} +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.forEach")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> + <li>{{jsxref("Array.prototype.map()")}}</li> + <li>{{jsxref("Array.prototype.every()")}}</li> + <li>{{jsxref("Array.prototype.some()")}}</li> + <li>{{jsxref("Map.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..201d4c9526 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,175 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>includes()</strong></code> determina se um array contém um determinado elemento, devolvendo <code>true</code> ou <code>false</code>. É utilizado o algoritmo sameValueZero para determinar se o elemento especificado foi encontrado.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-includes.html")}}</div> + + + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.includes(<var>searchElement[</var>, <var>fromIndex]</var>) +</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>searchElement</code></dt> + <dd>The element to search for.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>The position in this array at which to begin searching for <code>searchElement</code>. A negative value searches from the index of <code>array.length - fromIndex</code> by asc. Defaults to 0.</dd> +</dl> + +<h3 id="Return_value">Return value</h3> + +<p>A {{jsxref("Boolean")}}.</p> + +<h2 id="Examples">Examples</h2> + +<pre class="brush: js">[1, 2, 3].includes(2); // true +[1, 2, 3].includes(4); // false +[1, 2, 3].includes(3, 3); // false +[1, 2, 3].includes(3, -1); // true +[1, 2, NaN].includes(NaN); // true +</pre> + +<h3 id="fromIndex_is_greater_than_or_equal_to_the_array_length"><code>fromIndex</code> is greater than or equal to the array length</h3> + +<p>If <code>fromIndex</code> is greater than or equal to the length of the array, <code>false</code> is returned. The array will not be searched.</p> + +<pre class="brush: js">var arr = ['a', 'b', 'c']; + +arr.includes('c', 3); // false +arr.includes('c', 100); // false</pre> + +<h3 id="Computed_index_is_less_than_0">Computed index is less than 0</h3> + +<p>If <code>fromIndex</code> is negative, the computed index is calculated to be used as a position in the array at which to begin searching for <code>searchElement</code>. If the computed index is less than 0, the entire array will be searched.</p> + +<pre class="brush: js">// array length is 3 +// fromIndex is -100 +// computed index is 3 + (-100) = -97 + +var arr = ['a', 'b', 'c']; + +arr.includes('a', -100); // true +arr.includes('b', -100); // true +arr.includes('c', -100); // true</pre> + +<h3 id="includes()_used_as_a_generic_method"><code>includes()</code> used as a generic method</h3> + +<p><code>includes()</code> method is intentionally generic. It does not require <code>this</code> value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates <code>includes()</code> method called on the function's <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> object.</p> + +<pre class="brush: js">(function() { + console.log([].includes.call(arguments, 'a')); // true + console.log([].includes.call(arguments, 'd')); // false +})('a','b','c');</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.includes +if (!Array.prototype.includes) { + Object.defineProperty(Array.prototype, 'includes', { + value: function(searchElement, fromIndex) { + + if (this == null) { + throw new TypeError('"this" is null or not defined'); + } + + // 1. Let O be ? ToObject(this value). + var o = Object(this); + + // 2. Let len be ? ToLength(? Get(O, "length")). + var len = o.length >>> 0; + + // 3. If len is 0, return false. + if (len === 0) { + return false; + } + + // 4. Let n be ? ToInteger(fromIndex). + // (If fromIndex is undefined, this step produces the value 0.) + var n = fromIndex | 0; + + // 5. If n ≥ 0, then + // a. Let k be n. + // 6. Else n < 0, + // a. Let k be len + n. + // b. If k < 0, let k be 0. + var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); + + function sameValueZero(x, y) { + return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)); + } + + // 7. Repeat, while k < len + while (k < len) { + // a. Let elementK be the result of ? Get(O, ! ToString(k)). + // b. If SameValueZero(searchElement, elementK) is true, return true. + if (sameValueZero(o[k], searchElement)) { + return true; + } + // c. Increase k by 1. + k++; + } + + // 8. Return false + return false; + } + }); +} +</pre> + +<p>If you need to support truly obsolete JavaScript engines that don't support <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a></code>, it's best not to polyfill <code>Array.prototype</code> methods at all, as you can't make them non-enumerable.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ES7')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.includes")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("TypedArray.prototype.includes()")}}</li> + <li>{{jsxref("String.prototype.includes()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> + <li>{{jsxref("Array.prototype.find()")}}</li> + <li>{{jsxref("Array.prototype.findIndex()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..5f26f41549 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,440 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Class + - Exemplo + - Global Objects + - JavaScript + - Referencia + - 'l10n:priority' +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +<div>{{JSRef}}</div> + +<p>A classe de JavaScript <strong><code>Array</code></strong> é um objecto global que é utilizado na construção de matrizes; que são objectos de alto nível, semelhantes a listas.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Arrays são objectos em forma de lista, cujo protótipo tem métodos para realizar operações de travessia e mutação. Nem o comprimento de uma array JavaScript nem os tipos dos seus elementos são fixos. Uma vez que o comprimento de uma array pode mudar a qualquer momento, e os dados podem ser armazenados em locais não contíguos da array, não é garantido que uma array JavaScript seja densa; isto depende de como o programador opta por usá-las. Em geral, estas são características convenientes; mas se estas características não forem desejáveis para seu uso particular, você pode considerar o uso de arrays tipadas.</p> + +<p>Uma array não pode utilizar strings como índices de elementos (como num {{InterWiki("wikipedia", "Vetor_associativo", "array associativa")}}), deve utilizar números inteiros. A definição ou acesso através de não-inteiros usando notação de parênteses (ou notação de pontos) não definirá ou recuperará um elemento da própria lista da array, mas definirá ou acessará uma variável associada à <a href="pt-PT/docs/Web/JavaScript/Estruturas_de_dados#Objetos">coleção de propriedades dessa array</a>. As propriedades da array e a lista de elementos do mesmo são separadas, e as operações de translação e mutação da array não podem ser aplicadas a essas propriedades com nome.</p> + +<p><strong>Criar uma Array</strong></p> + +<pre class="brush: js notranslate">var fruits = ['Apple', 'Banana']; + +console.log(fruits.length); +// 2 +</pre> + +<p><strong>Aceder (através de índice) item<span class="original-content"> da </span>Array</strong></p> + +<pre class="brush: js notranslate">var first = fruits[0]; +// Apple + +var last = fruits[fruits.length - 1]; +// Banana +</pre> + +<p><strong>Loop over an Array</strong></p> + +<pre class="brush: js notranslate">fruits.forEach(function(item, index, array) { + console.log(item, index); +}); +// Apple 0 +// Banana 1 +</pre> + +<p><strong>Adicionar um item ao fim da Array</strong></p> + +<pre class="brush: js notranslate">var newLength = fruits.push('Orange'); +// ["Apple", "Banana", "Orange"] +</pre> + +<p><strong>Remover um item do fim da Array</strong></p> + +<pre class="brush: js notranslate">var last = fruits.pop(); // remove Orange (from the end) +// ["Apple", "Banana"]; +</pre> + +<p><strong>Remover um item do início da Array</strong></p> + +<pre class="brush: js notranslate">var first = fruits.shift(); // remove Apple from the front +// ["Banana"]; +</pre> + +<p><strong>Ad</strong><strong>icionar um item ao início da Array</strong></p> + +<pre class="brush: js notranslate">var newLength = fruits.unshift('Strawberry') // add to the front +// ["Strawberry", "Banana"]; +</pre> + +<p><strong>Encontrar o índice dum item na Array</strong></p> + +<pre class="brush: js notranslate">fruits.push('Mango'); +// ["Strawberry", "Banana", "Mango"] + +var pos = fruits.indexOf('Banana'); +// 1 +</pre> + +<p><strong>Remover um item pela posição do índice</strong></p> + +<pre class="brush: js notranslate">var removedItem = fruits.splice(pos, 1); // this is how to remove an item + +// ["Strawberry", "Mango"]</pre> + +<p><strong>Remover items pela posição do índice</strong></p> + +<pre class="brush: js notranslate">var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot']; +console.log(vegetables); +// ["Cabbage", "Turnip", "Radish", "Carrot"] + +var pos = 1, n = 2; + +var removedItems = vegetables.splice(pos, n); +// this is how to remove items, n defines the number of items to be removed, +// from that position(pos) onward to the end of array. + +console.log(vegetables); +// ["Cabbage", "Carrot"] (the original array is changed) + +console.log(removedItems); +// ["Turnip", "Radish"]</pre> + +<p><strong>Copiar uma Array</strong></p> + +<pre class="brush: js notranslate">var shallowCopy = fruits.slice(); // this is how to make a copy +// ["Strawberry"] +</pre> + +<h3 id="Como_aceder_a_elementos_da_array">Como aceder a elementos da array</h3> + +<p>JavaScript arrays are zero-indexed: the first element of an array is at index <code>0</code>, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1.</p> + +<pre class="brush: js notranslate">var arr = ['this is the first element', 'this is the second element']; +console.log(arr[0]); // logs 'this is the first element' +console.log(arr[1]); // logs 'this is the second element' +console.log(arr[arr.length - 1]); // logs 'this is the second element' +</pre> + +<p>Array elements are object properties in the same way that <code>toString</code> is a property, but trying to access an element of an array as follows throws a syntax error, because the property name is not valid:</p> + +<pre class="brush: js notranslate">console.log(arr.0); // a syntax error +</pre> + +<p>There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named <code>'3d'</code>, it can only be referenced using bracket notation. E.g.:</p> + +<pre class="brush: js notranslate">var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]; +console.log(years.0); // a syntax error +console.log(years[0]); // works properly +</pre> + +<pre class="brush: js notranslate">renderer.3d.setTexture(model, 'character.png'); // a syntax error +renderer['3d'].setTexture(model, 'character.png'); // works properly +</pre> + +<p>Note that in the <code>3d</code> example, <code>'3d'</code> had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., <code>years['2']</code> instead of <code>years[2]</code>), although it's not necessary. The 2 in <code>years[2]</code> is coerced into a string by the JavaScript engine through an implicit <code>toString</code> conversion. It is for this reason that <code>'2'</code> and <code>'02'</code> would refer to two different slots on the <code>years</code> object and the following example could be <code>true</code>:</p> + +<pre class="brush: js notranslate">console.log(years['2'] != years['02']); +</pre> + +<p>Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation(but it can be accessed by dot notation in firefox 40.0a2 at least):</p> + +<pre class="brush: js notranslate">var promise = { + 'var' : 'text', + 'array': [1, 2, 3, 4] +}; + +console.log(promise['var']); +</pre> + +<h3 id="Relationship_between_length_and_numerical_properties">Relationship between <code>length</code> and numerical properties</h3> + +<p>A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join")}}, {{jsxref("Array.slice", "slice")}}, {{jsxref("Array.indexOf", "indexOf")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push")}}, {{jsxref("Array.splice", "splice")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.</p> + +<pre class="brush: js notranslate">var fruits = []; +fruits.push('banana', 'apple', 'peach'); + +console.log(fruits.length); // 3 +</pre> + +<p>When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:</p> + +<pre class="brush: js notranslate">fruits[5] = 'mango'; +console.log(fruits[5]); // 'mango' +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 6 +</pre> + +<p>Increasing the {{jsxref("Array.length", "length")}}.</p> + +<pre class="brush: js notranslate">fruits.length = 10; +console.log(Object.keys(fruits)); // ['0', '1', '2', '5'] +console.log(fruits.length); // 10 +</pre> + +<p>Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.</p> + +<pre class="brush: js notranslate">fruits.length = 2; +console.log(Object.keys(fruits)); // ['0', '1'] +console.log(fruits.length); // 2 +</pre> + +<p>This is explained further on the {{jsxref("Array.length")}} page.</p> + +<h3 id="Creating_an_array_using_the_result_of_a_match">Creating an array using the result of a match</h3> + +<p>The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:</p> + +<pre class="brush: js notranslate">// Match one d followed by one or more b's followed by one d +// Remember matched b's and the following d +// Ignore case + +var myRe = /d(b+)(d)/i; +var myArray = myRe.exec('cdbBdbsbz'); +</pre> + +<p>The properties and elements returned from this match are as follows:</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <td class="header">Property/Element</td> + <td class="header">Description</td> + <td class="header">Example</td> + </tr> + <tr> + <td><code>input</code></td> + <td>A read-only property that reflects the original string against which the regular expression was matched.</td> + <td>cdbBdbsbz</td> + </tr> + <tr> + <td><code>index</code></td> + <td>A read-only property that is the zero-based index of the match in the string.</td> + <td>1</td> + </tr> + <tr> + <td><code>[0]</code></td> + <td>A read-only element that specifies the last matched characters.</td> + <td>dbBd</td> + </tr> + <tr> + <td><code>[1], ...[n]</code></td> + <td>Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.</td> + <td>[1]: bB<br> + [2]: d</td> + </tr> + </tbody> +</table> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Array.length</code></dt> + <dd>The <code>Array</code> constructor's length property whose value is 1.</dd> + <dt>{{jsxref("Array.@@species", "get Array[@@species]")}}</dt> + <dd>The constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Array.prototype")}}</dt> + <dd>Allows the addition of properties to all array objects.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Array.from()")}}</dt> + <dd>Creates a new <code>Array</code> instance from an array-like or iterable object.</dd> + <dt>{{jsxref("Array.isArray()")}}</dt> + <dd>Returns true if a variable is an array, if not false.</dd> + <dt>{{jsxref("Array.of()")}}</dt> + <dd>Creates a new <code>Array</code> instance with a variable number of arguments, regardless of number or type of the arguments.</dd> +</dl> + +<h2 id="Array_instances"><code>Array</code> instances</h2> + +<p>All <code>Array</code> instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the <code>Array</code> constructor can be modified to affect all <code>Array</code> instances.</p> + +<h3 id="Properties_2">Properties</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}</div> + +<h3 id="Methods_2">Methods</h3> + +<h4 id="Mutator_methods">Mutator methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}</div> + +<h4 id="Accessor_methods">Accessor methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}</div> + +<h4 id="Iteration_methods">Iteration methods</h4> + +<div>{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}</div> + +<h2 id="Array_generic_methods"><code>Array</code> generic methods</h2> + +<div class="warning"> +<p><strong>Array generics are non-standard, deprecated and will get removed in the near future</strong>. </p> +</div> + +<p>Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable <var>str</var> is a letter, you would write:</p> + +<pre class="brush: js notranslate">function isLetter(character) { + return character >= 'a' && character <= 'z'; +} + +if (Array.prototype.every.call(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:</p> + +<pre class="brush: js notranslate">if (Array.every(str, isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<p>{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.</p> + +<p>These are <strong>not</strong> part of ECMAScript standards and they are not supported by non-Gecko browsers. As a standard alternative, you can convert your object to a proper array using {{jsxref("Array.from()")}}; although that method may not be supported in old browsers:</p> + +<pre class="brush: js notranslate">if (Array.from(str).every(isLetter)) { + console.log("The string '" + str + "' contains only letters!"); +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Creating_an_array">Creating an array</h3> + +<p>The following example creates an array, <code>msgArray</code>, with a length of 0, then assigns values to <code>msgArray[0]</code> and <code>msgArray[99]</code>, changing the length of the array to 100.</p> + +<pre class="brush: js notranslate">var msgArray = []; +msgArray[0] = 'Hello'; +msgArray[99] = 'world'; + +if (msgArray.length === 100) { + console.log('The length is 100.'); +} +</pre> + +<h3 id="Creating_a_two-dimensional_array">Creating a two-dimensional array</h3> + +<p>The following creates a chess board as a two dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.</p> + +<pre class="brush: js notranslate">var board = [ + ['R','N','B','Q','K','B','N','R'], + ['P','P','P','P','P','P','P','P'], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + [' ',' ',' ',' ',' ',' ',' ',' '], + ['p','p','p','p','p','p','p','p'], + ['r','n','b','q','k','b','n','r'] ]; + +console.log(board.join('\n') + '\n\n'); + +// Move King's Pawn forward 2 +board[4][4] = board[6][4]; +board[6][4] = ' '; +console.log(board.join('\n')); +</pre> + +<p>Here is the output:</p> + +<pre class="eval notranslate">R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , , , , , + , , , , , , , +p,p,p,p,p,p,p,p +r,n,b,q,k,b,n,r + +R,N,B,Q,K,B,N,R +P,P,P,P,P,P,P,P + , , , , , , , + , , , , , , , + , , , ,p, , , + , , , , , , , +p,p,p,p, ,p,p,p +r,n,b,q,k,b,n,r +</pre> + +<h3 id="Using_an_array_to_tabulate_a_set_of_values">Using an array to tabulate a set of values</h3> + +<pre class="brush: js notranslate">values = []; +for (var x = 0; x < 10; x++){ + values.push([ + 2 ** x, + 2 * x ** 2 + ]) +}; +console.table(values)</pre> + +<p>Results in</p> + +<pre class="eval notranslate">0 1 0 +1 2 2 +2 4 8 +3 8 18 +4 16 32 +5 32 50 +6 64 72 +7 128 98 +8 256 128 +9 512 162</pre> + +<p>(First column is the (index))</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4', 'Array')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>New method added: {{jsxref("Array.prototype.includes()")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_Navegadores">Compatibilidade de Navegadores</h2> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir para os dados, por favor consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pull request.</div> + +<p>{{Compat("javascript.builtins.Array")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Indexing_object_properties">JavaScript Guide: “Indexing object properties”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object">JavaScript Guide: “Predefined Core Objects: <code>Array</code> Object”</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions">Array comprehensions</a></li> + <li><a href="https://github.com/plusdude/array-generics">Polyfill for JavaScript 1.8.5 Array Generics and ECMAScript 5 Array Extras</a></li> + <li><a href="/en-US/docs/JavaScript_typed_arrays">Typed Arrays</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..aec6f34cc2 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,90 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - JavaScript + - Prototipo + - Referencia + - Vector + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>join()</strong></code> cria e devolve uma <em>string</em> ao concatenar todos os elementos numa <em>array</em> (ou <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">objeto como um vetor / matriz</a>) numa cadeia separada por vírgulas ou outro separador especificado. Se a <em>array</em> tem um só item, esse item é devolvido sem o uso do separador.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-join.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>vec</var>.join([<var>separador</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>separador</code> {{optional_inline}}</dt> + <dd>Especifica uma <em>string</em> (cadeia de caracteres) para separar cada elemento do vetor. O separador é convertido em cadeia se for necessário. Se for omitido, os elementos serão separados por virgulas (","). Se <code>separador</code> é uma cadeia vazia, todos os elementos são unidos sem qualquer caráter entre eles.</dd> +</dl> + +<h3 id="Resultado">Resultado</h3> + +<p>Uma cadeia (de caracteres) com todos os elementos do vetor unidos. Se <code><em>vec</em>.length</code> é <code>0</code>, é devolvida uma cadeia vazia.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>As conversões de todos os elementos do vetor para cadeias (de caracteres) são unidas numa única cadeia.</p> + +<p>Caso algum elemento seja <code>undefined</code>, <code>null</code> ou um vetor vazio <code>[]</code>, este será convertido numa cadeia vazia.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Juntar_um_vetor_de_quatro_formas_diferentes">Juntar um vetor de quatro formas diferentes</h3> + +<p>O exemplo que se segue cria um vetor, <code>a</code>, com três elementos, depois disso une o vetor quatro vezes: usando o separador predefinido, uma vírgula e um espaço, o símbolo mais, e finalmente uma cadeia (de caracteres) vazia.</p> + +<pre class="brush: js notranslate">var a = ['Vento', 'Chuva', 'Fogo']; +a.join(); // 'Vento,Chuva,Fogo' +a.join(', '); // 'Vento, Chuva, Fogo' +a.join(' + '); // 'Vento + Chuva + Fogo' +a.join(''); // 'VentoChuvaFogo'</pre> + +<h3 id="Juntar_um_objeto_como_vetor">Juntar um objeto como vetor</h3> + +<p>O seguinte exemplo junta um objeto como vetor (<code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a></code>), ao chamar {{jsxref("Function.prototype.call")}} no <code>Array.prototype.join</code>.</p> + +<pre class="brush: js notranslate">function f(a, b, c) { + var s = Array.prototype.join.call(arguments); + console.log(s); // '<span class="message-body-wrapper"><span class="message-flex-body"><span class="devtools-monospace message-body"><span class="objectBox objectBox-string">1,a,true'</span></span></span></span> +} +f(1, 'a', true); +// valor devolvido: "1,a,true" +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("javascript.builtins.Array.join")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.toString()")}}</li> + <li>{{jsxref("TypedArray.prototype.join()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..12910ebc2a --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,366 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - JavaScript + - Prototype + - Referencia + - metodo + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary">O método <code><strong>map()</strong></code> <strong>cria uma nova array</strong> preenchida com os resultados da chamada de uma função fornecida em cada elemento da matriz de chamada.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/array-map.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate">let <var>new_array</var> = <var>arr</var>.map(function <var>callback</var>( <var>currentValue</var>[, <var>index</var>[, <var>array</var>]]) { + // retorna novo elemento para new_array +}[, <var>thisArg</var>]) +</pre> + +<h3 id="Parameteros">Parameteros</h3> + +<dl> + <dt><code><var>callback</var></code></dt> + <dd> + <p>Função que é chamada para cada elemento de <code>arr</code>. Cada vez que a função <code>callback</code> é executada, o valor devolvido é acrescentado a <code>new_array</code>.</p> + + <p>A função <code><var>callback</var></code> aceita os seguintes argumentos:</p> + + <dl> + <dt><code><var>currentValue</var></code></dt> + <dd>O elemento da matriz a ser processado.</dd> + <dt><code><var>index</var></code>{{optional_inline}}</dt> + <dd>O indice do elemento da matriz a ser processado.</dd> + <dt><code><var>array</var></code>{{optional_inline}}</dt> + <dd>A matriz em que a função <code>map</code> foi chamada.</dd> + </dl> + </dd> + <dt><code>thisArg</code>{{optional_inline}}</dt> + <dd>Valor para usar como <code>this</code> ao executar a função <code><var>callback</var></code>.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Uma nova matriz em que cada elemento é um resultado da função callback..</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>map</code> chama a função <code><var>callback</var></code> <strong>uma vez por cada elemento</strong> na matriz, por ordem, e cria uma matriz com os resultados. <code><var>callback</var></code> é só chamada nos indices da matriz que têm valores (inclusive {{jsxref("undefined")}}).</p> + +<p>Não é chamada para elementos que não pertecem à matriz; isto sendo:</p> + +<ul> + <li>indices que não pertencem pela matriz;</li> + <li>que foram eliminados; ou</li> + <li>que nunca tiveram um valor.</li> +</ul> + +<h3 id="Quando_não_usar_map">Quando não usar map()</h3> + +<p>Como <code>map</code> map cira uma nova matriz, é um <em>anti-pattern</em> usar a função quando não se vai usar o valor devolvido; use antes {{jsxref("Array/forEach", "forEach")}} ou {{jsxref("for...of", "for-of")}}.</p> + +<p>Não deve usar <code>map</code> se:</p> + +<ul> + <li>não vai usar o valor devolvido; e/ou</li> + <li>o <code>callback</code> não devolve um valor.</li> +</ul> + +<h3 id="Parameteros_em_detalhe">Parameteros em detalhe</h3> + +<p><code><var>callback</var></code> é chamada com três argumentos: o valor do elemento, o indice do elemento, e a matriz do objeto a ser mapeado.</p> + +<p>Se o parametero <code>thisArg</code> é fornecido, é usado como o valor de <code>this</code> na função <em><code>callback</code></em>. Se não, o valor {{jsxref("undefined")}} é usado como o valor de <code>this</code>. O valor de <code>this</code> no corpo da função <code><var>callback</var></code> é determinado de acordo com <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">as regras habituais para determinar o valor de this numa função</a>.</p> + +<p><code>map</code> não modifica a matriz em que é chamada (embora a função <em><code>callback</code></em>, se invocada, possa fazê-lo).</p> + +<p>A série de elementos processados por <code>map</code> é definida antes da primeira invocação de <em><code>callback</code></em>. Os elementos que são anexados ao conjunto após a chamada para <code>map</code> não serão visitados por <code><em>callback</em></code>. Se os elementos existentes da matriz forem alterados, o seu valor como passado para <em><code>callback</code></em> será o valor no momento em que <code>map</code> os visitar. Os elementos que são apagados após a chamada para <code>map</code> começa e antes de serem visitados, não são visitados.</p> + +<p>Devido ao algoritmo defenido na especificação, se a matriz em que <code>map</code> é chamada for esparsa, a matriz resultante também o será com os mesmos indices em branco.</p> + +<h2 id="Polyfill">Polyfill</h2> + +<p><code>map</code> was added to the ECMA-262 standard in the 5th edition. Therefore, it may not be present in all implementations of the standard.</p> + +<p>You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>map</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that <code>callback.call</code> evaluates to the original value of <code>{{jsxref("Function.prototype.call")}}</code>.</p> + +<pre class="brush: js notranslate">// Production steps of ECMA-262, Edition 5, 15.4.4.19 +// Reference: http://es5.github.io/#x15.4.4.19 +if (!Array.prototype.map) { + + Array.prototype.map = function(callback/*, thisArg*/) { + + var T, A, k; + + if (this == null) { + throw new TypeError('this is null or not defined'); + } + + // 1. Let O be the result of calling ToObject passing the |this| + // value as the argument. + var O = Object(this); + + // 2. Let lenValue be the result of calling the Get internal + // method of O with the argument "length". + // 3. Let len be ToUint32(lenValue). + var len = O.length >>> 0; + + // 4. If IsCallable(callback) is false, throw a TypeError exception. + // See: http://es5.github.com/#x9.11 + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + + // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. + if (arguments.length > 1) { + T = arguments[1]; + } + + // 6. Let A be a new array created as if by the expression new Array(len) + // where Array is the standard built-in constructor with that name and + // len is the value of len. + A = new Array(len); + + // 7. Let k be 0 + k = 0; + + // 8. Repeat, while k < len + while (k < len) { + + var kValue, mappedValue; + + // a. Let Pk be ToString(k). + // This is implicit for LHS operands of the in operator + // b. Let kPresent be the result of calling the HasProperty internal + // method of O with argument Pk. + // This step can be combined with c + // c. If kPresent is true, then + if (k in O) { + + // i. Let kValue be the result of calling the Get internal + // method of O with argument Pk. + kValue = O[k]; + + // ii. Let mappedValue be the result of calling the Call internal + // method of callback with T as the this value and argument + // list containing kValue, k, and O. + mappedValue = callback.call(T, kValue, k, O); + + // iii. Call the DefineOwnProperty internal method of A with arguments + // Pk, Property Descriptor + // { Value: mappedValue, + // Writable: true, + // Enumerable: true, + // Configurable: true }, + // and false. + + // In browsers that support Object.defineProperty, use the following: + // Object.defineProperty(A, k, { + // value: mappedValue, + // writable: true, + // enumerable: true, + // configurable: true + // }); + + // For best browser support, use the following: + A[k] = mappedValue; + } + // d. Increase k by 1. + k++; + } + + // 9. return A + return A; + }; +} +</pre> + +<h2 id="Examples">Examples</h2> + +<h3 id="Mapping_an_array_of_numbers_to_an_array_of_square_roots">Mapping an array of numbers to an array of square roots</h3> + +<p>The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.</p> + +<pre class="brush: js notranslate">let numbers = [1, 4, 9] +let roots = numbers.map(function(num) { + return Math.sqrt(num) +}) +// roots is now [1, 2, 3] +// numbers is still [1, 4, 9] +</pre> + +<h3 id="Using_map_to_reformat_objects_in_an_array">Using map to reformat objects in an array</h3> + +<p>The following code takes an array of objects and creates a new array containing the newly reformatted objects.</p> + +<pre class="brush: js notranslate">let kvArray = [{key: 1, value: 10}, + {key: 2, value: 20}, + {key: 3, value: 30}] + +let reformattedArray = kvArray.map(obj => { + let rObj = {} + rObj[obj.key] = obj.value + return rObj +}) +// reformattedArray is now [{1: 10}, {2: 20}, {3: 30}], + +// kvArray is still: +// [{key: 1, value: 10}, +// {key: 2, value: 20}, +// {key: 3, value: 30}] +</pre> + +<h3 id="Mapping_an_array_of_numbers_using_a_function_containing_an_argument">Mapping an array of numbers using a function containing an argument</h3> + +<p>The following code shows how <code>map</code> works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as <code>map</code> loops through the original array.</p> + +<pre class="brush: js notranslate">let numbers = [1, 4, 9] +let doubles = numbers.map(function(num) { + return num * 2 +}) + +// doubles is now [2, 8, 18] +// numbers is still [1, 4, 9] +</pre> + +<h3 id="Using_map_generically">Using map generically</h3> + +<p>This example shows how to use map on a {{jsxref("String")}} to get an array of bytes in the ASCII encoding representing the character values:</p> + +<pre class="brush: js notranslate">let map = Array.prototype.map +let a = map.call('Hello World', function(x) { + return x.charCodeAt(0) +}) +// a now equals [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] +</pre> + +<h3 id="Using_map_generically_querySelectorAll">Using map generically querySelectorAll</h3> + +<p>This example shows how to iterate through a collection of objects collected by <code>querySelectorAll</code>. This is because <code>querySelectorAll</code> returns a <code>NodeList</code> (which is a collection of objects).</p> + +<p>In this case, we return all the selected <code>option</code>s' values on the screen:</p> + +<pre class="brush: js notranslate">let elems = document.querySelectorAll('select option:checked') +let values = Array.prototype.map.call(elems, function(obj) { + return obj.value +}) +</pre> + +<p>An easier way would be the {{jsxref("Array.from()")}} method.</p> + +<h3 id="Tricky_use_case">Tricky use case</h3> + +<p>(<a href="http://www.wirfs-brock.com/allen/posts/166">inspired by this blog post</a>)</p> + +<p>It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.</p> + +<p>Consider:</p> + +<pre class="brush: js notranslate">["1", "2", "3"].map(parseInt)</pre> + +<p>While one might expect <code>[1, 2, 3]</code>, the actual result is <code>[1, NaN, NaN]</code>.</p> + +<p>{{jsxref("parseInt")}} is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, <code>Array.prototype.map</code> passes 3 arguments:</p> + +<ul> + <li>the element</li> + <li>the index</li> + <li>the array</li> +</ul> + +<p>The third argument is ignored by {{jsxref("parseInt")}}—but <em>not</em> the second one! This is the source of possible confusion.</p> + +<p>Here is a concise example of the iteration steps:</p> + +<pre class="brush: js notranslate">// parseInt(string, radix) -> map(parseInt(value, index)) +/* first iteration (index is 0): */ parseInt("1", 0) // 1 +/* second iteration (index is 1): */ parseInt("2", 1) // NaN +/* third iteration (index is 2): */ parseInt("3", 2) // NaN +</pre> + +<p>Then let's talk about solutions.</p> + +<pre class="brush: js notranslate">function returnInt(element) { + return parseInt(element, 10) +} + +['1', '2', '3'].map(returnInt); // [1, 2, 3] +// Actual result is an array of numbers (as expected) + +// Same as above, but using the concise arrow function syntax +['1', '2', '3'].map( str => parseInt(str) ) + +// A simpler way to achieve the above, while avoiding the "gotcha": +['1', '2', '3'].map(Number) // [1, 2, 3] + +// But unlike parseInt(), Number() will also return a float or (resolved) exponential notation: +['1.1', '2.2e2', '3e300'].map(Number) // [1.1, 220, 3e+300] + +// For comparison, if we use parseInt() on the array above: +['1.1', '2.2e2', '3e300'].map( str => parseInt(str) ) // [1, 2, 3] +</pre> + +<p>One alternative output of the map method being called with {{jsxref("parseInt")}} as a parameter runs as follows:</p> + +<pre class="brush: js notranslate">let xs = ['10', '10', '10'] + +xs = xs.map(parseInt) + +console.log(xs) +// Actual result of 10,NaN,2 may be unexpected based on the above description.</pre> + +<h3 id="Mapped_array_contains_undefined">Mapped array contains undefined</h3> + +<p>When {{jsxref("undefined")}} or nothing is returned:</p> + +<pre class="brush: js notranslate">let numbers = [1, 2, 3, 4] +let filteredNumbers = numbers.map(function(num, index) { + if (index < 3) { + return num + } +}) +// index goes from 0, so the filterNumbers are 1,2,3 and undefined. +// filteredNumbers is [1, 2, 3, undefined] +// numbers is still [1, 2, 3, 4] + +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.map")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Map")}} object</li> + <li>{{jsxref("Array.from()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..440ea3e6ee --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,96 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - JavaScript + - Lista + - Prototipo + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>pop()</strong></code> remove o último elemento de um array e retorna esse elemento. Este método altera o tamanho do array.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-pop.html")}}</div> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><var>arr</var>.pop()</pre> + +<h3 id="Valor_retornado">Valor retornado</h3> + +<p>O elemento removido do array; {{jsxref("undefined")}} se o array estiver vazio.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>pop</code> remove o último elemento de um array e retorna esse elemento para a função que o chamou.</p> + +<p><code>pop</code> é um método intencionalmente genérico; este método pode ser {{jsxref("Function.call", "called", "", 1)}} ou {{jsxref("Function.apply", "applied", "", 1)}} para objectos parecidos com arrays. Objectos que não contenham a propriedade <code>length</code> (tamanho) que reflete o último elemento numa lista de consecutivas propriedades numéricas zero-based, pode não se comportar de maneira significativa.</p> + +<p><code><font face="Open Sans, arial, x-locale-body, sans-serif"><span style="background-color: #ffffff;">Se o método </span></font>pop()</code> for chamado num array vazio este retorna {{jsxref("undefined")}}.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Remover_o_último_elemento_de_um_array">Remover o último elemento de um array</h3> + +<p>O seguinte exemplo cria um array <font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: rgba(220, 220, 220, 0.5);">peixes</span></font> que contêm quatro elementos, e depois remove o último elemento.</p> + +<pre class="brush: js">var peixes = ['anjo', 'palhaço', 'mandarim', 'esturjão']; + +var popped = peixes.pop(); + +console.log(peixes); // ['anjo', 'palhaço', 'mandarim'] + +console.log(popped); // 'esturjão'</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definição inicial. Implementada no JavaScript 1.2.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Array.pop")}}</p> +</div> + +<h2 id="Ver_também">Ver também </h2> + +<ul> + <li>{{jsxref("Array.prototype.push()")}}</li> + <li>{{jsxref("Array.prototype.shift()")}}</li> + <li>{{jsxref("Array.prototype.unshift()")}}</li> + <li>{{jsxref("Array.prototype.concat()")}}</li> + <li>{{jsxref("Array.prototype.splice()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..a442018c61 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,133 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>reverse()</strong></code> inverte um vector (<code>Array</code>). O primeiro elemento torna-se o último, e o último elemento torna-se o primeiro.</p> + +<pre class="brush: js">var a = ['um', 'dois', 'três']; +a.reverse(); + +console.log(a); // ['três', 'dois', 'um'] +</pre> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><var>a</var>.reverse()</pre> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>O vector (<code>Array</code>) invertido.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>reverse</code> transpõe os elementos do vector que o chamou, mudando o vector, e devolvendo uma referência para o vector.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Invertendo_os_elementos_num_vector">Invertendo os elementos num vector</h3> + +<p>O exemplo que se segue cria um vector <code>a</code>, que contém três elementos, e depois o inverte. A chamada a <code>reverse()</code> devolve uma referência para o vector invertido <code>a</code>.</p> + +<pre class="brush: js">var a = ['um', 'dois', 'três']; +var invertido = a.reverse(); + +console.log(a); // ['três', 'dois', 'um'] +console.log(invertido); // ['três', 'dois', 'um'] +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Edge</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("1.0")}}</td> + <td>{{CompatGeckoDesktop("1.7")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatIE("5.5")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Array.prototype.join()")}}</li> + <li>{{jsxref("Array.prototype.sort()")}}</li> + <li>{{jsxref("TypedArray.prototype.reverse()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html b/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..48820a1ff7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,154 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - Array + - JavaScript + - Prototipo + - Referencia + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>slice()</strong></code> devolve uma cópia rasa (é feita uma cópia dos <em>pointers</em> se for um objeto) de uma parte de uma matriz num novo objeto de <code>array</code> selecionado do <code>start</code> (início incluído) ao <code>end</code> (fim excluído) onde o <code>start</code> e o <code>end</code> representam o índice de itens dessa matriz. A matriz original não é modificada.</p> + +<div>{{EmbedInteractiveExample("pages/js/array-slice.html")}}</div> + +<p class="hidden">The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>arr</var>.slice([<var>start</var>[, <var>end</var>]]) +</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code><var>start</var></code> {{optional_inline}}</dt> + <dd>Indice de base zero, onde coméça a cópia.</dd> + <dd>Um índice negativo pode ser utilizado, indicando um intervalo a partir do fim da sequência. <code>slice(-2)</code> extrai os dois últimos elementos da sequência.</dd> + <dd>Se <code><var>start</var></code> é undefined, <code>slice</code> coméça a partir do indice <code>0</code>.</dd> + <dd>Se <code><var>start</var></code> é maior que o último índice da sequência, uma matriz vazia é devolvida.</dd> + <dt><code><var>end</var></code> {{optional_inline}}</dt> + <dd>Índice antes do qual se deve terminar a extração. <code>slice</code> extrai até o valor de indice <code>end</code>, mas sem incluir <code>end</code>. Por exemplo, <code>slice(1,4)</code> extrai do segundo até ao quarto elemento (elementos indexados 1, 2, e 3).</dd> + <dd>Pode ser utilizado um índice negativo, indicando o último índice a partir do fim da sequência. <code>slice(2,-1)</code> extrai do terceiro até ao penúltimo elemento na sequência.</dd> + <dd>Se <code>end</code> é omisso, <code>slice</code> extrai todos os elementos até ao fim da sequência (<code>arr.length</code>).</dd> + <dd>Se <code>end</code> é maior que o comprimento da sequência, <code>slice</code> extrai todos os elementos até ao fim da sequência (<code>arr.length</code>).</dd> +</dl> + +<h3 id="Resultado">Resultado</h3> + +<p>Uma matriz nova contendo os elementos extraídos.</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>slice</code> não altera a matriz original. Devolve uma cópia rasa dos elementos da matriz original. Os elementos da matriz original são copiados para a matriz devolvida como se segue:</p> + +<ul> + <li>Para referências de objectos (e não o objecto real), <code>slice</code> copia as referências de objectos para a nova matriz. Tanto o original como a nova matriz referem-se ao mesmo objecto. Se um objecto referenciado mudar, as mudanças são visíveis tanto para a nova matriz como para a original.</li> + <li>Para strings, números e booleanos (não {{jsxref("String")}}, {{jsxref("Number")}} e {{jsxref("Booleano")}} objetos), <code>slice</code> copia os valores para a nova matriz. Alterações à string, número, ou booleano numa matriz não afetam a outra matriz.</li> +</ul> + +<p>Se um novo elemento é adicionado a qualquer das matrizes, a outra matriz não é afetada.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Devolver_uma_porção_duma_matriz">Devolver uma porção duma matriz</h3> + +<pre class="brush: js notranslate">let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +let citrus = fruits.slice(1, 3) + +// fruits contêm ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] +// citrus contêm ['Orange','Lemon'] +</pre> + +<h3 id="Usar_slice">Usar <code>slice</code></h3> + +<p>No seguinte exemplo, <code>slice</code> cria uma <em>array</em> (matriz), <code>newCar</code>, a partir de <code>myCar</code>. Ambos incluem uma referência ao objeto <code>myHonda</code>. Quando a propriedade <em>color</em> (cor) de <code>myHonda</code> é mudada para <em>purple</em> (roxo), ambas matrizes refletem a alteração.</p> + +<pre class="brush: js notranslate">// Usando slice, cria newCar a partir de myCar. +let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } } +let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'] +let newCar = myCar.slice(0, 2) + +// Imprime os valors de myCar, newCar, a propriadade +// color de myHonda em ambas arrays. +console.log('myCar = ' + JSON.stringify(myCar)) +console.log('newCar = ' + JSON.stringify(newCar)) +console.log('myCar[0].color = ' + myCar[0].color) +console.log('newCar[0].color = ' + newCar[0].color) + +// Mude a propriadade color de myHonda. +myHonda.color = 'purple' +console.log('A nova cor de my Honda é ' + myHonda.color) + +// Imprime a propriadade color de myHonda em ambas arrays. +console.log('myCar[0].color = ' + myCar[0].color) +console.log('newCar[0].color = ' + newCar[0].color) +</pre> + +<p>Este <em>script</em> imprime:</p> + +<pre class="notranslate">myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, + 'cherry condition', 'purchased 1997'] +newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] +myCar[0].color = red +newCar[0].color = red +A nova cor de my Honda é purple +myCar[0].color = purple +newCar[0].color = purple +</pre> + +<h3 id="Objetos_parecidos_com_Array">Objetos parecidos com Array</h3> + +<p>O método <code>slice</code> tembém pode ser chamado para converter objetos / coleções do estilo matriz para um objeto <code>Array</code>. É só preciso {{jsxref("Function.prototype.bind", "<em>bind</em>")}} o método ao objeto. Os {{jsxref("Functions/arguments", "argumentos")}} dentro da função são um exemplo de um "objeto de estilo matriz".</p> + +<pre class="brush: js notranslate">function list() { + return Array.prototype.slice.call(arguments) +} + +let list1 = list(1, 2, 3) // [1, 2, 3] +</pre> + +<p><em>Binding</em> pode ser feito com o método {{jsxref("Function.prototype.call", "call()")}} de {{jsxref("Function.prototype")}} e também pode ser simplificado a usar <code>[].slice.call(arguments)</code> invés de <code>Array.prototype.slice.call</code>.</p> + +<p>Pode ser simplificado a usar {{jsxref("Function.prototype.bind", "bind")}}.</p> + +<pre class="brush: js notranslate">let unboundSlice = Array.prototype.slice +let slice = Function.prototype.call.bind(unboundSlice) + +function list() { + return slice(arguments) +} + +let list1 = list(1, 2, 3) // [1, 2, 3]</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("javascript.builtins.Array.slice")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Array.prototype.splice()")}}</li> + <li>{{jsxref("Function.prototype.call()")}}</li> + <li>{{jsxref("Function.prototype.bind()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html b/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..c612f44b26 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,219 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +<div>{{JSRef}}</div> + +<div><strong><code>ArrayBuffer </code></strong>é um objeto utilizado para representar um buffer de dados em binário de tamanho pré-definido. Não é possivel manipular o conteudo do buffer diretamente; em vez disso, tem de se criar um dos <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">typed array objects</a> ou um objeto {{jsxref("DataView")}} que representa um buffer num formato especifico, e usa-o para ler e escrever o conteudo do buffer. </div> + +<div> </div> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">new ArrayBuffer(length) +</pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>length</code></dt> + <dd>O tamanho, em bytes, do array buffer que se pretende criar.</dd> +</dl> + +<h3 id="Retorno">Retorno</h3> + +<p> Um novo objecto do tipo <code>ArrayBuffer</code> do tamanho especificado. O respetivo conteudo é inicializado a 0.</p> + +<h3 id="Excepções">Excepções</h3> + +<p>A {{jsxref("RangeError")}} é lançada caso o tamanho (<code>length) </code>é maior do que<code> </code>{{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) ou caso seja negativo.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O construtor de <code>ArrayBuffer</code> cria um novo objeto do tipo <code>ArrayBuffer</code> com o tamanho especificado em bytes.</p> + +<h3 id="Obter_um_array_buffer_a_partir_de_dados_existentes">Obter um array buffer a partir de dados existentes</h3> + +<ul> + <li><a href="/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Appendix.3A_Decode_a_Base64_string_to_Uint8Array_or_ArrayBuffer">From a Base64 string</a></li> + <li><a href="/en-US/docs/Web/API/FileReader#readAsArrayBuffer()">From a local file</a></li> +</ul> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code>ArrayBuffer.length</code></dt> + <dd>Propriedade length do construtor de <code>ArrayBuffer </code>cujo valor é 1.</dd> + <dt>{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}</dt> + <dd>A função do contrutor que é usado para criar objetos derivados.</dd> + <dt>{{jsxref("ArrayBuffer.prototype")}}</dt> + <dd>Permite adicionar novas propriedades a todos os objetos do tipo <code>ArrayBuffer.</code></dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}</dt> + <dd>Devolve <code>true </code>caso <code>arg </code>é um tipo de representação do ArrayBuffer, como <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray">typed array objects</a> ou {{jsxref("DataView")}}. Devolve <code>false </code>caso contrário</dd> + <dt>{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}</dt> + <dd>Devolve um novo objeto <code>ArrayBuffer </code>cujo conteúdo é obtido do <code>oldBuffer </code>e ou é truncado ou preenchido a zeros pelo <code> newByteLength.</code></dd> +</dl> + +<h2 id="Instâncias_ArrayBuffer">Instâncias ArrayBuffer</h2> + +<p>Todas as instâncias de <code>ArrayBuffer</code> herdam de {{jsxref("ArrayBuffer.prototype")}}.</p> + +<h3 id="Propriedades_2">Propriedades</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Properties')}}</p> + +<h3 id="Métodos_2">Métodos</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype','Methods')}}</p> + +<dl> + <dt>{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}</dt> + <dd>Tem a mesma funcionalidade que {{jsxref("ArrayBuffer.prototype.slice()")}}.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<p>Neste exemplo, criamos um buffer de 8 bytes com representação {{jsxref("Global_Objects/Int32Array", "Int32Array")}} a referênciar o buffer:</p> + +<pre class="brush: js">var buffer = new ArrayBuffer(8); +var view = new Int32Array(buffer);</pre> + +<h2 id="Especificação">Especificação</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Status</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('Typed Array')}}</td> + <td>{{Spec2('Typed Array')}}</td> + <td>Substituido por ECMAScript 6.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> + <p>Definição inicial no stardard da ECMA. Especificar que <code>new </code>era necessário.</p> + </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_nos_navegadores">Compatibilidade nos navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>7.0</td> + <td>{{CompatGeckoDesktop("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>5.1</td> + </tr> + <tr> + <td><code>ArrayBuffer()</code> without <code>new</code> throws</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ArrayBuffer.slice()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}} {{CompatGeckoDesktop("53")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>4.0</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("2")}}</td> + <td>10</td> + <td>11.6</td> + <td>4.2</td> + </tr> + <tr> + <td><code>ArrayBuffer()</code> without <code>new</code> throws</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("44")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td><code>ArrayBuffer.slice()</code> {{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<br> + {{CompatNo}} {{CompatGeckoMobile("53")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Notas_de_compatibilidade">Notas de compatibilidade</h2> + +<p>Com ECMAScript 2015, construtores de <code>ArrayBuffer </code>são obrigados a usar o operador<code> </code>{{jsxref("Operators/new", "new")}}. Daqui adiante ao invocar <code>ArrayBuffer </code>como uma função sem<code> new </code>irá lançar uma exceção {{jsxref("TypeError")}}.</p> + +<pre class="brush: js example-bad">var dv = ArrayBuffer(10); +// TypeError: calling a builtin ArrayBuffer constructor +// without new is forbidden</pre> + +<pre class="brush: js example-good">var dv = new ArrayBuffer(10);</pre> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">JavaScript typed arrays</a></li> + <li>{{jsxref("SharedArrayBuffer")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html new file mode 100644 index 0000000000..4e454bacd9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html @@ -0,0 +1,124 @@ +--- +title: AsyncFunction +slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction +translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction +--- +<div>{{JSRef}}</div> + +<div>O constructor da função <strong>Async</strong> cria um novo objecto {{jsxref("Statements/async_function", "async function")}}. Em Javascript todas as funções asíncronas são na verdade objectos <code>AsyncFunction.</code></div> + +<p> </p> + +<p>Note-se que <code>AsyncFunction</code> não é um objecto global. Pode ser obtido da seguinte forma.</p> + +<pre class="brush: js">Object.getPrototypeOf(async function(){}).constructor +</pre> + +<h2 id="Síntaxe">Síntaxe</h2> + +<pre class="syntaxbox">new AsyncFunction([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Nomes usados pela função como nomes formais de argumentos . Cada um dos argumentos tem que ser uma <em>string</em> que corresponde a um identificador válido JavaScript ou uma lista separada por vírgulas; por exemplo "<code>x</code>", "<code>theValue</code>", ou "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>Uma <em>string</em> com os termos JavaScript que fazem parte da definição da função.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Os objectos {{jsxref("Statements/async_function", "async function")}} criados com o <em>constructor</em> <code>AsyncFunction</code> passam por um <em>parsing</em> quando as funções são criadas. Isto é menos eficiente que declarar uma função asíncrona com {{jsxref("Statements/async_function", "async function expression")}} e chamá-la no código porque dessa forma a função passa pelo <em>parsing</em> ao mesmo tempo que o resto do código.</p> + +<p>Todos os argumentos passados à função são tratados como os nomes dos identificadores dos parâmetros na função a ser criada, na ordem que são declarados.</p> + +<div class="note"> +<p><strong>Nota:</strong> {{jsxref("Statements/async_function", "async functions")}} criado com o <em>constructor</em> <code>AsyncFunction</code> não estão encapsulados ao contexto da sua criação, são sempre criados no âmbito global.</p> + +<p>Ao correr, podem aceder às suas prórpias variáveis e às variáveis globais, no entanto não conseguem aceder às que estão no contexto donde o constructor <code>AsyncFunction</code> foi chamado. Isto é diferente de chamar {{jsxref("Global_Objects/eval", "eval")}} com código para uma função asíncrona.</p> +</div> + +<p>A invocação do constructor <code>AsyncFunction</code> como uma função, i.e. sem usar o operador <code>new</code> tem o mesmo efeito que invocá-lo como <em>constructor</em>.</p> + +<p>Invoking the <code>AsyncFunction</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code><strong>AsyncFunction.length</strong></code></dt> + <dd>A propriedade comprimento do <em>constructor</em> do <code>AsyncFunction</code>, cujo valor é 1.</dd> + <dt>{{jsxref("AsyncFunction.prototype")}}</dt> + <dd>Permite adicionar propriedades a todos os objectos que são funções asíncronas.</dd> +</dl> + +<h2 id="AsyncFunction_prototype_object"><code>AsyncFunction</code> prototype object</h2> + +<h3 id="Propriedades_2">Propriedades</h3> + +<div>{{page('/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype', 'Properties')}}</div> + +<h2 id="Instâncias_de_AsyncFunction">Instâncias de <code>AsyncFunction</code></h2> + +<p>As instâncias de <code>AsyncFunction</code> herdam métodos e propriedades do {{jsxref("AsyncFunction.prototype")}}. Tal como com qualquer <em>constructor</em> pode-se mudar o <em>prototype object</em> para aplicar mudanças a todos as instâncias de <code>AsyncFunction</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Exemplo_de_criação_de_uma_função_async_a_partir_de_um_constructor_AsyncFunction">Exemplo de criação de uma função <em>async</em> a partir de um <em>constructor</em> <code>AsyncFunction</code></h3> + +<pre class="brush: js">function resolveAfter2Seconds(x) { + return new Promise(resolve => { + setTimeout(() => { + resolve(x); + }, 2000); + }); +} + +var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor + +var a = new AsyncFunction('a', + 'b', + 'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);'); + +a(10, 20).then(v => { + console.log(v); // prints 30 after 4 seconds +}); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-objects', 'AsyncFunction object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definição inicial em ES2017.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegadores">Compatibilidade de navegadores</h2> + +<div> + + +<p>{{Compat("javascript.builtins.AsyncFunction")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/async_function", "async function function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> + <li>{{jsxref("Global_Objects/Function", "Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope", "", 1)}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html new file mode 100644 index 0000000000..8a085d6986 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html @@ -0,0 +1,55 @@ +--- +title: AsyncFunction.prototype +slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype +--- +<div>{{JSRef}}</div> + +<p>A propriedade <code><strong>AsyncFunction.prototype</strong></code> representa o objecto <em>prototype</em> {{jsxref("AsyncFunction")}}.</p> + +<h2 id="Description">Description</h2> + +<p>Os objectos {{jsxref("AsyncFunction")}} são herdados de <code>AsyncFunction.prototype</code> e não podem ser modificados.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code><strong>AsyncFunction.constructor</strong></code></dt> + <dd>O valor inicial é {{jsxref("AsyncFunction")}}.</dd> + <dt><code><strong>AsyncFunction.prototype[@@toStringTag]</strong></code></dt> + <dd>Retorna "AsyncFunction".</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-async-function-constructor-prototype', 'AsyncFunction.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Definição inicial ES2017.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_entre_navegadores">Compatibilidade entre navegadores</h2> + +<div> + + +<p>{{Compat("javascript.builtins.AsyncFunction.prototype")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("AsyncFunction")}}</li> + <li>{{jsxref("Function")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/boolean/index.html b/files/pt-pt/web/javascript/reference/global_objects/boolean/index.html new file mode 100644 index 0000000000..e8482a2c0e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/boolean/index.html @@ -0,0 +1,156 @@ +--- +title: Booliano +slug: Web/JavaScript/Reference/Global_Objects/Boolean +tags: + - Boolean + - Booliano + - Constructor + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +<div>{{JSRef}}</div> + +<p>O objeto <strong><code>Boolean</code></strong> é um <em>wrapper</em> objeto para um valor booliano.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">new Boolean([<var>value</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><em><code>value</code></em></dt> + <dd>Opcional. O valor incial do objeto <em><code>Boolean</code></em>.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>The value passed as the first parameter is converted to a boolean value, if necessary. If the value is omitted or is <code>0</code>, <code>-0</code>, {{jsxref("null")}}, <code>false</code>, {{jsxref("NaN")}}, {{jsxref("undefined")}}, or the empty string (<code>""</code>), the object has an initial value of <code>false</code>. If the DOM object {{domxref("document.all")}} is passed as a parameter, the new boolean object also has an initial value of <code>false</code>. All other values, including any object or the string <code>"false"</code>, create an object with an initial value of <code>true</code>.</p> + +<p>Do not confuse the primitive <code>Boolean</code> values <code>true</code> and <code>false</code> with the <code>true</code> and <code>false</code> values of the <code>Boolean</code> object.</p> + +<p>Any object of which the value is not {{jsxref("undefined")}} or {{jsxref("null")}}, including a <code>Boolean</code> object whose value is <code>false</code>, evaluates to <code>true</code> when passed to a conditional statement. For example, the condition in the following {{jsxref("Statements/if...else", "if")}} statement evaluates to <code>true</code>:</p> + +<pre class="brush: js">var x = new Boolean(false); +if (x) { + // this code is executed +} +</pre> + +<p>This behavior does not apply to <code>Boolean</code> primitives. For example, the condition in the following {{jsxref("Statements/if...else", "if")}} statement evaluates to <code>false</code>:</p> + +<pre class="brush: js">var x = false; +if (x) { + // this code is not executed +} +</pre> + +<p>Do not use a <code>Boolean</code> object to convert a non-boolean value to a boolean value. Instead, use <code>Boolean</code> as a function to perform this task:</p> + +<pre class="brush: js">var x = Boolean(expression); // preferred +var x = new Boolean(expression); // don't use +</pre> + +<p>If you specify any object, including a <code>Boolean</code> object whose value is <code>false</code>, as the initial value of a <code>Boolean</code> object, the new <code>Boolean</code> object has a value of <code>true</code>.</p> + +<pre class="brush: js">var myFalse = Boolean(false); // initial value of false +var g = Boolean(myFalse); // initial value of true +var myString = new String('Hello'); // string object +var s = Boolean(myString); // initial value of true +</pre> + +<p>Do not use a <code>Boolean</code> object in place of a <code>Boolean</code> primitive.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code>Boolean.length</code></dt> + <dd>Length property whose value is 1.</dd> + <dt>{{jsxref("Boolean.prototype")}}</dt> + <dd>Represents the prototype for the <code>Boolean</code> constructor.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<p>While the global <code>Boolean</code> object contains no methods of its own, it does inherit some methods through the prototype chain:</p> + +<h2 id="Instâncias_Boolean">Instâncias <em><code>Boolean</code></em></h2> + +<p>All <code>Boolean</code> instances inherit from {{jsxref("Boolean.prototype")}}. As with all constructors, the prototype object dictates instances' inherited properties and methods.</p> + +<h3 id="Propridades">Propridades</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Properties')}}</div> + +<h3 id="Métodos_2">Métodos</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Methods')}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Criar_objetos_Boolean_com_um_valor_inicial_de_false">Criar objetos <em><code>Boolean</code> </em>com um valor inicial de <em><code>false</code></em></h3> + +<pre class="brush: js">var bNoParam = Boolean(); +var bZero = Boolean(0); +var bNull = Boolean(null); +var bEmptyString = Boolean(''); +var bfalse = Boolean(false); +</pre> + +<h3 id="Criar_objetos_Boolean_com_um_valor_inicial_de_verdadeiro">Criar objetos <em><code>Boolean</code> </em>com um valor inicial de <em><code>verdadeiro</code></em></h3> + +<pre class="brush: js">var btrue = Boolean(true); +var btrueString = Boolean('true'); +var bfalseString = Boolean('false'); +var bSuLin = Boolean('Su Lin'); +var bArrayProto = Boolean([]); +var bObjProto = Boolean({}); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Boolean")}}</p> +</div> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>{{jsxref("Boolean.prototype")}}</li> + <li>{{Glossary("Booliano")}}</li> + <li><a href="https://pt.wikipedia.org/wiki/Booleano">Tipo de dados Booliano (Wikipedia)</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html b/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html new file mode 100644 index 0000000000..5f8c84ca8e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html @@ -0,0 +1,152 @@ +--- +title: encodeURI() +slug: Web/JavaScript/Reference/Global_Objects/encodeURI +translation_of: Web/JavaScript/Reference/Global_Objects/encodeURI +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>O método <code><strong>encodeURI()</strong></code> codifica um Uniform Resource Identifier (URI) substituindo cada instancia de determinados caracteres por um, dois, três, ou quatro sequências de escape que representem a codificação UTF-8 do caracter (apenas serão quatro sequências de caracteres de escape para caracteres compostos por dois caracteres de "substituição").</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>encodeURI(<em>URI</em>)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>URI</code></dt> + <dd>Um Uniform Resource Identifier completo.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Assumindo que o URI é um URI completo, não serão codificados caracteres reservados que tenham significado especial no URI.</p> + +<p><code>encodeURI</code> substitui todos os caracteres <strong>excepto</strong> as seguintes sequências de escape UTF-8:</p> + +<table class="standard-table"> + <tbody> + <tr> + <td class="header">Tipo</td> + <td class="header">Incluído</td> + </tr> + <tr> + <td>Caracteres reservados</td> + <td><code>;</code> <code>,</code> <code>/</code> <code>?</code> <code>:</code> <code>@</code> <code>&</code> <code>=</code> <code>+</code> <code>$</code></td> + </tr> + <tr> + <td>Caracteres excluídos</td> + <td>alfabéticos, dígitos decimais , <code>-</code> <code>_</code> <code>.</code> <code>!</code> <code>~</code> <code>*</code> <code>'</code> <code>(</code> <code>)</code></td> + </tr> + <tr> + <td>Ponto</td> + <td><code>#</code></td> + </tr> + </tbody> +</table> + +<p>Note-se que o método <code>encodeURI</code> <em>não consegue</em> criar correctamente os pedidos HTTP GET e POST, o mesmo aplica-se para XMLHTTPRequests, porque os caracteres "&", "+", e "=" não são codificados, por se tratarem de caracteres especiais nos pedidos GET e POST. {{jsxref("encodeURIComponent")}}, no entanto, codifica estes caracteres.</p> + +<p>Note-se que será lançado um {{jsxref("URIError")}} caso se tente codificar um substituto que não faça parte de um par superior-inferior, p.ex.,</p> + +<pre class="brush: js">// par superior-inferior ok +console.log(encodeURI('\uD800\uDFFF')); + +// substituição única de par superior lança "URIError: malformed URI sequence" +console.log(encodeURI('\uD800')); + +// substituição única de par inferior lança "URIError: malformed URI sequence" +console.log(encodeURI('\uDFFF')); </pre> + +<p>Note-se também que caso se pretenda seguir a mais recente norma para URLs <a href="http://tools.ietf.org/html/rfc3986">RFC3986</a>, que torna os parênteses rectos reservados (para IPv6) e, por consequência, não será codificado quando fizer parte de um URL (como um host), o seguinte exemplo de código pode ajudar:</p> + +<pre class="brush: js">function fixedEncodeURI (str) { + return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.1.3.3', 'encodeURI')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-encodeuri-uri', 'encodeURI')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_com_navegador">Compatibilidade com navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("decodeURI")}}</li> + <li>{{jsxref("encodeURIComponent")}}</li> + <li>{{jsxref("decodeURIComponent")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html b/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html new file mode 100644 index 0000000000..4c9bf9e96e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html @@ -0,0 +1,88 @@ +--- +title: Function.arguments +slug: Web/JavaScript/Reference/Global_Objects/Function/arguments +translation_of: Web/JavaScript/Reference/Global_Objects/Function/arguments +--- +<div>{{JSRef}} {{deprecated_header}}</div> + +<div>A propriedade <strong><code><em>function.arguments</em></code></strong> refere-se a um objecto com aspecto de <em>array</em> que corresponde aos argumentos da função. Ao invés disso, use a variável {{jsxref("Functions/arguments", "arguments")}}. Esta propriedade é proibida no modo <em>strict</em> devido ao <em><a href="http://www.ecma-international.org/ecma-262/6.0/#sec-addrestrictedfunctionproperties">tail call optimization</a></em>.</div> + +<h2 id="Descrição">Descrição</h2> + +<p>A síntaxe <code>function.arguments</code> está obsoleta. A forma recomendade de aceder ao objecto {{jsxref("Functions/arguments", "arguments")}} disponível nas função é usar simplesment a variável {{jsxref("Functions/arguments", "arguments")}}.</p> + +<p>No caso de recursão isto é, se uma funão <code>f</code> aparece várias vezes na <em>stack, </em>o valor de <code>f.arguments</code> representa os argumentos correspondentes à mais recente chamada da função.</p> + +<p>O valor da propriedade <code>arguments</code> é tipicamente <em>null</em> se não há nenuma invocação da função a acontecer, ou seja, a função foi chamada mas ainda não retornou.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js">function f(n) { g(n - 1); } + +function g(n) { + console.log('antes: ' + g.arguments[0]); + if (n > 0) { f(n); } + console.log('depois: ' + g.arguments[0]); +} + +f(2); + +console.log('retornado: ' + g.arguments); + +// Output + +// antes: 1 +// antes: 0 +// depois: 0 +// depois: 1 +// retornado: null +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td> + <p>Definição inicial. Implementado em JavaScript 1.0. Tornado obsoleto a favor de {{jsxref("Functions/arguments", "arguments")}} em ES3.</p> + </td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-10.6', 'arguments object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Objecto {{jsxref("Functions/arguments", "arguments")}}</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-arguments-object', 'arguments object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Objecto {{jsxref("Functions/arguments", "arguments")}}</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arguments-object', 'arguments object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Objecto {{jsxref("Functions/arguments", "arguments")}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_navegadores">Compatibilidade navegadores</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Function.arguments")}}</p> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>Objecto {{jsxref("Functions/arguments", "arguments")}}</li> + <li>{{jsxref("Functions", "Functions and function scope", "", 1)}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html b/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..fa3faee130 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,164 @@ +--- +title: Function.prototype.call() +slug: Web/JavaScript/Reference/Global_Objects/Function/call +tags: + - Function + - JavaScript + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>call()</strong></code> realiza a chamada de uma função com o parâmetros <code>this</code> além de outros parâmetros fornecidos individualmente.</p> + +<div>{{EmbedInteractiveExample("pages/js/function-call.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><var>func</var>.call([<var>thisArg</var>[, <var>arg1</var>, <var>arg2</var>, ...<var>argN</var>]])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><em><code>thisArg</code></em> {{optional_inline}}</dt> + <dd>O valor de <code>this</code> fornecido ao chamar <code><em>func</em></code>.</dd> +</dl> + +<div class="blockIndicator note"> +<p>Aviso: Em certos casos, <em><code>thisArg</code></em> pode não ser o valor que o método vê.</p> + +<p>Se o método for uma função em {{jsxref("Strict_mode", "non-strict mode", "", 1)}}, {{jsxref("Global_Objects/null", "null")}} e {{jsxref("Global_Objects/undefined", "undefined")}} são substituídos pelo objeto global, e valores primitivos são convertidos em objetos.</p> +</div> + +<dl> + <dt><em><code>arg1, arg2, ...argN</code></em> {{optional_inline}}</dt> + <dd>Parâmetros para a função.</dd> +</dl> + +<h3 id="Resultado">Resultado</h3> + +<p>O resultado ao chamar a função em questão com os parâmetros <code>this</code> e os outros argumentos especificados.</p> + +<h2 id="Descrição">Descrição</h2> + +<p><code>call()</code> permite uma função / método pertencendo a um objeto, ser atribuída a outro objeto e ser chamada desse mesmo.</p> + +<p><code>call()</code> fornece um novo valor para <code>this</code> à função / método. Com <code>call()</code>, pode escrever um método uma vez, e depois herdar o método noutro objeto, sem ter de rescrever a função para o novo objeto.</p> + +<div class="blockIndicator note"> +<p>Nota: Apesar de a sintaxe da função ser quase idêntica à da {{jsxref("Function.prototype.apply", "apply()")}}, a principal diferença é que <code>call()</code> aceita uma <strong>lista de argumentos</strong> (<code>arg1, arg2, ...argN</code>), enquanto <code>apply()</code> aceita <strong>uma matriz de argumentos</strong> (<code>[arg1, arg2, ...argN]</code>).</p> +</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usar_call_para_encadear_construtores_dum_objeto">Usar <code>call</code> para encadear construtores dum objeto</h3> + +<p>É possível utilizar <code>call</code> para encadear construtores para um objeto (como em Java).</p> + +<p>No exemplo abaixo, o construtor para o objeto <code>Product</code> é definido com dois parâmetros: <code>name</code> e <code>price</code>.</p> + +<p>Duas outras funções, <code>Food</code> e <code>Toy</code>, invocam <code>Product</code> passando os parâmetros <code>this</code><font face="Open Sans, arial, sans-serif">, </font><code>name</code> e <code>price</code>. As funções <code>Food</code> e <code>Toy</code> também definem a propriadade <code>category</code>.</p> + +<pre class="brush: js notranslate">function Product(name, price) { + this.name = name; + this.price = price; +} + +function Food(name, price) { + Product.call(this, name, price); + this.category = 'food'; +} + +function Toy(name, price) { + Product.call(this, name, price); + this.category = 'toy'; +} + +const cheese = new Food('feta', 5); +const fun = new Toy('robot', 40);</pre> + +<h3 id="Usar_call_para_invocar_uma_função_anónima">Usar <code>call</code> para invocar uma função anónima</h3> + +<p>Neste exemplo, criamos uma função anónima e utilizamos <code>call</code> para invocá-la em cada objeto na matriz.</p> + +<p>O principal objetivo da função anónima é inserir a função <code>print</code> em cada objeto. A função <code>print</code> imprimir o índice do objeto na matriz em que se encontra.</p> + +<div class="blockIndicator note"> +<p>Passar o objeto desta forma (como <code>this</code>) não é necessário, mas foi feito de forma a exemplificar a função.</p> +</div> + +<pre class="brush: js notranslate">var animals = [ + { species: 'Lion', name: 'King' }, + { species: 'Whale', name: 'Fail' } +]; + +for (var i = 0; i < animals.length; i++) { + (function(i) { + this.print = function() { + console.log('#' + i + ' ' + this.species + + ': ' + this.name); + } + this.print(); + }).call(animals[i], i); +} +</pre> + +<h3 id="Usar_call_para_invocar_a_função_sem_especificar_o_primeiro_argumento">Usar <code>call</code> para invocar a função sem especificar o primeiro argumento</h3> + +<p>No exemplo abaixo, quando chamamos a função <code>display</code> sem passar o primeiro argumento. Se o primeiro argumento não é especificado, o objeto global é atribuído a <code>this</code>.<br> + </p> + +<pre class="brush: js notranslate">var sData = 'Wisen'; + +function display() { + console.log('sData value is %s ', this.sData); +} + +display.call(); // sData value is Wisen</pre> + +<div class="note"> +<p><strong>Aviso:</strong> Em "strict mode", o valor de <code>this</code> é <code>undefined</code>, exemplificado em baixo.</p> +</div> + +<pre class="brush: js notranslate">'use strict'; + +var sData = 'Wisen'; + +function display() { + console.log('sData value is %s ', this.sData); +} + +display.call(); // Cannot read the property of 'sData' of undefined</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Function.call")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Function.prototype.bind()")}}</li> + <li>{{jsxref("Function.prototype.apply()")}}</li> + <li> + <p><a href="/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript">Introduction to Object-Oriented JavaScript</a></p> + </li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/function/index.html b/files/pt-pt/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..6ebfd66c44 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,192 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - Constructor + - Function + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +<div>{{JSRef}}</div> + +<p>The <strong><code>Function</code> constructor</strong> creates a new <code>Function</code> object. In JavaScript every function is actually a <code>Function</code> object.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code>new Function ([<var>arg1</var>[, <var>arg2</var>[, ...<var>argN</var>]],] <var>functionBody</var>)</code></pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p><code>Function</code> objects created with the <code>Function</code> constructor are parsed when the function is created. This is less efficient than declaring a function with a <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> or <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> and calling it within your code, because such functions are parsed with the rest of the code.</p> + +<p>All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.</p> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Properties_and_Methods_of_Function">Properties and Methods of <code>Function</code></h2> + +<p>The global <code>Function</code> object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.</p> + +<h2 id="Function_prototype_object"><code>Function</code> prototype object</h2> + +<h3 id="Properties">Properties</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}</div> + +<h3 id="Methods">Methods</h3> + +<div>{{page('/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}</div> + +<h2 id="Function_instances"><code>Function</code> instances</h2> + +<p><code>Function</code> instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all <code>Function</code> instances.</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Specifying_arguments_with_the_Function_constructor">Specifying arguments with the <code>Function</code> constructor</h3> + +<p>The following code creates a <code>Function</code> object that takes two arguments.</p> + +<pre class="brush: js">// Example can be run directly in your JavaScript console + +// Create a function that takes two arguments and returns the sum of those arguments +var adder = new Function('a', 'b', 'return a + b'); + +// Call the function +adder(2, 6); +// > 8 +</pre> + +<p>The arguments "<code>a</code>" and "<code>b</code>" are formal argument names that are used in the function body, "<code>return a + b</code>".</p> + +<h3 id="Difference_between_Function_constructor_and_function_declaration">Difference between Function constructor and function declaration</h3> + +<p>Functions created with the <code>Function</code> constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the <code>Function</code> constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.</p> + +<pre class="brush: js">var x = 10; + +function createFunction1() { + var x = 20; + return new Function('return x;'); // this |x| refers global |x| +} + +function createFunction2() { + var x = 20; + function f() { + return x; // this |x| refers local |x| above + } + return f; +} + +var f1 = createFunction1(); +console.log(f1()); // 10 +var f2 = createFunction2(); +console.log(f2()); // 20 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.3', 'Function')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Functions", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/index.html b/files/pt-pt/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..f3850bdfd2 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/index.html @@ -0,0 +1,173 @@ +--- +title: Objetos integrados padrão +slug: Web/JavaScript/Reference/Global_Objects +tags: + - Built-in + - JavaScript + - Objects + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects +--- +<div>{{jsSidebar("Objects")}}</div> + +<h2 id="Summary" name="Summary">Resumo</h2> + +<p>Este capítulo documenta todos os objectos built-in do JavaScript standard, juntamente com os seus métodos e propriedades.</p> + +<div class="onlyinclude"> +<p>O termo "objectos globais" (ou objectos built-in standard) não é para ser confundido com <em>objecto global</em>. Aqui, os objectos globais referem-se a objectos no scope global (mas apenas se o modo strict do ECMAScript 5 não estiver a ser usado! Senão retorna <code>undefined</code>). O próprio <em>global object</em> pode ser acedido através do operador {{jsxref("Operators/this", "this")}} no scope global. Na verdade, o scope global consiste nas propriedades do objecto global (incluíndo propriedades herdadas, se alguma).</p> + +<p>Outros objectos no scope global são <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">criados através do script do utilizador</a> or fornecidos pela aplicação host. Os objectos do host disponíveis no contexto browser são documentados na <a href="/en-US/docs/Web/API/Reference">referência da API</a>. Para mais informações sobre a distinção entre <a href="/en-US/docs/DOM/DOM_Reference">DOM</a> e o núcleo do <a href="/en-US/docs/Web/JavaScript">JavaScript</a>, ver <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">exposição das tecnologias do JavaScript</a>.</p> + +<h2 id="Objetos_padrão_(por_categoria)">Objetos padrão (por categoria)</h2> + +<h3 id="Propriedades_do_valor">Propriedades do valor</h3> + +<p>Estas propriedades globais devolvem um valor simples; estas não têm propriedades ou métodos.</p> + +<ul> + <li>{{jsxref("Infinity")}}</li> + <li>{{jsxref("NaN")}}</li> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}} literal</li> +</ul> + +<h3 id="Propriedades_da_função">Propriedades da função</h3> + +<p>Estas funções globais - funções que são chamadas no mundo ao invés de um objeto - devolvem diretamente os seus resultados para o chamador.</p> + +<ul> + <li>{{jsxref("Global_Objects/eval", "eval()")}}</li> + <li>{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline()}}</li> + <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> + <li>{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}</li> + <li>{{jsxref("Global_Objects/parseInt", "parseInt()")}}</li> + <li>{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}</li> + <li>{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}</li> + <li>{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</li> + <li>{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline()}}</li> + <li>{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline()}}</li> +</ul> + +<h3 id="Objetos_fundamentais">Objetos fundamentais</h3> + +<p>Estes são os objetos básicos, fundamentais, em que todos os outros objetos são baseados. Isto inclui objetos que representam objetos gerais, funções, e erros.</p> + +<ul> + <li>{{jsxref("Object")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Boolean")}}</li> + <li>{{jsxref("Symbol")}} {{experimental_inline()}}</li> + <li>{{jsxref("Error")}}</li> + <li>{{jsxref("EvalError")}}</li> + <li>{{jsxref("InternalError")}}</li> + <li>{{jsxref("RangeError")}}</li> + <li>{{jsxref("ReferenceError")}}</li> + <li>{{jsxref("StopIteration")}}</li> + <li>{{jsxref("SyntaxError")}}</li> + <li>{{jsxref("TypeError")}}</li> + <li>{{jsxref("URIError")}}</li> +</ul> + +<h3 id="Números_e_datas">Números e datas</h3> + +<p>Objectos que lidam com números, datas e cálculos matemáticos.</p> + +<ul> + <li>{{jsxref("Number")}}</li> + <li>{{jsxref("Math")}}</li> + <li>{{jsxref("Date")}}</li> +</ul> + +<h3 id="Processamento_de_texto">Processamento de texto</h3> + +<p>Objectos para manipular texto.</p> + +<ul> + <li>{{jsxref("String")}}</li> + <li>{{jsxref("RegExp")}}</li> +</ul> + +<h3 id="Coleções_indexadas">Coleções indexadas</h3> + +<p>Coleções ordenadas por um indíce. Objectos do tipo array.</p> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Int8Array")}}</li> + <li>{{jsxref("Uint8Array")}}</li> + <li>{{jsxref("Uint8ClampedArray")}}</li> + <li>{{jsxref("Int16Array")}}</li> + <li>{{jsxref("Uint16Array")}}</li> + <li>{{jsxref("Int32Array")}}</li> + <li>{{jsxref("Uint32Array")}}</li> + <li>{{jsxref("Float32Array")}}</li> + <li>{{jsxref("Float64Array")}}</li> + <li>{{jsxref("ParallelArray")}} {{non-standard_inline()}}</li> +</ul> + +<h3 id="Coleções_por_chave">Coleções por chave</h3> + +<p>Coleções de objectos como chaves. Elementos iteráveis por ordem de inserção.</p> + +<ul> + <li>{{jsxref("Map")}} {{experimental_inline()}}</li> + <li>{{jsxref("Set")}} {{experimental_inline()}}</li> + <li>{{jsxref("WeakMap")}} {{experimental_inline()}}</li> + <li>{{jsxref("WeakSet")}} {{experimental_inline()}}</li> +</ul> + +<h3 id="Dados_estruturados">Dados estruturados</h3> + +<p>Buffers de dados e <strong>J</strong>ava<strong>S</strong>cript <strong>O</strong>bject <strong>N</strong>otation (JSON).</p> + +<ul> + <li>{{jsxref("ArrayBuffer")}}</li> + <li>{{jsxref("DataView")}}</li> + <li>{{jsxref("JSON")}}</li> +</ul> + +<h3 id="Objectos_de_abstração_de_controlo">Objectos de abstração de controlo</h3> + +<ul> + <li>{{jsxref("Iterator")}} {{non-standard_inline()}}</li> + <li>{{jsxref("Generator")}} {{experimental_inline()}}</li> + <li>{{jsxref("Promise")}} {{experimental_inline()}}</li> +</ul> + +<h3 id="Reflexão">Reflexão</h3> + +<ul> + <li>{{jsxref("Reflect")}} {{experimental_inline()}}</li> + <li>{{jsxref("Proxy")}} {{experimental_inline()}}</li> +</ul> + +<h3 id="Internacionalização">Internacionalização</h3> + +<p>Adições ao núcleo do ECMAScript para funcionalidades de linguagens sensíveis.</p> + +<ul> + <li>{{jsxref("Intl")}}</li> + <li>{{jsxref("Global_Objects/Collator", "Intl.Collator")}}</li> + <li>{{jsxref("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}</li> + <li>{{jsxref("Global_Objects/NumberFormat", "Intl.NumberFormat")}}</li> +</ul> + +<h3 id="Objetos_não_padrão">Objetos não padrão</h3> + +<ul> + <li>{{jsxref("Iterator")}} {{non-standard_inline}}</li> + <li>{{jsxref("ParallelArray")}} {{non-standard_inline}}</li> + <li>{{jsxref("StopIteration")}} {{non-standard_inline}}</li> +</ul> + +<h3 id="Outros">Outros</h3> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">Argumentos</a></code></li> +</ul> +</div> + +<p> </p> diff --git a/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html b/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html new file mode 100644 index 0000000000..818471e60e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,69 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +tags: + - JavaScript + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +<div>{{jsSidebar("Objects")}}</div> + +<p>A propriedade global <code><strong>Infinity</strong></code> é um valor numérico que representa o infinito.</p> + +<p>{{js_property_attributes(0,0,0)}}</p> + +<div>{{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}}</div> + +<div class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div> + +<h2 id="Descrição">Descrição</h2> + +<p><code>Infinity</code> é uma propriedade do objeto <code>global</code>. Isto é para dizer que é um variável com um escopo global.</p> + +<p>O valor inicial do <code>Infinity</code> é {{jsxref("Number.POSITIVE_INFINITY")}}. O valor <code>Infinity</code> (infinito positivo) é maior que qualquer outro número.</p> + +<p>Este valor age de form diferente do infinito matematico; veja {{jsxref("Number.POSITIVE_INFINITY")}} para mais detalhes.</p> + +<p>Como definido na especificação ECMAScript 5, <code>Infinity</code> é <em>read-only</em> (implementado em JavaScript 1.8.5 / Firefox 4).</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usar_Infinity">Usar Infinity</h3> + +<pre class="brush: js notranslate">console.log(Infinity ); /* Infinity */ +console.log(Infinity + 1 ); /* Infinity */ +console.log(Math.pow(10, 1000)); /* Infinity */ +console.log(Math.log(0) ); /* -Infinity */ +console.log(1 / Infinity ); /* 0 */ +console.log(1 / 0 ); /* Infinity */ +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("javascript.builtins.Infinity")}}</p> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Number.NEGATIVE_INFINITY")}}</li> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html b/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..c89b15567a --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,161 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +<div>{{JSRef}}</div> + +<p>A função <strong><code>Math.ceil()</code></strong> retorna um inteiro smallest (sem casas decimais) maior ou igual ao n.º passado como parâmetro. Por exemplo ao fazer Math.ceil(3.01) o valor retornado é 4, ao fazer Math.ceil(-5.01) o retorno é -5, ao fazer Math.ceil(7) o valor devolvido é 7. </p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>Math.ceil(<var>x</var>)</code></pre> + +<h3 id="Parametros">Parametros</h3> + +<dl> + <dt><code>x</code></dt> + <dd>Um número.</dd> +</dl> + +<h3 id="Valor_de_retorno">Valor de retorno</h3> + +<p>Um inteiro smallest maior ou igual ao n.º passado como parâmetro.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Como <code>ceil()</code> é um método estático de <code>Math</code>, pode sempre ser usado como <code>Math.ceil()</code>, o objeto <code>Math</code> não é um construtor. </p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Utilizando_Math.ceil">Utilizando <code>Math.ceil()</code></h3> + +<p>Seguem exemplos da utilização de <code>Math.ceil()</code>.</p> + +<pre class="brush: js">Math.ceil(.95); // 1 +Math.ceil(4); // 4 +Math.ceil(7.004); // 8 +Math.ceil(-0.95); // -0 +Math.ceil(-4); // -4 +Math.ceil(-7.004); // -7 +</pre> + +<h3 id="Ajustamento_decimal">Ajustamento decimal </h3> + +<pre class="brush: js">// Closure +(function() { + /** + * Decimal adjustment of a number. + * + * @param {String} type The type of adjustment. + * @param {Number} value The number. + * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). + * @returns {Number} The adjusted value. + */ + function decimalAdjust(type, value, exp) { + // If the exp is undefined or zero... + if (typeof exp === 'undefined' || +exp === 0) { + return Math[type](value); + } + value = +value; + exp = +exp; + // If the value is not a number or the exp is not an integer... + if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + return NaN; + } + // Shift + value = value.toString().split('e'); + value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + // Shift back + value = value.toString().split('e'); + return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); + } + + // Decimal round + if (!Math.round10) { + Math.round10 = function(value, exp) { + return decimalAdjust('round', value, exp); + }; + } + // Decimal floor + if (!Math.floor10) { + Math.floor10 = function(value, exp) { + return decimalAdjust('floor', value, exp); + }; + } + // Decimal ceil + if (!Math.ceil10) { + Math.ceil10 = function(value, exp) { + return decimalAdjust('ceil', value, exp); + }; + } +})(); + +// Round +Math.round10(55.55, -1); // 55.6 +Math.round10(55.549, -1); // 55.5 +Math.round10(55, 1); // 60 +Math.round10(54.9, 1); // 50 +Math.round10(-55.55, -1); // -55.5 +Math.round10(-55.551, -1); // -55.6 +Math.round10(-55, 1); // -50 +Math.round10(-55.1, 1); // -60 +// Floor +Math.floor10(55.59, -1); // 55.5 +Math.floor10(59, 1); // 50 +Math.floor10(-55.51, -1); // -55.6 +Math.floor10(-51, 1); // -60 +// Ceil +Math.ceil10(55.51, -1); // 55.6 +Math.ceil10(51, 1); // 60 +Math.ceil10(-55.59, -1); // -55.5 +Math.ceil10(-59, 1); // -50 +</pre> + +<h2 id="Especificações">Especificações </h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Math.ceil")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Math.abs()")}}</li> + <li>{{jsxref("Math.floor()")}}</li> + <li>{{jsxref("Math.round()")}}</li> + <li>{{jsxref("Math.sign()")}}</li> + <li>{{jsxref("Math.trunc()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/math/index.html b/files/pt-pt/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..867c783782 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,214 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +<div>{{JSRef}}</div> + +<p><strong><code>Math</code></strong> é um objecto integrado que tem propriedades e métodos correspondentes a constantes e funções matemáticas. Não é um objecto função.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Contrariamente aos outros objectos globais, <code>Math</code> não é um construtor. Todas as propriedades e métodos de <code>Math</code> são estáticas. Refere-se a constante pi com <code>Math.PI</code> e chama-se a função de seno com <code>Math.sin(x)</code>, em que x é o argumento do método. As constantes estão definidas com a precisão completa dos números reais do JavaScript.</p> + +<p>Para extender o objecto <code>Math</code>, não se usa o protótipo. Em vez disso extende-se directamente o objecto <code>Math</code>:</p> + +<p>Math.nomeProp=valorProp;</p> + +<p>Math.nomeMetodo=refMetodo;</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("Math.E")}}</dt> + <dd>Euler's constant and the base of natural logarithms, approximately 2.718.</dd> + <dt>{{jsxref("Math.LN2")}}</dt> + <dd>Natural logarithm of 2, approximately 0.693.</dd> + <dt>{{jsxref("Math.LN10")}}</dt> + <dd>Natural logarithm of 10, approximately 2.303.</dd> + <dt>{{jsxref("Math.LOG2E")}}</dt> + <dd>Base 2 logarithm of E, approximately 1.443.</dd> + <dt>{{jsxref("Math.LOG10E")}}</dt> + <dd>Base 10 logarithm of E, approximately 0.434.</dd> + <dt>{{jsxref("Math.PI")}}</dt> + <dd>Ratio of the circumference of a circle to its diameter, approximately 3.14159.</dd> + <dt>{{jsxref("Math.SQRT1_2")}}</dt> + <dd>Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.</dd> + <dt>{{jsxref("Math.SQRT2")}}</dt> + <dd>Square root of 2, approximately 1.414.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<div class="note"> +<p>Note that the trigonometric functions (<code>sin()</code>, <code>cos()</code>, <code>tan()</code>, <code>asin()</code>, <code>acos()</code>, <code>atan()</code>, <code>atan2()</code>) expect or return angles in radians. To convert radians to degrees, divide by <code>(Math.PI / 180)</code>, and multiply by this to convert the other way.</p> +</div> + +<div class="note"> +<p>Note that many math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.</p> +</div> + +<dl> + <dt>{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}</dt> + <dd>Returns the absolute value of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}</dt> + <dd>Returns the arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}</dt> + <dd>Returns the hyperbolic arccosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}</dt> + <dd>Returns the arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}</dt> + <dd>Returns the hyperbolic arcsine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}</dt> + <dd>Returns the arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}</dt> + <dd>Returns the hyperbolic arctangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}</dt> + <dd>Returns the arctangent of the quotient of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}</dt> + <dd>Returns the cube root of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}</dt> + <dd>Returns the smallest integer greater than or equal to a number.</dd> + <dt>{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}</dt> + <dd>Returns the number of leading zeroes of a 32-bit integer.</dd> + <dt>{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}</dt> + <dd>Returns the cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}</dt> + <dd>Returns the hyperbolic cosine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}</dt> + <dd>Returns E<sup>x</sup>, where <var>x</var> is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.</dd> + <dt>{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}</dt> + <dd>Returns subtracting 1 from <code>exp(x)</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}</dt> + <dd>Returns the largest integer less than or equal to a number.</dd> + <dt>{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}</dt> + <dd>Returns the nearest <a href="http://en.wikipedia.org/wiki/Single-precision_floating-point_format" title="link to the wikipedia page on single precision">single precision</a> float representation of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}</dt> + <dd>Returns the square root of the sum of squares of its arguments.</dd> + <dt>{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}</dt> + <dd>Returns the result of a 32-bit integer multiplication.</dd> + <dt>{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}</dt> + <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}</dt> + <dd>Returns the natural logarithm (log<sub>e</sub>, also ln) of <code>1 + x</code> for a number x.</dd> + <dt>{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}</dt> + <dd>Returns the base 10 logarithm of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}</dt> + <dd>Returns the base 2 logarithm of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}</dt> + <dd>Returns the largest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}</dt> + <dd>Returns the smallest of zero or more numbers.</dd> + <dt>{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}</dt> + <dd>Returns base to the exponent power, that is, <code>base<sup>exponent</sup></code>.</dd> + <dt>{{jsxref("Global_Objects/Math/random", "Math.random()")}}</dt> + <dd>Returns a pseudo-random number between 0 and 1.</dd> + <dt>{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}</dt> + <dd>Returns the value of a number rounded to the nearest integer.</dd> + <dt>{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}</dt> + <dd>Returns the sign of the x, indicating whether x is positive, negative or zero.</dd> + <dt>{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}</dt> + <dd>Returns the sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}</dt> + <dd>Returns the hyperbolic sine of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}</dt> + <dd>Returns the positive square root of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}</dt> + <dd>Returns the tangent of a number.</dd> + <dt>{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}</dt> + <dd>Returns the hyperbolic tangent of a number.</dd> + <dt><code>Math.toSource()</code> {{non-standard_inline}}</dt> + <dd>Returns the string <code>"Math"</code>.</dd> + <dt>{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}</dt> + <dd>Returns the integral part of the number x, removing any fractional digits.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.8', 'Math')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-math-object', 'Math')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..9ac8497a44 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,213 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +tags: + - JavaScript + - Number + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p>O objecto JavaScript <strong><code>Number</code></strong> é um objecto abstraído que te permite trabalhar com valores numéricos. Um objecto <code>Number</code> é criado usando o constructor <code>Number().</code></p> + +<h2 id="Constructor">Constructor</h2> + +<pre class="syntaxbox">new Number(valor);</pre> + +<h3 id="Parâmetro">Parâmetro</h3> + +<dl> + <dt><code>valor</code></dt> + <dd>O valor numérico representado pelo objecto que está a ser criado.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Os usos mais comuns para o objecto <code>Number</code> são:</p> + +<ul> + <li>Se o argumento não puder ser convertido num número, retorna {{jsxref("NaN")}}.</li> + <li>Num contexto não-constructor (isto é, sem o operador {{jsxref("Operators/new", "new")}}), <code>Number</code> pode ser usado para uma conversão de tipo.</li> +</ul> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("Number.EPSILON")}} {{experimental_inline}}</dt> + <dd>O intervalo mais pequeno entre dois números representáveis.</dd> + <dt>{{jsxref("Number.MAX_SAFE_INTEGER")}} {{experimental_inline}}</dt> + <dd>O maior inteiro bem representado em JavaScript (<code>2<sup>53</sup> - 1</code>).</dd> + <dt>{{jsxref("Number.MAX_VALUE")}}</dt> + <dd>O maior número positivo representável.</dd> + <dt>{{jsxref("Number.MIN_SAFE_INTEGER")}} {{experimental_inline}}</dt> + <dd>O menor inteiro bem representado em JavaScript (<code>-(2<sup>53</sup> - 1)</code>).</dd> + <dt>{{jsxref("Number.MIN_VALUE")}}</dt> + <dd>O menor número positivo representável - ou seja, o número positivo mais próximo de zero (sem ser o zero).</dd> + <dt>{{jsxref("Number.NaN")}}</dt> + <dd>Valor especial para representar um "não número".</dd> + <dt>{{jsxref("Number.NEGATIVE_INFINITY")}}</dt> + <dd>Valor especial para representar o infinito negativo; retornado em caso de overflow.</dd> + <dt>{{jsxref("Number.POSITIVE_INFINITY")}}</dt> + <dd>Valor especial para representar o infinito; retornado em caso de overflow.</dd> + <dt>{{jsxref("Number.prototype")}}</dt> + <dd>Permite adicionar propriedades ao objecto <code>Number</code>.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("Number.isNaN()")}} {{experimental_inline}}</dt> + <dd>Determina se o valor passado é NaN.</dd> + <dt>{{jsxref("Number.isFinite()")}} {{experimental_inline}}</dt> + <dd>Determina se o valor passado é um número finito.</dd> + <dt>{{jsxref("Number.isInteger()")}} {{experimental_inline}}</dt> + <dd>Determina se o número passado é um inteiro.</dd> + <dt>{{jsxref("Number.isSafeInteger()")}} {{experimental_inline}}</dt> + <dd>Determina se o valor passado é um inteiro bem representado (número entre <code>-(2<sup>53</sup> - 1)</code> e <code>2<sup>53</sup> - 1</code>).</dd> + <dt><s class="obsoleteElement">{{jsxref("Number.toInteger()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Usado para avaliar o valor passado e convertê-lo num inteiro (ou {{jsxref("Global_Objects/Infinity", "Infinity")}}), mas foi removido.</s></dd> + <dt>{{jsxref("Number.parseFloat()")}} {{experimental_inline}}</dt> + <dd>O valor é o mesmo que {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} de um objecto global.</dd> + <dt>{{jsxref("Number.parseInt()")}} {{experimental_inline}}</dt> + <dd>O valor é o mesmo que {{jsxref("Global_Objects/parseInt", "parseInt()")}} de um objecto global.</dd> +</dl> + +<h2 id="Instâncias_de_Number"><code>Instâncias de Number</code></h2> + +<p>Todas as instâncias de <code>Number </code>herdam de {{jsxref("Number.prototype")}}. O objecto protótipo (prototype) do constructor de <code>Number</code> pode ser modificado para afectar todas as instâncias de <code>Number</code>.</p> + +<h3 id="Métodos_2">Métodos</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/prototype', 'Methods')}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usar_o_objecto_Number_para_atribuír_valores_a_variáveis_numéricas">Usar o objecto <code>Number </code>para atribuír valores a variáveis numéricas</h3> + +<p>O seguinte exemplo usa as propriedades do objecto <code>Number</code> para atribuír valores a várias variáveis numéricas: </p> + +<pre class="brush: js">var biggestNum = Number.MAX_VALUE; +var smallestNum = Number.MIN_VALUE; +var infiniteNum = Number.POSITIVE_INFINITY; +var negInfiniteNum = Number.NEGATIVE_INFINITY; +var notANum = Number.NaN; +</pre> + +<h3 id="Limite_inteiro_para_Number"><code>Limite inteiro para Number</code></h3> + +<p>O seguinte exemplo mostra o mínimo e máximo valores inteiros que podem ser representados como um objecto <code>Number</code> (para mais detalhes, consulta o standard do ECMAScript, capítulo <em>8.5 The Number Type</em>):</p> + +<pre class="brush: js">var biggestInt = 9007199254740992; +var smallestInt = -9007199254740992; +</pre> + +<p>Ao analisar dados que foram serializados para JSON, os valores inteiros fora deste limite são expectáveis de ficar corrompidos quando o analisador de JSON os tentar converter para o tipo <code>Number</code>. Como possível alternativa, usa {{jsxref("String")}}.</p> + +<h3 id="Usar_Number_para_converter_um_objecto_Date">Usar <code>Number </code>para converter um objecto <code>Date</code></h3> + +<p>O seguinte exemplo converte o objecto {{jsxref("Date")}} num valor numérico usando <code>Number</code> como função:</p> + +<pre class="brush: js">var d = new Date('December 17, 1995 03:24:00'); +console.log(Number(d)); +</pre> + +<p>Este código imprime "819199440000".</p> + +<h3 id="Converter_strings_numéricas_para_números">Converter strings numéricas para números</h3> + +<pre class="brush: js">Number("123") // 123 +Number("") // 0 +Number("0x11") // 17 +Number("0b11") // 3 +Number("0o11") // 9 +Number("foo") // NaN +Number("100a") // NaN +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number-objects', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Adicionados novas propriedades e métodos: ({{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}})</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("NaN")}}</li> + <li>The {{jsxref("Math")}} global object</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html new file mode 100644 index 0000000000..9b70ca6a98 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html @@ -0,0 +1,126 @@ +--- +title: Number.isFinite() +slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite +tags: + - Experimental + - Finite + - JavaScript + - Method + - Método(2) + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>Number.isFinite()</code></strong> determina se o valor passado é um número finito.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>Number.isFinite(valor)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>valor</code></dt> + <dd>O valor a ser testado.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Em comparação com a função global {{jsxref("Global_Objects/isFinite", "isFinite()")}}, <strong><code>Number.isFinite()</code></strong> não converte forçosamente o parâmetro num number. Isto significa que apenas para valores do tipo number, finitos, retorna <code>true</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js">Number.isFinite(Infinity); // false +Number.isFinite(NaN); // false +Number.isFinite(-Infinity); // false + +Number.isFinite(0); // true +Number.isFinite(2e64); // true + +Number.isFinite('0'); // false, teria sido true com a função + // global isFinite('0') +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isFinite = Number.isFinite || function(value) { + return typeof value === "number" && isFinite(value); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatChrome("19")}}</td> + <td>{{CompatGeckoDesktop("16")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera("15")}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("16")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>O objecto {{jsxref("Global_Objects/Number", "Number")}} ao qual pertence.</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html new file mode 100644 index 0000000000..8c6dc79bb7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html @@ -0,0 +1,125 @@ +--- +title: Number.isInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isInteger +tags: + - Experimental + - JavaScript + - Method + - Método(2) + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isInteger +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>Number.isInteger()</code></strong> determina se o valor passado é um inteiro.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>Number.isInteger(valor)</code></pre> + +<h3 id="Parâmteros">Parâmteros</h3> + +<dl> + <dt><code>valor</code></dt> + <dd>O valor a ser testado por ser um inteiro.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Se o valor a ser testado for um inteiro, retorna <code>true</code>, senão retorna <code>false</code>. Se o valor for {{jsxref("Global_Objects/NaN", "NaN")}} ou infinito, retorna <code>false</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js">Number.isInteger(0.1); // false +Number.isInteger(1); // true +Number.isInteger(Math.PI); // false +Number.isInteger(-100000); // true +Number.isInteger(NaN); // false +Number.isInteger(0); // true +Number.isInteger("10"); // false +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isInteger = Number.isInteger || function(value) { + return typeof value === "number" && + isFinite(value) && + Math.floor(value) === value; +}; +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("16")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("16")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>O objecto {{jsxref("Global_Objects/Number", "Number")}} ao qual pertence.</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html new file mode 100644 index 0000000000..0b242adbbe --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html @@ -0,0 +1,136 @@ +--- +title: Number.isNaN() +slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN +tags: + - ECMAScript6 + - Experimental + - JavaScript + - Method + - Método(2) + - Number +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>Number.isNaN()</code></strong> determina se o valor passado é {{jsxref("Global_Objects/NaN", "NaN")}}. Esta é uma versão mais robusta que {{jsxref("Global_Objects/isNaN", "isNaN()")}}.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code>Number.isNaN(valor)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>valor</code></dt> + <dd>O valor a ser testado se é {{jsxref("Global_Objects/NaN", "NaN")}}.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Due to both equality operators, {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} and {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}, evaluating to <code>false</code> when checking if {{jsxref("Global_Objects/NaN", "NaN")}} <em>is</em> {{jsxref("Global_Objects/NaN", "NaN")}}, the function <code>Number.isNaN()</code> has become necessary. This situation is unlike all other possible value comparisons in JavaScript.</p> + +<p>In comparison to the global {{jsxref("Global_Objects/isNaN", "isNaN()")}} function, <code>Number.isNaN()</code> doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to {{jsxref("Global_Objects/NaN", "NaN")}}, but aren't actually the same value as {{jsxref("Global_Objects/NaN", "NaN")}}. This also means that only values of the type number, that are also {{jsxref("Global_Objects/NaN", "NaN")}}, return <code>true</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: js">Number.isNaN(NaN); // true +Number.isNaN(Number.NaN); // true +Number.isNaN(0 / 0) // true + +// e.g. these would have been true with global isNaN() +Number.isNaN("NaN"); // false +Number.isNaN(undefined); // false +Number.isNaN({}); // false +Number.isNaN("blabla"); // false + +// These all return false +Number.isNaN(true); +Number.isNaN(null); +Number.isNaN(37); +Number.isNaN("37"); +Number.isNaN("37.37"); +Number.isNaN(""); +Number.isNaN(" "); +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<pre class="brush: js">Number.isNaN = Number.isNaN || function(value) { + return typeof value === "number" && isNaN(value); +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Definição inicial.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome("25")}}</td> + <td>{{CompatGeckoDesktop("15")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>9</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("15")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>iOS 9+</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Global_Objects/Number", "Number")}}</li> + <li>{{jsxref("Global_Objects/isNaN", "isNaN()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html new file mode 100644 index 0000000000..cd1666ecbc --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html @@ -0,0 +1,119 @@ +--- +title: Number.MAX_VALUE +slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE +tags: + - JavaScript + - Number + - Property + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.MAX_VALUE </code></strong>representa o máximo valor numérico representável em JavaScript.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>A propriedade <code>MAX_VALUE</code> tem um valor aproximado de <code>1.79E+308</code>. Valores maiores do que <code>MAX_VALUE</code> são representados como "<code>Infinity</code>".</p> + +<p>Dado que <code>MAX_VALUE</code> é uma propriedade estática (static) de {{jsxref("Number")}}, tu deves sempre usá-la na forma <code>Number.MAX_VALUE</code>, em vez de na forma de uma propriedade de um objecto {{jsxref("Number")}} que tenhas criado.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_MAX_VALUE">Usando <code>MAX_VALUE</code></h3> + +<p>O seguinte código multiplica dois valores numéricos. Se o resultado for inferior ou igual a <code>MAX_VALUE</code>, a função <code>func1</code> é chamada; senão será chamada a função <code>func2</code>.</p> + +<pre class="brush: js">if (num1 * num2 <= Number.MAX_VALUE) { + func1(); +} else { + func2(); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.2', 'Number.MAX_VALUE')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.max_value', 'Number.MAX_VALUE')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number.MIN_VALUE")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html new file mode 100644 index 0000000000..852b37426b --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html @@ -0,0 +1,121 @@ +--- +title: Number.MIN_VALUE +slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE +tags: + - JavaScript + - Number + - Property + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.MIN_VALUE </code></strong>representa o mínimo valor numérico representável em JavaScript.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>A propriedade <code>MIN_VALUE</code> representa o valor mais próximo de 0 (zero), não negativo, que o JavaScript consegue representar.</p> + +<p>A propriedade <code>MIN_VALUE</code> tem um valor aproximado de <code>5e-324</code>. Valores menores do que <code>MIN_VALUE </code>("underflow values") são são convertidos para 0 (zero).</p> + +<p>Dado que <code>MIN_VALUE</code> é uma propriedade estática (static) de {{jsxref("Number")}}, tu deves sempre usá-la na forma <code>Number.MIN_VALUE</code>, em vez de na forma de uma propriedade de um objecto {{jsxref("Number")}} que tenhas criado.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_MIN_VALUE">Usando <code>MIN_VALUE</code></h3> + +<p>O seguinte código divide dois valores numéricos. Se o resultado for superior ou igual a <code>MIN_VALUE</code>, a função <code>func1</code> é chamada; senão será chamada a função <code>func2</code>.</p> + +<pre class="brush: js">if (num1 / num2 >= Number.MIN_VALUE) { + func1(); +} else { + func2(); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.3', 'Number.MIN_VALUE')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.min_value', 'Number.MIN_VALUE')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number.MAX_VALUE")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html new file mode 100644 index 0000000000..c3213486b7 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html @@ -0,0 +1,103 @@ +--- +title: Number.NaN +slug: Web/JavaScript/Reference/Global_Objects/Number/NaN +tags: + - JavaScript + - Number + - Property + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NaN +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.NaN </code></strong>representa um Não-Número. Equivalente a {{jsxref("NaN")}}.</p> + +<p>Não precisas de criar um objecto {{jsxref("Number")}} para aceder a esta propriedade estática (static) (usa <code>Number.NaN</code>).</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado no JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>O objecto global {{jsxref("NaN")}}.</li> + <li>O objecto {{jsxref("Number")}} ao qual pertence.</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html new file mode 100644 index 0000000000..a2a7d0f962 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html @@ -0,0 +1,91 @@ +--- +title: Number.NEGATIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +tags: + - JavaScript + - Number + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.NEGATIVE_INFINITY</code></strong> representa o valor negativo Infinito.</p> + +<p>Não tem de criar um objecto {{jsxref("Number")}} para aceder a esta propriedade estática (usa <code>Number.NEGATIVE_INFINITY</code>).</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>O valor de <code>Number.NEGATIVE_INFINITY</code> é o mesmo que o valor negativo da propriedade {{jsxref("Infinity")}} do objeto global.</p> + +<p>Este valor comporta-se de forma ligeiramente diferente do infinito matemático:</p> + +<ul> + <li>Qualquer valor positivo, incluindo {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, multiplicado por <code>NEGATIVE_INFINITY</code> é igual a <code>NEGATIVE_INFINITY</code>.</li> + <li>Qualquer valor negativo, incluindo,<code>NEGATIVE_INFINITY</code> multiplicado por <code>NEGATIVE_INFINITY</code> é igual a {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}.</li> + <li>O valor 0 (zero) multiplicado por <code>NEGATIVE_INFINITY</code> é igual a {{jsxref("NaN")}}.</li> + <li>{{jsxref("NaN")}} multiplicado por <code>NEGATIVE_INFINITY</code> é igual a {{jsxref("NaN")}}.</li> + <li><code>NEGATIVE_INFINITY</code>, dividido por qualquer valor negativo excepto <code>NEGATIVE_INFINITY</code>, é igual a {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}.</li> + <li><code>NEGATIVE_INFINITY</code>, dividido por qualquer valor positivo exceto {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, é igual a <code>NEGATIVE_INFINITY</code>.</li> + <li><code>NEGATIVE_INFINITY</code>, dividido por outro <code>NEGATIVE_INFINITY</code> ou {{jsxref("Number.POSITIVE_INFINITY", "POSITIVE_INFINITY")}}, é igual a {{jsxref("NaN")}}.</li> + <li>Qualquer número dividido por <code>NEGATIVE_INFINITY</code> é igual a 0 (zero).</li> +</ul> + +<p>Pode usar a propriedade <code>Number.NEGATIVE_INFINITY</code> para indicar uma condição de erro numa situação em que, no caso de sucesso, é retornado um valor finito.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_NEGATIVE_INFINITY">Usando <code>NEGATIVE_INFINITY</code></h3> + +<p>No seguinte exemplo, é atribuído à variável <code>smallNumber</code> um valor inferior ao valor mínimo. Quando a linha de código {{jsxref("Statements/if...else", "if")}} é executada, a variável <code>smallNumber</code> tem o valor <code>-Infinity</code>, então é atribuída à mesma variável um valor finito antes de continuar.</p> + +<pre class="brush: js notranslate">var smallNumber = (-Number.MAX_VALUE) * 2; + +if (smallNumber == Number.NEGATIVE_INFINITY) { + smallNumber = returnFinite(); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.3.5', 'Number.NEGATIVE_INFINITY')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}</td> + <td>{{Spec2('ES6')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<p class="hidden">The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p> + +<p>{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number.POSITIVE_INFINITY")}}</li> + <li>{{jsxref("Number.isFinite()")}}</li> + <li>{{jsxref("Global_Objects/Infinity", "Infinity")}}</li> + <li>{{jsxref("Global_Objects/isFinite", "isFinite()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html new file mode 100644 index 0000000000..7bd7fb8739 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html @@ -0,0 +1,130 @@ +--- +title: Number.prototype +slug: Web/JavaScript/Reference/Global_Objects/Number/prototype +tags: + - JavaScript + - Number + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>Number.prototype</code></strong> representa o protótipo (prototype) para o constructor de {{jsxref("Number")}}.</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>Todas as instâncias de {{jsxref("Number")}} herdam de <code>Number.prototype</code>. O objecto protótipo (prototype) do constructor de {{jsxref("Number")}} pode ser modificado para afectar todas as instâncias de {{jsxref( "Number")}}.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt><code>Number.prototype.constructor</code></dt> + <dd>Retorna a função criadora das instâncias deste objecto. Por predifinição este é o objecto {{jsxref("Number")}}.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("Number.prototype.toExponential()")}}</dt> + <dd>Retorna uma representação em string do número em notação científica.</dd> + <dt>{{jsxref("Number.prototype.toFixed()")}}</dt> + <dd>Retorna uma representação em string do número em notação de ponto fixo.</dd> + <dt>{{jsxref("Number.prototype.toLocaleString()")}}</dt> + <dd>Retorna uma string do número numa representação sensível à linguagem. Faz override do método {{jsxref("Object.prototype.toLocaleString()")}}.</dd> + <dt>{{jsxref("Number.prototype.toPrecision()")}}</dt> + <dd>Retorna uma representação em string do número numa precisão especificada em ponto fixo ou notação científica.</dd> + <dt>{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Retorna um objecto literal representando o objecto {{jsxref("Number")}} especificado; podes usar este valor para criar um novo objecto. Faz override ao método {{jsxref("Object.prototype.toSource()")}}.</dd> + <dt>{{jsxref("Number.prototype.toString()")}}</dt> + <dd>Retorna uma representação em string do objecto especificado na base especificada. Faz override ao método {{jsxref("Object.prototype.toString()")}}.</dd> + <dt>{{jsxref("Number.prototype.valueOf()")}}</dt> + <dd>Retorna o valor primitivo do objecto especificado. Faz override ao método {{jsxref("Object.prototype.valueOf()")}}.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição Inicial. Implementado em JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html new file mode 100644 index 0000000000..1ff4892314 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html @@ -0,0 +1,146 @@ +--- +title: Number.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Number/toString +tags: + - JavaScript + - Number + - Prototype + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toString +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>toString()</code></strong> retorna uma string com o valor do objecto {{jsxref("Number")}} especificado.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>numObj</var>.toString([<var>radix</var>])</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>base</code></dt> + <dd>Opcional. Um inteiro entre [2, 36] especificando a base usada para representar o valor númerico.</dd> +</dl> + +<h3 id="Erros_possíveis">Erros possíveis</h3> + +<dl> + <dt>{{jsxref("RangeError")}}</dt> + <dd>Se o valor do parâmetro base não estiver entre [2, 36], o erro {{jsxref("RangeError")}} é lançado.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>O objecto {{jsxref("Number")}} faz override ao método <code>toString()</code> do objecto {{jsxref("Object")}}; não herda de {{jsxref("Object.prototype.toString()")}}. Para os objectos {{jsxref( "Number")}}, o método <code>toString() </code>retorna uma representação em string do ojecto na base especificada.</p> + +<p>O método <code>toString() </code>analisa o seu primeiro argumento e tenta retornar uma representação em string na base especificada. Para bases superiores a 10, as letras do alfabeto representam numerais maiores do que 9 (por ordem alfabética: a, b, c ...). Por exemplo, para números hexadecimais (base 16) são usadasa as letras do alfabeto até <code>f</code>.</p> + +<p>Se a <code>base </code>não for especificada, o seu valor assumido é 10.</p> + +<p>Se o <code><var>numObj </var></code>tem um valor negativo (< 0), o sinal é preservado. O mesmo se aplica se a base tiver o valor 2; a string retornada é a representação positiva do binário de <code><var>numObj </var></code>precedida pelo sinal negativo (-), e não complement para 2 de <code>numObj</code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_toString">Usando <code>toString</code></h3> + +<pre class="brush: js">var count = 10; + +console.log(count.toString()); // imprime '10' +console.log((17).toString()); // imprime '17' + +var x = 6; + +console.log(x.toString(2)); // imprime '110' +console.log((254).toString(16)); // imprime 'fe' + +console.log((-10).toString(2)); // imprime '-1010' +console.log((-0xff).toString(2)); // imprime'-11111111' +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.1.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.7.4.2', 'Number.prototype.tostring')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>BSuporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("Number.prototype.toFixed()")}}</li> + <li>{{jsxref("Number.prototype.toExponential()")}}</li> + <li>{{jsxref("Number.prototype.toPrecision()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..2c91823404 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,187 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +tags: + - JavaScript + - Objeto + - Prototipo + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +<div>{{JSRef}}</div> + +<p>O método <code><strong>hasOwnProperty()</strong></code> retorna um booleano indicando se o objeto tem a propriedade especificada.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>obj</var>.hasOwnProperty(<var>prop</var>)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>O nome da propriedade para testar.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Cada objecto descendente de {{jsxref("Object")}} herda o método <code>hasOwnProperty</code>. Este método pode ser usado para determinar se um objecto contém a propriedade especificada como uma propriedade direta desse objeto; ao contrário do operador {{jsxref("Operators/in", "in")}}, este método não verifica a cadeia de objetos do protótipo.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_hasOwnProperty_para_testar_a_existência_de_uma_propriedade">Usando <code>hasOwnProperty</code> para testar a existência de uma propriedade</h3> + +<p>O seguinte exemplo determina se o objecto "o" contém a propriedade "<code>prop"</code>:</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'existe'; + +function changeO() { + o.newprop = o.prop; + delete o.prop; +} + +o.hasOwnProperty('prop'); // retorna true +changeO(); +o.hasOwnProperty('prop'); // retorna false +</pre> + +<h3 id="Direto_versus_propriedades_herdadas">Direto versus propriedades herdadas</h3> + +<p>O seguinte exemplo diferencia entre propriedades diretas e propriedades herdadas através da cadeia de protótipos:</p> + +<pre class="brush: js">o = new Object(); +o.prop = 'existe'; +o.hasOwnProperty('prop'); // retorna true +o.hasOwnProperty('toString'); // retorna false +o.hasOwnProperty('hasOwnProperty'); // retorna false +</pre> + +<h3 id="Iteração_entre_as_propriedades_de_um_objeto">Iteração entre as propriedades de um objeto</h3> + +<p>O seguinte exemplo mostra como iterar entre as propriedades de um objeto sem executar em propriedades herdadas. Note que o ciclo {{jsxref("Statements/for...in", "for...in")}} já está apenas repetindo itens enumeráveis então um não devia assumir baseado na falta de propriedades não-enumeráveis mostrado no ciclo que <code>hasOwnProperty</code> em si é estritamente limitado aos itens enumeráveis (como com {{jsxref("Object.getOwnPropertyNames()")}}).</p> + +<pre class="brush: js">var buz = { + fog: 'stack' +}; + +for (var name in buz) { + if (buz.hasOwnProperty(name)) { + console.log('Isto é fog (' + name + ') com certeza. Valor: ' + buz[name]); + } + else { + console.log(name); // toString ou outra coisa + } +} +</pre> + +<h3 id="Usando_hasOwnProperty_como_um_nome_de_uma_propriedade">Usando <code>hasOwnProperty</code> como um nome de uma propriedade</h3> + +<p>JavaScript não protege a propriedade <code>hasOwnProperty</code>; assim, se a possibilidade existe de um objeto poder ter uma propriedade com este nome, é necessário usar um <code>hasOwnProperty</code> externo para obter resultados corretos:</p> + +<pre class="brush: js">var foo = { + hasOwnProperty: function() { + return false; + }, + bar: 'Aqui os dragões' +}; + +foo.hasOwnProperty('bar'); // sempre retornará false + +// Use outro objeto hasOwnProperty e chame-o com 'this' definido como foo +({}).hasOwnProperty.call(foo, 'bar'); // true + +// É também possível usar a propriedade hasOwnProperty através do protótipo do objeto para este propósito +Object.prototype.hasOwnProperty.call(foo, 'bar'); // true +</pre> + +<p>Note que no último caso, não há objetos recém-criados.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES3')}}</td> + <td>{{Spec2('ES3')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.5.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_entre_browsers">Compatibilidade entre browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li><a href="/en-US/docs/Enumerability_and_ownership_of_properties">Enumerabilidade e posse de propriedades</a></li> + <li>{{jsxref("Object.getOwnPropertyNames()")}}</li> + <li>{{jsxref("Statements/for...in", "for...in")}}</li> + <li>{{jsxref("Operators/in", "in")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Inheritance_Revisited">Guia JavaScript: Herança e a cadeia de protótipos</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..e393f833b8 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,184 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - Construtor + - JavaScript + - Object + - Objeto +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p>o construtor <code><strong>Object</strong></code> cria um wrapper de objeto.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">// Object initialiser or literal +{ [ <var>nameValuePair1</var>[, <var>nameValuePair2</var>[, ...<var>nameValuePairN</var>] ] ] } + +// Called as a constructor +new Object([<var>value</var>])</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>nameValuePair1, nameValuePair2, ... nameValuePair<em>N</em></code></dt> + <dd>Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.</dd> + <dt><code>value</code></dt> + <dd>Any value.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>The <code>Object</code> constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.</p> + +<p>When called in a non-constructor context, <code>Object</code> behaves identically to <code>new Object()</code>.</p> + +<p>See also the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal syntax</a>.</p> + +<h2 id="Propriedades_de_um_construtor_Object">Propriedades de um construtor <code>Object</code></h2> + +<dl> + <dt><code>Object.length</code></dt> + <dd>Tem um valor de 1.</dd> + <dt>{{jsxref("Object.prototype")}}</dt> + <dd>Permite a adição de propriedades para todos os objetos do tipo <em>Object</em>.</dd> +</dl> + +<h2 id="Métodos_de_um_construtor_Object">Métodos de um construtor <code>Object</code></h2> + +<dl> + <dt>{{jsxref("Object.assign()")}}</dt> + <dd>Copies the values of all enumerable own properties from one or more source objects to a target object.</dd> + <dt>{{jsxref("Object.create()")}}</dt> + <dd>Creates a new object with the specified prototype object and properties.</dd> + <dt>{{jsxref("Object.defineProperty()")}}</dt> + <dd>Adds the named property described by a given descriptor to an object.</dd> + <dt>{{jsxref("Object.defineProperties()")}}</dt> + <dd>Adds the named properties described by the given descriptors to an object.</dd> + <dt>{{jsxref("Object.entries()")}}</dt> + <dd>Returns an array containing all of the <code>[key, value]</code> pairs of a given object's <strong>own</strong> enumerable string properties.</dd> + <dt>{{jsxref("Object.freeze()")}}</dt> + <dd>Freezes an object: other code can't delete or change any properties.</dd> + <dt>{{jsxref("Object.fromEntries()")}}</dt> + <dd>Returns a new object from an iterable of key-value pairs (reverses {{jsxref("Object.entries")}}).</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptor()")}}</dt> + <dd>Returns a property descriptor for a named property on an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyDescriptors()")}}</dt> + <dd>Returns an object containing all own property descriptors for an object.</dd> + <dt>{{jsxref("Object.getOwnPropertyNames()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable and non-enumerable properties.</dd> + <dt>{{jsxref("Object.getOwnPropertySymbols()")}}</dt> + <dd>Returns an array of all symbol properties found directly upon a given object.</dd> + <dt>{{jsxref("Object.getPrototypeOf()")}}</dt> + <dd>Returns the prototype of the specified object.</dd> + <dt>{{jsxref("Object.is()")}}</dt> + <dd>Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).</dd> + <dt>{{jsxref("Object.isExtensible()")}}</dt> + <dd>Determines if extending of an object is allowed.</dd> + <dt>{{jsxref("Object.isFrozen()")}}</dt> + <dd>Determines if an object was frozen.</dd> + <dt>{{jsxref("Object.isSealed()")}}</dt> + <dd>Determines if an object is sealed.</dd> + <dt>{{jsxref("Object.keys()")}}</dt> + <dd>Returns an array containing the names of all of the given object's <strong>own</strong> enumerable string properties.</dd> + <dt>{{jsxref("Object.preventExtensions()")}}</dt> + <dd>Prevents any extensions of an object.</dd> + <dt>{{jsxref("Object.seal()")}}</dt> + <dd>Prevents other code from deleting properties of an object.</dd> + <dt>{{jsxref("Object.setPrototypeOf()")}}</dt> + <dd>Sets the prototype (i.e., the internal <code>[[Prototype]]</code> property).</dd> + <dt>{{jsxref("Object.values()")}}</dt> + <dd>Returns an array containing the values that correspond to all of a given object's <strong>own</strong> enumerable string properties.</dd> +</dl> + +<h2 id="Instâcias_de_Object_e_objeto_protótipo_Object">Instâcias de <code>Object</code> e objeto protótipo <code>Object</code></h2> + +<p>All objects in JavaScript are descended from <code>Object</code>; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the <code>constructor</code> property and provide their own <code>toString()</code> methods. Changes to the <code>Object</code> prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.</p> + +<h3 id="Propriedades">Propriedades</h3> + +<div>{{page('//pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Propriedades') }}</div> + +<h3 id="Métodos">Métodos</h3> + +<div>{{page('//pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', 'Métodos') }}</div> + +<h2 id="Deleting_a_property_from_an_object">Deleting a property from an object</h2> + +<p>There isn't any method in an Object itself to delete its own properties (e.g. like <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete">Map.prototype.delete()</a></code>). To do so one has to use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete operator</a>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Using_Object_given_undefined_and_null_types">Using <code>Object</code> given <code>undefined</code> and <code>null</code> types</h3> + +<p>The following examples store an empty <code>Object</code> object in <code>o</code>:</p> + +<pre class="brush: js">var o = new Object(); +</pre> + +<pre class="brush: js">var o = new Object(undefined); +</pre> + +<pre class="brush: js">var o = new Object(null); +</pre> + +<h3 id="Using_Object_to_create_Boolean_objects">Using <code>Object</code> to create <code>Boolean</code> objects</h3> + +<p>The following examples store {{jsxref("Boolean")}} objects in <code>o</code>:</p> + +<pre class="brush: js">// equivalent to o = new Boolean(true); +var o = new Object(true); +</pre> + +<pre class="brush: js">// equivalent to o = new Boolean(false); +var o = new Object(Boolean()); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2', 'Object')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td>Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores/Inicializador_objeto">Inicializador de objeto</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..c98a57ec52 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,198 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - Objeto + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +<div>{{JSRef}}</div> + +<p>A propriedade <code><strong>Object.prototype</strong></code> representa o <em>prototype object</em> {{jsxref("Object","Objeto")}} .</p> + +<div>{{js_property_attributes(0, 0, 0)}}</div> + +<h2 id="Descrição">Descrição</h2> + +<p>Nearly all objects in JavaScript are instances of {{jsxref("Object")}}; a typical object inherits properties (including methods) from <code>Object.prototype</code>, although these properties may be shadowed (a.k.a. overridden). However, an <code>Object</code> may be deliberately created for which this is not true (e.g. by {{jsxref("Object.create", "Object.create(null)")}}), or it may be altered so that this is no longer true (e.g. with {{jsxref("Object.setPrototypeOf")}}).</p> + +<p>Changes to the <code>Object</code> prototype object are seen by <strong>all</strong> objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior.</p> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("Object.prototype.constructor")}}</dt> + <dd>Specifies the function that creates an object's prototype.</dd> + <dt>{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}</dt> + <dd>Points to the object which was used as prototype when the object was instantiated.</dd> + <dt>{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}</dt> + <dd>Allows a function to be defined that will be executed when an undefined object member is called as a method.</dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to return the number of enumerable properties directly on a user-defined object, but has been removed.</s></dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to point to an object's context, but has been removed.</s></dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Associates a function with a property that, when accessed, executes that function and returns its return value.</dd> + <dt>{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Associates a function with a property that, when set, executes that function which modifies the property.</dd> + <dt>{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} method.</dd> + <dt>{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}</dt> + <dd>Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} method.</dd> + <dt>{{jsxref("Object.prototype.hasOwnProperty()")}}</dt> + <dd>Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.</dd> + <dt>{{jsxref("Object.prototype.isPrototypeOf()")}}</dt> + <dd>Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.</dd> + <dt>{{jsxref("Object.prototype.propertyIsEnumerable()")}}</dt> + <dd>Returns a boolean indicating if the internal <a href="/en-US/docs/Web/JavaScript/Data_structures#Properties">ECMAScript [[Enumerable]] attribute</a> is set.</dd> + <dt>{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}</dt> + <dd>Returns string containing the source of an object literal representing the object that this method is called upon; you can use this value to create a new object.</dd> + <dt>{{jsxref("Object.prototype.toLocaleString()")}}</dt> + <dd>Calls {{jsxref("Object.toString", "toString()")}}.</dd> + <dt>{{jsxref("Object.prototype.toString()")}}</dt> + <dd>Returns a string representation of the object.</dd> + <dt>{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}</dt> + <dd>Removes a watchpoint from a property of the object.</dd> + <dt>{{jsxref("Object.prototype.valueOf()")}}</dt> + <dd>Returns the primitive value of the specified object.</dd> + <dt>{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}</dt> + <dd>Adds a watchpoint to a property of the object.</dd> + <dt><s class="obsoleteElement">{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}</s></dt> + <dd><s class="obsoleteElement">Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.</s></dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>When altering the behavior of existing Object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic. For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.</p> + +<p>When a function is called, the arguments to the call are held in the array-like "variable" <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>. For example, in the call "myFn(a, b, c)", the arguments within myFn's body will contain 3 array-like elements corresponding to (a, b, c). When modifying prototypes with hooks, simply pass this & the arguments (the call state) to the current behavior by calling apply() on the function. This pattern can be used for any prototype, such as Node.prototype, Function.prototype, etc.</p> + +<pre class="brush: js">var current = Object.prototype.valueOf; + +// Since my property "-prop-value" is cross-cutting and isn't always +// on the same prototype chain, I want to modify Object.prototype: +Object.prototype.valueOf = function() { + if (this.hasOwnProperty('-prop-value')) { + return this['-prop-value']; + } else { + // It doesn't look like one of my objects, so let's fall back on + // the default behavior by reproducing the current behavior as best we can. + // The apply behaves like "super" in some other languages. + // Even though valueOf() doesn't take arguments, some other hook may. + return current.apply(this, arguments); + } +} +</pre> + +<p>Since JavaScript doesn't exactly have sub-class objects, prototype is a useful workaround to make a “base class” object of certain functions that act as objects. For example:</p> + +<pre class="brush: js">var Person = function(name) { + this.name = name; + this.canTalk = true; +}; + +Person.prototype.greet = function() { + if (this.canTalk) { + console.log('Hi, I am ' + this.name); + } +}; + +var Employee = function(name, title) { + Person.call(this, name); + this.title = title; +}; + +Employee.prototype = Object.create(Person.prototype); + +Employee.prototype.greet = function() { + if (this.canTalk) { + console.log('Hi, I am ' + this.name + ', the ' + this.title); + } +}; + +var Customer = function(name) { + Person.call(this, name); +}; + +Customer.prototype = Object.create(Person.prototype); + +var Mime = function(name) { + Person.call(this, name); + this.canTalk = false; +}; + +Mime.prototype = Object.create(Person.prototype); + +var bob = new Employee('Bob', 'Builder'); +var joe = new Customer('Joe'); +var rg = new Employee('Red Green', 'Handyman'); +var mike = new Customer('Mike'); +var mime = new Mime('Mime'); + +bob.greet(); +// Hi, I am Bob, the Builder + +joe.greet(); +// Hi, I am Joe + +rg.greet(); +// Hi, I am Red Green, the Handyman + +mike.greet(); +// Hi, I am Mike + +mime.greet(); +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Object.prototype")}}</p> +</div> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Learn/JavaScript/Objects">Introdução ao JavaScript Orientado a Objetos</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..4ccc8f5f81 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,326 @@ +--- +title: String +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - Referencia + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +<div>{{JSRef}}</div> + +<p>O objeto global <strong><code>String</code></strong> é um construtor de <em>strings</em> ou sequência de carateres.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<p>Os literais de string assumem as formas:</p> + +<pre class="syntaxbox"><code>'string text' +"string text" +"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"</code></pre> + +<p>As Strings podem também ser criadas usando o objecto global string directamente:</p> + +<pre class="syntaxbox"><code>String(thing) +new String(thing)</code></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>thing</code></dt> + <dd>Qualquer parâmetro para ser convertido numa <em>string</em>.</dd> +</dl> + +<h3 id="Strings_modelo"><em>Strings </em>modelo</h3> + +<p>A partir de ECMAScript 2015, os literais de <em>strings</em> podem também ser chamados de <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">Modelo strings</a>:</p> + +<pre class="brush: js"><code>`hello world`</code> +`hello! + world!` +<code>`hello ${who}`</code> +<code>escape `<a>${who}</a>`</code></pre> + +<dl> +</dl> + +<h3 id="Notação_Escape">Notação <em>Escape</em></h3> + +<p>Além dos carateres regulares e imprmiveis, os carateres especiais também podem ser codificados com notação <em>escape</em>:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Código</th> + <th scope="col">Resultado</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\XXX</code> (<code>XXX</code> = 1 - 3 octal digits; range of 0 - 377)</td> + <td>ISO-8859-1 character / Unicode code point between U+0000 and U+00FF</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Aspas simples</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Aspas duplas</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Barra invertida</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>Nova linha</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>carriage return</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Tab vertical</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>form feed</td> + </tr> + <tr> + <td><code>\uXXXX</code> (<code>XXXX</code> = 4 hex digits; range of 0x0000 - 0xFFFF)</td> + <td>UTF-16 code unit / Unicode code point between U+0000 and U+FFFF</td> + </tr> + <tr> + <td><code>\u{X}</code> ... <code>\u{XXXXXX}</code> (<code>X…XXXXXX</code> = 1 - 6 hex digits; range of 0x0 - 0x10FFFF)</td> + <td>UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF {{experimental_inline}}</td> + </tr> + <tr> + <td><code>\xXX</code> (<code>XX</code> = 2 hex digits; range of 0x00 - 0xFF)</td> + <td>ISO-8859-1 character / Unicode code point between U+0000 and U+00FF</td> + </tr> + </tbody> +</table> + +<div class="note"> +<p><strong>Note: </strong>Ao contrário de algumas outras linguagens, o Javascript não faz distinção entre strings com aspas simples e aspas duplas; Portanto a notação "escape" funciona em strings independente se foi utilizada aspas simples, ou aspas duplas na criação.</p> +</div> + +<h3 id="Strings_literais_longas"><em>Strings </em>literais longas</h3> + +<p>Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.</p> + +<p>You can use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition_()">+</a> operator to append multiple strings together, like this:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable."; +</pre> + +<p>Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:</p> + +<pre class="brush: js">let longString = "This is a very long string which needs \ +to wrap across multiple lines because \ +otherwise my code is unreadable."; +</pre> + +<p>Both of these result in identical strings being created.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/String_Operators">+ and += string operators</a>, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.</p> + +<h3 id="Acesso_de_caráter">Acesso de caráter</h3> + +<p>There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:</p> + +<pre class="brush: js">return 'cat'.charAt(1); // returns "a" +</pre> + +<p>The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:</p> + +<pre class="brush: js">return 'cat'[1]; // returns "a" +</pre> + +<p>For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)</p> + +<h3 id="Comparação_de_strings">Comparação de <em>strings</em></h3> + +<p>C developers have the <code>strcmp()</code> function for comparing strings. In JavaScript, you just use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">less-than and greater-than operators</a>:</p> + +<pre class="brush: js">var a = 'a'; +var b = 'b'; +if (a < b) { // true + console.log(a + ' is less than ' + b); +} else if (a > b) { + console.log(a + ' is greater than ' + b); +} else { + console.log(a + ' and ' + b + ' are equal.'); +} +</pre> + +<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<h3 id="Distinção_entre_string_primitivas_e_objetos_String">Distinção entre <em>string</em> primitivas e objetos <em><code>String</code></em></h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.</p> + +<pre class="brush: js">var a = 'a'; +var b = 'b'; +if (a < b) { // true + console.log(a + ' is less than ' + b); +} else if (a > b) { + console.log(a + ' is greater than ' + b); +} else { + console.log(a + ' and ' + b + ' are equal.'); +} +</pre> + +<p>A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by <code>String</code> instances.</p> + +<div class="blockIndicator note"> +<p>Nota: <code>a == b</code> compares the strings in a and b for being equal in the usual case-sensitive way. If you wish to compare without regard to upper or lower case characters, use a function similar to this:</p> + +<p><code>function isEqual(str1, str2)<br> + {<br> + return str1.toUpperCase()===str2.toUpperCase();<br> + } // isEqual</code></p> + +<p>Upper case is used instead of lower case in this function due to problems with certain UTF-8 character conversions.</p> +</div> + +<h3 id="Distinção_entre_string_primitivas_e_objetos_String_2">Distinção entre <em>string</em> primitivas e objetos <em><code>String</code></em></h3> + +<p>Note that JavaScript distinguishes between <code>String</code> objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)</p> + +<p>String literals (denoted by double or single quotes) and strings returned from <code>String</code> calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to <code>String</code> objects, so that it's possible to use <code>String</code> object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.</p> + +<pre class="brush: js">var s_prim = 'foo'; +var s_obj = new String(s_prim); + +console.log(typeof s_prim); // Logs "string" +console.log(typeof s_obj); // Logs "object" +</pre> + +<p>String primitives and <code>String</code> objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to <code>eval</code> are treated as source code; <code>String</code> objects are treated as all other objects are, by returning the object. For example:</p> + +<pre class="brush: js">var s1 = '2 + 2'; // creates a string primitive +var s2 = new String('2 + 2'); // creates a String object +console.log(eval(s1)); // returns the number 4 +console.log(eval(s2)); // returns the string "2 + 2" +</pre> + +<p>For these reasons, the code may break when it encounters <code>String</code> objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.</p> + +<p>A <code>String</code> object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.</p> + +<pre class="brush: js">console.log(eval(s2.valueOf())); // returns the number 4 +</pre> + +<div class="note"><strong>Nota:</strong> For another possible approach to strings in JavaScript, please read the article about <a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a>.</div> + +<h2 id="Propriedades">Propriedades</h2> + +<dl> + <dt>{{jsxref("String.prototype")}}</dt> + <dd>Allows the addition of properties to a <code>String</code> object.</dd> +</dl> + +<h2 id="Métodos">Métodos</h2> + +<dl> + <dt>{{jsxref("String.fromCharCode()")}}</dt> + <dd>Returns a string created by using the specified sequence of Unicode values.</dd> + <dt>{{jsxref("String.fromCodePoint()")}}</dt> + <dd>Returns a string created by using the specified sequence of code points.</dd> + <dt>{{jsxref("String.raw()")}} {{experimental_inline}}</dt> + <dd>Returns a string created from a raw template string.</dd> +</dl> + +<h2 id="Instâncias_de_String">Instâncias de <em><code>String</code></em></h2> + +<h3 id="Propriedades_2">Propriedades</h3> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}</div> + +<h3 id="Métodos_2">Métodos</h3> + +<h4 id="Methods_unrelated_to_HTML">Methods unrelated to HTML</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}</div> + +<h4 id="HTML_wrapper_methods">HTML wrapper methods</h4> + +<div>{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Conversão_de_String">Conversão de <em>String</em></h3> + +<p>It's possible to use <code>String</code> as a more reliable {{jsxref("String.prototype.toString()", "toString()")}} alternative, as it works when used on {{jsxref("null")}}, {{jsxref("undefined")}}, and on {{jsxref("Symbol", "symbols")}}. For example:</p> + +<pre class="brush: js">var outputStrings = []; +for (var i = 0, n = inputValues.length; i < n; ++i) { + outputStrings.push(String(inputValues[i])); +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-string-objects', 'String')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5', 'String')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.builtins.String",2)}}</p> + +<h2 id="Consulte_também">Consulte também:</h2> + +<ul> + <li>{{domxref("DOMString")}}</li> + <li><a href="/en-US/Add-ons/Code_snippets/StringView"><code>StringView</code> — a C-like representation of strings based on typed arrays</a></li> + <li><a href="/en-US/docs/Web/API/DOMString/Binary">Binary strings</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html new file mode 100644 index 0000000000..721fb3c913 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html @@ -0,0 +1,191 @@ +--- +title: String.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/String/indexOf +tags: + - JavaScript + - Method + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>indexOf()</code></strong> retorna o indíce da primeira ocorrência do valor especificado no objeto {{jsxref("String")}}, começando a procura a partir de <code>fromIndex</code>. Retorna -1 se o valor não for encontrado.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>str</var>.indexOf(<var>searchValue</var>[, <var>fromIndex</var>]</code>)</pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>searchValue</code></dt> + <dd>Uma string com o valor pelo qual se procura.</dd> + <dt><code>fromIndex</code> {{optional_inline}}</dt> + <dd>O ponto da string a partir do qual a procura deverá começar. Pode ter o valor de um qualquer inteiro. O valor por predefinição é 0. Se o <code>fromIndex < 0</code> a procura é feita em toda a string (o mesmo que passar o valor 0). Se <code>fromIndex >= str.length</code>, o método retornará -1, exceção feita quando o valor de <code>searchValue</code> é uma string vazia, nesse caso retorna <code>str.length</code>.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>Os caractéres numa string são indexadas da esquerda para a direita. O índice do primeira caractér é 0, e o índice do último caractér da string, chamado de <code>stringName,</code> é <code>stringName.length - 1</code>.</p> + +<pre class="brush: js">'Blue Whale'.indexOf('Blue'); // retorna 0 +'Blue Whale'.indexOf('Blute'); // retorna -1 +'Blue Whale'.indexOf('Whale', 0); // retorna 5 +'Blue Whale'.indexOf('Whale', 5); // retorna 5 +'Blue Whale'.indexOf('', 9); // retorna 9 +'Blue Whale'.indexOf('', 10); // retorna 10 +'Blue Whale'.indexOf('', 11); // retorna 10 +</pre> + +<h3 id="Case-sensitivity">Case-sensitivity</h3> + +<p>O método <code>indexOf()</code> é sensível a maiúsculas e minúsculas. Por exemplo, a seguinte expressão retorna -1:</p> + +<pre class="brush: js">'Blue Whale'.indexOf('blue'); // retorna -1 +</pre> + +<h3 id="Verificando_ocorrências">Verificando ocorrências</h3> + +<p>Repara que '0' não é avaliado como <code>true</code> e '-1' não é avaliado como <code>false</code>. Sendo assim, a forma correta de verificar se uma string específica existe dentro de outra string deverá ser:</p> + +<pre class="brush: js">'Blue Whale'.indexOf('Blue') !== -1; // true +'Blue Whale'.indexOf('Bloe') !== -1; // false +</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usando_indexOf()_e_lastIndexOf()">Usando <code>indexOf()</code> e <code>lastIndexOf()</code></h3> + +<p>O seguinte exemplo usa <code>indexOf()</code> e {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} para localizar valores na string <code>"Brave new world"</code>.</p> + +<pre class="brush: js">var anyString = 'Brave new world'; + +console.log('O índice do primeiro w desde o início é ' + anyString.indexOf('w')); +// imprime 8 +console.log('O índice do primeiro w desde o fim é ' + anyString.lastIndexOf('w')); +// imprime 10 + +console.log('O índice de "new" desde o início é ' + anyString.indexOf('new')); +// imprime 6 +console.log('O índice de "new" desde o fim é ' + anyString.lastIndexOf('new')); +// imprime 6 +</pre> + +<h3 id="indexOf()_e_sensibilidade_a_maiúsculas_e_minúsculas"><code>indexOf()</code> e sensibilidade a maiúsculas e minúsculas</h3> + +<p>O seguinte exemplo define duas variáveis do tipo string. As variáveis contêm a mesma string exceto o facto da segunda string conter as todas as letras maiúsculas. O primeiro método {{domxref("console.log()")}} apresenta 19. Mas porque o método <code>indexOf()</code> é sensível a maiúsculas e minúsculas, a string <code>"cheddar"</code> não é encontrada em <code>myCapString</code>, logo o segundo método <code>console.log()</code> apresenta -1.</p> + +<pre class="brush: js">var myString = 'brie, pepper jack, cheddar'; +var myCapString = 'Brie, Pepper Jack, Cheddar'; + +console.log('myString.indexOf("cheddar") é ' + myString.indexOf('cheddar')); +// imprime 19 +console.log('myCapString.indexOf("cheddar") é ' + myCapString.indexOf('cheddar')); +// imprime -1 +</pre> + +<h3 id="Usando_indexOf()_para_contar_as_ocorrências_de_uma_letra_numa_string">Usando <code>indexOf()</code> para contar as ocorrências de uma letra numa string</h3> + +<p>O seguinte exemplo atribuí à variável <code>count</code> o número de ocorrências da letra 'e' na string <code>str</code>:</p> + +<pre class="brush: js">var str = 'To be, or not to be, that is the question.'; +var count = 0; +var pos = str.indexOf('e'); + +while (pos !== -1) { + count++; + pos = str.indexOf('e', pos + 1); +} + +console.log(count); // imprime 4 +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("String.prototype.charAt()")}}</li> + <li>{{jsxref("String.prototype.lastIndexOf()")}}</li> + <li>{{jsxref("String.prototype.split()")}}</li> + <li>{{jsxref("Array.prototype.indexOf()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html new file mode 100644 index 0000000000..7774170252 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html @@ -0,0 +1,125 @@ +--- +title: String.length +slug: Web/JavaScript/Reference/Global_Objects/String/length +tags: + - JavaScript + - Property + - Prototype + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String/length +--- +<div>{{JSRef}}</div> + +<p>A propriedade <strong><code>length</code></strong> representa o comprimento de uma string.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>str</var>.length</code></pre> + +<h2 id="Descrição">Descrição</h2> + +<p>Esta propriedade retorna o número de code units na string. {{interwiki("wikipedia", "UTF-16")}}, o formato usado pelo JavaScript para a string, usa um single 16-bit code unit para representar os caracteres mais comuns, mas necessita de usar two code units para os caracteres menos comuns, pelo que é possível que o valor retornado por <code>length</code> não seja igual ao número de caracteres numa string.</p> + +<p>Para uma string vazia, <code>length</code> is 0.</p> + +<p>A propriedade estática (static) <code>String.length</code> retorna o valor 1.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Uso_simples">Uso simples</h3> + +<pre class="brush: js">var x = 'Mozilla'; +var empty = ''; + +console.log('Mozilla tem de tamanho ' + x.length + ' code units'); +/* "Mozilla tem de tamanho 7 code units" */ + +console.log('Uma string vazia tem tamanho ' + empty.length); +/* "Uma string vazia tem tamanho 0" */ +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Definição inicial. Implementado em JavaScript 1.0.</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_dos_browsers">Compatibilidade dos browsers</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Chrome para Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="http://developer.teradata.com/blog/jasonstrimpel/2011/11/javascript-string-length-and-internationalizing-web-applications">JavaScript <code>String.length</code> and Internationalizing Web Applications</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html new file mode 100644 index 0000000000..8ef29112f8 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html @@ -0,0 +1,139 @@ +--- +title: String.prototype.trim() +slug: Web/JavaScript/Reference/Global_Objects/String/Trim +tags: + - ECMAScript 5 + - JavaScript + - Prototipo + - Referencia + - String + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim +--- +<div>{{JSRef}}</div> + +<p>O método <strong><code>trim()</code></strong> elimina espaço em branco de ambos os extremos dum <em>string</em>. Espaço em branco neste contexto são todos os caracteres que apenas representam espaço (espaço, tabulação, espaço fixo, etc.) e todos os caracteres que representam limites de linha (LF, CR, etc.).</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><code><var>str</var>.trim()</code></pre> + +<h3 id="Valor_devolvido">Valor devolvido</h3> + +<p>Um novo <em>string</em> que representa o <em>string</em> que chamou despojado do espaço em branco de ambos os extremos.</p> + +<h2 id="Descrição">Descrição</h2> + +<p>O método <code>trim()</code> devolve o <em>string</em> despojado do espaço em branco de ambos os extremos. <code>trim()</code> não afecta o valor do <em>string</em> em si.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Using_trim()">Using <code>trim()</code></h3> + +<p>O exemplo que se segue mostra o <em>string</em> <code>'foo' em minúsculas</code>:</p> + +<pre class="brush: js">var orig = ' foo '; +console.log(orig.trim()); // 'foo' + +// Outro exemplo de .trim() eliminando espaço em branco de apenas um lado. + +var orig = 'foo '; +console.log(orig.trim()); // 'foo' +</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>Ao correr o código que se segue antes de qualquer outro criará <code>trim()</code> se não estiver nativamente disponível.</p> + +<pre class="brush: js">if (!String.prototype.trim) { + String.prototype.trim = function () { + return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + }; +} +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Definição inicial. Implementada em JavaScript 1.8.1.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ES6')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegadores">Compatibilidade de navegadores</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("1.9.1")}}</td> + <td>{{CompatIE("9")}}</td> + <td>{{CompatOpera("10.5")}}</td> + <td>{{CompatSafari("5")}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Característica</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}</li> + <li>{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html b/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html new file mode 100644 index 0000000000..3ba9666678 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html @@ -0,0 +1,114 @@ +--- +title: Symbol.hasInstance +slug: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance +tags: + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance +--- +<div>{{JSRef}}</div> + +<p>O symbol bem-conhecido <strong><code>Symbol.hasInstance</code></strong> é usado para determinar se um objecto construtor reconhece um objecto como de sua instância. O comportamento do operador {{jsxref("Operators/instanceof", "instanceof")}} pode ser customizado por este symbol.</p> + +<div>{{js_property_attributes(0,0,0)}}</div> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Tu podes implementar o comportamento customizado do seu <code>instanceof</code> deste jeito; por exemplo:</p> + +<pre class="brush: js">class MyArray { + static [Symbol.hasInstance](instance) { + return this.prototype.isPrototypeOf(instance) || + Array.isArray(instance); + } +} + +console.log([] instanceof MyArray); // true +console.log(new MyArray instanceof MyArray); // true +console.log(new Image instanceof MyArray); // false + +class MySubArray extends MyArray {} +console.log(new MySubArray instanceof MySubArray); // true +console.log(new MySubArray instanceof MyArray); // true +console.log(new MyArray instanceof MySubArray); // false</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_com_os_navegadores">Compatibilidade com os navegadores</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(51)}}</td> + <td>{{ CompatGeckoDesktop(50) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{ CompatGeckoMobile(50) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Veja_também">Veja também</h2> + +<ul> + <li>{{jsxref("Operators/instanceof", "instanceof")}}</li> + <li>{{jsxref("Global_Objects/Object/isPrototypeOf", "isPrototypeOf()")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html b/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html new file mode 100644 index 0000000000..00148cd9b1 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/global_objects/symbol/index.html @@ -0,0 +1,458 @@ +--- +title: Symbol +slug: Web/JavaScript/Reference/Global_Objects/Symbol +tags: + - ECMAScript6 + - JavaScript + - NeedsTranslation + - Symbol + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Symbol +--- +<div>{{JSRef}}</div> + +<p>A <strong>symbol</strong> is a unique and immutable data type. It may be used as an identifier for object properties. The <em>Symbol object</em> is an implicit object wrapper for the symbol {{Glossary("Primitive", "primitive data type")}}.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox">Symbol(<em>[description]</em>)</pre> + +<h3 id="Parameters">Parameters</h3> + +<dl> + <dt><code>description</code> {{optional_inline}}</dt> + <dd>Optional, string. A description of the symbol which can be used for debugging but not to access the symbol itself.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>To create a new primitive symbol, you write <code>Symbol()</code> with an optional string as its description:</p> + +<pre class="brush: js">var sym1 = Symbol(); +var sym2 = Symbol("foo"); +var sym3 = Symbol("foo"); +</pre> + +<p>The above code creates three new symbols. Note that <code>Symbol("foo")</code> does not coerce the string "foo" into a symbol. It creates a new symbol each time:</p> + +<pre class="brush: js">Symbol("foo") === Symbol("foo"); // false</pre> + +<p>The following syntax with the {{jsxref("Operators/new", "new")}} operator will throw a {{jsxref("TypeError")}}:</p> + +<pre class="brush: js">var sym = new Symbol(); // TypeError</pre> + +<p>This prevents authors from creating an explicit <code>Symbol</code> wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, <code>new Boolean</code>, <code>new String</code> and <code>new Number</code>).</p> + +<p>If you really want to create a <code>Symbol</code> wrapper object, you can use the <code>Object()</code> function:</p> + +<pre class="brush: js">var sym = Symbol("foo"); +typeof sym; // "symbol" +var symObj = Object(sym); +typeof symObj; // "object" +</pre> + +<h3 id="Shared_symbols_in_the_global_symbol_registry">Shared symbols in the global symbol registry</h3> + +<p>The above syntax using the <code>Symbol()</code> function will not create a global symbol that is available in your whole codebase. To create symbols available across files and even across realms (each of which has its own global scope), use the methods {{jsxref("Symbol.for()")}} and {{jsxref("Symbol.keyFor()")}} to set and retrieve symbols from the global symbol registry.</p> + +<h3 id="Finding_symbol_properties_on_objects">Finding symbol properties on objects</h3> + +<p>The method {{jsxref("Object.getOwnPropertySymbols()")}} returns an array of symbols and lets you find symbol properties on a given object. Note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt><code>Symbol.length</code></dt> + <dd>Length property whose value is 0.</dd> + <dt>{{jsxref("Symbol.prototype")}}</dt> + <dd>Represents the prototype for the <code>Symbol</code> constructor.</dd> +</dl> + +<h3 id="Well-known_symbols">Well-known symbols</h3> + +<p>In addition to your own symbols, JavaScript has some built-in symbols which represent internal language behaviors which were not exposed to developers in ECMAScript 5 and before. These symbols can be accessed using the following properties:</p> + +<h4 id="Iteration_symbols">Iteration symbols</h4> + +<dl> + <dt>{{jsxref("Symbol.iterator")}}</dt> + <dd>A method returning the default iterator for an object. Used by <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for...of</code></a>.</dd> +</dl> + +<h4 id="Regular_expression_symbols">Regular expression symbols</h4> + +<dl> + <dt>{{jsxref("Symbol.match")}}</dt> + <dd>A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by {{jsxref("String.prototype.match()")}}.</dd> + <dt>{{jsxref("Symbol.replace")}}</dt> + <dd>A method that replaces matched substrings of a string. Used by {{jsxref("String.prototype.replace()")}}.</dd> + <dt>{{jsxref("Symbol.search")}}</dt> + <dd>A method that returns the index within a string that matches the regular expression. Used by {{jsxref("String.prototype.search()")}}.</dd> + <dt>{{jsxref("Symbol.split")}}</dt> + <dd>A method that splits a string at the indices that match a regular expression. Used by {{jsxref("String.prototype.split()")}}.</dd> +</dl> + +<h4 id="Other_symbols">Other symbols</h4> + +<dl> + <dt>{{jsxref("Symbol.hasInstance")}}</dt> + <dd>A method determining if a constructor object recognizes an object as its instance. Used by {{jsxref("Operators/instanceof", "instanceof")}}.</dd> + <dt>{{jsxref("Symbol.isConcatSpreadable")}}</dt> + <dd>A Boolean value indicating if an object should be flattened to its array elements. Used by {{jsxref("Array.prototype.concat()")}}.</dd> + <dt>{{jsxref("Symbol.unscopables")}}</dt> + <dd>An object value of whose own and inherited property names are excluded from the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/with">with</a></code> environment bindings of the associated object.</dd> + <dt>{{jsxref("Symbol.species")}}</dt> + <dd>A constructor function that is used to create derived objects.</dd> + <dt>{{jsxref("Symbol.toPrimitive")}}</dt> + <dd>A method converting an object to a primitive value.</dd> + <dt>{{jsxref("Symbol.toStringTag")}}</dt> + <dd>A string value used for the default description of an object. Used by {{jsxref("Object.prototype.toString()")}}.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<dl> + <dt>{{jsxref("Symbol.for()", "Symbol.for(key)")}}</dt> + <dd>Searches for existing symbols with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.</dd> + <dt>{{jsxref("Symbol.keyFor", "Symbol.keyFor(sym)")}}</dt> + <dd>Retrieves a shared symbol key from the global symbol registry for the given symbol.</dd> +</dl> + +<h2 id="Symbol_prototype"><code>Symbol</code> prototype</h2> + +<p>All Symbols inherit from {{jsxref("Symbol.prototype")}}.</p> + +<h3 id="Properties_2">Properties</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Properties')}}</p> + +<h3 id="Methods_2">Methods</h3> + +<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/Symbol/prototype','Methods')}}</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_the_typeof_operator_with_symbols">Using the <code>typeof</code> operator with symbols</h3> + +<p>The {{jsxref("Operators/typeof", "typeof")}} operator can help you to identify symbols.</p> + +<pre class="brush: js">typeof Symbol() === 'symbol' +typeof Symbol('foo') === 'symbol' +typeof Symbol.iterator === 'symbol' +</pre> + +<h3 id="Symbol_type_conversions">Symbol type conversions</h3> + +<p>Some things to note when working with type conversion of symbols.</p> + +<ul> + <li>When trying to convert a symbol to a number, a {{jsxref("TypeError")}} will be thrown<br> + (e.g. <code>+sym</code> or <code>sym | 0</code>).</li> + <li>When using loose equality, <code>Object(sym) == sym</code> returns <code>true.</code></li> + <li><code>Symbol("foo") + "bar" </code>throws a {{jsxref("TypeError")}} (can't convert symbol to string). This prevents you from silently creating a new string property name from a symbol, for example.</li> + <li>The <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#String_conversion">"safer" <code>String(sym)</code> conversion</a> works like a call to {{jsxref("Symbol.prototype.toString()")}} with symbols, but note that <code>new String(sym)</code> will throw.</li> +</ul> + +<h3 id="Symbols_and_for...in_iteration">Symbols and <code>for...in</code> iteration</h3> + +<p>Symbols are not enumerable in <a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> iterations. In addition, {{jsxref("Object.getOwnPropertyNames()")}} will not return symbol object properties, however, you can use {{jsxref("Object.getOwnPropertySymbols()")}} to get these.</p> + +<pre class="brush: js">var obj = {}; + +obj[Symbol("a")] = "a"; +obj[Symbol.for("b")] = "b"; +obj["c"] = "c"; +obj.d = "d"; + +for (var i in obj) { + console.log(i); // logs "c" and "d" +}</pre> + +<h3 id="Symbols_and_JSON.stringify()">Symbols and <code>JSON.stringify()</code></h3> + +<p>Symbol-keyed properties will be completely ignored when using <code>JSON.stringify()</code>:</p> + +<pre class="brush: js">JSON.stringify({[Symbol("foo")]: "foo"}); +// '{}'</pre> + +<p>For more details, see {{jsxref("JSON.stringify()")}}.</p> + +<h3 id="Symbol_wrapper_objects_as_property_keys">Symbol wrapper objects as property keys</h3> + +<p>When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol:</p> + +<pre class="brush: js">var sym = Symbol("foo"); +var obj = {[sym]: 1}; +obj[sym]; // 1 +obj[Object(sym)]; // still 1 +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-symbol-objects', 'Symbol')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-symbol-objects', 'Symbol')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop(36)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.iterator (@@iterator)</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop(36)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.unscopables (@@unscopables)</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.match (@@match)</td> + <td>{{CompatChrome(50)}}</td> + <td>{{CompatGeckoDesktop(40)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.species (@@species)</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatGeckoDesktop(41)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.toPrimitive (@@toPrimitive)</td> + <td>{{CompatChrome(48)}}</td> + <td>{{CompatGeckoDesktop(44)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.replace (@@replace)</td> + <td>{{CompatChrome(50)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.search (@@search)</td> + <td>{{CompatChrome(50)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.split (@@split)</td> + <td>{{CompatChrome(50)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.isConcatSpreadable (@@isconcatspreadable)</td> + <td>{{CompatChrome(48)}}</td> + <td>{{CompatGeckoDesktop(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.hasInstance (@@hasInstance)</td> + <td>{{CompatChrome(51)}}</td> + <td>{{CompatGeckoDesktop(50)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.toStringTag (@@toStringTag)</td> + <td>{{CompatChrome(49)}}</td> + <td>{{CompatGeckoDesktop(51)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoMobile(36)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.iterator (@@iterator)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoMobile(36)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.unscopables (@@unscopables)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(38)}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>9</td> + </tr> + <tr> + <td>Symbol.match (@@match)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(40)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.species (@@species)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(41)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.toPrimitive (@@toPrimitive)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(44)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.replace (@@replace)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.search (@@search)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.split (@@split)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.isConcatSpreadable (@@isconcatspreadable)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(48)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.hasInstance (@@hasInstance)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(50)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Symbol.toStringTag (@@toStringTag)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile(51)}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Glossary/Symbol">Glossary: Symbol data type</a></li> + <li>{{jsxref("Operators/typeof", "typeof")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-symbols/">"ES6 In Depth: Symbols" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/index.html b/files/pt-pt/web/javascript/reference/index.html new file mode 100644 index 0000000000..aa2f94e880 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/index.html @@ -0,0 +1,307 @@ +--- +title: Referência de JavaScript +slug: Web/JavaScript/Reference +tags: + - ECMAScript6 + - ES6 + - 'I10n:priority' + - JS + - JavaScript + - Programação + - Página Landing + - Referencia + - es +translation_of: Web/JavaScript/Reference +--- +<div>{{JsSidebar}}</div> + +<p>Esta parte da secção de JavaScript na MDN serve como um repositório de factos sobre a linguage JavaScript. Leia mais <a href="/pt-PT/docs/Web/JavaScript/Reference/Sobre">sobre esta referência</a>.</p> + +<h2 id="Integrações">Integrações</h2> + +<p><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">Objetos integrados padrões de JavaScript</a>, em conjunto com os seus métodos e propriedades.</p> + +<ul class="card-grid"> + <li><span>Propriedades de Valor</span> + + <p>{{JSxRef("Infinity")}}<br> + {{JSxRef("NaN")}}<br> + {{JSxRef("undefined")}}<br> + {{JSxRef("globalThis")}}</p> + </li> + <li><span>Propriedades de Função</span> + <p>{{JSxRef("Global_Objects/eval", "eval()")}}<br> + {{JSxRef("Global_Objects/isFinite", "isFinite()")}}<br> + {{JSxRef("Global_Objects/isNaN", "isNaN()")}}<br> + {{JSxRef("Global_Objects/parseFloat", "parseFloat()")}}<br> + {{JSxRef("Global_Objects/parseInt", "parseInt()")}}<br> + {{JSxRef("Global_Objects/decodeURI", "decodeURI()")}}<br> + {{JSxRef("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}<br> + {{JSxRef("Global_Objects/encodeURI", "encodeURI()")}}<br> + {{JSxRef("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}</p> + </li> + <li><span>Objetos Fundamentais</span> + <p>{{JSxRef("Object")}}<br> + {{JSxRef("Function")}}<br> + {{JSxRef("Boolean")}}<br> + {{JSxRef("Symbol")}}</p> + </li> + <li><span>Objetos de Erro</span> + <p>{{JSxRef("Error")}}<br> + {{JSxRef("AggregateError")}}<br> + {{JSxRef("EvalError")}}<br> + {{JSxRef("InternalError")}}<br> + {{JSxRef("RangeError")}}<br> + {{JSxRef("ReferenceError")}}<br> + {{JSxRef("SyntaxError")}}<br> + {{JSxRef("TypeError")}}<br> + {{JSxRef("URIError")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Números e Datas</span> + + <p>{{JSxRef("Number")}}<br> + {{JSxRef("BigInt")}}<br> + {{JSxRef("Math")}}<br> + {{JSxRef("Date")}}</p> + </li> + <li><span>Processamento de Texto</span> + <p>{{JSxRef("String")}}<br> + {{JSxRef("RegExp")}}</p> + </li> + <li><span>Coleções Indexadas</span><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers"> </a>{{JSxRef("Array")}}<br> + {{JSxRef("Int8Array")}}<br> + {{JSxRef("Uint8Array")}}<br> + {{JSxRef("Uint8ClampedArray")}}<br> + {{JSxRef("Int16Array")}}<br> + {{JSxRef("Uint16Array")}}<br> + {{JSxRef("Int32Array")}}<br> + {{JSxRef("Uint32Array")}}<br> + {{JSxRef("Float32Array")}}<br> + {{JSxRef("Float64Array")}}<br> + {{JSxRef("BigInt64Array")}}<br> + {{JSxRef("BigUint64Array")}}</li> + <li><span>Coleções ''Keyed''</span> + <p>{{JSxRef("Map")}}<br> + {{JSxRef("Set")}}<br> + {{JSxRef("WeakMap")}}<br> + {{JSxRef("WeakSet")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Dados Estruturados</span> + + <p>{{JSxRef("ArrayBuffer")}}<br> + {{JSxRef("SharedArrayBuffer")}}<br> + {{JSxRef("Atomics")}}<br> + {{JSxRef("DataView")}}<br> + {{JSxRef("JSON")}}</p> + </li> + <li><span>Abstração de Controlo</span> + <p>{{JSxRef("Promise")}}<br> + {{JSxRef("Generator")}}<br> + {{JSxRef("GeneratorFunction")}}<br> + {{JSxRef("AsyncFunction")}}</p> + </li> + <li><span>Reflexão</span> + <p>{{JSxRef("Reflect")}}<br> + {{JSxRef("Proxy")}}</p> + </li> + <li><span>Internacionalização</span> + <p>{{JSxRef("Intl")}}<br> + {{JSxRef("Global_Objects/Collator", "Intl.Collator")}}<br> + {{JSxRef("Global_Objects/DateTimeFormat", "Intl.DateTimeFormat")}}<br> + {{JSxRef("Global_Objects/ListFormat", "Intl.ListFormat")}}<br> + {{JSxRef("Global_Objects/NumberFormat", "Intl.NumberFormat")}}<br> + {{JSxRef("Global_Objects/PluralRules", "Intl.PluralRules")}}<br> + {{JSxRef("Global_Objects/RelativeTimeFormat", "Intl.RelativeTimeFormat")}}<br> + {{JSxRef("Global_Objects/Locale", "Intl.Locale")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>WebAssembly</span> + + <p>{{JSxRef("WebAssembly")}}<br> + {{JSxRef("WebAssembly.Module")}}<br> + {{JSxRef("WebAssembly.Instance")}}<br> + {{JSxRef("WebAssembly.Memory")}}<br> + {{JSxRef("WebAssembly.Table")}}<br> + {{JSxRef("WebAssembly.CompileError")}}<br> + {{JSxRef("WebAssembly.LinkError")}}<br> + {{JSxRef("WebAssembly.RuntimeError")}}</p> + </li> +</ul> + +<h2 id="Declações_Statements">Declações (Statements)</h2> + +<p><a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações">Declarações e instruções de JavaScript</a></p> + +<ul class="card-grid"> + <li><span>Control flow</span>{{jsxref("Statements/block", "Block")}}<br> + {{jsxref("Statements/break", "break")}}<br> + {{jsxref("Statements/continue", "continue")}}<br> + {{jsxref("Statements/Empty", "Empty")}}<br> + {{jsxref("Statements/if...else", "if...else")}}<br> + {{jsxref("Statements/switch", "switch")}}<br> + {{jsxref("Statements/throw", "throw")}}<br> + {{jsxref("Statements/try...catch", "try...catch")}}</li> + <li><span>Declarations</span> + <p>{{jsxref("Statements/var", "var")}}<br> + {{jsxref("Statements/let", "let")}}<br> + {{jsxref("Statements/const", "const")}}</p> + </li> + <li><span>Functions and classes</span> + <p>{{jsxref("Statements/function", "function")}}<br> + {{jsxref("Statements/function*", "function*")}}<br> + {{jsxref("Statements/async_function", "async function")}}<br> + {{jsxref("Statements/return", "return")}}<br> + {{jsxref("Statements/class", "class")}}</p> + </li> + <li><span>Iterations</span> + <p>{{jsxref("Statements/do...while", "do...while")}}<br> + {{jsxref("Statements/for", "for")}}<br> + {{jsxref("Statements/for_each...in", "for each...in")}}<br> + {{jsxref("Statements/for...in", "for...in")}}<br> + {{jsxref("Statements/for...of", "for...of")}}<br> + {{jsxref("Statements/for-await...of", "for await...of")}}<br> + {{jsxref("Statements/while", "while")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Outros</span> + + <p>{{jsxref("Statements/debugger", "debugger")}}<br> + {{jsxref("Statements/import", "import")}}<br> + {{jsxref("Statements/label", "label")}}<br> + {{jsxref("Statements/with", "with")}}</p> + </li> +</ul> + +<h2 id="Expressões_e_operadores">Expressões e operadores</h2> + +<p><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores">Expressões e operadores de JavaScript</a>. </p> + +<div> +<ul class="card-grid"> + <li><span>Primary expressions</span>{{JSxRef("Operators/this", "this")}}<br> + {{JSxRef("Operators/function", "function")}}<br> + {{JSxRef("Operators/class", "class")}}<br> + {{JSxRef("Operators/function*", "function*")}}<br> + {{JSxRef("Operators/yield", "yield")}}<br> + {{JSxRef("Operators/yield*", "yield*")}}<br> + {{JSxRef("Operators/async_function", "async function")}}<br> + {{JSxRef("Operators/await", "await")}}<br> + {{JSxRef("Global_Objects/Array", "[]")}}<br> + {{JSxRef("Operators/Object_initializer", "{}")}}<br> + {{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}<br> + {{JSxRef("Operators/Grouping", "( )")}}<br> + {{JSxRef("null")}}</li> + <li><span>Left-hand-side expressions</span> + <p>{{JSxRef("Operators/Property_accessors", "Property accessors", "", 1)}}<br> + {{JSxRef("Operators/new", "new")}}<br> + {{JSxRef("Operators/new%2Etarget", "new.target")}}<br> + {{JSxRef("Operators/super", "super")}}<br> + {{JSxRef("Operators/Spread_syntax", "...obj")}}</p> + </li> + <li><span>Increment & decrement</span> + <p>{{JSxRef("Operators/Arithmetic_Operators", "A++", "#Increment")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "A--", "#Decrement")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "++A", "#Increment")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</p> + </li> + <li><span>Unary operators</span> + <p>{{JSxRef("Operators/delete", "delete")}}<br> + {{JSxRef("Operators/void", "void")}}<br> + {{JSxRef("Operators/typeof", "typeof")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}<br> + {{JSxRef("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}<br> + {{JSxRef("Operators/Logical_Operators", "!", "#Logical_NOT")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Arithmetic operators</span> + + <p>{{JSxRef("Operators/Arithmetic_Operators", "+", "#Addition")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "-", "#Subtraction")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "/", "#Division")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "*", "#Multiplication")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "%", "#Remainder")}}<br> + {{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}</p> + </li> + <li><span>Relational operators</span> + <p>{{JSxRef("Operators/in", "in")}}<br> + {{JSxRef("Operators/instanceof", "instanceof")}}<br> + {{JSxRef("Operators/Comparison_Operators", "<", "#Less_than_operator")}}<br> + {{JSxRef("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}<br> + {{JSxRef("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}<br> + {{JSxRef("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</p> + </li> + <li><span>Equality operators</span> + <p>{{JSxRef("Operators/Comparison_Operators", "==", "#Equality")}}<br> + {{JSxRef("Operators/Comparison_Operators", "!=", "#Inequality")}}<br> + {{JSxRef("Operators/Comparison_Operators", "===", "#Identity")}}<br> + {{JSxRef("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</p> + </li> + <li><span>Bitwise shift operators</span> + <p>{{JSxRef("Operators/Bitwise_Operators", "<<", "#Left_shift")}}<br> + {{JSxRef("Operators/Bitwise_Operators", ">>", "#Right_shift")}}<br> + {{JSxRef("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</p> + </li> +</ul> + +<ul class="card-grid"> + <li><span>Binary bitwise operators</span>{{JSxRef("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}<br> + {{JSxRef("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}<br> + {{JSxRef("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</li> + <li><span>Binary logical operators</span> + <p>{{JSxRef("Operators/Logical_Operators", "&&", "#Logical_AND")}}<br> + {{JSxRef("Operators/Logical_Operators", "||", "#Logical_OR")}}</p> + </li> + <li><span>Ternary operator</span> + <p>{{JSxRef("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</p> + </li> + <li><span>Assignment operators</span> + <p>{{JSxRef("Operators/Assignment_Operators", "=", "#Assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "/=", "#Division_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}<br> + {{JSxRef("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}<br> + {{JSxRef("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{JSxRef("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</p> + </li> +</ul> +</div> + +<h2 id="Funções">Funções</h2> + +<p>This chapter documents how to work with <a href="/en-US/docs/Web/JavaScript/Reference/Functions">JavaScript functions</a> to develop your applications.</p> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Funcoes/arguments"><code>argumentos (arguments)</code></a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">Default parameters</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a></li> +</ul> + +<h2 id="Páginas_adicionais_de_referência">Páginas adicionais de referência</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Data_structures">Data types and data structures</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">Strict mode</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Deprecated features</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/operadores/função/index.html b/files/pt-pt/web/javascript/reference/operadores/função/index.html new file mode 100644 index 0000000000..450183b727 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operadores/função/index.html @@ -0,0 +1,139 @@ +--- +title: Expressão função (Function expression) +slug: Web/JavaScript/Reference/Operadores/função +tags: + - Expressões Primárias + - Funiconaldiade de Linguagem + - Função + - JavaScript + - Operador +translation_of: Web/JavaScript/Reference/Operators/function +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>A palavra-chave <strong><code>function</code></strong> pode ser utilziada para definir uma função dentro de uma expressão.</p> + +<p>You can also define functions using the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"><code>Function</code></a> constructor and a <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function"><code>function declaration</code></a>.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox">let <var>myFunction</var> = function [<var>name</var>]([<var>param1</var>[, <var>param2[</var>, ..., <var>paramN</var>]]]) { + <var>statements</var> +};</pre> + +<p>As of ES2015, you can also use {{jsxref("Functions/Arrow_functions", "arrow functions")}}.</p> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code><var>name</var></code> {{optional_inline}}</dt> + <dd>The function name. Can be omitted, in which case the function is <em>anonymous</em>. The name is only local to the function body.</dd> + <dt><code><var>paramN</var></code> {{optional_inline}}</dt> + <dd>The name of an argument to be passed to the function.</dd> + <dt><code><var>statements</var></code> {{optional_inline}}</dt> + <dd>The statements which comprise the body of the function.</dd> +</dl> + +<h2 id="Descrição">Descrição</h2> + +<p>A function expression is very similar to and has almost the same syntax as a function declaration (see {{jsxref("Statements/function", "function statement")}} for details). The main difference between a function expression and a function declaration is the <em>function name</em>, which can be omitted in function expressions to create <em>anonymous</em> functions. A function expression can be used as an <a href="/en-US/docs/Glossary/IIFE">IIFE (Immediately Invoked Function Expression)</a> which runs as soon as it is defined. See also the chapter about {{jsxref("Functions", "functions")}} for more information.</p> + +<h3 id="Function_expression_hoisting">Function expression hoisting</h3> + +<p>Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:</p> + +<pre class="brush: js">console.log(notHoisted) // undefined +// even though the variable name is hoisted, the definition isn't. so it's undefined. +notHoisted(); // TypeError: notHoisted is not a function + +var notHoisted = function() { + console.log('bar'); +}; +</pre> + +<h3 id="Named_function_expression">Named function expression</h3> + +<p>If you want to refer to the current function inside the function body, you need to create a named function expression. <u><strong>This name is then local only to the function body (scope)</strong></u>. This also avoids using the non-standard {{jsxref("Functions/arguments/callee", "arguments.callee")}} property.</p> + +<pre class="brush: js">let math = { + 'factit': function factorial(n) { + console.log(n) + if (n <= 1) { + return 1; + } + return n * factorial(n - 1); + } +}; + +math.factit(3) //3;2;1; +</pre> + +<p>The variable the function expression is assigned to will have a <code>name</code> property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to {{jsxref("Functions/Arrow_functions", "arrow functions")}} (arrows don't have a name so you can only give the variable an implicit name).</p> + +<pre class="brush: js">var foo = function() {} +foo.name // "foo" + +var foo2 = foo +foo2.name // "foo" + +var bar = function baz() {} +bar.name // "baz" + +console.log(foo === foo2); // true +console.log(typeof baz); // undefined +console.log(bar === baz); // false (errors because baz == undefined) +</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<p>The following example defines an unnamed function and assigns it to <code>x</code>. The function returns the square of its argument:</p> + +<pre class="brush: js">var x = function(y) { + return y * y; +}; +</pre> + +<p>More commonly it is used as a <a href="/en-US/docs/Glossary/Callback_function">callback</a>:</p> + +<pre class="brush: js">button.addEventListener('click', function(event) { + console.log('button is clicked!') +})</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.operators.function")}}</p> + +<h2 id="Consulte_também">Consulte também </h2> + +<ul> + <li>{{jsxref("Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions_and_function_scope", "Functions and function scope")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Statements/async_function", "async function")}}</li> + <li>{{jsxref("Operators/async_function", "async function expression")}}</li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/operadores/index.html b/files/pt-pt/web/javascript/reference/operadores/index.html new file mode 100644 index 0000000000..02a550b7b0 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operadores/index.html @@ -0,0 +1,309 @@ +--- +title: Expressões e operadores +slug: Web/JavaScript/Reference/Operadores +tags: + - JavaScript + - Operadores + - Página Landing + - Resumo + - Sinopse +translation_of: Web/JavaScript/Reference/Operators +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>Este capítulo documenta todos os operadores, expressões e palavras-chave da linguagem JavaScript.</p> + +<h2 id="Expressões_e_operadores_por_categoria">Expressões e operadores por categoria</h2> + +<p>For an alphabetical listing see the sidebar on the left.</p> + +<h3 id="Expressões_primárias">Expressões primárias</h3> + +<p>Basic keywords and general expressions in JavaScript.</p> + +<dl> + <dt>{{JSxRef("Operators/this", "this")}}</dt> + <dd>The <code>this</code> keyword refers to a special property of an execution context.</dd> + <dt>{{JSxRef("Operators/function", "function")}}</dt> + <dd>The <code>function</code> keyword defines a function expression.</dd> + <dt>{{JSxRef("Operators/class", "class")}}</dt> + <dd>The <code>class</code> keyword defines a class expression.</dd> + <dt>{{JSxRef("Operators/function*", "function*")}}</dt> + <dd>The <code>function*</code> keyword defines a generator function expression.</dd> + <dt>{{JSxRef("Operators/yield", "yield")}}</dt> + <dd>Pause and resume a generator function.</dd> + <dt>{{JSxRef("Operators/yield*", "yield*")}}</dt> + <dd>Delegate to another generator function or iterable object.</dd> + <dt>{{JSxRef("Operators/async_function", "async function")}}</dt> + <dd>The <code>async function</code> defines an async function expression.</dd> + <dt>{{JSxRef("Operators/await", "await")}}</dt> + <dd>Pause and resume an async function and wait for the promise's resolution/rejection.</dd> + <dt>{{JSxRef("Global_Objects/Array", "[]")}}</dt> + <dd>Array initializer/literal syntax.</dd> + <dt>{{JSxRef("Operators/Object_initializer", "{}")}}</dt> + <dd>Object initializer/literal syntax.</dd> + <dt>{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}</dt> + <dd>Regular expression literal syntax.</dd> + <dt>{{JSxRef("Operators/Grouping", "( )")}}</dt> + <dd>Grouping operator.</dd> +</dl> + +<h3 id="Expressões_Left-hand-side">Expressões "Left-hand-side"</h3> + +<p>Left values are the destination of an assignment.</p> + +<dl> + <dt>{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}</dt> + <dd>Member operators provide access to a property or method of an object<br> + (<code>object.property</code> and <code>object["property"]</code>).</dd> + <dt>{{jsxref("Operators/new", "new")}}</dt> + <dd>The <code>new</code> operator creates an instance of a constructor.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a></dt> + <dd>In constructors, <code>new.target</code> refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.</dd> + <dt>{{jsxref("Operators/super", "super")}}</dt> + <dd>The <code>super</code> keyword calls the parent constructor.</dd> + <dt>{{jsxref("Operators/Spread_operator", "...obj")}}</dt> + <dd>The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.</dd> +</dl> + +<h3 id="Aumento_e_diminuição">Aumento e diminuição</h3> + +<p>Postfix/prefix increment and postfix/prefix decrement operators.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}</dt> + <dd>Postfix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}</dt> + <dd>Postfix decrement operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}</dt> + <dd>Prefix increment operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}</dt> + <dd>Prefix decrement operator.</dd> +</dl> + +<h3 id="Operadores_unários">Operadores unários</h3> + +<p>A unary operation is operation with only one operand.</p> + +<dl> + <dt>{{jsxref("Operators/delete", "delete")}}</dt> + <dd>The <code>delete</code> operator deletes a property from an object.</dd> + <dt>{{jsxref("Operators/void", "void")}}</dt> + <dd>The <code>void</code> operator discards an expression's return value.</dd> + <dt>{{jsxref("Operators/typeof", "typeof")}}</dt> + <dd>The <code>typeof</code> operator determines the type of a given object.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}</dt> + <dd>The unary plus operator converts its operand to Number type.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}</dt> + <dd>The unary negation operator converts its operand to Number type and then negates it.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}</dt> + <dd>Bitwise NOT operator.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}</dt> + <dd>Logical NOT operator.</dd> +</dl> + +<h3 id="Operadores_de_aritmética">Operadores de aritmética</h3> + +<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.</p> + +<dl> + <dt>{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}</dt> + <dd>Addition operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}</dt> + <dd>Subtraction operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}</dt> + <dd>Division operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}</dt> + <dd>Multiplication operator.</dd> + <dt>{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}</dt> + <dd>Remainder operator.</dd> +</dl> + +<dl> + <dt>{{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}</dt> + <dd>Exponentiation operator.</dd> +</dl> + +<h3 id="Operadores_relacionais">Operadores relacionais</h3> + +<p>A comparison operator compares its operands and returns a <code>Boolean</code> value based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/in", "in")}}</dt> + <dd>The <code>in</code> operator determines whether an object has a given property.</dd> + <dt>{{jsxref("Operators/instanceof", "instanceof")}}</dt> + <dd>The <code>instanceof</code> operator determines whether an object is an instance of another object.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}</dt> + <dd>Less than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}</dt> + <dd>Greater than operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}</dt> + <dd>Less than or equal operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}</dt> + <dd>Greater than or equal operator.</dd> +</dl> + +<div class="note"> +<p><strong>Nota: =></strong> não é um operador, mas a notação para <a href="/pt-PT/docs/Web/JavaScript/Reference/Funcoes/Funcoes_seta">funções seta (<em>arrow</em></a>).</p> +</div> + +<h3 id="Operadores_de_equality">Operadores de <em>equality</em></h3> + +<p>The result of evaluating an equality operator is always of type <code>Boolean</code> based on whether the comparison is true.</p> + +<dl> + <dt>{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}</dt> + <dd>Equality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}</dt> + <dd>Inequality operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}</dt> + <dd>Identity operator.</dd> + <dt>{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}</dt> + <dd>Nonidentity operator.</dd> +</dl> + +<h3 id="Bitwise_shift_operators">Bitwise shift operators</h3> + +<p>Operations to shift all bits of the operand.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}</dt> + <dd>Bitwise left shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}</dt> + <dd>Bitwise right shift operator.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}</dt> + <dd>Bitwise unsigned right shift operator.</dd> +</dl> + +<h3 id="Operadores_de_binário_bitwise">Operadores de binário <em>bitwise</em></h3> + +<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.</p> + +<dl> + <dt>{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}</dt> + <dd>Bitwise AND.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}</dt> + <dd>Bitwise OR.</dd> + <dt>{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}</dt> + <dd>Bitwise XOR.</dd> +</dl> + +<h3 id="Operadores_de_binário_logical">Operadores de binário <em>logical</em></h3> + +<p>Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.</p> + +<dl> + <dt>{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}</dt> + <dd>Logical AND.</dd> + <dt>{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}</dt> + <dd>Logical OR.</dd> +</dl> + +<h3 id="Operdor_condicional_ternário">Operdor condicional (ternário)</h3> + +<dl> + <dt>{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}</dt> + <dd> + <p>The conditional operator returns one of two values based on the logical value of the condition.</p> + </dd> +</dl> + +<h3 id="Operadores_de_Assignment">Operadores de <em>Assignment</em></h3> + +<p>An assignment operator assigns a value to its left operand based on the value of its right operand.</p> + +<dl> + <dt>{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}</dt> + <dd>Assignment operator.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}</dt> + <dd>Multiplication assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}</dt> + <dd>Division assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}</dt> + <dd>Remainder assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}</dt> + <dd>Addition assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}</dt> + <dd>Subtraction assignment</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}</dt> + <dd>Left shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}</dt> + <dd>Right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}</dt> + <dd>Unsigned right shift assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}</dt> + <dd>Bitwise AND assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}</dt> + <dd>Bitwise XOR assignment.</dd> + <dt>{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}</dt> + <dd>Bitwise OR assignment.</dd> + <dt>{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}<br> + {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}</dt> + <dd> + <p>Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.</p> + </dd> +</dl> + +<h3 id="Operador_de_aspas">Operador de aspas</h3> + +<dl> + <dt>{{jsxref("Operators/Comma_Operator", ",")}}</dt> + <dd>The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.</dd> +</dl> + +<h3 id="Funcionalidades_não_padrão">Funcionalidades não padrão</h3> + +<dl> + <dt>{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}</dt> + <dd>The <code>function</code> keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}</dt> + <dd>The expression closure syntax is a shorthand for writing simple function.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}</dt> + <dd>Array comprehensions.</dd> + <dt>{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}</dt> + <dd>Generator comprehensions.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName('ES1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11', 'Expressions')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Spread operator, destructuring assignment, <code>super</code> keyword.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.operators")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores/Precedencia_operador">Precedência de operador</a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html b/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html new file mode 100644 index 0000000000..e797f92953 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html @@ -0,0 +1,94 @@ +--- +title: Operador Vírgula +slug: Web/JavaScript/Reference/Operadores/Operador_virgula +tags: + - Composto + - Expressão + - Funcionalidade de Linguagem + - JavaScript + - Operador + - Referencia + - Vírgula +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +<div>Operador {{jsSidebar("Operators")}}</div> + +<p>O <strong>operador vírgula </strong>(<strong><code>,</code></strong>) avalia cada um dos seus operandos (da esquerda para a direita) e devolve o valor do último operando. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for">for</a></code> loop.</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}</div> + + + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox"><em>expr1</em>, <em>expr2, expr3...</em></pre> + +<h3 id="Parâmetros">Parâmetros</h3> + +<dl> + <dt><code>expr1</code>, <code>expr2</code>, <code>expr3</code>...</dt> + <dd>One or more expressions, the last of which is returned as the value of the compound expression.</dd> +</dl> + +<h2 id="Notas_de_utilização">Notas de utilização</h2> + +<p>You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a <code>for</code> loop.</p> + +<p>The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<p>If <code>a</code> is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment <code>i</code> and decrement <code>j</code> at once.</p> + +<p>The following code prints the values of the diagonal elements in the array:</p> + +<pre class="brush:js;highlight:[1]">for (var i = 0, j = 9; i <= 9; i++, j--) + console.log('a[' + i + '][' + j + '] = ' + a[i][j]);</pre> + +<p>Note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. In the following example, <code>a</code> is set to the value of <code>b = 3</code> (which is 3), but the <code>c = 4</code> expression still evaluates and its result returned to console (i.e., 4). This is due to <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence and associativity</a>.</p> + +<pre class="brush: js">var a, b, c; + +a = b = 3, c = 4; // Returns 4 in console +console.log(a); // 3 (left-most) + +var x, y, z; + +x = (y = 5, z = 6); // Returns 6 in console +console.log(x); // 6 (right-most) +</pre> + +<h3 id="Processing_and_then_returning">Processing and then returning</h3> + +<p>Another example that one could make with comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:</p> + +<pre class="brush: js">function myFunc() { + var x = 0; + + return (x += 1, x); // the same as return ++x; +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + + + +<p>{{Compat("javascript.operators.comma")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li>Repetição (<em>loop</em>) de <a href="/pt-PT/docs/Web/JavaScript/Reference/Extratos_e_declarações/for"><code>for</code> </a></li> +</ul> diff --git a/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html b/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html new file mode 100644 index 0000000000..03d4345410 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html @@ -0,0 +1,461 @@ +--- +title: Precedência de operador +slug: Web/JavaScript/Reference/Operadores/Precedencia_operador +tags: + - Guía + - JavaScript + - precedência +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +<div>{{jsSidebar("Operators")}}</div> + +<p>A <strong>precedência de operador</strong> determina a maneira pela qual os operadores são analisados em relação a cada um. Os operadores com maior precedência tornam-se operandos dos operadores com menor precedência..</p> + +<div>{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}</div> + + + +<h2 id="Precedência_e_Associabilidade">Precedência e Associabilidade</h2> + +<p>Consider an expression describable by the representation below. Note that both OP<sub>1</sub> and OP<sub>2 </sub>are fill-in-the-blanks for OPerators.</p> + +<pre class="syntaxbox">a OP b OP c +</pre> + +<p>If <code>OP<sub>1</sub></code> and <code>OP<sub>2</sub></code> have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher associativity than addition and executed first, even though addition is written first in the code.</p> + +<pre>console.log(3 + 10 * 2); // logs 23 +console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous +console.log((3 + 10) * 2); // logs 26 because the parentheses change the order </pre> + +<p>Left-associativity (left-to-right) means that it is processed as <code>(a OP<sub>1</sub> b) OP<sub>2</sub> c</code>, while right-associativity (right-to-left) means it is interpreted as <code>a OP<sub>1</sub> (b OP<sub>2</sub> c)</code>. Assignment operators are right-associative, so you can write:</p> + +<pre>a = b = 5; // same as writing a = (b = 5); +</pre> + +<p>with the expected result that <code>a</code> and <code>b</code> get the value 5. This is because the assignment operator returns the value that is assigned. First, <code>b</code> is set to 5. Then the <code>a</code> is also set to 5, the return value of <code>b = 5</code>, aka right operand of the assignment.</p> + +<p>As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.</p> + +<table> + <tbody> + <tr> + <td>Código</td> + <td>Resultado</td> + </tr> + <tr> + <td> + <pre> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the division operator (/) +console.log(echo("left", 6) / echo("right", 2)); +</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the right side +3 +</pre> + </td> + </tr> + <tr> + <td> + <pre> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the exponentiation operator (**) +console.log(echo("left", 2) ** echo("right", 3));</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the right side +8</pre> + </td> + </tr> + </tbody> +</table> + +<p>The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity does affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.</p> + +<table> + <tbody> + <tr> + <td>Código</td> + <td>Resultado</td> + </tr> + <tr> + <td> + <pre> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the division operator (/) +console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3)); +</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +1 +</pre> + </td> + </tr> + <tr> + <td> + <pre> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the exponentiation operator (**) +console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2)); +</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +512 +</pre> + </td> + </tr> + <tr> + <td> + <pre> +function echo(name, num) { + console.log("Evaluating the " + name + " side"); + return num; +} +// Notice the parentheses around the left and middle exponentiation +console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));</pre> + </td> + <td> + <pre> +Evaluating the left side +Evaluating the middle side +Evaluating the right side +64</pre> + </td> + </tr> + </tbody> +</table> + +<p>Looking at the code snippets above, <code>6 / 3 / 2</code> is the same as <code>(6 / 3) / 2</code> because division is left-associative. Exponentiation, on the other hand, is right-associative, so <code>2 ** 3 ** 2</code> is the same as <code>2 ** (3 ** 2)</code>. Thus, doing (<code>2 ** 3) ** 2</code> changes the order and results in the 64 seen in the table above.</p> + +<p>Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, <code>2 ** 3 / 3 ** 2</code> results in 0.8888888888888888 because it is the same as <code>(2 ** 3) / (3 ** 2)</code>.</p> + +<h3 id="Note_on_Grouping_and_Short-Circuiting">Note on Grouping and Short-Circuiting</h3> + +<p>In the table below, <strong>Grouping</strong> is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols <code>( … )</code> is evaluated first, especially when it comes to short-circuiting.</p> + +<p>Short-circuiting is jargon for conditional evaluation. For example, in the expression <code>a && (b + c)</code>, if <code>a</code> is <a href="https://wiki.developer.mozilla.org/en-US/docs/Glossary/Falsy">“falsy”</a>, then the sub-expression <code>(b + c)</code> will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator (“OR”) is “short-circuited”. Along with logical disjunction, other short-circuited operators include logical conjunction (“AND”), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.</p> + +<pre>a || (b * c); // evaluate `a` first, then produce `a` if `a` is “truthy” +a && (b < c); // evaluate `a` first, then produce `a` if `a` is “falsy” +a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined` +a?.b.c; // evaluate `a` first, then produce `a` if `a` is `null` or `undefined` +</pre> + +<h2 id="Exemplos">Exemplos</h2> + +<pre>3 > 2 && 2 > 1 +// returns true + +3 > 2 > 1 +// Returns false because 3 > 2 is true, then true is converted to 1 in inequality operators, therefore true > 1 becomes 1 > 1, which +// is false. Adding parentheses makes things clear: (3 > 2) > 1. + +</pre> + +<h2 id="Tabela">Tabela</h2> + +<p>The following table is ordered from highest (20) to lowest (1) precedence.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>Precedência</th> + <th>Tipo de operador (Operator)</th> + <th>Associatividade</th> + <th>Operadores individuais</th> + </tr> + <tr> + <td>20</td> + <td>{{jsxref("Operators/Grouping", "Grouping")}}</td> + <td>n/a</td> + <td><code>( … )</code></td> + </tr> + <tr> + <td colspan="1" rowspan="4">19</td> + <td>{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}}</td> + <td>left-to-right</td> + <td><code>… . …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}}</td> + <td>left-to-right</td> + <td><code>… [ … ]</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/new","new")}} (with argument list)</td> + <td>n/a</td> + <td><code>new … ( … )</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Function Call</a></td> + <td>left-to-right</td> + <td><code>… ( <var>… </var>)</code></td> + </tr> + <tr> + <td rowspan="1">18</td> + <td>{{jsxref("Operators/new","new")}} (without argument list)</td> + <td>right-to-left</td> + <td><code>new …</code></td> + </tr> + <tr> + <td rowspan="2">17</td> + <td>{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}}</td> + <td colspan="1" rowspan="2">n/a</td> + <td><code>… ++</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}}</td> + <td><code>… --</code></td> + </tr> + <tr> + <td colspan="1" rowspan="10">16</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT">Logical NOT</a></td> + <td colspan="1" rowspan="10">right-to-left</td> + <td><code>! …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT">Bitwise NOT</a></td> + <td><code>~ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus">Unary Plus</a></td> + <td><code>+ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_negation">Unary Negation</a></td> + <td><code>- …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment">Prefix Increment</a></td> + <td><code>++ …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement">Prefix Decrement</a></td> + <td><code>-- …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof</a></td> + <td><code>typeof …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/void">void</a></td> + <td><code>void …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></td> + <td><code>delete …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/await">await</a></td> + <td><code>await …</code></td> + </tr> + <tr> + <td>15</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation">Exponentiation</a></td> + <td>right-to-left</td> + <td><code>… ** …</code></td> + </tr> + <tr> + <td rowspan="3">14</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Multiplication">Multiplication</a></td> + <td colspan="1" rowspan="3">left-to-right</td> + <td><code>… * …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Division">Division</a></td> + <td><code>… / …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder">Remainder</a></td> + <td><code>… % …</code></td> + </tr> + <tr> + <td rowspan="2">13</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition">Addition</a></td> + <td colspan="1" rowspan="2">left-to-right</td> + <td><code>… + …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Subtraction">Subtraction</a></td> + <td><code>… - …</code></td> + </tr> + <tr> + <td rowspan="3">12</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Left Shift</a></td> + <td colspan="1" rowspan="3">left-to-right</td> + <td><code>… << …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Right Shift</a></td> + <td><code>… >> …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators">Bitwise Unsigned Right Shift</a></td> + <td><code>… >>> …</code></td> + </tr> + <tr> + <td rowspan="6">11</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than_operator">Less Than</a></td> + <td colspan="1" rowspan="6">left-to-right</td> + <td><code>… < …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Less_than__or_equal_operator">Less Than Or Equal</a></td> + <td><code>… <= …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator">Greater Than</a></td> + <td><code>… > …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_or_equal_operator">Greater Than Or Equal</a></td> + <td><code>… >= …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/in">in</a></td> + <td><code>… in …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/instanceof">instanceof</a></td> + <td><code>… instanceof …</code></td> + </tr> + <tr> + <td rowspan="4">10</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Equality">Equality</a></td> + <td colspan="1" rowspan="4">left-to-right</td> + <td><code>… == …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Inequality">Inequality</a></td> + <td><code>… != …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity">Strict Equality</a></td> + <td><code>… === …</code></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Nonidentity">Strict Inequality</a></td> + <td><code>… !== …</code></td> + </tr> + <tr> + <td>9</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_AND">Bitwise AND</a></td> + <td>left-to-right</td> + <td><code>… & …</code></td> + </tr> + <tr> + <td>8</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_XOR">Bitwise XOR</a></td> + <td>left-to-right</td> + <td><code>… ^ …</code></td> + </tr> + <tr> + <td>7</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR">Bitwise OR</a></td> + <td>left-to-right</td> + <td><code>… | …</code></td> + </tr> + <tr> + <td>6</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_AND">Logical AND</a></td> + <td>left-to-right</td> + <td><code>… && …</code></td> + </tr> + <tr> + <td>5</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR">Logical OR</a></td> + <td>left-to-right</td> + <td><code>… || …</code></td> + </tr> + <tr> + <td>4</td> + <td><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">Conditional</a></td> + <td>right-to-left</td> + <td><code>… ? … : …</code></td> + </tr> + <tr> + <td rowspan="13">3</td> + <td rowspan="13"><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators">Assignment</a></td> + <td rowspan="13">right-to-left</td> + <td><code>… = …</code></td> + </tr> + <tr> + <td><code>… += …</code></td> + </tr> + <tr> + <td><code>… -= …</code></td> + </tr> + <tr> + <td><code>… **= …</code></td> + </tr> + <tr> + <td><code>… *= …</code></td> + </tr> + <tr> + <td><code>… /= …</code></td> + </tr> + <tr> + <td><code>… %= …</code></td> + </tr> + <tr> + <td><code>… <<= …</code></td> + </tr> + <tr> + <td><code>… >>= …</code></td> + </tr> + <tr> + <td><code>… >>>= …</code></td> + </tr> + <tr> + <td><code>… &= …</code></td> + </tr> + <tr> + <td><code>… ^= …</code></td> + </tr> + <tr> + <td><code>… |= …</code></td> + </tr> + <tr> + <td rowspan="2">2</td> + <td>{{jsxref("Operators/yield", "yield")}}</td> + <td colspan="1" rowspan="2">right-to-left</td> + <td><code>yield …</code></td> + </tr> + <tr> + <td>{{jsxref("Operators/yield*", "yield*")}}</td> + <td><code>yield* …</code></td> + </tr> + <tr> + <td>1</td> + <td><a href="/pt-PT/docs/Web/JavaScript/Reference/Operadores/Operador_virgula">Vírgula / Sequência</a></td> + <td>left-to-right</td> + <td><code>… , …</code></td> + </tr> + </tbody> +</table> diff --git a/files/pt-pt/web/javascript/reference/sobre/index.html b/files/pt-pt/web/javascript/reference/sobre/index.html new file mode 100644 index 0000000000..3b2a79ac32 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/sobre/index.html @@ -0,0 +1,52 @@ +--- +title: Sobre a referência de JavaScript +slug: Web/JavaScript/Reference/Sobre +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/About +--- +<div>{{JsSidebar}}</div> + +<p>The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title "JavaScript reference"). If you're learning JavaScript, or need help understanding some of its capabilities or features, check out the <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript guide</a>.</p> + +<p>The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.</p> + +<h2 id="Onde_encontrar_informação_sobre_JavaScript">Onde encontrar informação sobre JavaScript</h2> + +<p>JavaScript documentation of core language features (pure <a href="/en-US/docs/Web/JavaScript/Language_Resources">ECMAScript</a>, for the most part) includes the following:</p> + +<ul> + <li><a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a></li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference">Referência JavaScript</a></li> +</ul> + +<p>If you are new to JavaScript, start with the <a href="/en-US/docs/Web/JavaScript/Guide">guide</a>. Once you have a firm grasp of the fundamentals, you can use the <a href="/en-US/docs/Web/JavaScript/Reference">reference</a> to get more details on individual objects and language constructs.</p> + +<h2 id="Estrutura_da_referência">Estrutura da referência</h2> + +<p>In the JavaScript reference you can find the following chapters:</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects">Standard built-in objects</a></dt> + <dd>This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Statements">Statements and declarations</a></dt> + <dd>JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Operators">Expressions and operators</a></dt> + <dd>This chapter documents all the JavaScript language operators, expressions and keywords.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></dt> + <dd>Chapter about JavaScript functions.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></dt> + <dd>Chapter about JavaScript classes introduced in ECMAScript 6.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Errors">Errors</a></dt> + <dd>Chapter about specific errors, exceptions and warnings thrown by JavaScript.</dd> + <dt><a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">New in JavaScript</a></dt> + <dd>Chapter about JavaScript version history.</dd> +</dl> + +<h3 id="Mais_páginas_de_referência">Mais páginas de referência</h3> + +<ul> + <li><a href="https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Funcionalidades_obsoletas">Funcionalidades obsoletas</a></li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference/Gramatica_lexical">Gramática Lexical</a></li> + <li><a href="/pt-PT/docs/Web/JavaScript/Estruturas_de_dados">Tipos de dados e estruturas de dados</a></li> +</ul> diff --git a/files/pt-pt/web/manifest/index.html b/files/pt-pt/web/manifest/index.html new file mode 100644 index 0000000000..f6329c8353 --- /dev/null +++ b/files/pt-pt/web/manifest/index.html @@ -0,0 +1,121 @@ +--- +title: Web App Manifest (Manifesto da Aplicação da Web) +slug: Web/Manifest +tags: + - Aplicação + - Manifest + - Manifesto + - Referencia + - Web +translation_of: Web/Manifest +--- +<div>{{QuickLinksWithSubpages("/en-US/docs/Web/Manifest")}}</div> + +<div>{{SeeCompatTable}}</div> + +<p>Manifestos de aplicação da Web são parte de uma coleção de tecnologias da Web chamadas de <a href="/en-US/docs/Web/Apps/Progressive">progressive web apps</a> (PWAs), que são sites da Web que podem ser instalados num ecrã inicial do dispositivo sem uma loja de aplicações. Unlike regular web apps with simple homescreen links or bookmarks, PWAs can be downloaded in advance and can work offline, as well as use regular <a href="/en-US/docs/Web/API">Web APIs</a>.</p> + +<p>The web app manifest provides information about a web application in a <a href="/en-US/docs/Glossary/JSON">JSON</a> text file, necessary for the web app to be downloaded and be presented to the user similarly to a native app (e.g., be installed on the homescreen of a device, providing users with quicker access and a richer experience). PWA manifests include its name, author, icon(s), version, description, and list of all the necessary resources (among other things).</p> + +<div class="hidden"> +<p>Can PWA manifest contain comments?<br> + It is a <a href="/en-US/docs/Glossary/JSON">JSON</a>-formatted file, with one exception: it is allowed to contain "<code>//</code>"-style comments.</p> +</div> + +<h2 id="Membros">Membros</h2> + +<p>Web manifests can contain the following keys. Click on each one to link through to more information about it:</p> + +<p>{{ListSubpages("/en-US/docs/Web/Manifest")}}</p> + +<h2 id="Manifest_exemplo"><em>Manifest</em> exemplo</h2> + +<pre class="brush: json">{ + "name": "HackerWeb", + "short_name": "HackerWeb", + "start_url": ".", + "display": "standalone", +<span class="pl-s"><span class="pl-pds"> "</span>background_color<span class="pl-pds">"</span></span>: <span class="pl-s"><span class="pl-pds">"</span>#fff<span class="pl-pds">"</span></span>, + "description": "A simply readable Hacker News app.", + "icons": [{ + "src": "images/touch/homescreen48.png", + "sizes": "48x48", + "type": "image/png" + }, { + "src": "images/touch/homescreen72.png", + "sizes": "72x72", + "type": "image/png" + }, { + "src": "images/touch/homescreen96.png", + "sizes": "96x96", + "type": "image/png" + }, { + "src": "images/touch/homescreen144.png", + "sizes": "144x144", + "type": "image/png" + }, { + "src": "images/touch/homescreen168.png", + "sizes": "168x168", + "type": "image/png" + }, { + "src": "images/touch/homescreen192.png", + "sizes": "192x192", + "type": "image/png" + }], + "related_applications": [{ + "platform": "play", + "url": "https://play.google.com/store/apps/details?id=cheeaun.hackerweb" + }] +}</pre> + +<h2 id="Deploying_a_manifest_with_the_link_tag" name="Deploying_a_manifest_with_the_link_tag">Deploying a manifest</h2> + +<p>Web app manifests are deployed in your HTML pages using a {{HTMLElement("link")}} element in the {{HTMLElement("head")}} of a document:</p> + +<pre class="brush: html"><link rel="manifest" href="/manifest.webmanifest"></pre> + +<div class="note"> +<p><strong>Note</strong>: The <code>.webmanifest</code> extension is specified in the <a href="https://w3c.github.io/manifest/#media-type-registration">Media type registration</a> section of the specification (the response of the manifest file should return <code>Content-Type: application/manifest+json</code>). Browsers generally support manifests with other appropriate extensions like <code>.json</code> (<code>Content-Type: application/json</code>).</p> +</div> + +<div class="note"> +<p><strong>Note</strong>: If the manifest requires credentials to fetch - the <code><a href="/en-US/docs/Web/HTML/CORS_settings_attributes">crossorigin</a></code> attribute must be set to <code>"use-credentials"</code>, even if the manifest file is in the same origin as the current page.</p> +</div> + +<ul> +</ul> + +<h2 id="Splash_screens">Splash screens</h2> + +<p>In Chrome 47 and later, a splash screen is displayed for sites launched from a homescreen. This splashscreen is auto-generated from properties in the web app manifest, specifically:</p> + +<ul> + <li><code><a href="/docs/Web/Manifest/name">name</a></code></li> + <li><code><a href="/docs/Web/Manifest/background_color">background_color</a></code></li> + <li>The icon in the <code><a href="/docs/Web/Manifest/icons">icons</a></code> array that is closest to 128dpi for the device.</li> +</ul> + +<h2 id="Mime_type">Mime type</h2> + +<p>Manifests should be served using the <code>application/manifest+json</code> MIME type. However, it is optional to do so. </p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + <tr> + <td>{{SpecName("Manifest")}}</td> + <td>{{Spec2("Manifest")}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{Compat("html.manifest")}}</p> diff --git a/files/pt-pt/web/mathml/attribute/index.html b/files/pt-pt/web/mathml/attribute/index.html new file mode 100644 index 0000000000..ce3ac3011c --- /dev/null +++ b/files/pt-pt/web/mathml/attribute/index.html @@ -0,0 +1,481 @@ +--- +title: Referência de atributos de MathML +slug: Web/MathML/Attribute +tags: + - MathML + - Referência de MathML +translation_of: Web/MathML/Attribute +--- +<div>{{MathMLRef}}</div> + +<p>Isto é uma lista alfabética de atributos de MathML. Mais detalhes para cada atributo estão disponiveis em certas <a href="/pt-PT/docs/Web/MathML/Element">páginas de elementos</a>.</p> + +<p>Notes:</p> + +<ul> + <li>Os elementos de MathML {{ MathMLElement("mstyle") }} e {{ MathMLElement("math") }} {{ gecko_minversion_inline("7.0") }} aceitam todos os atributos de elementos de apresentação de MathML.</li> + <li>Veja <a href="/pt-PT/docs/Web/MathML/Attribute/Valores" title="/en-US/docs/MathML/Attributes/Values">valores</a> para notas sobre valores e unidades de MathML.</li> + <li>Os atributos <code>background</code>, <code>color</code>, <code>fontfamily</code>, <code>fontsize</code>, <code>fontstyle</code>, <code>fontweight</code> e <code>xlink:href</code> estão obsoletos.</li> + <li>Os atributos de <a href="/en-US/docs/Glossary/XLink">XLink</a> em elementos de MathML: <code>xlink:actuate</code>, <code>xlink:href</code>, <code>xlink:show</code> e <code>xlink:type</code> estão obsoletos também.</li> +</ul> + +<table class="standard-table"> + <thead> + <tr> + <th>Nome</th> + <th>Elementos que aceitam o atributo</th> + <th>Descrição</th> + </tr> + </thead> + <tbody> + <tr id="accent"> + <td><code>accent</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mover") }}, {{ MathMLElement("munderover") }}</td> + <td>Um valor booleano a indicar se o operador deve ser tratado como um acento.</td> + </tr> + <tr id="accentunder"> + <td><code>accentunder</code></td> + <td>{{ MathMLElement("munder") }}, {{ MathMLElement("munderover") }}</td> + <td>Um valor booleano a indicar se o operador deve ser tratado como um acento.</td> + </tr> + <tr id="actiontype"> + <td><code>actiontype</code></td> + <td>{{ MathMLElement("maction") }}</td> + <td>Um valor <em>string</em> a indicar a ação.</td> + </tr> + <tr id="align"> + <td><code>align</code> {{deprecated_inline}}</td> + <td>{{ MathMLElement("mtable") }}<br> + {{ MathMLElement("munder") }}, {{ MathMLElement("mover") }}, {{ MathMLElement("munderover") }}<br> + {{ MathMLElement("mstack") }}</td> + <td>Indica o alinhamento de vários elementos (ver páginas de elementos para detalhes).</td> + </tr> + <tr id="alignmentscope"> + <td>{{ unimplemented_inline() }} <code>alignmentscope</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Um valor booleano a indicar se colunas da tabela devem agir como campos de alinhamento ou não.</td> + </tr> + <tr id="alt-*"> + <td>{{ unimplemented_inline() }}<br> + <code>altimg</code><br> + <code>altimg-width</code><br> + <code>altimg-height</code><br> + <code>altimg-valign</code><br> + <code>alttext</code></td> + <td>{{ MathMLElement("math") }}</td> + <td>Opções de <em>fall-back</em> visual e textual.</td> + </tr> + <tr id="bevelled"> + <td><code>bevelled</code> {{deprecated_inline}}</td> + <td>{{ MathMLElement("mfrac") }}</td> + <td>Indica o estilo em que a fração deve aparecer. Obsoleto. Use antes U+2044 (barra de fração).</td> + </tr> + <tr id="charalign"> + <td>{{ unimplemented_inline() }} <code>charalign</code></td> + <td>{{ MathMLElement("mstack") }}</td> + <td>Indica o alinhamento horizontal dos dígitos.</td> + </tr> + <tr id="close"> + <td><code>close</code></td> + <td>{{ MathMLElement("mfenced") }}</td> + <td>Uma <em>string</em> para o delimitador final.</td> + </tr> + <tr id="columnalign"> + <td><code>columnalign</code></td> + <td>{{ MathMLElement("mtable") }}, {{ MathMLElement("mtd") }}, {{ MathMLElement("mtr") }}, {{ MathMLElement("mlabeledtr") }}</td> + <td>Indica o alinhamento horizontal das células da tabela.</td> + </tr> + <tr id="columnlines"> + <td><code>columnlines</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Indica as bordas das colunas da tabela.</td> + </tr> + <tr id="columnspacing"> + <td><code>columnspacing</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Indica o espaço entre as colunas da tabela.</td> + </tr> + <tr id="columnspan"> + <td><code>columnspan</code></td> + <td>{{ MathMLElement("mtd") }}</td> + <td>Um valor integral não negativoque indica sob quantas colunas a célula se extende.</td> + </tr> + <tr id="columnwidth"> + <td>{{ unimplemented_inline() }} <code>columnwidth</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Indica a largura das colunas da tabela.</td> + </tr> + <tr id="crossout"> + <td>{{ unimplemented_inline() }} <code>crossout</code></td> + <td>{{ MathMLElement("mscarry") }}</td> + <td>Indica que linha é desenhada para riscar <em>carries</em>.</td> + </tr> + <tr id="decimalpoint"> + <td>{{ unimplemented_inline() }} <code>decimalpoint</code></td> + <td>{{ MathMLElement("mstyle") }}</td> + <td>Se o valor de <code>decimalpoint</code> é usado para indicar o alinhamento, este atributo indica carater do ponto de alinhamento dentro das colunas {{ MathMLElement("mstack") }} e {{ MathMLElement("mtable") }}.</td> + </tr> + <tr id="denomalign"> + <td><code>denomalign</code> {{deprecated_inline}}</td> + <td>{{ MathMLElement("mfrac") }}</td> + <td>O alinhamento do denominador debaixo da fração.</td> + </tr> + <tr id="depth"> + <td><code>depth</code></td> + <td>{{ MathMLElement("mpadded") }}</td> + <td>Decide ou altera a profundidade. Ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a>.</td> + </tr> + <tr id="dir"> + <td><code>dir</code></td> + <td>{{ MathMLElement("math") }}, {{ MathMLElement("mi") }}, {{ MathMLElement("mo") }}, {{ MathMLElement("mrow") }}, {{ MathMLElement("ms") }}, {{ MathMLElement("mtext") }}</td> + <td>A direção geral das fórmulas. Os valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</td> + </tr> + <tr id="display"> + <td><code>display</code></td> + <td>{{ MathMLElement("math") }}</td> + <td>Indica o modo de renderização. Os valores possiveis são <code>block</code> e <code>inline</code>.</td> + </tr> + <tr id="displaystyle"> + <td><code>displaystyle</code></td> + <td>{{ MathMLElement("mstyle") }}, {{ MathMLElement("mtable") }}</td> + <td>Um valor <code>Boolean</code> que indica se mais espaço é usado para visualizar equações ou, se <code>false</code>, uma apresentação mais compacta é usada para apresentar as formulas.</td> + </tr> + <tr id="edge"> + <td>{{ unimplemented_inline() }} <code>edge</code></td> + <td>{{ MathMLElement("malignmark") }}</td> + <td></td> + </tr> + <tr id="equalcolumns"> + <td>{{ unimplemented_inline() }} <code>equalcolumns</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Um valor <code>Boolean</code> que indica se todas as colunas devem ser forçadas a ter a mesma altura total.</td> + </tr> + <tr id="equalrows"> + <td>{{ unimplemented_inline() }} <code>equalrows</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Um valor <code>Boolean</code> que indica se todas as linhas devem ser forçadas a ter a mesma altura total.</td> + </tr> + <tr id="fence"> + <td><code>fence</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>Um valor <code>Boolean</code> que indica se o operador é uma cerca (como as parenteses). Não existe um efeito visual para este atributo.</td> + </tr> + <tr id="form"> + <td>{{ unimplemented_inline() }} <code>form</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>Indica a função do operador dentro duma expressão.</td> + </tr> + <tr id="frame"> + <td><code>frame</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Indica as bordas do elemento {{ MathMLElement("mtable") }}. Os valores possiveis são: <code>none</code> (pré-definido), <code>solid</code> e <code>dashed</code>.</td> + </tr> + <tr id="framespacing"> + <td><code>framespacing</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Indica o espaço adicional entre a tabela e a <code>frame</code>.</td> + </tr> + <tr id="groupalign"> + <td>{{ unimplemented_inline() }} <code>groupalign</code></td> + <td>{{ MathMLElement("maligngroup") }}, {{ MathMLElement("mtable") }}, {{ MathMLElement("mtd") }}, {{ MathMLElement("mtr") }}</td> + <td></td> + </tr> + <tr id="height"> + <td><code>height</code></td> + <td>{{ MathMLElement("mglyph") }}, {{ MathMLElement("mpadded") }}, {{ MathMLElement("mspace") }}</td> + <td>Indica a altura desejada. Ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimentos</a> para os valores aceites.</td> + </tr> + <tr id="href"> + <td><code>href</code></td> + <td><em>Todos</em></td> + <td>Usado para criar uma hiperligação apontando a uma URI especificado.</td> + </tr> + <tr id="id"> + <td><code>id</code></td> + <td><em>Todos</em></td> + <td>Define um identificador unico associado ao elemento.</td> + </tr> + <tr id="indentalign"> + <td>{{ unimplemented_inline() }} <code>indentalign</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="indentalignfirst"> + <td>{{ unimplemented_inline() }} <code>indentalignfirst</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="indentalignlast"> + <td>{{ unimplemented_inline() }} <code>indentalignlast</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="indentshift"> + <td>{{ unimplemented_inline() }} <code>indentshift</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="indentshiftfirst"> + <td>{{ unimplemented_inline() }} <code>indentshiftfirst</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="indentshiftlast"> + <td>{{ unimplemented_inline() }} <code>indentshiftlast</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="indenttarget"> + <td>{{ unimplemented_inline() }} <code>indenttarget</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="infixlinebreakstyle"> + <td>{{ unimplemented_inline() }} <code>infixlinebreakstyle</code></td> + <td>{{ MathMLElement("mstyle") }}</td> + <td>Indica o <code>linebreakstyle</code> pré-definido para usar com operadores <em>infix</em>.</td> + </tr> + <tr id="largeop"> + <td><code>largeop</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>Indica se o operador dwvw ser desenhado maior que o normal.</td> + </tr> + <tr id="length"> + <td><code>length</code></td> + <td>{{ MathMLElement("msline") }}</td> + <td></td> + </tr> + <tr id="linebreak"> + <td>{{ unimplemented_inline() }} <code>linebreak</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="linebreakmultchar"> + <td>{{ unimplemented_inline() }} <code>linebreakmultchar</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="linebreakstyle"> + <td>{{ unimplemented_inline() }} <code>linebreakstyle</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="lineleading"> + <td>{{ unimplemented_inline() }} <code>lineleading</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mspace") }}</td> + <td></td> + </tr> + <tr id="linethickness"> + <td><code>linethickness</code></td> + <td>{{ MathMLElement("mfrac") }}</td> + <td>A espessura da linha de fração horizontal.</td> + </tr> + <tr id="location"> + <td>{{ unimplemented_inline() }} <code>location</code></td> + <td>{{ MathMLElement("mscarries") }}</td> + <td></td> + </tr> + <tr id="longdivstyle"> + <td>{{ unimplemented_inline() }} <code>longdivstyle</code></td> + <td>{{ MathMLElement("mlongdiv") }}</td> + <td>Controla o estilo da apresentação da divisão longa.</td> + </tr> + <tr id="lspace"> + <td><code>lspace</code></td> + <td>{{ MathMLElement("mo") }}, {{ MathMLElement("mpadded") }}</td> + <td>A quantidade de espaço antes do operador (ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> para valores e unidades).</td> + </tr> + <tr id="lquote"> + <td><code>lquote</code></td> + <td>{{ MathMLElement("ms") }}</td> + <td>O carácter de citação de abertura (depende da direção indicada por <code>dir</code>) para delimitar o conteúdo. O valor pré-definido é <code>&quot;</code>.</td> + </tr> + <tr id="mathbackground"> + <td><code>mathbackground</code></td> + <td><em>Todos</em></td> + <td>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</td> + </tr> + <tr id="mathcolor"> + <td><code>mathcolor</code></td> + <td><em>Todos</em></td> + <td>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</td> + </tr> + <tr id="mathsize"> + <td><code>mathsize</code></td> + <td>{{ MathMLElement("mi") }}, {{ MathMLElement("mn") }}, {{ MathMLElement("mo") }}, {{ MathMLElement("ms") }}, {{ MathMLElement("mtext") }}</td> + <td>O tamanho do conteúdo.</td> + </tr> + <tr id="mathvariant"> + <td><code>mathvariant</code></td> + <td>{{ MathMLElement("mi") }}, {{ MathMLElement("mn") }}, {{ MathMLElement("mo") }}, {{ MathMLElement("ms") }}, {{ MathMLElement("mtext") }}</td> + <td> A classe lógica do identificador, que varia em tipografia.</td> + </tr> + <tr id="maxsize"> + <td><code>maxsize</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>O tamanho máximo do operador.</td> + </tr> + <tr id="minlabelspacing"> + <td>{{ unimplemented_inline() }} <code>minlabelspacing</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td> + <p>Um <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">valor de comprimento</a> que indica o espaço minimimo entre uma etiqueta e a célula adjacente numa linha.</p> + </td> + </tr> + <tr id="minsize"> + <td><code>minsize</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>O tamanho minimo do operador.</td> + </tr> + <tr id="movablelimits"> + <td><code>movablelimits</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>Indicia se <em>under-</em> e <em>overscripts</em> auxiliares movem para posições de <em>sub-</em> e <em>superscript</em>.</td> + </tr> + <tr id="notation"> + <td><code>notation</code></td> + <td>{{ MathMLElement("menclose") }}</td> + <td>A lista de notações, separada por espaços, para aplicar aos elementos filhos.</td> + </tr> + <tr id="numalign"> + <td><code>numalign</code> {{deprecated_inline}}</td> + <td>{{ MathMLElement("mfrac") }}</td> + <td>O alinhamento do numerador sob a fração.</td> + </tr> + <tr id="open"> + <td><code>open</code></td> + <td>{{ MathMLElement("mfenced") }}</td> + <td>Uma <em>string</em> para o delimitador inicial.</td> + </tr> + <tr id="overflow"> + <td>{{ unimplemented_inline() }} <code>overflow</code></td> + <td>{{ MathMLElement("math") }}</td> + <td>Especifica como a expressão se comporta no caso de ser demasiada comprida para a largura máxima permitida.</td> + </tr> + <tr id="position"> + <td>{{ unimplemented_inline() }} <code>position</code></td> + <td>{{ MathMLElement("msgroup") }}, {{ MathMLElement("msrow") }}, {{ MathMLElement("mscarries") }}, {{ MathMLElement("msline") }}</td> + <td></td> + </tr> + <tr id="rowalign"> + <td><code>rowalign</code></td> + <td>{{ MathMLElement("mtable") }}, {{ MathMLElement("mtd") }}, {{ MathMLElement("mtr") }}</td> + <td>Indica o alinhamento vertical das células da tabela.</td> + </tr> + <tr id="rowlines"> + <td><code>rowlines</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Especifica o estilo das bordas das linhas da tabela.</td> + </tr> + <tr id="rowspacing"> + <td><code>rowspacing</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Specifies the space between table rows.</td> + </tr> + <tr id="rowspan"> + <td><code>rowspan</code></td> + <td>{{ MathMLElement("mtd") }}</td> + <td>Um integral não negativo que indica qual o número de linhas (<em>rows</em>) sob qual a célula se estende.</td> + </tr> + <tr id="rspace"> + <td><code>rspace</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>O espaço após o operador.</td> + </tr> + <tr id="rquote"> + <td><code>rquote</code></td> + <td>{{ MathMLElement("ms") }}</td> + <td>O carácter de citação de fecho (depende da direção indicada por <code>dir</code>) para delimitar o conteúdo. O valor pré-definido é <code>&quot;</code>.</td> + </tr> + <tr id="scriptlevel"> + <td><code>scriptlevel</code></td> + <td>{{ MathMLElement("mstyle") }}</td> + <td>Controla sobretudo o tamanho da fonte. Quanto mais alto for valor do <code>scriptlevel</code>, menor será o tamanho da fonte.</td> + </tr> + <tr id="scriptminsize"> + <td><code>scriptminsize</code></td> + <td>{{ MathMLElement("mstyle") }}</td> + <td>Indica o mínimo valor permitido do tamanho da fonte devido a mudanças causadas por <code>scriptlevel</code>.</td> + </tr> + <tr id="scriptsizemultiplier"> + <td><code>scriptsizemultiplier</code></td> + <td>{{ MathMLElement("mstyle") }}</td> + <td>Indica o multiplicadorque deve ser usado para ajustar o tamanho da fonte devido a mudanças causadas por <code>scriptlevel</code>.</td> + </tr> + <tr id="selection"> + <td><code>selection</code></td> + <td>{{ MathMLElement("maction") }}</td> + <td>O elemento, contido dentro do elemento que detem o atributo, a qual a ação se aplica.</td> + </tr> + <tr id="separator"> + <td><code>separator</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>Não existe um efeito visual para este atributo, mas indica se o operador é um separador (como virgulas).</td> + </tr> + <tr id="separators"> + <td><code>separators</code></td> + <td>{{ MathMLElement("mfenced") }}</td> + <td>Uma sequencia de 0 ou mais carateres para serem usados como diferentes separadores.</td> + </tr> + <tr id="shift"> + <td>{{ unimplemented_inline() }} <code>shift</code></td> + <td>{{ MathMLElement("msgroup") }}</td> + <td></td> + </tr> + <tr id="side"> + <td>{{ unimplemented_inline() }} <code>side</code></td> + <td>{{ MathMLElement("mtable") }}</td> + <td>Indica a posição onde a etiqueta de {{ MathMLElement("mlabeledtr") }} deve ser posta.</td> + </tr> + <tr id="src"> + <td>{{ unimplemented_inline() }} <code>src</code></td> + <td>{{ MathMLElement("mglyph") }}</td> + <td>O local de origem dos dados da imagem.</td> + </tr> + <tr id="stackalign"> + <td>{{ unimplemented_inline() }} <code>stackalign</code></td> + <td>{{ MathMLElement("mstack") }}</td> + <td></td> + </tr> + <tr id="stretchy"> + <td><code>stretchy</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>Indica se o operador estica até ao tamanho do elemento adjacente.</td> + </tr> + <tr id="subscriptshift"> + <td><code>subscriptshift</code> {{deprecated_inline}}</td> + <td>{{ MathMLElement("mmultiscripts") }}, {{ MathMLElement("msub") }}, {{ MathMLElement("msubsup") }}</td> + <td>O espaço minimo para adicionar entre o subscript e a linha base da expressão.</td> + </tr> + <tr id="supscriptshift"> + <td><code>supscriptshift</code> {{deprecated_inline}}</td> + <td>{{ MathMLElement("mmultiscripts") }}, {{ MathMLElement("msup") }}, {{ MathMLElement("msubsup") }}</td> + <td>O espaço minimo para adicionar entre o superscript e a linha base da expressão.</td> + </tr> + <tr id="symmetric"> + <td><code>symmetric</code></td> + <td>{{ MathMLElement("mo") }}</td> + <td>Se <code>stretchy</code> é <code>true</code>, este atributo indica se o operador deve ser verticalmente simetrico à volta do eixo imaginario (linha de fracção centrada).</td> + </tr> + <tr id="voffset"> + <td><code>voffset</code></td> + <td>{{ MathMLElement("mpadded") }}</td> + <td>Indica a posição vertical do conteúdo.</td> + </tr> + <tr id="width"> + <td><code>width</code></td> + <td>{{ MathMLElement("mglyph") }}, {{ MathMLElement("mpadded") }}, {{ MathMLElement("mspace") }}, {{ MathMLElement("mtable") }}</td> + <td>Indica a largura desejada. Ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" title="/en-US/docs/MathML/Attributes/Values#Lengths">comprimentos</a> para valores possíveis.</td> + </tr> + <tr id="xlink-href"> + <td><code>xlink:href</code> {{deprecated_inline}}</td> + <td><em>Todos</em></td> + <td>Pode ser usado para criar uma hiperligação a uma URI. Porem, autores são encorajados antes a usar o atributo <code>href</code>.</td> + </tr> + <tr id="xmlns"> + <td><code>xmlns</code></td> + <td>{{ MathMLElement("math") }}</td> + <td>Indica o URI para o <em>namespace</em> de MathML (<code><a class="external" href="http://www.w3.org/1998/Math/MathML" rel="freelink">http://www.w3.org/1998/Math/MathML</a></code>)</td> + </tr> + </tbody> +</table> diff --git a/files/pt-pt/web/mathml/attribute/valores/index.html b/files/pt-pt/web/mathml/attribute/valores/index.html new file mode 100644 index 0000000000..62a23acd8d --- /dev/null +++ b/files/pt-pt/web/mathml/attribute/valores/index.html @@ -0,0 +1,153 @@ +--- +title: Valores +slug: Web/MathML/Attribute/Valores +tags: + - Guía + - MathML + - Referência de MathML +translation_of: Web/MathML/Attribute/Values +--- +<div>{{MathMLRef}}</div> + +<h2 id="Comprimentos">Comprimentos</h2> + +<p>Vários elementos de apresentação MathML têm atributos que aceitam valores de comprimento usados para dimensões ou espaçamento. MathML aceita diferentes unidades e constantes para indicar comprimentos.</p> + +<h3 id="Unidades">Unidades</h3> + +<table class="standard-table"> + <thead> + <tr> + <th>Unidade</th> + <th>Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>em</code></td> + <td>Unidade {{ Cssxref("font-size", "relativa à fonte") }}</td> + </tr> + <tr> + <td><code>ex</code></td> + <td>Unidade {{ Cssxref("font-size", "relativa à fonte") }}. (A altura "x" do elemento, <code>1ex ≈ 0.5em</code> em muitas fontes)</td> + </tr> + <tr> + <td><code>px</code></td> + <td>Pixeis</td> + </tr> + <tr> + <td><code>in</code></td> + <td>Polegadas (1 polegada = 2,54 centímetros)</td> + </tr> + <tr> + <td><code>cm</code></td> + <td>Centímetros</td> + </tr> + <tr> + <td><code>mm</code></td> + <td>Milímetros</td> + </tr> + <tr> + <td><code>pt</code></td> + <td>Pontos (1 ponto = 1/72 polegada)</td> + </tr> + <tr> + <td><code>pc</code></td> + <td>Picas (1 pica = 12 pontos)</td> + </tr> + <tr> + <td><code>%</code></td> + <td>Percentagem do valor padrão.</td> + </tr> + </tbody> +</table> + +<h3 id="Constantes">Constantes</h3> + +<p>{{deprecated_header}}</p> + +<p>Um substituto para as constantes depreciadas abaixo é:</p> + +<pre class="notranslate"><code>veryverythinmathspace => 0.05555555555555555em +verythinmathspace => 0.1111111111111111em +thinmathspace => 0.16666666666666666em +mediummathspace => 0.2222222222222222em +thickmathspace => 0.2777777777777778em +verythickmathspace => 0.3333333333333333em +veryverythickmathspace => 0.3888888888888889em</code></pre> + +<table class="standard-table"> + <thead> + <tr> + <th>Constante</th> + <th>Valor</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>veryverythinmathspace</code></td> + <td>1/18<code>em</code></td> + </tr> + <tr> + <td><code>verythinmathspace</code></td> + <td>2/18<code>em</code></td> + </tr> + <tr> + <td><code>thinmathspace</code></td> + <td>3/18<code>em</code></td> + </tr> + <tr> + <td><code>mediummathspace</code></td> + <td>4/18<code>em</code></td> + </tr> + <tr> + <td><code>thickmathspace</code></td> + <td>5/18<code>em</code></td> + </tr> + <tr> + <td><code>verythickmathspace</code></td> + <td>6/18<code>em</code></td> + </tr> + <tr> + <td><code>veryverythickmathspace</code></td> + <td>7/18<code>em</code></td> + </tr> + </tbody> + <thead> + <tr> + <th colspan="2"><em>Constantes</em> negativas são introduzidas em Gecko 7.0 {{ geckoRelease("7.0") }} ({{ bug(650530) }})</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>negativeveryverythinmathspace</code></td> + <td>-1/18<code>em</code></td> + </tr> + <tr> + <td><code>negativeverythinmathspace</code></td> + <td>-2/18<code>em</code></td> + </tr> + <tr> + <td><code>negativethinmathspace</code></td> + <td>-3/18<code>em</code></td> + </tr> + <tr> + <td><code>negativemediummathspace</code></td> + <td>-4/18<code>em</code></td> + </tr> + <tr> + <td><code>negativethickmathspace</code></td> + <td>-5/18<code>em</code></td> + </tr> + <tr> + <td><code>negativeverythickmathspace</code></td> + <td>-6/18<code>em</code></td> + </tr> + <tr> + <td><code>negativeveryverythickmathspace</code></td> + <td>-7/18<code>em</code></td> + </tr> + </tbody> +</table> + +<p>Nota: <a class="external" href="http://www.w3.org/TR/MathML3/chapter3.html#id.3.3.4.2.1" rel="external" title="http://www.w3.org/TR/MathML3/chapter3.html#id.3.3.4.2.1">Associação através de <em>namespace</em> está depreciado</a> em MathML3 e foi removido em Gecko 15.0 {{ geckoRelease("15.0") }} (<a class="external" href="https://bugzilla.mozilla.org/show_bug.cgi?id=673759" rel="external">bug 673759</a>).</p> diff --git a/files/pt-pt/web/mathml/authoring/index.html b/files/pt-pt/web/mathml/authoring/index.html new file mode 100644 index 0000000000..065bee238b --- /dev/null +++ b/files/pt-pt/web/mathml/authoring/index.html @@ -0,0 +1,350 @@ +--- +title: Escrever MathML +slug: Web/MathML/Authoring +tags: + - Beginner + - MathML + - Projeto MathML +translation_of: Web/MathML/Authoring +--- +<p>Esta página explica como se escreve matemática através da linguagem MathML. Como o HTML, o MathML é descrito com tags e atributos. O HTML torna-se verboso quando o seu documento contém estruturas avançadas como listas ou tabelas mas felizmente existem muitos geradores de simples notações, editores WYSIWYG e outros Sistemas de Gestão de Conteúdos para ajudar a escrever páginas Web.</p> + +<p>Mathematical notations are even more complex with structures like fractions, square roots or matrices that are likely to require their own tags. As a consequence, good MathML authoring tools are more important and we describe some tools below. In particular, the Mozilla MathML team has been developing <a href="https://github.com/fred-wang/TeXZilla/">TeXZilla</a>, a Javascript Unicode LaTeX-to-MathML converter that is intended to be used in many scenarios described here. Of course, the list is by no means exhaustive and you are invited to check out the <a class="external" href="http://www.w3.org/Math/Software/">W3C MathML software list</a> where you can find various other tools.</p> + +<p>As notações matemáticas são ainda mais complexas com estruturas como fracções, raízes quadradas ou matrizes que provavelmente exigirão as suas próprias etiquetas. Como consequência, as boas ferramentas de autoria de MathML são mais importantes, e descrevemos algumas ferramentas abaixo. Em particular, a equipa do Mozilla MathML tem vindo a desenvolver o <a href="https://github.com/fred-wang/TeXZilla/">TeXZilla</a>, um conversor Javascript Unicode LaTeX para MathML que se destina a ser utilizado em muitos cenários aqui descritos. É claro que a lista não é de modo algum exaustiva e está convidado a consultar <a href="http://www.w3.org/Math/Software/">a lista de software MathML do W3C</a>, onde pode encontrar várias outras ferramentas.</p> + +<p>MathML está bem integrado em HTML5 e, em particular, pode usar características habituais da Web como CSS, DOM, Javascript ou SVG. Isto está fora do âmbito deste documento, mas qualquer pessoa com conhecimentos básicos de línguas Web poderá facilmente misturar estas características com MathML. Consulte <a href="/en-US/docs/Mozilla/MathML_Project#Sample_MathML_Documents">as nossas demos</a> e <a href="/pt-PT/docs/Web/MathML">referências de MathML</a> para mais detalhes.</p> + +<h2 id="Usar_MathML">Usar MathML</h2> + +<h4 id="Example_in_HTML5_texthtml" name="Example_in_HTML5_(text/html)">MathML em páginas de HTML</h4> + +<p>Pode usar <em>Presentation MathML</em> dentro de documentos de HTML5:</p> + +<pre class="brush: html notranslate"><!DOCTYPE html> +<html> +<head> + <title>MathML in HTML5</title> +</head> +<body> + + <h1>MathML in HTML5</h1> + + <p> + Square root of two: + <math> + <msqrt> + <mn>2</mn> + </msqrt> + </math> + </p> + +</body> +</html> </pre> + +<p><em>Content MathML</em> não é suportado por navegadores. É recomendado converter o conteudo de <em>Content MathML</em> em <em>Presentation MathML</em> antes do publicar, como o <em>stylesheet</em> <a class="external" href="http://code.google.com/p/web-xslt/source/browse/trunk/#trunk/ctop">ctop.xsl</a>. As ferramentas mencionadas nesta página gerem <em>Presentation MathML</em>.</p> + +<h4 id="Contingência_para_navegadores_que_não_apoiam_MathML">Contingência para navegadores que não apoiam MathML</h4> + +<p>Infelizmente, alguns navegadores não são capazes de fazer equações MathML ou têm apenas um suporte limitado. Consequentemente, será necessário utilizar um polyfil para MathML para fornecer alguma renderização de recurso. Se precisar apenas de construções matemáticas básicas como as utilizadas nesta wiki MDN, então uma pequena folha de estilo <a href="https://github.com/fred-wang/mathml.css">mathml.css</a> poderá ser suficiente. Para a utilizar, basta inserir uma linha no cabeçalho do seu documento:</p> + +<pre class="brush: html notranslate"><script src="https://fred-wang.github.io/mathml.css/mspace.js"></script></pre> + +<p>Se precisar de construções mais complexas, poderá, em vez disso, considerar a utilização da biblioteca MathJax mais pesada como um polifill MathML:</p> + +<p>Se precisar de construções mais complexas, poderá, em vez disso, considerar a utilização da biblioteca <a href="http://www.mathjax.org">MathJax</a> mais pesada como um polifill MathML:</p> + +<pre class="brush: html notranslate"><script src="https://fred-wang.github.io/mathjax.js/mpadded-min.js"></script></pre> + +<p>É de destacar que estes dois <em>scripts</em> realizam a detecção dos elementos <a href="/pt-PT/docs/Web/MathML/Element/mspace">mspace</a> ou <a href="/pt-PT/docs/Web/MathML/Element/mpadded">mpadded</a> (ver a tabela de compatibilidade nestas páginas). Existe também um script semelhante para exibir um aviso no topo da página para navegadores sem bom suporte MathML e deixar os utilizadores escolherem entre uma das alternativas acima:</p> + +<pre class="brush: html notranslate"><script src="https://fred-wang.github.io/mathml-warning.js/mpadded-min.js"></script></pre> + +<p>Se não quiser utilizar esta hiperligação para o GitHub mas sim integrar estes polyfills ou outros no seu próprio projecto, poderá precisar dos scripts de detecção para verificar o nível de suporte de MathML. Por exemplo, a função seguinte verifica o suporte MathML testando o elemento mspace (pode substituir o <code>mspace</code> por <code>mpadded</code>):</p> + +<pre class="brush: js notranslate"> function hasMathMLSupport() { + var div = document.createElement("div"), box; + div.innerHTML = "<math><mspace height='23px' width='77px'/></math>"; + document.body.appendChild(div); + box = div.firstChild.firstChild.getBoundingClientRect(); + document.body.removeChild(div); + return Math.abs(box.height - 23) <= 1 && Math.abs(box.width - 77) <= 1; +}</pre> + +<p>Em alternativa, o seguinte deteção de strings do UA permitirá detectar os motores de renderização com suporte nativo de MathML (Gecko e WebKit). Note-se que a deteção de strings do UA não é o método mais fiável e pode falhar de versão para versão:</p> + +<pre class="brush: js notranslate">var ua = navigator.userAgent; +var isGecko = ua.indexOf("Gecko") > -1 && ua.indexOf("KHTML") === -1 && ua.indexOf('Trident') === -1; +var isWebKit = ua.indexOf('AppleWebKit') > -1 && ua.indexOf('Chrome') === -1; +</pre> + +<h4 id="Fontes_matemáticas">Fontes matemáticas</h4> + +<p>A fim de obter uma boa formatação ou de permitir um estilo diferente, é importante ter fontes matemáticas disponíveis. É sempre bom fornecer uma ligação às <a href="/pt-PT/docs/Mozilla/MathML_Project/Fonts">Instruções de Fontes da MDN</a>, para que os seus visitantes possam verificar se têm fontes apropriadas instaladas no seu sistema. Também é bom fornecer um contigente com fontes da Web.</p> + +<p>Antes de Gecko 31.0 {{GeckoRelease("31.0")}}, era um pouco aborrecido configurar fontes matemáticas (ver as instruções da fonte para Mozilla 2.0). Para Gecko 31.0 {{GeckoRelease("31.0")}}, isto é muito mais simples e é compatível com qualquer motor de renderização Web com suporte MathML. Por exemplo, aqui está uma folha de estilo mínima para usar o latim moderno para o texto e o latim moderno matemático para a matemática:</p> + +<pre class="brush: css notranslate">@namespace url('http://www.w3.org/1999/xhtml'); +@namespace m url('http://www.w3.org/1998/Math/MathML'); + +body, m|mtext { + font-family: Latin Modern; +} +m|math { + font-family: Latin Modern Math; +}</pre> + +<p>Pode usar a regra <a href="/pt-PT/docs/Web/CSS/@font-face">@font-face</a> como normal para ofrecer uma alternativa WOFF para <em>Latin Modern</em> e <em>Latin Modern Math</em>. Veja este <a href="https://github.com/fred-wang/MathFonts">repositório no GitHub para encontrar fontes WOFF e exemplos de stylesheets de CSS</a> para usar no seu site e verifique <a href="http://fred-wang.github.io/MathFonts/">a página de teste</a>.</p> + +<h4 id="MathML_em_documentos_de_XML_XHTML_EPUB_etc">MathML em documentos de XML (XHTML, EPUB, etc)</h4> + +<p>Se por alguma razão precisar de usar MathML em documentos de XML, certifique-se que satisfaz os requerimentos habituais: um documento bem formatado, o tipo de MIME correto, o <em>namespace</em> de MathML <code>"http://www.w3.org/1998/Math/MathML"</code> nas raizes <code><math></code>. Por exemplo, a versão XHTML do exemplo anterior fica assim:</p> + +<pre class="brush: xml notranslate"><?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" + "http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <title>XHTML+MathML Example</title> +</head> +<body> + +<h1>XHTML+MathML Example</h1> + + <p> + Square root of two: + <math xmlns="http://www.w3.org/1998/Math/MathML"> + <msqrt> + <mn>2</mn> + </msqrt> + </math> + </p> + +</body> +</html> </pre> + +<h4 id="MathML_em_email_e_clientes_de_comunicação_instantânea">MathML em email e clientes de comunicação instantânea</h4> + +<p>Os clientes de correio modernos podem enviar e receber correio electrónico no formato HTML5 e assim podem utilizar expressões MathML. Certifique-se de que as opções "enviar como HTML" e "ver como HTML" estão activadas. No Thunderbird, pode usar o comando "Inserir HTML" para colar o seu código HTML e MathML. <a href="http://disruptive-innovations.com/zoo/MathBird/">MathBird</a> é um add-on conveniente para o Thunderbird inserir tais expressões MathML usando a sintaxe de AsciiMath. Além disso, uma caixa de entrada LaTeX-to-MathML foi também integrada no <a href="http://www.seamonkey-project.org/">SeaMonkey</a> desde a versão 2.28 e no <a href="https://www.mozilla.org/thunderbird/">Thunderbird</a> desde a versão 31. A forma como o MathML é tratado e a qualidade da renderização do MathML <a href="http://web.archive.org/web/20160304021257/http://www.maths-informatique-jeux.com/blog/frederic/?post/2012/11/14/Writing-mathematics-in-emails#c121">depende do cliente de correio</a> e mesmo que o seu browser suporte MathML, o seu Webmail pode impedi-lo de enviar ou receber e-mails com MathML dentro.</p> + +<p>Os clientes de mensagens instantâneas baseadas no Gecko podem integrar um conversor de texto para MathML baseado em Javascript (mencionado abaixo) e depois renderizar as expressões MathML geradas a partir das mensagens instantâneas (em texto simples). Por exemplo, existe um add-on para o Instantbird que trata das expressões LaTeX.</p> + +<h2 id="Converção_a_partir_de_Sintaxe_Simples">Converção a partir de Sintaxe Simples</h2> + +<p>Existem muitas notações simples (por exemplo, wiki ou sintaxes markdown) para gerar páginas HTML. O mesmo é válido para MathML: por exemplo, as sintaxes ASCII utilizadas em calculadoras ou a linguagem mais poderosa LaTeX, muito popular entre a comunidade científica. Nesta secção, apresentamos algumas destas ferramentas para converter de uma simples sintaxe para MathML.</p> + +<ul> + <li>pros: + <ul> + <li>Escrever expressões matemáticas pode requerer só um editor de texto simples.</li> + <li>Muitas ferramentas estão disponiveis, algumas são compativeis com o workflow clássico de LaTeX-to-pdf.</li> + <li>Oferece accesso a funções avancadas de macros estilo LaTeX.</li> + </ul> + </li> + <li>cons: + <ul> + <li>Pode ser mais dificil de usar: o utilizador tem de aprender o sintaxe, pois erros no código podem causar erros no processamento, na apresentação final, etc.</li> + <li>A interface não é muito accessivel: é só um editor de texto sem a apresentação imediata do produto final.</li> + <li>O sintaxe não tem um padrão decidido, fazendo com que a compatibilidade entre conversores seja dificil. Até a linguagem populat LaTeX continua a crescer e a ser atualizada.</li> + </ul> + </li> +</ul> + +<h3 id="Converção_client-side">Converção <em>client-side</em></h3> + +<p>In a Web environment, the most obvious method to convert a simple syntax into a DOM tree is to use Javascript and of course many libraries have been developed to perform that task.</p> + +<ul> + <li>pros: + <ul> + <li>This is very easy setup: only a few Javascript and CSS files to upload and/or a link to add to your document header.</li> + <li>This is a pure Web-based solution: everything is done by the browsers and no other programs must be installed or compiled.</li> + </ul> + </li> + <li>cons: + <ul> + <li>This won't work if the visitor has Javascript disabled.</li> + <li>The MathML code is not exposed to Web crawlers (e.g. those of math search engines or feed aggregators). In particular, your content won't show up properly on Planet.</li> + <li>The conversion must be done at each page load, may be slow and may conflict with the HTML parsing (e.g. "<" for tags or "$" for money amounts)</li> + <li>You may need to synchronize the Javascript converter with other Javascript programs on your page.</li> + </ul> + </li> +</ul> + +<p><a href="https://github.com/fred-wang/TeXZilla">TeXZilla</a> has an <a href="https://github.com/fred-wang/x-tex"><x-tex></a> custom element, that can be used to write things like</p> + +<pre class="notranslate"><span class="brush: html"><<span class="start-tag">x-tex</span>></span><span>\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1</span><span class="brush: html"></<span class="end-tag">x-tex</span>></span></pre> + +<p>and get it automatically converted into MathML. This is still a work-in-progress, but could be improved in the future thanks to Web Components and shadow DOM. Alternatively, you can use the more traditional <a href="https://github.com/fred-wang/TeXZilla/wiki/Advanced-Usages#parsing-tex-expressions-in-your-web-page">Javascript parsing of expressions at load time</a> as all the other tools in this section do.</p> + +<p>One simple client-side conversion tools is <a href="http://www1.chapman.edu/~jipsen/mathml/asciimath.html" title="http://www1.chapman.edu/~jipsen/mathml/asciimath.html">ASCIIMathML</a>. Just download the <a href="http://mathcs.chapman.edu/~jipsen/mathml/ASCIIMathML.js" title="http://mathcs.chapman.edu/~jipsen/mathml/ASCIIMathML.js">ASCIIMathML.js</a> script and copy it to your Web site. Then on your Web pages, add a <code><script></code> tag to load ASCIIMathML and the mathematical expressions delimited by <code>`</code> (grave accent) will be automatically parsed and converted to MathML:</p> + +<pre class="brush: html notranslate"><html> +<head> +... +<script type="text/javascript" src="ASCIIMathML.js"></script> +... +</head> +<body> +... +<p>blah blah `x^2 + y^2 = r^2` blah ... +... +</pre> + +<p><a href="http://math.etsu.edu/LaTeXMathML/" title="http://math.etsu.edu/LaTeXMathML/">LaTeXMathML</a> is a similar script that allows to parse more LaTeX commands. The installation is similar: copy <a href="http://math.etsu.edu/LaTeXMathML/LaTeXMathML.js" title="http://math.etsu.edu/LaTeXMathML/LaTeXMathML.js">LaTeXMathML.js</a> and <a href="http://math.etsu.edu/LaTeXMathML/LaTeXMathML.standardarticle.css" title="http://math.etsu.edu/LaTeXMathML/LaTeXMathML.standardarticle.css">LaTeXMathML.standardarticle.css</a>, add links in the header of your document and the LaTeX content of your Web page marked by the "LaTeX" class will be automatically parsed and converted to HTML+MathML:</p> + +<pre class="brush: html notranslate"><span><<span class="start-tag">head</span>></span> +<span>... +</span><span><<span class="start-tag">script</span> <span class="attribute-name">type</span>="<a class="attribute-value">text/javascript</a>" <span class="attribute-name">src</span>="<a class="attribute-value">LaTeXMathML.js</a>"></span><span></<span class="end-tag">script</span>></span><span> +</span><span><<span class="start-tag">link</span> <span class="attribute-name">rel</span>="<a class="attribute-value">stylesheet</a>" <span class="attribute-name">type</span>="<a class="attribute-value">text/css</a>" <span class="attribute-name">href</span>="<a class="attribute-value">LaTeXMathML.standardarticle.css</a>" <span>/</span>></span><span> +... +</span><span></<span class="end-tag">head</span>></span><span> + +</span><span><<span class="start-tag">body</span>></span><span> +... + +</span><div class="LaTeX"> +\documentclass[12pt]{article} + +\begin{document} + +\title{LaTeXML Example} +\maketitle + +\begin{abstract} +This is a sample LaTeXML document. +\end{abstract} + +\section{First Section} + + $$ \sum_{n=1}^{+\infty} \frac{1}{n^2} = \frac{\pi^2}{6} $$ + +\end{document} +</div> +...</pre> + +<p><a href="http://mathscribe.com/author/jqmath.html" title="http://mathscribe.com/author/jqmath.html">jqMath</a> is another script to parse a simple LaTeX-like syntax but which also accepts non-ASCII characters like <code>√{∑↙{n=1}↖{+∞} 6/n^2} = π</code> to write <math> <mrow> <msqrt> <mrow class="ma-repel-adj"> <munderover> <mo>∑</mo> <mrow> <mi>n</mi> <mo>=</mo> <mn>1</mn> </mrow> <mrow> <mo>+</mo> <mi>∞</mi> </mrow> </munderover> <mfrac> <mn>6</mn> <msup> <mi>n</mi> <mn>2</mn> </msup> </mfrac> </mrow> </msqrt> <mo>=</mo> <mi>π</mi> </mrow> </math>. The installation is similar: download and copy the relevant <a href="http://mathscribe.com/downloads/mathscribe-unix-0.4.0.zip" title="http://mathscribe.com/downloads/mathscribe-unix-0.4.0.zip">Javascript and CSS files</a> on your Web site and reference them in your page header (see the <code>COPY-ME.html</code> file from the zip archive for an example). One of the advantage of jqMath over the previous scripts is that it will automatically add some simple CSS rules to do the mathematical layout and make the formulas readable on browsers with limited MathML support.</p> + +<h3 id="Programas_de_linha_de_comando">Programas de linha de comando</h3> + +<p>An alternative way is to parse the simple syntax before publishing your web pages. That is, you use command-line programs to generate them and publish these static pages on your server.</p> + +<ul> + <li>pros: + <ul> + <li>You get static Web pages: the LaTeX source don't need to be parsed at each page load, the MathML code is exposed to Web crawlers and you can put them easily on any Web server.</li> + <li>Binary programs may run faster than Javascript programs and can be more sophisticated e.g. have a much complete LaTeX support or generate other formats like EPUB.</li> + <li>You can keep compatibility with other tools to generate pdf e.g. you can use the same .tex source for both latex and latexml.</li> + </ul> + </li> + <li>cons: + <ul> + <li>This requires to install programs on your computer, which may be a bit more difficult or they may not be available on all platforms.</li> + <li>You must run the programs on your computer and have some kind of workflow to get the Web pages at the end ; that may be a bit tedious.</li> + <li>Binary programs are not appropriate to integrate them in a Mozilla extension or XUL application.</li> + </ul> + </li> +</ul> + +<p><a href="https://github.com/fred-wang/TeXZilla">TeXZilla</a> can be used <a href="https://github.com/fred-wang/TeXZilla/wiki/Using-TeXZilla#usage-from-the-command-line">from the command line</a> and will essentially have the same support as itex2MML described below. However, the stream filter behavior is not implemented yet.</p> + +<p>If you only want to parse simple LaTeX mathematical expressions, you might want to try tools like <a href="http://golem.ph.utexas.edu/~distler/blog/itex2MML.html" title="http://golem.ph.utexas.edu/~distler/blog/itex2MML.html">itex2MML</a> or <a href="http://gva.noekeon.org/blahtexml/" title="http://gva.noekeon.org/blahtexml/">Blahtex</a>. The latter is often available on Linux distributions. Let's consider the former, which was originally written by Paul Gartside at the beginning of the Mozilla MathML project and has been maintained by Jacques Distler since then. It's a small stream filter written in C/C++ and generated with flex and bison ; in particular it is very fast. Install flex/bison as well as the classical compiler and make tools. On Unix, you can then download itex2MML, build and install it:</p> + +<pre class="brush: bash notranslate">wget http://golem.ph.utexas.edu/~distler/blog/files/itexToMML.tar.gz; \ +tar -xzf itexToMML.tar.gz; \ +cd itex2MML/itex-src; +make +sudo make install +</pre> + +<p>Now suppose that you have a HTML page with TeX fragments delimited by dollars:</p> + +<pre class="brush: html notranslate">input.html + +... +</head> +<body> + <p>$\sqrt{a^2-3c}$</p> + <p>$$ {\sum_{i=1}^N i} = \frac{N(N+1)}{2} $$</p> +</body> +</html> +</pre> + +<p>Then to generate the HTML page input.html with TeX expressions replaced by MathML expressions, just do</p> + +<pre class="notranslate">cat input.html | itex2MML > output.html</pre> + +<p>There are even more sophisticated tools to convert arbitrary LaTeX documents into HTML+MathML. For example <a href="https://www.tug.org/tex4ht/">TeX4ht</a> is often included in TeX distributions and has an option to use MathML instead of PNG images. This command will generate an XHTML+MathML document foo.xml from a foo.tex LaTeX source:</p> + +<pre class="notranslate"> mk4ht mzlatex foo.tex # Linux/Mac platforms + mzlatex foo.tex # Windows platform +</pre> + +<p>Note that <a href="https://github.com/michal-h21/tex4ebook">tex4ebook</a> relies on TeX4ht to generate EPUB documents.</p> + +<p><a href="http://dlmf.nist.gov/LaTeXML/" name="LaTeXML">LaTeXML</a> is another tool that can generate HTML5 and EPUB documents. Windows users can watch this <a href="https://www.youtube.com/watch?v=Dg881w2e-lI">video tutorial</a>. Given a foo.tex LaTeX file, you can use these simple commands:</p> + +<pre class="notranslate"> latexmlc --dest foo.html foo.tex # Generate a HTML5 document foo.html + latexmlc --dest foo.epub foo.tex # Generate an EPUB document foo.epub</pre> + +<p>To handle the case of browsers without MathML support, you can use the <code>--javascript</code> parameter to tell LaTeXML to include one of the <a href="#Fallback_for_Browsers_without_MathML_support">fallback scripts</a>:</p> + +<pre class="notranslate"> latexmlc --dest foo.html --javascript=<code class="language-html"><span class="script token"><span class="tag token"><span class="attr-value token">https://fred-wang.github.io/mathml.css/mspace.js</span></span></span></code> foo.tex # Add the CSS fallback + latexmlc --dest foo.html --javascript=<code class="language-html"><span class="script token"><span class="tag token"><span class="attr-value token">https://fred-wang.github.io/mathjax.js/mpadded-min.js</span></span></span></code> foo.tex # Add the MathJax fallback +</pre> + +<p>If your LaTeX document is big, you might want to split it into several small pages rather than putting everything in a single large page. For example, this will split the pages at the <code>\section</code> level:</p> + +<pre class="notranslate"> latexmlc --dest foo.html --splitat=section foo.tex +</pre> + +<h3 id="Converção_server-side">Converção <em>server-side</em></h3> + +<ul> + <li>pros: + <ul> + <li>Conversion is done server-side and the MathML output can be cached, which is more efficient and cleaner than client-side conversion.</li> + </ul> + </li> + <li>cons: + <ul> + <li>This might be a bit more difficult to set up, since you need some admin right on your server.</li> + </ul> + </li> +</ul> + +<p><a href="https://github.com/fred-wang/TeXZilla">TeXZilla</a>, <a href="http://dlmf.nist.gov/LaTeXML/">LaTeXML</a> and <a href="https://github.com/gwicke/mathoid">Mathoid</a> and can be used to to perform server-side LaTeX-to-MathML conversion.<a href="http://instiki.org/show/HomePage"> Instiki</a> and <a href="https://www.mediawiki.org/wiki/MediaWiki">MediaWiki</a> are two wiki engines that support LaTeX-to-MathML conversion.</p> + +<h2 id="Interface_Gráfica">Interface Gráfica</h2> + +<h3 id="Caixa_de_entrada">Caixa de entrada</h3> + +<p><a href="https://github.com/fred-wang/TeXZilla">TeXZilla</a> has several interfaces, including a <a href="http://ckeditor.com/addon/texzilla">CKEditor plugin</a> used on MDN, an <a href="http://fred-wang.github.io/TeXZilla/">online demo</a>, a <a href="https://addons.mozilla.org/en-US/firefox/addon/texzilla/">Firefox add-on</a> or a <a href="https://marketplace.firefox.com/app/texzilla-1/">FirefoxOS Webapp</a>. It has also been integrated into <a href="http://www.seamonkey-project.org/">SeaMonkey</a> since version 2.28 and into <a href="https://www.mozilla.org/thunderbird/">Thunderbird</a> since version 31.<a href="http://abisource.org/"> Abiword</a> contains a small equation editor, based on itex2MML. Finally,<a href="http://www.bluegriffon.com/"> Bluegriffon</a> has an add-on to insert MathML formulas in your document, using ASCII/LaTeX-like syntax.</p> + +<p style="text-align: center;"><img alt="BlueGriffon" src="http://www.bluegriffon.com/public/shots/mathml-shot1.png" style="height: 467px; width: 358px;"></p> + +<h3 id="Editores_WYSIYWG">Editores WYSIYWG</h3> + +<p><a href="http://www.firemath.info/">Firemath</a> é uma extensão para Firefox que fornece um editor WYSIWYG MathML. Uma pré-visualização da fórmula é apresentada utilizando o motor da renderização do Mozilla. O código MathML gerado está visivel na parte inferior. Utilize o campo de texto para elementos simbólicos e botões para construir construções avançadas. Uma vez terminado, pode guardar o seu documento como uma página XHTML.</p> + +<p><a href="http://www.lyx.org/">LyX</a> é um editor gráfico LaTeX, que tem suporte integrado para exportação de XHTML e MathML e pode ser configurado para utilizar conversores LaTeX-para-(X)HTML semelhantes. Pode, por exemplo, configurá-lo para utilizar <a href="https://github.com/brucemiller/LaTeXML/wiki/Integrating-LaTeXML-into-TeX-editors#lyx">a exportação LaTeXML HTML5/EPUB</a>.</p> + +<p>O <a href="http://www.openoffice.org/">OpenOffice</a> e o <a href="http://libreoffice.org/">LibreOffice</a> têm um editor de equações (File → New → Formula). Isto é parecido a um WYSIWYG: o utilizador escreve o código usando um painel/teclado e uma pré-visualização é regularmente atualizada. O editor usa o seu próprio sintaxe "StarMath", mas MathML também e criado quando o documneto é guardado. Para aceder ao código MathML, guarda o documento como um <code>.mml</code> e abre o ficheiro com um editor de texto. Em alternativa, pode extrair o ficheiro <code>.odf</code> (que na realidade é um arquivo ZIP) e abrir um ficheiro XML chamado <code>content.xml</code>.</p> + +<p style="text-align: center;"><img alt="Open Office Math" src="/@api/deki/files/4261/=openoffice.png" style="height: 527px; width: 483px;"></p> + +<p><a href="http://www.w3.org/Amaya/">Amaya</a> é o editor da web do W3C, que é capaz de lidar com MathML dentro de documentos XHTML. Utilize os painéis de Elementos e Cartas Especiais para criar várias construções matemáticas avançadas. Texto simples como <code>a+2</code> é automaticamente analisado e a marcação MathML apropriada é gerada. Uma vez terminado, pode guardar directamente a sua página XHTML e abri-la em Mozilla.</p> + +<h2 id="Reconhecimento_óptico_de_carácter_e_caligrafia">Reconhecimento óptico de carácter e caligrafia</h2> + +<p><a href="http://www.inftyreader.org/">Inftyreader</a> é capaz de fazer o reconhecimento óptico de carateres, inclusive a conversão de equações matemáticas para MathML. Outras ferramentas fazem reconhecimento de caligrafia, como o <em><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd371698(v=vs.85).aspx">Windows Math Input Panel</a></em> ou o conversor online <em><a href="https://webdemo.myscript.com/views/math.html" title="http://webdemo.visionobjects.com/portal.html">Web Equation</a></em>.</p> + +<div class="originaldocinfo"> +<h3 id="Original_Document_Information">Original Document Information</h3> + +<ul> + <li>Author(s): Frédéric Wang</li> + <li>Other Contributors: Florian Scholz</li> + <li>Copyright Information: Portions of this content are © 2010 by individual mozilla.org contributors; content available under a Creative Commons license | <a class="external" href="http://www.mozilla.org/foundation/licensing/website-content.html">Details</a>.</li> +</ul> +</div> diff --git a/files/pt-pt/web/mathml/element/index.html b/files/pt-pt/web/mathml/element/index.html new file mode 100644 index 0000000000..904de1a607 --- /dev/null +++ b/files/pt-pt/web/mathml/element/index.html @@ -0,0 +1,234 @@ +--- +title: Referência de elementos MathML +slug: Web/MathML/Element +tags: + - MathML + - Referência de MathML +translation_of: Web/MathML/Element +--- +<p>{{MathMLRef}}</p> + +<p>Isto é uma lista alfabética de elementos de <strong>presentação</strong> MathML.</p> + +<p>O termo <em><strong>presentation markup</strong></em> é usado para descrever o <em>layout</em> da estrutura da notação matemática enquanto <em><strong>content markup</strong></em> oferece o significado matemático e não é suposto ser visualizado pelo processador MathML (veja {{ bug(276028) }}). Se deseja aprender mais sobre <em>content markup</em> deve ver <em><a class="external" href="http://www.w3.org/TR/MathML3/chapter4.html" title="http://www.w3.org/TR/MathML3/chapter4.html">Chapter 4</a></em> no <em><a class="external" href="http://www.w3.org/TR/MathML3/" title="http://www.w3.org/TR/MathML3/">MathML 3 specification</a></em>.</p> + +<p>Elementos MathML implementam a classe {{domxref("MathMLElement")}}.</p> + +<h2 id="Elementos_de_apresentação_MathML_de_A_a_Z">Elementos de apresentação MathML de A a Z</h2> + +<div class="multiColumnList"> +<h3 id="math">math</h3> + +<ul> + <li>{{MathMLElement("math")}} (Elemento de raiz)</li> +</ul> + +<h3 id="A">A</h3> + +<ul> + <li>{{MathMLElement("maction")}} (Ações associadas a subexpressões)</li> + <li>{{MathMLElement("maligngroup")}} (Grupo de alinhamento)</li> + <li>{{MathMLElement("malignmark")}} (Pontos de alinhamento)</li> +</ul> + +<h3 id="E">E</h3> + +<ul> + <li>{{MathMLElement("menclose")}} (Conteúdos enclausurados)</li> + <li>{{MathMLElement("merror")}} (Conteúdos enclausurados de sintaxe de mensagens de erro)</li> +</ul> + +<h3 id="F">F</h3> + +<ul> + <li>{{MathMLElement("mfenced")}} (Parênteses) {{deprecated_inline}}</li> + <li>{{MathMLElement("mfrac")}} (Fração)</li> +</ul> + +<h3 id="G">G</h3> + +<ul> + <li>{{MathMLElement("mglyph")}} (Apresentar símbolos não standard)</li> +</ul> + +<h3 id="I">I</h3> + +<ul> + <li>{{MathMLElement("mi")}} (Identificador)</li> +</ul> + +<h3 id="L">L</h3> + +<ul> + <li>{{MathMLElement("mlabeledtr")}} (Fila marcada numa tabela ou matriz)</li> + <li>{{MathMLElement("mlongdiv")}} (Notação de divisão longa)</li> +</ul> + +<h3 id="M">M</h3> + +<ul> + <li>{{MathMLElement("mmultiscripts")}} (<em>Prescripts</em> e índices de tensores)</li> +</ul> + +<h3 id="N">N</h3> + +<ul> + <li>{{MathMLElement("mn")}} (Numero)</li> +</ul> + +<h3 id="O">O</h3> + +<ul> + <li>{{MathMLElement("mo")}} (Operador)</li> + <li>{{MathMLElement("mover")}} (<em>Overscript</em>)</li> +</ul> + +<h3 id="P">P</h3> + +<ul> + <li>{{MathMLElement("mpadded")}} (Espaço à volta de conteúdo)</li> + <li>{{MathMLElement("mphantom")}} (Conteúdo invisível com espaço reservado)</li> +</ul> + +<h3 id="R">R</h3> + +<ul> + <li>{{MathMLElement("mroot")}} (Radical com índice especidicado)</li> + <li>{{MathMLElement("mrow")}} (Sub-expressõs agrupadas)</li> +</ul> + +<h3 id="S">S</h3> + +<ul> + <li>{{MathMLElement("ms")}} (String literal)</li> + <li>{{MathMLElement("mscarries")}} (Anotações como carries)</li> + <li>{{MathMLElement("mscarry")}} (Carry, elemento pertencente a {{MathMLElement("mscarries")}})</li> + <li>{{MathMLElement("msgroup")}} (Filas agrupadas dos elementos {{MathMLElement("mstack")}} e {{MathMLElement("mlongdiv")}})</li> + <li>{{MathMLElement("msline")}} (Linhas horizontais dentro de elementos {{MathMLElement("mstack")}})</li> + <li>{{MathMLElement("mspace")}} (Espaço)</li> + <li>{{MathMLElement("msqrt")}} (Raiz quadrada sem índice)</li> + <li>{{MathMLElement("msrow")}} (Filas dentro de elementos {{MathMLElement("mstack")}})</li> + <li>{{MathMLElement("mstack")}} (Alinhamento em pilha)</li> + <li>{{MathMLElement("mstyle")}} (Mudar estilo)</li> + <li>{{MathMLElement("msub")}} (<em>Subscript</em>)</li> + <li>{{MathMLElement("msup")}} (<em>Superscript</em>)</li> + <li>{{MathMLElement("msubsup")}} (Par de <em>subscript-superscript</em>)</li> +</ul> + +<h3 id="T">T</h3> + +<ul> + <li>{{MathMLElement("mtable")}} (Tabela ou matriz)</li> + <li>{{MathMLElement("mtd")}} (Célula numa tabela ou matriz)</li> + <li>{{MathMLElement("mtext")}} (Texto)</li> + <li>{{MathMLElement("mtr")}} (Fila numa tabela ou matriz)</li> +</ul> + +<h3 id="U">U</h3> + +<ul> + <li>{{MathMLElement("munder")}} (<em>Underscript</em>)</li> + <li>{{MathMLElement("munderover")}} (Par de <em>underscript-overscript</em>)</li> +</ul> + +<h3 id="Outros_elementos">Outros elementos</h3> + +<ul> + <li>{{MathMLElement("semantics")}} (Contentor para anotações semânticas)</li> + <li><a href="/pt-PT/docs/Web/MathML/Element/semantics#annotation"><code><annotation></code></a> (Anotações de dados)</li> + <li><a href="/pt-PT/docs/Web/MathML/Element/semantics#annotation-xml"><code><annotation-xml></code></a> (Anotações de XML)</li> +</ul> +</div> + +<h2 id="Elementos_de_apresentação_MathML_por_categoria">Elementos de apresentação MathML por categoria</h2> + +<h3 id="Elementos_de_raiz">Elementos de raiz</h3> + +<ul> + <li>{{MathMLElement("math")}}</li> +</ul> + +<h3 id="Elementos_token">Elementos token</h3> + +<ul> + <li>{{MathMLElement("mglyph")}}</li> + <li>{{MathMLElement("mi")}}</li> + <li>{{MathMLElement("mn")}}</li> + <li>{{MathMLElement("mo")}}</li> + <li>{{MathMLElement("ms")}}</li> + <li>{{MathMLElement("mspace")}}</li> + <li>{{MathMLElement("mtext")}}</li> +</ul> + +<h3 id="Layout_geral"><em>Layout</em> geral</h3> + +<ul> + <li>{{MathMLElement("menclose")}}</li> + <li>{{MathMLElement("merror")}}</li> + <li>{{MathMLElement("mfenced")}} {{deprecated_inline}}</li> + <li>{{MathMLElement("mfrac")}}</li> + <li>{{MathMLElement("mpadded")}}</li> + <li>{{MathMLElement("mphantom")}}</li> + <li>{{MathMLElement("mroot")}}</li> + <li>{{MathMLElement("mrow")}}</li> + <li>{{MathMLElement("msqrt")}}</li> + <li>{{MathMLElement("mstyle")}}</li> +</ul> + +<h3 id="Elementos_de_script_e_limite">Elementos de <em>script</em> e limite</h3> + +<ul> + <li>{{MathMLElement("mmultiscripts")}}</li> + <li>{{MathMLElement("mover")}}</li> + <li>{{MathMLElement("mprescripts")}}</li> + <li>{{MathMLElement("msub")}}</li> + <li>{{MathMLElement("msubsup")}}</li> + <li>{{MathMLElement("msup")}}</li> + <li>{{MathMLElement("munder")}}</li> + <li>{{MathMLElement("munderover")}}</li> + <li>{{MathMLElement("none")}}</li> +</ul> + +<h3 id="Matemática_tabular">Matemática tabular</h3> + +<ul> + <li>{{MathMLElement("maligngroup")}}</li> + <li>{{MathMLElement("malignmark")}}</li> + <li>{{MathMLElement("mlabeledtr")}}</li> + <li>{{MathMLElement("mtable")}}</li> + <li>{{MathMLElement("mtd")}}</li> + <li>{{MathMLElement("mtr")}}</li> +</ul> + +<h3 id="Matemática_elementar">Matemática elementar</h3> + +<ul> + <li>{{MathMLElement("mlongdiv")}}</li> + <li>{{MathMLElement("mscarries")}}</li> + <li>{{MathMLElement("mscarry")}}</li> + <li>{{MathMLElement("msgroup")}}</li> + <li>{{MathMLElement("msline")}}</li> + <li>{{MathMLElement("msrow")}}</li> + <li>{{MathMLElement("mstack")}}</li> +</ul> + +<h3 id="Elementos_sem_categoria">Elementos sem categoria</h3> + +<ul> + <li>{{MathMLElement("maction")}}</li> +</ul> + +<h2 id="Anotações_semânticas">Anotações semânticas</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/MathML/Element/semantics#annotation"><code><annotation></code></a></li> + <li><a href="/pt-PT/docs/Web/MathML/Element/semantics#annotation-xml"><code><annotation-xml></code></a></li> + <li>{{MathMLElement("semantics")}}</li> +</ul> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/MathML" title="/en-US/docs/Web/MathML">MathML</a></li> + <li><a href="/pt-PT/docs/Web/MathML/Attribute" title="/en-US/docs/Web/MathML/Attribute">Referência de atributos MathML</a></li> +</ul> diff --git a/files/pt-pt/web/mathml/element/maction/index.html b/files/pt-pt/web/mathml/element/maction/index.html new file mode 100644 index 0000000000..b176d8e159 --- /dev/null +++ b/files/pt-pt/web/mathml/element/maction/index.html @@ -0,0 +1,124 @@ +--- +title: <maction> +slug: Web/MathML/Element/maction +tags: + - MathML + - 'MathML:Element' + - 'MathML:Enlivening Expressions' + - Referência de MathML +translation_of: Web/MathML/Element/maction +--- +<div>{{MathMLRef}}</div> + +<div class="summary"> +<p>O elemento de MathML <strong><code><maction></code></strong> oferece a possibilidade de associar ações a (sub-) expressões. A ação é indicada pelo atributo <code>actiontype</code>, que aceita vários valores. Para indicar que elementos são afetados pela ação, pode usar o atributo <code>selection</code>.</p> +</div> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-actiontype">actiontype</dt> + <dd>A ação que indica o que acontecerá ao elemento. Os valores possíveis são: + <ul> + <li><code>statusline</code>: Se o utilizador carregar ou tiver o cursor sob a expressão, a mensagem é enviada para a <em>status line</em> do navegador. A sintaxe é: <code><maction actiontype="statusline"> <em>expression</em> <em>message</em> </maction>.</code></li> + <li><code>toggle</code>: Quando a sub-expressão é carregada, a expressão alterna com outra expressão selecionada. Cada vez que é carregada o valor de <code>selection</code> aumenta.A sintaxe é: <code><maction actiontype="toggle" selection="<em>positive-integer</em>" > <em>expression1</em> <em>expression2</em> <em>expressionN</em> </maction></code>.</li> + <li><code>tooltip</code>: Quando o cursor está sob a expressão, uma <em>tooltip</em> com uma mensagem é feita visível perto da expressão.<br> + A sintaxe é:<code> <maction actiontype="tooltip"> <em>expression</em> <em>message</em> </maction>.</code></li> + </ul> + </dd> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto e da linha da fração. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> + <dt id="attr-selection">selection</dt> + <dd>O elemento que no qual a ação tem efeito. O valor pré-definido é <code>1</code>, que representa o primeiro elemento do grupo.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>O seguinte exemplo usa o "<em>toggle</em>" <code>actiontype</code>:</p> + +<pre class="brush: html notranslate"><math> + +<maction actiontype="toggle"> + + <mfrac> + <mn>6</mn> + <mn>8</mn> + </mfrac> + + <mfrac> + <mrow> + <mn>3</mn> + <mo>&sdot;</mo> + <mn>2</mn> + </mrow> + <mrow> + <mn>4</mn> + <mo>&sdot;</mo> + <mn>2</mn> + </mrow> + </mfrac> + + <mfrac> + <mn>3</mn> + <mn>4</mn> + </mfrac> + +</maction> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.maction', 'maction') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.maction', 'maction') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + + + +<p>{{Compat("mathml.elements.maction")}}</p> + + + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>Anterior ao Gecko 9.0 {{ geckoRelease("9.0") }} o valor não <em>standard</em> <code>restyle</code> no atributo <code>actiontype</code> era suportado. Este valor foi removido.</li> + <li>Anterior ao Gecko 14.0 {{ geckoRelease("14.0") }} a ação <code>statusline</code> usava uma sintaxe não <em>standard</em> (ver abaixo). Agora segue a especificação da MathML.<br> + + <pre class="brush: html notranslate"><maction actiontype="statusline#(message)"> +(expression) +</maction> +</pre> + </li> + <li>No Gecko 15.0 {{geckoRelease("15.0")}} o atributo <code>selection</code> só é utilizado pela ação <code>"toggle"</code>.</li> + <li>A partir do Gecko 16.0 {{geckoRelease("16.0")}} o atributo <code>selection</code> é utilizado para <code>actiontype</code> desconhecidos. Se um <code>actiontype</code> não é indicado (o atributo é deixado vazio) ou o atributo <code>selection</code> é invalido, a marcação apresenta um erro MathML (<em>invalid-markup</em>).</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/math/index.html b/files/pt-pt/web/mathml/element/math/index.html new file mode 100644 index 0000000000..3439ad15e9 --- /dev/null +++ b/files/pt-pt/web/mathml/element/math/index.html @@ -0,0 +1,161 @@ +--- +title: <math> +slug: Web/MathML/Element/math +tags: + - MathML + - 'MathML:Element' + - Referência MathML +translation_of: Web/MathML/Element/math +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento top-level em MathML é <code><math></code>. Qualquer instância valida de MathML tem de ser envolto por <code><math></code>. Ademais não se deve por um elemento de <code><math></code> dentro de outro, mas pode se ter qualquer numero de outros elementos dentro desse elemento.</p> + +<h2 id="Atributos">Atributos</h2> + +<p>Para além dos seguintes atributos, o elemento <code><math></code> aceita qualquer atributo do elemento {{ MathMLElement("mstyle") }}.</p> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/pt-PT/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-dir">dir</dt> + <dd>A direção geral das fórmulas. Valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-display">display</dt> + <dd>Este atributo enumerado especifica como é que o <em>markup</em> da MathML deve ser impressa. Pode ter um dos seguintes valores: + <ul> + <li><code>block</code>, que significa que o elemento será impresso fora do <em>span</em> de texto em que se encontra, como um <em>block</em> que pode ser posicionado em qualquer lugar sem mudar o significado do texto;</li> + <li><code>inline</code>, que significa que o elemento será impresso dentro do <em>span</em> de texto em que se encontra, e não pode ser movido para fora dele sem mudar o significado do texto.</li> + </ul> + + <p>Se não estiver presente, o valor padrão é <code>inline</code>.</p> + </dd> + <dt id="attr-mode">mode {{deprecated_inline}}</dt> + <dd>Obsoleto, use antes o <a href="/pt-PT/docs/Web/MathML/Element/math#attr-display">atributo display</a>.<br> + Valores aceites são: <code>display</code> (que tem o mesmo efeito que <code>display="block"</code>) e <code>inline</code>.</dd> + <dt id="attr-overflow">overflow</dt> + <dd>Especifica como a expressão se comporta no caso de ser demasiada comprida para a largura máxima permitida. Valores aceites são: <code>linebreak</code> (valor padrão), <code>scroll</code>, <code>elide</code>, <code>truncate</code> e <code>scale</code>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p><img alt="Theorem of Pythagoras" src="/files/3157/math.jpg"></p> + +<h3 id="Notação_HTML5">Notação HTML5</h3> + +<pre class="brush: html notranslate"><!DOCTYPE html> +<html> + <head> + <title>MathML in HTML5</title> + </head> + <body> + + <math> + <mrow> + <mrow> + <msup> + <mi>a</mi> + <mn>2</mn> + </msup> + <mo>+</mo> + <msup> + <mi>b</mi> + <mn>2</mn> + </msup> + </mrow> + <mo>=</mo> + <msup> + <mi>c</mi> + <mn>2</mn> + </msup> + </mrow> + </math> + + </body> +</html> +</pre> + +<h3 id="Notação_de_XHTML">Notação de XHTML</h3> + +<pre class="brush: xml notranslate"><?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/xhtml-math11-f.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <title>MathML in XHTML</title> +</head> +<body> + + <math xmlns="http://www.w3.org/1998/Math/MathML"> + <mrow> + <mrow> + <msup> + <mi>a</mi> + <mn>2</mn> + </msup> + <mo>+</mo> + <msup> + <mi>b</mi> + <mn>2</mn> + </msup> + </mrow> + <mo>=</mo> + <msup> + <mi>c</mi> + <mn>2</mn> + </msup> + </mrow> + </math> + +</body> +</html></pre> + +<p><strong>Notes</strong>: Documentos de XHTML com MathML devem ser servidos como <code>application/xhtml+xml</code>. Pode satisfazer isto facilmente usando a extensão <code>.xhtml</code> para ficheiros locais. Para um servidor Apache <a class="external" href="http://httpd.apache.org/docs/2.4/mod/mod_mime.html#addtype">configura o seu ficheiro <code>.htaccess</code></a> para mapear as extensões ao tipo Mime correto. Já que o MathML está num documento XML, também deve se certificar que o documento XML está corretamente estruturado.</p> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter2.html#interf.toplevel', 'The Top-Level math Element') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter7.html#interf.toplevel', 'The Top-Level math Element') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.math")}}</p> + +<h2 id="Notas_para_Firefox">Notas para Firefox</h2> + +<p>Firefox 7 introduziu suporte para aceitar todos os atributos de MathML no elemento top-level <code>math</code> (i.e. o mesmo comportamento que o elemento {{ MathMLElement("mstyle") }}). Contudo, o atributo <code>displaystyle</code> foi falhado e <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=669719">só foi adicionado</a> no Firefox 8.</p> + +<p>Um apoio textual (<code>alttext</code>) ou referir a uma imagem alternativa usando os atributos <code>altimg</code>, <code>altimg-width</code>, <code>altimg-height</code> ou <code>altimg-valign</code> não está implementado no Firefox de momento.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>Elemento de HTML <em>top-level</em>: {{ HTMLElement("html") }}</li> + <li>Elemento de SVG <em>top-level</em>: {{ SVGElement("svg") }}</li> + <li><a href="http://eyeasme.com/Joe/MathML/MathML_browser_test.html">Teste de navegador MathML</a></li> +</ul> diff --git a/files/pt-pt/web/mathml/element/menclose/index.html b/files/pt-pt/web/mathml/element/menclose/index.html new file mode 100644 index 0000000000..bae255350e --- /dev/null +++ b/files/pt-pt/web/mathml/element/menclose/index.html @@ -0,0 +1,196 @@ +--- +title: <menclose> +slug: Web/MathML/Element/menclose +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/menclose +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><menclose></code> apresenta os seus conteúdos dentro da notação indicada pelo atributo <code>notation</code>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-notation">notation</dt> + <dd>A lista de notações, separada por espaços, para aplicar aos elementos filhos. Os símbolos são desenhados como se os outros não estivessem presentes, e por isso podem sobrepor-se. Os valores possíveis são: + <table class="standard-table"> + <tbody> + <tr> + <th>Valor</th> + <th>Exemplo de apresentação</th> + <th>Apresentação no seu navegador</th> + <th>Descrição</th> + </tr> + <tr> + <td><code>longdiv</code> (default)</td> + <td><img alt="longdiv" src="/files/3167/default.png"></td> + <td><math> <menclose notation="longdiv"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>símbolo de longa divisão</td> + </tr> + <tr> + <td><code>actuarial</code></td> + <td><img alt="actuarial" src="/files/3168/actuarial.png"></td> + <td><math> <menclose notation="actuarial"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td><a class="external" href="http://en.wikipedia.org/wiki/Actuarial_notation" title="http://en.wikipedia.org/wiki/Actuarial_notation">símbolo atuarial</a></td> + </tr> + <tr> + <td><code>radical</code> {{deprecated_inline}}</td> + <td><img alt="radical" src="/files/3169/radical.png"></td> + <td><math> <menclose notation="radical"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>símbolo de raiz quadrada. Depreciado. Use {{MathMLElement("msqrt")}}.</td> + </tr> + <tr> + <td><code>box</code></td> + <td><img alt="box" src="/files/3170/box.png"></td> + <td><math> <menclose notation="box"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>caixa</td> + </tr> + <tr> + <td><code>roundedbox</code></td> + <td><img alt="roundedbox" src="/files/3171/roundedbox.png"></td> + <td><math> <menclose notation="roundedbox"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>caixa arredondada</td> + </tr> + <tr> + <td><code>circle</code></td> + <td><img alt="circle" src="/files/3172/circle.png"></td> + <td><math> <menclose notation="circle"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>circulo</td> + </tr> + <tr> + <td><code>left</code></td> + <td><img alt="left" src="/files/3173/left.png"></td> + <td><math> <menclose notation="left"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>linha vertical à esquerda dos conteúdos</td> + </tr> + <tr> + <td><code>right</code></td> + <td><img alt="right" src="/files/3174/right.png"></td> + <td><math> <menclose notation="right"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>linha vertical à direita dos conteúdos</td> + </tr> + <tr> + <td><code>top</code></td> + <td><img alt="top" src="/files/3175/top.png"></td> + <td><math> <menclose notation="top"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>linha horizontal acima dos conteúdos</td> + </tr> + <tr> + <td><code>bottom</code></td> + <td><img alt="bottom" src="/files/3176/bottom.png"></td> + <td><math> <menclose notation="bottom"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>linha horizontal abaixo dos conteúdos</td> + </tr> + <tr> + <td><code>updiagonalstrike</code></td> + <td><img alt="updiagonalstrike" src="/files/3177/updiagonalstrike.png"></td> + <td><math> <menclose notation="updiagonalstrike"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>linha através do conteúdo da parte inferior esquerda para a parte superior direita</td> + </tr> + <tr> + <td><code>downdiagonalstrike</code></td> + <td><img alt="downdiagonalstrike" src="/files/3178/downdiagonalstrike.png"></td> + <td><math> <menclose notation="downdiagonalstrike"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>linha através do conteúdo da parte superior esquerda para a parte inferior direita</td> + </tr> + <tr> + <td><code>verticalstrike</code></td> + <td><img alt="verticalstrike" src="/files/3179/verticalstrike.png"></td> + <td><math> <menclose notation="verticalstrike"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>linha vertical através do conteúdo</td> + </tr> + <tr> + <td><code>horizontalstrike</code></td> + <td><img alt="horizontalstrike" src="/files/3180/horizontalstrike.png"></td> + <td><math> <menclose notation="horizontalstrike"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>linha horizontal através do conteúdo</td> + </tr> + <tr> + <td><code>madruwb</code></td> + <td><img alt="madruwb" src="/files/3181/madruwb.png"></td> + <td><math> <menclose notation="madruwb"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td><a class="external" href="http://en.wikipedia.org/wiki/Modern_Arabic_mathematical_notation#Arithmetic_and_algebra" title="http://en.wikipedia.org/wiki/Modern_Arabic_mathematical_notation#Arithmetic_and_algebra">símbolo fatorial arábico</a></td> + </tr> + <tr> + <td><code>updiagonalarrow</code></td> + <td><img alt="" src="https://mdn.mozillademos.org/files/6255/updiagonalarrow.png" style="height: 38px; width: 83px;"></td> + <td><math> <menclose notation="updiagonalarrow"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>seta diagonal</td> + </tr> + <tr> + <td><code>phasorangle</code></td> + <td><img alt="Screenshot of the phasorangle notation" src="https://mdn.mozillademos.org/files/7851/phasorangle.png" style="height: 34px; width: 93px;"></td> + <td><math> <menclose notation="phasorangle"> <msup><mi>a</mi><mn>2</mn></msup> <mo>+</mo> <msup><mi>b</mi><mn>2</mn></msup> </menclose> </math></td> + <td>ângulo fasor</td> + </tr> + </tbody> + </table> + </dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + + <menclose notation="circle box"> + <mi> x </mi> + <mo> + </mo> + <mi> y </mi> + </menclose> + +</math></pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.menclose', 'menclose') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.menclose', 'menclose') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.menclose")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>Valores adicionais para o atributo <code>notation</code> foram adicionados nas seguintes publicações: + + <ul> + <li><code>madruwb</code> em Gecko 2.0 {{GeckoRelease("2.0")}}.</li> + <li><code>updiagonalarrow</code> em Gecko 24.0 {{GeckoRelease("24.0")}}</li> + <li><code>phasorangle</code> em Gecko 32.0 {{GeckoRelease("32.0")}}</li> + </ul> + </li> +</ul> diff --git a/files/pt-pt/web/mathml/element/merror/index.html b/files/pt-pt/web/mathml/element/merror/index.html new file mode 100644 index 0000000000..d69380bd1a --- /dev/null +++ b/files/pt-pt/web/mathml/element/merror/index.html @@ -0,0 +1,73 @@ +--- +title: <merror> +slug: Web/MathML/Element/merror +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/merror +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><merror></code> é usado para mostrar os seus conteúdos como mensagens de erro. No Firefox esta mensagem é renderizada de forma parecida à mensagem de erro de XML. Note que este erro <strong>não</strong> aparece quando a linguagem de marcação (<em>markup</em>) está errada ou o XML está mal formatado. Irá receber um erro de processamento do XML (no caso de notação XHTML de MathML), que não é relacionado ao <code><merror></code>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto e da linha de fração. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores de HTML</a>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + +<merror> + <mrow> + <mtext> Division by zero: </mtext> + <mfrac> + <mn> 1 </mn> + <mn> 0 </mn> + </mfrac> + </mrow> +</merror> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.merror', 'merror') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.merror', 'merror') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.merror")}}</p> diff --git a/files/pt-pt/web/mathml/element/mfenced/index.html b/files/pt-pt/web/mathml/element/mfenced/index.html new file mode 100644 index 0000000000..f10d7643af --- /dev/null +++ b/files/pt-pt/web/mathml/element/mfenced/index.html @@ -0,0 +1,81 @@ +--- +title: <mfenced> +slug: Web/MathML/Element/mfenced +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Obsoleto + - Referência de MathML +translation_of: Web/MathML/Element/mfenced +--- +<div>{{MathMLRef}}</div> + +<p><span class="seoSummary">O elemento obsoleto <code><mfenced></code> costumava oferecer a possibilidade de adicionar parênteses e separadores personalizados a uma expressão. Foi removido das normas mais recente de MathML e navegadores modernos já não o apoiam.</span> Use os elementos {{MathMLElement("mrow")}} e {{MathMLElement("mo")}}.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style"><code>class</code>, <code>id</code>, <code>style</code></dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-close"><code>close</code></dt> + <dd>Uma <em>string</em> para o delimitador final. O valor padrão é "<code>)</code>" e espaços em branco são removidos.</dd> + <dt id="attr-href"><code>href</code></dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground"><code>mathbackground</code></dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor"><code>mathcolor</code></dt> + <dd>A cor do texto e da linha de fração. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores de HTML</a>.</dd> + <dt id="attr-open"><code>open</code></dt> + <dd>Uma <em>string</em> para o delimitador inicial. O valor padrão é "<code>(</code>" e espaços em branco são removidos.</dd> + <dt id="attr-separators"><code>separators</code></dt> + <dd> + <p>Uma sequência de zero ou mais caracteres a ser utilizada para diferentes separadores, opcionalmente divididos por espaço branco, que é ignorado. O valor pré-definido é ",". Ao especificar mais de um carácter, é possível definir separadores diferentes para cada argumento na expressão. Se houver demasiados separadores, todo o excesso é ignorado. Se houver muito poucos separadores na expressão, o último separador especificado é repetido.</p> + </dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="O_último_separador_é_repetido">O último separador é repetido (<code>,</code>)</h3> + +<p>Exemplo: <img alt="{a;b;c,d,e}" src="/files/3193/mfenced01.png"></p> + +<p>Exemplo renderizado no seu navegador: <math> <mfenced close="}" open="{" separators=";;,"> <mi>a</mi> <mi>b</mi> <mi>c</mi> <mi>d</mi> <mi>e</mi> </mfenced> </math></p> + +<pre class="brush: html notranslate"><math> + <mfenced open="{" close="}" separators=";;,"> + <mi>a</mi> + <mi>b</mi> + <mi>c</mi> + <mi>d</mi> + <mi>e</mi> + </mfenced> +</math> +</pre> + +<h3 id="Todo_o_excesso_é_ignorado">Todo o excesso é ignorado (<code>,</code>)</h3> + +<p>Exemplo: <img alt="[a|b|c|d|e]" src="/files/3195/mfenced02.png"></p> + +<p>Exemplo renderizado no seu navegador: <math> <mfenced close="]" open="[" separators="||||,"> <mi>a</mi> <mi>b</mi> <mi>c</mi> <mi>d</mi> <mi>e</mi> </mfenced> </math></p> + +<pre class="brush: html notranslate"><math> + <mfenced open="[" close="]" separators="||||,"> + <mi>a</mi> + <mi>b</mi> + <mi>c</mi> + <mi>d</mi> + <mi>e</mi> + </mfenced> +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<p>O elemento <mfenced> já não pertence às <a href="https://github.com/mathml-refresh/mathml/issues/2">normas mais recentes de MathML</a>. Use os elementos {{MathMLElement("mrow")}} e {{MathMLElement("mo")}}, ou para ter compatibilidade veja <a href="https://github.com/mathml-refresh/mathml-polyfills/tree/master/mfenced">mathml-polyfills/mfenced.</a></p> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mfenced")}}</p> diff --git a/files/pt-pt/web/mathml/element/mfrac/index.html b/files/pt-pt/web/mathml/element/mfrac/index.html new file mode 100644 index 0000000000..5a402ba510 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mfrac/index.html @@ -0,0 +1,92 @@ +--- +title: <mfrac> +slug: Web/MathML/Element/mfrac +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/mfrac +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento MathML <code><mfrac></code> é usado para apresentar frações.</p> + +<h2 id="Sintaxe">Sintaxe</h2> + +<pre class="syntaxbox notranslate"><mfrac><em>numerator</em> <em>denominator</em></mfrac></pre> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-bevelled"><code>bevelled</code> {{deprecated_inline}}</dt> + <dd>Indica como a fração é apresentada. Se o valor é <code>true</code>, a linha de fração é <em>beveled</em>, que significa que o numerador e o denominador são apresentados lado a lado e separados por uma barra (/). Se o valor é <code>false</code> (o valor pré-definido), o numerador e o denominador são postos um acima do outro.<br> + Este atributo está obsoleto e será removido no futuro. Use antes U+2044 (barra de fração).</dd> + <dt id="attr-class-id-style"><code>class</code>, <code>id</code>, <code>style</code></dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-denomalign"><code>denomalign</code> {{deprecated_inline}}</dt> + <dd>O alinhamento do denominador abaixo da linha de fração. Os valores aceites são: <code>left</code>, <code>center</code> (pré-definido), e <code>right</code>.<br> + Este atributo está obsoleto e será removido no futuro. Use antes o CSS <code><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/text-align">text-align</a></code>.</dd> + <dt id="attr-href"><code>href</code></dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-linethickness"><code>linethickness</code></dt> + <dd>A espessura da linha de fração horizontal. Este atributo aceito <a href="/en-US/docs/CSS/length">valores de comprimento</a>.<br> + Os valores <code>medium</code>, <code>thin</code>, e <code>thick</code> estão obsoletos e serão removidos no futuro.</dd> + <dt id="attr-mathbackground"><code>mathbackground</code></dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor"><code>mathcolor</code></dt> + <dd>A cor do texto e da linha de fração. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-numalign"><code>numalign</code> {{deprecated_inline}}</dt> + <dd>O alinhamento do numerador sob a fração. Os valores aceites são: <code>left</code>, <code>center</code> (pré-definido), e <code>right</code>.<br> + Este atributo está obsoleto e será removido no futuro. Use antes o CSS <code><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/text-align">text-align</a></code>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="(a/b)/(c/d)" src="/files/3194/mfrac.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <mfrac bevelled="true"> <mfrac> <mi> a </mi> <mi> b </mi> </mfrac> <mfrac> <mi> c </mi> <mi> d </mi> </mfrac> </mfrac> </math></p> + +<pre class="brush: html notranslate"><math> + <mfrac bevelled="true"> + <mfrac> + <mi> a </mi> + <mi> b </mi> + </mfrac> + <mfrac> + <mi> c </mi> + <mi> d </mi> + </mfrac> + </mfrac> +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mfrac', 'mfrac') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mfrac', 'mfrac') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inical</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mfrac")}}</p> diff --git a/files/pt-pt/web/mathml/element/mglyph/index.html b/files/pt-pt/web/mathml/element/mglyph/index.html new file mode 100644 index 0000000000..1ae5f170dc --- /dev/null +++ b/files/pt-pt/web/mathml/element/mglyph/index.html @@ -0,0 +1,72 @@ +--- +title: <mglyph> +slug: Web/MathML/Element/mglyph +tags: + - MathML + - 'MathML:Element' + - Referência de MathML +translation_of: Web/MathML/Element/mglyph +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><mglyph></code> é usado para apresentar símbolos sem carateres de Unicode disponíveis. Pode ser usado dentro de <em><a href="/pt-PT/docs/tag/MathML:Token Elements">token elements</a></em>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-alt">alt</dt> + <dd>Este atributo define o texto alternativo que descreve a imagem. Os utilizadores verão isto apresentado se o URL da imagem estiver errado, se a imagem não estiver num dos <a href="/en-US/docs/HTML/Element/Img#Supported_image_formats">formatos suportados</a>, ou até a imagem ser descarregada.</dd> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-height">height</dt> + <dd>A altura da imagem.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo (se a imagem tem transparência). Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores de HTML</a>.</dd> + <dt id="attr-src">src</dt> + <dd>O URL da imagem.</dd> + <dt id="attr-valign">valign</dt> + <dd>Indica o alinhamento vertical com respeito à linha de base atual.</dd> + <dt id="attr-width">width</dt> + <dd>A largura da imagem.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + <mi><mglyph src="my-glyph.png" alt="my glyph"/></mi> +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mglyph', 'mglyph') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mglyph', 'mglyph') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + + + +<p>{{Compat("mathml.elements.mglyph")}}</p> diff --git a/files/pt-pt/web/mathml/element/mi/index.html b/files/pt-pt/web/mathml/element/mi/index.html new file mode 100644 index 0000000000..554bbc7a72 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mi/index.html @@ -0,0 +1,114 @@ +--- +title: <mi> +slug: Web/MathML/Element/mi +tags: + - MathML + - 'MathML:Element' + - 'MathML:Token Elements' + - Referência de MathML +translation_of: Web/MathML/Element/mi +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><mi></code> indica se o conteúdo deve ser apresentado como um <strong>identificador</strong> como nomes de funções, variáveis ou constantes simbólicas. Também pode ter texto arbitrário para a marcação de termos.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-dir">dir</dt> + <dd>A direção geral das fórmulas. Valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> + <dt id="attr-mathsize">mathsize</dt> + <dd>O tamanho do conteúdo. Ver <a class="external external-icon" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" rel="noopener">comprimento</a> para os valores aceites.<br> + Valores obsoletos: <code>small</code>, <code>normal</code> e <code>big</code>. Estes serão removidos no futuro.</dd> + <dt id="attr-mathvariant">mathvariant</dt> + <dd>Este atributo especifica a classe lógica do identificador, que varia em tipografia. Ou seja, embora os nomes sugerem o estilo tipográfico da classe, semanticamente, os itens com a mesma classe são tratados "da mesma forma" dentro de uma expressão, o que pode ou não envolver a sua exibição com a tipografia nomeada. São permitidos os seguintes valores: + <ul> + <li><code>normal</code> (Valor pré-definido para <em>mais que um caráter</em>) ; <math><mi mathvariant="normal">Exemplo</mi></math></li> + <li><code>bold</code> ; <math><mi mathvariant="bold">Exemplo</mi></math></li> + <li><code>italic</code> (Valor pré-definido para <em>um caráter individual</em>) ; <math><mi mathvariant="italic">Exemplo</mi></math></li> + <li><code>bold-italic</code> ; <math><mi mathvariant="bold-italic">Exemplo</mi></math></li> + </ul> + + <ul> + <li><code>double-struck</code> ; <math><mi mathvariant="double-struck">Exemplo</mi></math></li> + <li><code>bold-fraktur</code> ; <math><mi mathvariant="bold-fraktur">Exemplo</mi></math></li> + <li><code>script</code> ; <math><mi mathvariant="script">Exemplo</mi></math></li> + <li><code>bold-script</code> ; <math><mi mathvariant="bold-script">Exemplo</mi></math></li> + <li><code>fraktur</code> ; <math><mi mathvariant="fraktur">Exemplo</mi></math></li> + </ul> + + <ul> + <li><code>sans-serif</code> ; <math><mi mathvariant="sans-serif">Exemplo</mi></math></li> + <li><code>bold-sans-serif</code> ; <math><mi mathvariant="bold-sans-serif">Exemplo</mi></math></li> + <li><code>sans-serif-italic</code> ; <math><mi mathvariant="sans-serif-italic">Exemplo</mi></math></li> + <li><code>sans-serif-bold-italic</code> ; <math><mi mathvariant="sans-serif-bold-italic">Exemplo</mi></math></li> + <li><code>monospace</code> ; <math><mi mathvariant="monospace">Exemplo</mi></math></li> + </ul> + + <ul> + <li><code>initial</code> ; <math><mi mathvariant="initial">مثال</mi></math></li> + <li><code>tailed</code> ; <math><mi mathvariant="tailed">مثال</mi></math></li> + <li><code>looped</code> ; <math><mi mathvariant="looped">مثال</mi></math></li> + <li><code>stretched</code> ; <math><mi mathvariant="stretched">مثال</mi></math></li> + </ul> + </dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + + <mi> y </mi> + + <mi> sin </mi> + + <mi mathvariant="monospace"> x </mi> + + <mi mathvariant="bold"> &pi; </mi> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mi', 'mi') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mi', 'mi') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mi")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>Alguns valores de <code>mathvariant</code> só estão implementados a partir de Gecko 28.0 {{ geckoRelease("28.0") }} e requerem as <a href="/en-US/docs/Mozilla/MathML_Project/Fonts">fontes de matemática</a> apropriadas.</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mlabeledtr/index.html b/files/pt-pt/web/mathml/element/mlabeledtr/index.html new file mode 100644 index 0000000000..6f91a6b2d7 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mlabeledtr/index.html @@ -0,0 +1,99 @@ +--- +title: <mlabeledtr> +slug: Web/MathML/Element/mlabeledtr +tags: + - MathML + - 'MathML:Element' + - 'MathML:Tabular Math' + - Referência de MathML +translation_of: Web/MathML/Element/mlabeledtr +--- +<div>{{MathMLRef}}</div> + +<p>O elemento MathML <code><mlabeledtr></code> é utilizado para representar um rótulo/etiqueta numa fila quer do lado esquerdo, quer do direito (determinado utilizando o atributo <code>side</code> no elemento {{MathMLElement("mtable") }}). Os elementos criança de <code><mlabeledtr></code> devem ser {{MathMLElement("mtd") }} elementos. A primeira criança é o rótulo, enquanto todas as outras crianças representam conteúdos de linha e são tratadas de forma idêntica às crianças de elementos {{MathMLElement("mtr") }}.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-columnalign">columnalign</dt> + <dd>Indica o alinhamento horizontal desta célula e sobrepõe o valor especificado por {{ MathMLElement("mtable") }}.<br> + Os valores possíveis são: <code>left</code>, <code>center</code> e <code>right</code>.</dd> + <dt>groupalign</dt> + <dd>{{ unimplemented_inline() }}</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-rowalign">rowalign</dt> + <dd>Indica o alinhamento vertical desta célula e sobrepõe o valor especificado por {{ MathMLElement("mtable") }}.<br> + Os valores possíveis são: <code>axis</code>, <code>baseline</code>, <code>bottom</code>, <code>center</code> e <code>top</code>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="sample rendering for mlabeledtr" src="/files/3590/mlabeledtr.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<pre class="brush: html notranslate"><math> + <mtable> + + <mlabeledtr> + <mtd><mn>1</mn></mtd> <!-- label --> + <mtd><mi>A</mi></mtd> + <mtd><mi>B</mi></mtd> + </mlabeledtr> + + <mtr> + <mtd><mi>C</mi></mtd> + <mtd><mi>D</mi></mtd> + <mtd><mi>E</mi></mtd> + </mtr> + + </mtable> +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mlabeledtr', 'mlabeledtr') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mlabeledtr', 'mlabeledtr') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mlabeledtr")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<p>A começar com Gecko 9.0 {{ geckoRelease("9.0") }} etiquetas são escondidas por pré-definição (<code>mlabeledtr > mtd:first-child {display: none}</code>) e não estragam a apresentação de tabelas por completo (ver {{ bug("356870") }}). Para ver a implementação deste elemento veja {{ bug("689641") }}.</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mtable") }} (Tabela)</li> + <li>{{ MathMLElement("mtd") }} (Célula de tabela)</li> + <li>{{ MathMLElement("mtr") }} (Fila de Tabela)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mmultiscripts/index.html b/files/pt-pt/web/mathml/element/mmultiscripts/index.html new file mode 100644 index 0000000000..56ec2d5115 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mmultiscripts/index.html @@ -0,0 +1,131 @@ +--- +title: <mmultiscripts> +slug: Web/MathML/Element/mmultiscripts +tags: + - MathML + - 'MathML:Element' + - 'MathML:Script and Limit Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/mmultiscripts +--- +<div>{{MathMLRef}}</div> + +<p>O elemento MathML <code><mmultiscripts></code> permite a criação de objetos de tipo tensor. {{ interwiki("wikipedia", "Tensor", "Tensores") }} são entidades geométricas introduzidas na matemática e na física para generalizar a noção de escalares, vetores e matrizes. O grau de um tensor depende das dimensões duma matriz representativa. Por exemplo, um número é uma matriz de 0 dimensões, ou um tensor de 0ª ordem. Uma matriz unidimensional (por exemplo, vetores) é um tensor de 1ª ordem, por isso são necessários tensores de 2ª ordem para representar matrizes quadradas.</p> + +<p>MathML usa uma sintaxe especial para descrever <em>subscripts</em>, <em>superscripts</em>, ou ambos adicionados a uma expressão base:</p> + +<pre class="syntaxbox notranslate"><mmultiscripts> + <em>base</em> + (<em>subscript superscript</em>)* + [ <mprescripts/> (<em>presubscript presuperscript</em>)* ] +</mmultiscripts> +</pre> + +<p>Após a expressão base pode especificar um <em>post-subscript</em> e um <em>post-superscript</em>. Os <em>prescripts</em> são opcionais e são separados pela etiqueta vazia <code><mprescripts/></code> (apenas um <code><mprescripts/></code> elemento é permitido, caso contrário obterá um erro <code>DuplicateMprescripts</code> na Consola de Erros e "invalid-markup" na sua renderização). Além disso, é possível utilizar <code><none/></code> como espaço reservado para <em>scripts</em> vazios (não para a base). Veja a secção de exemplos para uma utilização correta.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style"><code>class</code>, <code>id</code>, <code>style</code></dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href"><code>href</code></dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground"><code>mathbackground</code></dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor"><code>mathcolor</code></dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-subscriptshift"><code>subscriptshift</code> {{deprecated_inline}}</dt> + <dd>O espaço mínimo entre o <em>subscript</em> e a linha de base da expressão, como um <a class="external external-icon" href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" rel="noopener">valor de comprimento.</a><br> + Este atributo está obsoleto e será removido no futuro.</dd> + <dt id="attr-superscriptshift"><code>superscriptshift</code> {{deprecated_inline}}</dt> + <dd>O espaço mínimo entre o <em>superscript</em> e a linha de base da expressão, como um <a class="external external-icon" href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" rel="noopener">valor de comprimento.</a><br> + Este atributo está obsoleto e será removido no futuro.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Usar_<mprescripts>">Usar <code><mprescripts/></code></h3> + +<p>Exemplo: <img alt="" src="/files/3223/mmultiscripts_prescripts.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <mmultiscripts> <mi>X</mi> <mi>d</mi> <mi>c</mi> <mprescripts></mprescripts> <mi>b</mi> <mi>a</mi> </mmultiscripts> </math></p> + +<pre class="brush: html notranslate"><math> + + <mmultiscripts> + + <mi>X</mi> <!-- base expression --> + + <mi>d</mi> <!-- postsubscript --> + <mi>c</mi> <!-- postsuperscript --> + + <mprescripts /> + <mi>b</mi> <!-- presubscript --> + <mi>a</mi> <!-- presuperscript --> + + </mmultiscripts> + +</math> +</pre> + +<h3 id="Usar_<none>">Usar <code><none/></code></h3> + +<p>Exemplo: <img alt="" src="/files/3222/mmultiscripts_none.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <mmultiscripts> <mi>X</mi> <none></none> <mi>c</mi> <mprescripts></mprescripts> <mi>b</mi> <none></none> </mmultiscripts> </math></p> + +<pre class="brush: html notranslate"><math> + + <mmultiscripts> + + <mi>X</mi> <!-- base expression --> + + <none /> <!-- postsubscript --> + <mi>c</mi> <!-- postsuperscript --> + + <mprescripts /> + <mi>b</mi> <!-- presubscript --> + <none /> <!-- presuperscript --> + + </mmultiscripts> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mmultiscripts', 'mmultiscripts') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mmultiscripts', 'mmultiscripts') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mmultiscripts")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("msub") }} (<em>Subscript</em>)</li> + <li>{{ MathMLElement("msup") }} (<em>Superscript</em>)</li> + <li>{{ MathMLElement("msubsup") }} (Par de <em>subscript-superscript</em>)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mn/index.html b/files/pt-pt/web/mathml/element/mn/index.html new file mode 100644 index 0000000000..431a62f8e9 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mn/index.html @@ -0,0 +1,116 @@ +--- +title: <mn> +slug: Web/MathML/Element/mn +tags: + - MathML + - 'MathML:Element' + - 'MathML:Token Elements' + - Referência de MathML +translation_of: Web/MathML/Element/mn +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><mn></code> representa uma <em>numeric literal</em> que tipicamente é uma sequência de dígitos com um possível separador (um ponto ou uma vírgula). Contudo, também é permissível ter um texto arbitrário que representa um número, por exemplo "onze".</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-dir">dir</dt> + <dd>A direção geral das fórmulas. Valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> + <dt id="attr-mathsize">mathsize</dt> + <dd>O tamanho do conteúdo. Ver <a class="external external-icon" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" rel="noopener">comprimento</a> para os valores aceites.<br> + Valores obsoletos: <code>small</code>, <code>normal</code> e <code>big</code>. Estes serão removidos no futuro.</dd> + <dt id="attr-mathvariant">mathvariant</dt> + <dd>Este atributo especifica a classe lógica do identificador, que varia em tipografia. Ou seja, embora os nomes sugerem o estilo tipográfico da classe, semanticamente, os itens com a mesma classe são tratados "da mesma forma" dentro de uma expressão, o que pode ou não envolver a sua exibição com a tipografia nomeada. São permitidos os seguintes valores: + <ul> + <li><code>normal</code> (Valor pré-definido) ; <math><mn mathvariant="normal">Exemplo</mn></math></li> + <li><code>bold</code> ; <math><mn mathvariant="bold">Exemplo</mn></math></li> + <li><code>italic</code> ; <math><mn mathvariant="italic">Exemplo</mn></math></li> + <li><code>bold-italic</code> ; <math><mn mathvariant="bold-italic">Exemplo</mn></math></li> + </ul> + + <ul> + <li><code>double-struck</code> ; <math><mn mathvariant="double-struck">Exemplo</mn></math></li> + <li><code>bold-fraktur</code> ; <math><mn mathvariant="bold-fraktur">Exemplo</mn></math></li> + <li><code>script</code> ; <math><mn mathvariant="script">Exemplo</mn></math></li> + <li><code>bold-script</code> ; <math><mn mathvariant="bold-script">Exemplo</mn></math></li> + <li><code>fraktur</code> ; <math><mn mathvariant="fraktur">Exemplo</mn></math></li> + </ul> + + <ul> + <li><code>sans-serif</code> ; <math><mn mathvariant="sans-serif">Exemplo</mn></math></li> + <li><code>bold-sans-serif</code> ; <math><mn mathvariant="bold-sans-serif">Exemplo</mn></math></li> + <li><code>sans-serif-italic</code> ; <math><mn mathvariant="sans-serif-italic">Exemplo</mn></math></li> + <li><code>sans-serif-bold-italic</code> ; <math><mn mathvariant="sans-serif-bold-italic">Exemplo</mn></math></li> + <li><code>monospace</code> ; <math><mn mathvariant="monospace">Exemplo</mn></math></li> + </ul> + + <ul> + <li><code>initial</code> ; <math><mn mathvariant="initial">مثال</mn></math></li> + <li><code>tailed</code> ; <math><mn mathvariant="tailed">مثال</mn></math></li> + <li><code>looped</code> ; <math><mn mathvariant="looped">مثال</mn></math></li> + <li><code>stretched</code> ; <math><mn mathvariant="stretched">مثال</mn></math></li> + </ul> + </dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + + <mn> 0 </mn> + + <mn> 1.337 </mn> + + <mn> twelve </mn> + + <mn> XVI </mn> + + <mn> 2e10 </mn> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mn', 'mn') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mn', 'mn') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mn")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>Alguns valores para <code>mathvariant</code> só estão implementados a partir de Gecko 28.0 {{ geckoRelease("28.0") }} e requerem a <a href="/en-US/docs/Mozilla/MathML_Project/Fonts">fonte de matemática</a> correta.</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mo/index.html b/files/pt-pt/web/mathml/element/mo/index.html new file mode 100644 index 0000000000..c9b995eb47 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mo/index.html @@ -0,0 +1,171 @@ +--- +title: <mo> +slug: Web/MathML/Element/mo +tags: + - MathML + - 'MathML:Element' + - 'MathML:Token Elements' + - Referência de MathML +translation_of: Web/MathML/Element/mo +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><mo></code> representa um operador. Para além de operadores de matemática, este elemento inclui "operadores" como parênteses, separadores como a vírgula ou ponto e virgula, ou barras do "valor absoluto".</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-accent">accent</dt> + <dd>Se o operador for utilizado como <em><a href="/pt-PT/docs/MathML/Element/munder">under</a>-</em> ou <em><a href="/pt-PT/docs/MathML/Element/mover">overscript</a></em> este atributo especifica se o operador deve ser tratado como um acento.<br> + Os valores permitidos são <code>true</code> ou <code>false</code>.</dd> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-dir">dir</dt> + <dd>A direção geral das fórmulas. Valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</dd> + <dt id="attr-fence">fence</dt> + <dd>Não existe um efeito visual para este atributo, mas indica se o operador é uma cerca (como parênteses).<br> + Os valores permitidos são <code>true</code> ou <code>false</code>.</dd> + <dt id="attr-form">form</dt> + <dd>Especifica o papel do operador numa expressão fechada, o que afeta o espaçamento e outras propriedades pré-definidas. Para os operadores normais (+, -, etc.) normalmente não é necessário especificar explicitamente este atributo.<br> + Os valores aceites são: + <ul> + <li><code>prefix</code>, para a abertura de cercas. (Isto é o valor pré-definido se o operador é o primeiro argumento num elemento de {{ MathMLElement("mrow") }} com mais que um argumento.)</li> + <li><code>infix</code>, para separadores. (É o valor pré-definido se o operador não está incluído num elemento de {{ MathMLElement("mrow") }}.)</li> + <li><code>postfix</code>, para fechar cercas. (Isto é o valor pré-definido se o operador é o último argumento num elemento de {{ MathMLElement("mrow") }} com mais que um argumento.)</li> + </ul> + </dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-largeop">largeop</dt> + <dd>Specifies whether the operator should be drawn larger than normal when <code>displaystyle="true"</code> is set. Allowed values are either <code>true</code> or <code>false</code>.</dd> + <dt id="attr-lspace">lspace</dt> + <dd>O espaço antes de um operador (ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> para valores e unidades). O constante <code>thickmathspace</code> (5/18em) é o valor pré-definido.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> + <dt id="attr-mathsize">mathsize</dt> + <dd>O tamanho do conteúdo. Ver <a class="external external-icon" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" rel="noopener">comprimento</a> para os valores aceites.<br> + Valores obsoletos: <code>small</code>, <code>normal</code> e <code>big</code>. Estes serão removidos no futuro.</dd> + <dt id="attr-mathvariant">mathvariant</dt> + <dd>Este atributo especifica a classe lógica do identificador, que varia em tipografia. Ou seja, embora os nomes sugerem o estilo tipográfico da classe, semanticamente, os itens com a mesma classe são tratados "da mesma forma" dentro de uma expressão, o que pode ou não envolver a sua exibição com a tipografia nomeada. São permitidos os seguintes valores + <ul> + <li><code>normal</code> (valor pré-definido) ; <math><mo mathvariant="normal">Exemplo</mo></math></li> + <li><code>bold</code> ; <math><mo mathvariant="bold">Exemplo</mo></math></li> + <li><code>italic</code> ; <math><mo mathvariant="italic">Exemplo</mo></math></li> + <li><code>bold-italic</code> ; <math><mo mathvariant="bold-italic">Exemplo</mo></math></li> + </ul> + + <ul> + <li><code>double-struck</code> ; <math><mo mathvariant="double-struck">Exemplo</mo></math></li> + <li><code>bold-fraktur</code> ; <math><mo mathvariant="bold-fraktur">Exemplo</mo></math></li> + <li><code>script</code> ; <math><mo mathvariant="script">Exemplo</mo></math></li> + <li><code>bold-script</code> ; <math><mo mathvariant="bold-script">Exemplo</mo></math></li> + <li><code>fraktur</code> ; <math><mo mathvariant="fraktur">Exemplo</mo></math></li> + </ul> + + <ul> + <li><code>sans-serif</code> ; <math><mo mathvariant="sans-serif">Exemplo</mo></math></li> + <li><code>bold-sans-serif</code> ; <math><mo mathvariant="bold-sans-serif">Exemplo</mo></math></li> + <li><code>sans-serif-italic</code> ; <math><mo mathvariant="sans-serif-italic">Exemplo</mo></math></li> + <li><code>sans-serif-bold-italic</code> ; <math><mo mathvariant="sans-serif-bold-italic">Exemplo</mo></math></li> + <li><code>monospace</code> ; <math><mo mathvariant="monospace">Exemplo</mo></math></li> + </ul> + + <ul> + <li><code>initial</code> ; <math><mo mathvariant="initial">مثال</mo></math></li> + <li><code>tailed</code> ; <math><mo mathvariant="tailed">مثال</mo></math></li> + <li><code>looped</code> ; <math><mo mathvariant="looped">مثال</mo></math></li> + <li><code>stretched</code> ; <math><mo mathvariant="stretched">مثال</mo></math></li> + </ul> + </dd> + <dt id="attr-maxsize">maxsize</dt> + <dd>Se <code>stretchy</code> é <code>true</code>, este atributo indica o tamanho máximo do operador. Os valores permitidos são: + <ul> + <li><code>infinity</code></li> + <li>um <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> arbitrário</li> + </ul> + </dd> + <dt id="attr-minsize">minsize</dt> + <dd>Se <code>stretchy</code> é <code>true</code>, este atributo indica o tamanho mínimo do operador. Os valores permitidos são: + <ul> + <li><code>infinity</code></li> + <li>um <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> arbitrário</li> + </ul> + </dd> + <dt id="attr-movablelimits">movablelimits</dt> + <dd>Indicia se <em>under-</em> e <em>overscripts</em> auxiliares movem para posições <em>sub-</em> e <em>superscript</em> quando <code>displaystyle</code> é <code>false</code>.<br> + Valores permitidos são <code>true</code> ou <code>false.</code></dd> + <dt id="attr-rspace">rspace</dt> + <dd>O espaço após o operador (ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> para valores e unidades). O constante <code>thickmathspace</code> (5/18em) é o valor pré-definido.</dd> + <dt id="attr-separator">separator</dt> + <dd>Não existe um efeito visual para este atributo, mas indica se o operador é um separador (como as vírgulas).<br> + Os valores permitidos são <code>true</code> ou <code>false</code>.</dd> + <dt id="attr-stretchy">stretchy</dt> + <dd>Indica se o operador estica-se até o tamanho do elemento adjacente.<br> + Os valores permitidos são <code>true</code> or <code>false</code>.</dd> + <dt id="attr-symmetric">symmetric</dt> + <dd>Se <code>stretchy</code> é <code>true</code>, este atributo indica se o operador deve ser verticalmente simétrico à volta do eixo imaginário (linha de fração centrada).<br> + O valor pré-definido é <code>true</code> se <em><strong>stretchy</strong></em> é <code>true</code> também, senão é <code>false</code>. Os valores aceites são <code>true</code> ou <code>false</code>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + +<mrow> + <mn>5</mn> + <mo>+</mo> + <mn>5</mn> +</mrow> + +<mrow> + <mo> [ </mo> <!-- default form value: prefix --> + <mrow> + <mn> 0 </mn> + <mo> ; </mo> <!-- default form value: infix --> + <mn> 1 </mn> + </mrow> + <mo> ) </mo> <!-- default form value: postfix --> +</mrow> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mo', 'mo') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mo', 'mo') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mo")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>A começar com o Gecko 16.0 {{ geckoRelease("16.0") }} os valores pré-definidos de <code>lspace</code> e <code>rspace</code> foram corrigidos para serem igual à especificação de MathML3. O valor pré-definido é agora o <code>thickmathspace</code> (5/18em).</li> + <li>Alguns valores de <code>mathvariant</code> só foram implementados a partir do Gecko 28.0 (Firefox 28.0 / Thunderbird 28.0 / SeaMonkey 2.25) e requerem as <a href="https://developer.mozilla.org/en-US/docs/Mozilla/MathML_Project/Fonts">fontes de matemática</a> corretas.</li> + <li>Quaisquer atributos de <a class="external" href="http://www.w3.org/TR/MathML3/chapter3.html#presm.lbattrs" title="http://www.w3.org/TR/MathML3/chapter3.html#presm.lbattrs">quebra de linha</a> ou <a class="external" href="http://www.w3.org/TR/MathML3/chapter3.html#presm.lbindent.attrs" title="http://www.w3.org/TR/MathML3/chapter3.html#presm.lbindent.attrs">atributos de indentação</a> ainda não estão implementados. Ver {{ bug("534962") }}.</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mover/index.html b/files/pt-pt/web/mathml/element/mover/index.html new file mode 100644 index 0000000000..d91f7e02c1 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mover/index.html @@ -0,0 +1,91 @@ +--- +title: <mover> +slug: Web/MathML/Element/mover +tags: + - MathML + - 'MathML:Element' + - 'MathML:Script and Limit Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/mover +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><mover></code> é usado para adicionar um acento ou limite sob uma expressão. Use antes a sintaxe seguinte: <code><mover> <em>base overscript</em> </mover></code></p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-accent">accent</dt> + <dd>Se <code>true</code>, o elemento é um acento, que então é desenhado mais perto da expressão base.<br> + Se <code>false</code> (valor pré-definido), o elemento é um limite acima da expressão base.</dd> + <dt id="attr-align">align {{deprecated_inline}}</dt> + <dd>O alinhamento do <em>overscript</em>. Os valores possíveis são: <code>left</code>, <code>center</code>, and <code>right</code>.<br> + Este atributo está obsoleto e será removido no futuro. Use antes o atributo de CSS <code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/CSS/text-align">text-align</a></code>.</dd> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="x+y+z" src="/files/3196/mover.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <mover accent="true"> <mrow> <mi> x </mi> <mo> + </mo> <mi> y </mi> <mo> + </mo> <mi> z </mi> </mrow> <mo> ⏞ </mo> </mover> </math></p> + +<pre class="brush: html notranslate"><math> + +<mover accent="true"> + <mrow> + <mi> x </mi> + <mo> + </mo> + <mi> y </mi> + <mo> + </mo> + <mi> z </mi> + </mrow> + <mo> &#x23DE; <!--TOP CURLY BRACKET--> </mo> +</mover> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificações</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mover', 'mover') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mover', 'mover') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação incial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mover")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("munder") }} (<em>Underscript</em>)</li> + <li>{{ MathMLElement("munderover") }} (Par de <em>underscript-overscript</em>)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mpadded/index.html b/files/pt-pt/web/mathml/element/mpadded/index.html new file mode 100644 index 0000000000..3d48b92ddd --- /dev/null +++ b/files/pt-pt/web/mathml/element/mpadded/index.html @@ -0,0 +1,96 @@ +--- +title: <mpadded> +slug: Web/MathML/Element/mpadded +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/mpadded +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento MathML <code><mpadded></code> é usado para adicionar extra <em>padding</em> e para ajustar a posição e o tamanho de elementos enroupados.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-depth">depth</dt> + <dd>Decide ou altera a profundidade. Os valores possíveis: Qualquer <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> ou um incremento/decremento (um comprimento com um prefixo de "+" ou "-").</dd> + <dt id="attr-height">height</dt> + <dd>Decide ou altera a altura. Os valores possíveis: Qualquer <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> ou um incremento/decremento (um comprimento com um prefixo de "+" ou "-").</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-lspace">lspace</dt> + <dd>Decide ou altera a posição horizontal. Os valores possíveis: Qualquer <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> ou um incremento/decremento (um comprimento com um prefixo de "+" ou "-").</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-voffset">voffset</dt> + <dd>Decide ou altera a posição vertical. Os valores possíveis: Qualquer <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> ou um incremento/decremento (um comprimento com um prefixo de "+" ou "-").</dd> + <dt id="attr-width">width</dt> + <dd>Decide ou altera a largura. Os valores possíveis: Qualquer <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> ou um incremento/decremento (um comprimento com um prefixo de "+" ou "-").</dd> +</dl> + +<h3 id="Pseudo-unidades">Pseudo-unidades</h3> + +<p>É possível utilizar as palavras-chave "<code>depth</code>", "<code>height</code>", e "<code>width</code>" como pseudo-unidade para os atributos <code>depth</code>, <code>height</code>, <code>lspace</code>, <code>voffset</code>, e <code>width</code>. Estes representam o comprimento da dimensão com o mesmo nome.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + + <mpadded height="+150px" width="100px" lspace="2height"> + <mi> x </mi> + <mo> + </mo> + <mi> y </mi> + </mpadded> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mpadded', 'mpadded') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mpadded', 'mpadded') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mpadded")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>Antes do Gecko 7.0 {{ geckoRelease("7.0") }} a pseudo-unidade <code>lspace</code> da MathML2 era permitido, que já não está presente na Recomendação MathML3 e foi removido agora.</li> +</ul> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mphantom") }}</li> + <li>{{ MathMLElement("mspace") }}</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mphantom/index.html b/files/pt-pt/web/mathml/element/mphantom/index.html new file mode 100644 index 0000000000..bfbbd09dfd --- /dev/null +++ b/files/pt-pt/web/mathml/element/mphantom/index.html @@ -0,0 +1,80 @@ +--- +title: <mphantom> +slug: Web/MathML/Element/mphantom +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/mphantom +--- +<div>{{MathMLRef}}</div> + +<p class="summary"><span class="seoSummary">O elemento de MathML <code><mphantom></code> é feito invisível, mas as suas dimensões (como a altura, largura e posição base) são mantidas.</span></p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="x+ z" src="/files/3199/mphantom.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <mrow> <mi> x </mi> <mo> + </mo> <mphantom> <mi> y </mi> <mo> + </mo> </mphantom> <mi> z </mi> </mrow> </math></p> + +<pre class="brush: html notranslate"><math> + +<mrow> + <mi> x </mi> + <mo> + </mo> + <mphantom> + <mi> y </mi> + <mo> + </mo> + </mphantom> + <mi> z </mi> +</mrow> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mphantom', 'mphantom') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mphantom', 'mphantom') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mphantom")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mspace") }}</li> + <li>{{ MathMLElement("mpadded") }}</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mroot/index.html b/files/pt-pt/web/mathml/element/mroot/index.html new file mode 100644 index 0000000000..03c87f1c7f --- /dev/null +++ b/files/pt-pt/web/mathml/element/mroot/index.html @@ -0,0 +1,78 @@ +--- +title: <mroot> +slug: Web/MathML/Element/mroot +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/mroot +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><mroot></code> apresenta raízes com um índice explicito. Dois argumentos são aceites, com a sintaxe seguinte: <code><mroot> <em>base index</em> </mroot></code>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto e a cor do simbolo da raiz também. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="x" src="/files/3200/mroot.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <mroot> <mi>x</mi> <mn>3</mn> </mroot> </math></p> + +<pre class="brush: html notranslate"><math> + + <mroot> + <mi>x</mi> + <mn>3</mn> + </mroot> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mroot', 'mroot') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mroot', 'mroot') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mroot")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("msqrt") }} (Raiz quadrada sem índice)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mrow/index.html b/files/pt-pt/web/mathml/element/mrow/index.html new file mode 100644 index 0000000000..1e79df2bac --- /dev/null +++ b/files/pt-pt/web/mathml/element/mrow/index.html @@ -0,0 +1,95 @@ +--- +title: <mrow> +slug: Web/MathML/Element/mrow +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/mrow +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><mrow></code> é utilizado para agrupar sub-expressões, que normalmente contêm um ou mais operadores com os seus respetivos operandos (tais como {{ MathMLElement("mi") }} e {{ MathMLElement("mn") }}). Este elemento é apresentado como uma linha horizontal contendo os seus argumentos.</p> + +<p>Ao escrever uma expressão MathML, deve agrupar elementos dentro de um <code><mrow></code> da mesma forma que são agrupados na interpretação matemática da expressão. O agrupamento adequado ajuda a renderizar a expressão de várias maneiras:</p> + +<ul> + <li>Pode melhorar a visualização, afetando possivelmente o espaçamento.</li> + <li>Permite implementar quebras de linha e indentação mais inteligente.</li> + <li>Simplifica a interpretação da expressão por sistemas automatizados, tais como sistemas de álgebra informática e leitores.</li> +</ul> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-dir">dir</dt> + <dd>A direção geral das fórmulas. Valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + + <mrow> + <mn> 1 </mn> + <mo> + </mo> + <mn> 1 </mn> + </mrow> + + <mrow> + <mo> ( </mo> + <mrow> + <mi> x </mi> + <mo> , </mo> + <mi> y </mi> + </mrow> + <mo> ) </mo> + </mrow> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mrow', 'mrow') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mrow', 'mrow') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mrow")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>Elemento de agrupamento de HTML: {{ HTMLElement("div") }}</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/ms/index.html b/files/pt-pt/web/mathml/element/ms/index.html new file mode 100644 index 0000000000..a3489d64ed --- /dev/null +++ b/files/pt-pt/web/mathml/element/ms/index.html @@ -0,0 +1,112 @@ +--- +title: <ms> +slug: Web/MathML/Element/ms +tags: + - MathML + - 'MathML:Element' + - 'MathML:Token Elements' + - Referência de MathML +translation_of: Web/MathML/Element/ms +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><ms></code> representa uma <em>string literal</em> que deve ser intrepetada por linguagens de programação e sistemas de álgebra informática. Por norma, os <em>string literals</em> são exibidos como delimitados por aspas duplas (<code>&quot;</code>); utilizando os atributos <code>lquote</code> e <code>rquote</code>, é possível definir caracteres personalizados para exibir. Note que as aspas não devem ser especificadas a menos que façam parte da cadeia de caracteres literal. O conteúdo de um elemento <ms> não é uma <em>string</em> de ASCII, mas sim uma sequência de caracteres e os elementos {{MathMLElement("mglyph") }} e {{MathMLElement("malignmark") }}.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-dir">dir</dt> + <dd>A direção geral das fórmulas. Valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</dd> + <dt id="attr-lquote">lquote</dt> + <dd>O carácter de citação de abertura (depende da direção indicada por <code>dir</code>) para delimitar o conteúdo. O valor pré-definido é <code>&quot;</code>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathsize">mathsize</dt> + <dd>O tamanho do conteúdo. Ver <a class="external external-icon" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" rel="noopener">comprimento</a> para os valores aceites.<br> + Valores obsoletos: <code>small</code>, <code>normal</code> e <code>big</code>. Estes serão removidos no futuro.</dd> + <dt id="attr-mathvariant">mathvariant</dt> + <dd>Este atributo especifica a classe lógica do identificador, que varia em tipografia. Ou seja, embora os nomes sugerem o estilo tipográfico da classe, semanticamente, os itens com a mesma classe são tratados "da mesma forma" dentro de uma expressão, o que pode ou não envolver a sua exibição com a tipografia nomeada. São permitidos os seguintes valores: + <ul> + <li><code>normal</code> (Default value) ; <math><ms mathvariant="normal">Exemplo</ms></math></li> + <li><code>bold</code> ; <math><ms mathvariant="bold">Exemplo</ms></math></li> + <li><code>italic</code> ; <math><ms mathvariant="italic">Exemplo</ms></math></li> + <li><code>bold-italic</code> ; <math><ms mathvariant="bold-italic">Exemplo</ms></math></li> + </ul> + + <ul> + <li><code>double-struck</code> ; <math><ms mathvariant="double-struck">Exemplo</ms></math></li> + <li><code>bold-fraktur</code> ; <math><ms mathvariant="bold-fraktur">Exemplo</ms></math></li> + <li><code>script</code> ; <math><ms mathvariant="script">Exemplo</ms></math></li> + <li><code>bold-script</code> ; <math><ms mathvariant="bold-script">Exemplo</ms></math></li> + <li><code>fraktur</code> ; <math><ms mathvariant="fraktur">Exemplo</ms></math></li> + </ul> + + <ul> + <li><code>sans-serif</code> ; <math><ms mathvariant="sans-serif">Exemplo</ms></math></li> + <li><code>bold-sans-serif</code> ; <math><ms mathvariant="bold-sans-serif">Exemplo</ms></math></li> + <li><code>sans-serif-italic</code> ; <math><ms mathvariant="sans-serif-italic">Exemplo</ms></math></li> + <li><code>sans-serif-bold-italic</code> ; <math><ms mathvariant="sans-serif-bold-italic">Exemplo</ms></math></li> + <li><code>monospace</code> ; <math><ms mathvariant="monospace">Exemplo</ms></math></li> + </ul> + + <ul> + <li><code>initial</code> ; <math><ms mathvariant="initial">مثال</ms></math></li> + <li><code>tailed</code> ; <math><ms mathvariant="tailed">مثال</ms></math></li> + <li><code>looped</code> ; <math><ms mathvariant="looped">مثال</ms></math></li> + <li><code>stretched</code> ; <math><ms mathvariant="stretched">مثال</ms></math></li> + </ul> + </dd> + <dt id="attr-rquote">rquote</dt> + <dd>O carácter de citação de fecho (depende da direção indicada por <code>dir</code>) para delimitar o conteúdo. O valor pré-definido é <code>&quot;</code>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + + <ms lquote="„" rquote="“"> abc </ms> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.ms', 'ms') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Current specification</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.ms', 'ms') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Initial specification</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.ms")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>Alguns valores de <code>mathvariant</code> só estão implementados a começar com Gecko 28.0 (Firefox 28.0 / Thunderbird 28.0 / SeaMonkey 2.25) e requerem as <a href="https://developer.mozilla.org/en-US/docs/Mozilla/MathML_Project/Fonts">fontes matemáticas</a> apropriadas.</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mspace/index.html b/files/pt-pt/web/mathml/element/mspace/index.html new file mode 100644 index 0000000000..1d5161228e --- /dev/null +++ b/files/pt-pt/web/mathml/element/mspace/index.html @@ -0,0 +1,88 @@ +--- +title: <mspace> +slug: Web/MathML/Element/mspace +tags: + - MathML + - 'MathML:Element' + - 'MathML:Token Element' + - Referência de MathML +translation_of: Web/MathML/Element/mspace +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><mspace></code> é usado para visualizar um espaço em branco, cujo tamanho é decidido pelos seus atributos.</p> + +<h2 id="Attributos">Attributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/pt-PT/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-depth">depth</dt> + <dd>A profundidade desejada (abaixo da linha de base) do espaço (ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> para valores e unidades).</dd> + <dt id="attr-height">height</dt> + <dd>A altura desejada (acima da linha de base) do espaço (ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> para valores e unidades).</dd> + <dt id="attr-linebreak">linebreak</dt> + <dd>Indica uma quebra de linha no espaço. Valores aceites: <code>auto</code> (valor padrão), <code>newline</code>, <code>nobreak</code>, <code>goodbreak</code> e <code>badbreak</code>.<br> + A começar com MathML 3, é de preferencia usar {{ MathMLElement("mo") }} para controlar quebras de linha.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-width">width</dt> + <dd>A largura desejada do espaço (ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> para valores e unidades).</dd> +</dl> + +<p>Note que alguns atributos comuns como <code>mathcolor</code>, <code>mathvariant</code> ou <code>dir</code> não tem efeito no <code><mspace></code>.</p> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + + <mspace depth="40px" height="20px" /> + + <mspace width="100px" /> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mspace', 'mspace') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mspace', 'mspace') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mspace")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li><a class="external" href="http://www.w3.org/TR/MathML3/chapter3.html#presm.lbindent.attrs" title="http://www.w3.org/TR/MathML3/chapter3.html#presm.lbindent.attrs">Atributos de indentação</a> ainda não implementados (for Gecko see {{ bug("534962") }}).</li> + <li>Suporte para valores negativos do atributo <code>width</code> foram implementados em Gecko 23.0 {{geckoRelease("23.0")}}.</li> +</ul> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mpadded") }}</li> + <li>{{ MathMLElement("mphantom") }}</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/msqrt/index.html b/files/pt-pt/web/mathml/element/msqrt/index.html new file mode 100644 index 0000000000..0261764216 --- /dev/null +++ b/files/pt-pt/web/mathml/element/msqrt/index.html @@ -0,0 +1,77 @@ +--- +title: <msqrt> +slug: Web/MathML/Element/msqrt +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/msqrt +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><msqrt></code> é usado para apresentar raízes quadradas (sem índice à vista). A raiz quadrada aceita só um argumento, com a sintaxe seguinte: <code><msqrt> <em>base</em> </msqrt></code>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto e a cor do símbolo da raiz também. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="root-x" src="/files/3201/msqrt.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <msqrt> <mi>x</mi> </msqrt> </math></p> + +<pre class="brush: html notranslate"><math> + + <msqrt> + <mi>x</mi> + </msqrt> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mroot', 'msqrt') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.msqrt', 'msqrt') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.msqrt")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mroot") }} (Radical com um índice)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mstyle/index.html b/files/pt-pt/web/mathml/element/mstyle/index.html new file mode 100644 index 0000000000..b23916e66e --- /dev/null +++ b/files/pt-pt/web/mathml/element/mstyle/index.html @@ -0,0 +1,126 @@ +--- +title: <mstyle> +slug: Web/MathML/Element/mstyle +tags: + - MathML + - 'MathML:Element' + - 'MathML:General Layout Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/mstyle +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento MathML <code><mstyle></code> é utilizado para mudar o estilo dos seus elementos filhos. Aceita todos os atributos de todos os elementos de apresentação MathML com algumas excepções e atributos adicionais listados abaixo.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-dir"><code>dir</code></dt> + <dd>A direção geral das fórmulas. Os valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</dd> + <dt id="attr-decimalpoint"><code>decimalpoint</code></dt> + <dd>Se o valor de <code>decimalpoint</code> é usado para indicar o alinhamento, este indica qual o carater do ponto de alinhamento dentro das colunas de <code><a class="new" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Element/mstack" rel="nofollow" title="<mstack>"><mstack></a></code> e <code><a class="new" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Element/mtable" rel="nofollow" title="<mtable>"><mtable></a></code>.</dd> + <dt id="attr-displaystyle"><code>displaystyle</code></dt> + <dd>Um valor <code>Boolean</code> que indica se mais espaço é usado para visualizar equações ou, se <code>false</code>, uma apresentação mais compacta é usada para apresentar as fórmulas. O efeito principal é que versões maiores de operadores são apresentados quando <code>displaystyle</code> é <code>true</code>. Ver <code>largeop</code> e <code>movablelimits</code> em {{ MathMLElement("mo") }}.</dd> + <dt id="attr-infixlinebreakstyle"><code>infixlinebreakstyle</code></dt> + <dd>Indica o <code>linebreakstyle</code> pré-definido para usar com operadores <em>infix</em>. Os valores <code>before</code>, <code>after</code> e <code>duplicate</code> são permitidos.</dd> + <dt id="attr-scriptlevel"><code>scriptlevel</code></dt> + <dd> + <p>Controla sobretudo o tamanho da fonte. Quanto mais alto for o valor do <code>scriptlevel</code>, menor será o tamanho da fonte. Este atributo aceita um inteiro não negativo, assim como um sinal "+" ou "-", que aumenta ou diminui o valor atual. Além disso, o atributo de <code>scriptlevel</code> nunca pode reduzir o tamanho da fonte abaixo do tamanho do <code>scriptminsize</code>, de modo a evitar tamanhos de fonte ilegíveis e depende do multiplicador especificado no <code>scriptizemultiplier</code>.</p> + </dd> + <dt id="attr-scriptminsize"><code>scriptminsize</code></dt> + <dd>Indica o mínimo valor permitido do tamanho da fonte devido a mudanças causadas por <code>scriptlevel</code>. O valor pré-definido é 8pt.</dd> + <dt id="attr-scriptsizemultiplier"><code>scriptsizemultiplier</code></dt> + <dd>Indica o multiplicadorque deve ser usado para ajustar o tamanho da fonte devido a mudanças causadas por <code>scriptlevel</code>. O valor pré-definido é 0.71.</dd> +</dl> + +<p>O elemento <code><mstyle></code> aceita <a href="/pt-PT/docs/Web/MathML/Attribute">todos os atributos</a> de todos os elementos de apresentação, à exceção dos seguintes atributos:</p> + +<ul> + <li><code>height</code>, <code>depth</code> e <code>width</code> não se aplicam ao {{ MathMLELement("mglyph") }}, {{ MathMLELement("mpadded") }} ou {{ MathMLELement("mtable") }}.</li> + <li><code>rowalign</code>, <code>columnalign</code>, e <code>groupalign</code> não se aplicam ao {{ MathMLELement("mtr") }}, {{ MathMLELement("mlabeledtr") }}, {{ MathMLELement("mtd") }} ou {{ MathMLELement("maligngroup") }}.</li> + <li><code>lspace</code> e <code>voffset</code> não se aplicam ao {{ MathMLELement("mpadded") }}.</li> + <li><code>fontfamily</code> não se aplica ao {{ MathMLELement("mglyph") }}.</li> + <li><code>align</code> não se aplica ao {{ MathMLELement("mtable") }} ou {{ MathMLELement("mstack") }}.</li> + <li><code>index</code> não pode ser atribuído ao <code><mstyle></code>.</li> + <li><code>src</code> e <code>alt</code> no{{ MathMLElement("mglyph" ) }} não pode ser atribuído ao <code><mstyle></code>.</li> + <li><code>actiontype</code> no {{ MathMLElement("maction") }} não pode ser atribuído ao <code><mstyle></code>.</li> +</ul> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Usar <code>displaystyle</code> e <code>mathcolor</code> para efetuar mudanças no estilo do formato da equação.</p> + +<pre class="brush: html notranslate"><math> + + <mstyle displaystyle="true" mathcolor="teal"> + <mrow> + + <munderover> + <mo stretchy="true" form="prefix">&sum;</mo> + <mrow> + <mi>i</mi> + <mo form="infix">=</mo> + <mn>1</mn> + </mrow> + <mi>n</mi> + </munderover> + + <mstyle displaystyle="true"> + <mfrac> + <mn>1</mn> + <mi>n</mi> + </mfrac> + </mstyle> + + </mrow> + </mstyle> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mstyle', 'mstyle') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mstyle', 'mstyle') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mstyle")}}</p> + +<h2 id="Gecko-specific_notes">Gecko-specific notes</h2> + +<ul> + <li>Antes do Gecko 6.0 {{ geckoRelease("6.0") }} a implementação do <code><mstyle></code> não estava completa, e desde então <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=569125">foi corrigida</a>. Particularmente, os valores dos seguintes atributos no <code>mstyle</code> não têm efeito nos filhos do elemento: + + <ul> + <li>O atributo <code>bevelled</code> não afeta o {{ MathMLElement("mfrac") }}.</li> + <li>O atributo <code>notation</code> não afeta {{ MathMLElement("menclose") }}.</li> + <li>Os atributos <code>open</code>, <code>close</code> e <code>separators</code> não afetam {{ MathMLElement("mfenced") }}.</li> + <li>Os atributos <code>accent</code> e <code>accentunder</code> não afetam o {{ MathMLElement("mover") }}, {{ MathMLElement("munder") }} e {{ MathMLElement("munderover") }} elements.</li> + <li>O atributo <code>selection</code> não afeta o {{ MathMLElement("maction") }}.</li> + <li>O atributo <code>mathvariant</code> não afeta o {{ MathMLElement("mi") }}.</li> + </ul> + </li> + <li>A começar com o Gecko 29.0 {{geckoRelease("29.0")}}, os atributos aceites no elemento <code><mstyle></code> foram restritos aos que são usados na prática: <code>id</code>, <code>class,</code> <code>style</code>, <code>href</code>, <code>mathcolor</code>, <code>mathbackground</code>, <code>scriptlevel</code>, <code>displaystyle,</code> <code>scriptsizemultiplier</code>, <code>scriptminsize</code>, <code>dir</code>, <code>mathsize</code>, <code>mathvariant,</code> <code>fontfamily</code>, <code>fontweight</code>, <code>fontstyle</code>, <code>fontsize</code>, <code>color</code> e <code>background</code>.</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/msub/index.html b/files/pt-pt/web/mathml/element/msub/index.html new file mode 100644 index 0000000000..c7584186cf --- /dev/null +++ b/files/pt-pt/web/mathml/element/msub/index.html @@ -0,0 +1,85 @@ +--- +title: <msub> +slug: Web/MathML/Element/msub +tags: + - MathML + - 'MathML:Element' + - 'MathML:Script and Limit Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/msub +--- +<div>{{MathMLRef}}</div> + +<p><span class="seoSummary">O elemento de MathML <code><msub></code> para adicionar um <em>subscript</em> a uma expressão.</span></p> + +<p>Usa a seguinte sintaxe: <code><msub> <em>base subscript</em> </msub></code>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style"><code>class</code>, <code>id</code>, <code>style</code></dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href"><code>href</code></dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground"><code>mathbackground</code></dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor"><code>mathcolor</code></dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-subscriptshift"><code>subscriptshift</code> {{deprecated_inline}}</dt> + <dd>O espaço mínimo entre o <em>subscript</em> e a linha de base da expressão, como um <a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">valor de comprimento.</a><br> + Este atributo está obsoleto e será removido no futuro.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="x1" src="/files/3202/msub.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <msub> <mi>X</mi> <mn>1</mn> </msub> </math></p> + +<pre class="brush: html notranslate"><math> + + <msub> + <mi>X</mi> + <mn>1</mn> + </msub> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.msub', 'msub') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.msub', 'msub') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.msub")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("msup") }} (<em>Superscript</em>)</li> + <li>{{ MathMLElement("msubsup") }} (Par de <em>subscript-superscript</em>)</li> + <li>{{ MathMLElement("mmultiscripts") }} (<em>Prescripts</em> e índices tensores)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/msubsup/index.html b/files/pt-pt/web/mathml/element/msubsup/index.html new file mode 100644 index 0000000000..0091ba6c73 --- /dev/null +++ b/files/pt-pt/web/mathml/element/msubsup/index.html @@ -0,0 +1,89 @@ +--- +title: <msubsup> +slug: Web/MathML/Element/msubsup +tags: + - MathML + - 'MathML:Element' + - 'MathML:Script and Limit Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/msubsup +--- +<div>{{MathMLRef}}</div> + +<p><span class="seoSummary">O elemento de MathML <code><msubsup></code> é usado para adicionar um <em>subscript</em> e um <em>superscript</em>, juntos, a uma expressão.</span></p> + +<p>Usa a sintaxe seguinte: <code><msubsup> <em>base subscript superscript</em> </msubsup></code>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style"><code>class</code>, <code>id</code>, <code>style</code></dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href"><code>href</code></dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground"><code>mathbackground</code></dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor"><code>mathcolor</code></dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-subscriptshift"><code>subscriptshift</code> {{deprecated_inline}}</dt> + <dd>O espaço mínimo entre o <em>subscript</em> e a linha de base da expressão, como um <a class="external external-icon" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" rel="noopener">valor de comprimento.</a><br> + Este atributo está obsoleto e será removido no futuro.</dd> + <dt id="attr-superscriptshift"><code>superscriptshift</code> {{deprecated_inline}}</dt> + <dd>O espaço mínimo entre o <em>superscript</em> e a linha de base da expressão, como um <a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">valor de comprimento.</a><br> + Este atributo está obsoleto e será removido no futuro.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="x1" src="/files/3204/msubsup.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math displaystyle="true"> <msubsup> <mo> ∫</mo> <mn> 0 </mn> <mn> 1 </mn> </msubsup> </math></p> + +<pre class="brush: html notranslate"><math displaystyle="true"> + + <msubsup> + <mo> &#x222B;<!--Integral --> </mo> + <mn> 0 </mn> + <mn> 1 </mn> + </msubsup> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.msubsup', 'msubsup') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.msubsup', 'msubsup') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.msubsup")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("msub") }} (<em>Subscript</em>)</li> + <li>{{ MathMLElement("msup") }} (<em>Superscript</em>)</li> + <li>{{ MathMLElement("mmultiscripts") }} (<em>Prescripts</em> e índices tensores)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/msup/index.html b/files/pt-pt/web/mathml/element/msup/index.html new file mode 100644 index 0000000000..029486dce2 --- /dev/null +++ b/files/pt-pt/web/mathml/element/msup/index.html @@ -0,0 +1,85 @@ +--- +title: <msup> +slug: Web/MathML/Element/msup +tags: + - MathML + - 'MathML:Element' + - 'MathML:Script and Limit Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/msup +--- +<div>{{MathMLRef}}</div> + +<p><span class="seoSummary">O elemento de MathML <code><msup></code> é usado para adicionar um superscript a uma expressão.</span></p> + +<p>Usa a sintaxe seguinte: <code><msup> <em>base superscript</em> </msup></code>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style"><code>class</code>, <code>id</code>, <code>style</code></dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href"><code>href</code></dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground"><code>mathbackground</code></dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor"><code>mathcolor</code></dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a></dd> + <dt id="attr-superscriptshift"><code>superscriptshift</code> {{deprecated_inline}}</dt> + <dd>O espaço mínimo entre o <em>superscript</em> e a linha de base da expressão, como um <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">valor de comprimento.</a><br> + Este atributo está obsoleto e será removido no futuro.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="x1" src="/files/3203/msup.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <msup> <mi>X</mi> <mn>2</mn> </msup> </math></p> + +<pre class="brush: html notranslate"><math> + + <msup> + <mi>X</mi> + <mn>2</mn> + </msup> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.msup', 'msup') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.msup', 'msup') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.msup")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("msub") }} (<em>Subscript</em>)</li> + <li>{{ MathMLElement("msubsup") }} (par de <em>subscript-superscript</em>)</li> + <li>{{ MathMLElement("mmultiscripts") }} (<em>Prescripts</em> e índices tensores)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mtable/index.html b/files/pt-pt/web/mathml/element/mtable/index.html new file mode 100644 index 0000000000..90c763e3f2 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mtable/index.html @@ -0,0 +1,140 @@ +--- +title: <mtable> +slug: Web/MathML/Element/mtable +tags: + - MathML + - 'MathML:Element' + - 'MathML:Tabular Math' + - Referência de MathML +translation_of: Web/MathML/Element/mtable +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento MathML <code><mtable></code> permite criar tabelas e matrizes. Dentro de um <code><mtable></code> só podem aparecer os elementos {{ MathMLElement("mtr") }} e {{ MathMLElement("mtd") }}. Estes elementos são semelhantes aos elementos de <a href="/pt-PT/docs/HTML">HTML</a> {{ HTMLElement("table") }} , {{ HTMLElement("tr") }} e {{ HTMLElement("td") }}.</p> + +<div class="note"> +<p><strong>Nota: </strong>O elemento <code><mtable></code> restaura o valor do atributo <code>displaystyle</code> para <code>false</code>. Se quiser usar este elemento com o formatação de <em>inline-block</em>, deve criar o elemento com o atributo <code>displaystyle</code> com o valor <code>true</code>, por exemplo <code><mtable displaystyle="true">...</mtable></code>.</p> +</div> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-align">align</dt> + <dd>Especifica o alinhamento <strong>vertical</strong> da mesa em relação ao seu ambiente.<br> + Os valores aceites são: + <ul> + <li><code>axis</code> (pré-definido): O centro vertical da tabela alinha-se no eixo do ambiente (tipicamente o sinal menos).</li> + <li><code>baseline</code>: O centro vertical da mesa alinha-se com a linha de base do ambiente.</li> + <li><code>bottom</code>: O fundo da tabela alinha-se com a linha de base do ambiente.</li> + <li><code>center</code>: Ver linha de base.</li> + <li><code>top</code>: O topo da tabela alinha-se com a linha de base do ambiente.</li> + </ul> + Além disso, os valores do atributo <code>align</code> podem terminar com um número de <code>rownumber</code> (por exemplo <code>align="center 3"</code>). Isto permite alinhar a linha especificada da tabela em vez de toda a tabela. Um valor integral negativo conta as linhas do fundo da tabela. Começando com Gecko 8.0 {{ geckoRelease("8.0") }}, a interpretação dos valores negativos foi corrigida ({{ bug(601436) }}). Em Gecko 17.0 {{ geckoRelease("17.0") }}, a análise foi atualizada para tratar corretamente o espaço em branco.</dd> + <dt id="attr-alignmentscope">alignmentscope</dt> + <dd>{{ unimplemented_inline() }}</dd> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-columnalign">columnalign</dt> + <dd>Indica o alinhamento horizontal das células da tabela. São permitidos valores múltiplos separados por espaço e aplicam-se às colunas correspondentes (e.x. <code>columnalign="left right center"</code>). Os valores aceites são: <code>left</code>, <code>center</code> (pré-definido) e <code>right</code>.</dd> + <dt id="attr-columnlines">columnlines</dt> + <dd>Indica as bordas das colunas da tabela. São permitidos valores múltiplos separados por espaço e aplicam-se às colunas correspondentes (e.x. <code>columnlines="none none solid"</code>). Os valores aceites são: <code>none</code> (pré-definido), <code>solid</code> e <code>dashed</code>.</dd> + <dt id="attr-columnspacing">columnspacing</dt> + <dd>Indica o espaço entre as colunas da tabela.</dd> + <dt id="attr-columnwidth">{{ unimplemented_inline() }} columnwidth</dt> + <dd>Indica a largura das colunas da tabela.</dd> + <dt id="attr-displaystyle">displaystyle</dt> + <dd>Um valor <code>Boolean</code> que indica se mais espaço é usado para visualizar equações ou, se <code>false</code>, uma apresentação mais compacta é usada para apresentar as fórmulas. O efeito principal é que versões maiores de operadores são apresentados quando <code>displaystyle</code> é <code>true</code>.</dd> + <dt id="attr-equalcolumns">{{ unimplemented_inline() }} equalcolumns</dt> + <dd>Um valor <code>Boolean</code> que indica se todas as colunas devem ser forçadas a ter a mesma altura total. <code>false</code> é o valor pré-definido.</dd> + <dt id="attr-equalrows">{{ unimplemented_inline() }} equalrows</dt> + <dd>Um valor <code>Boolean</code> que indica se todas as linhas devem ser forçadas a ter a mesma altura total. <code>false</code> é o valor pré-definido.</dd> + <dt id="attr-frame">frame</dt> + <dd>Indica as bordas do elemento <code><a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Element/mtable" title="<mtable>"><mtable></a></code>. Os valores possiveis são: <code>none</code> (pré-definido), <code>solid</code> e <code>dashed</code>.</dd> + <dt id="attr-framespacing">framespacing</dt> + <dd>Indica o espaço adicional entre a tabela e a <code>frame</code>.</dd> + <dt id="attr-groupalign">groupalign</dt> + <dd>{{ unimplemented_inline() }}</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação apontando a uma URI especificado.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-minlabelspacing">{{ unimplemented_inline() }} minlabelspacing</dt> + <dd>Um <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">valor de comprimento</a> que indica o espaço minimimo entre uma etiqueta e a célula adjacente numa linha.</dd> + <dt id="attr-rowalign">rowalign</dt> + <dd>Indica o alinhamento vertical das células da tabela. São permitidos valores múltiplos separados por espaço e aplicam-se às linhas correspondentes (e.x. <code>rowalign="top bottom axis"</code>). Os valores aceites: <code>axis</code>, <code>baseline</code> (pré-definido), <code>bottom</code>, <code>center</code> e <code>top</code>.</dd> + <dt id="attr-rowlines">rowlines</dt> + <dd>Especifica o estilo das bordas das linhas da tabela. São permitidos valores múltiplos separados por espaço e aplicam-se às linhas correspondentes (e.x. <code>rowlines="none none solid"</code>). Os valores aceites são: <code>none</code> (pré-definido), <code>solid</code> e <code>dashed</code>.</dd> + <dt id="attr-rowspacing">{{ unimplemented_inline() }} rowspacing</dt> + <dd>Specifies the space between table rows.</dd> + <dt id="attr-side">{{ unimplemented_inline() }} side</dt> + <dd>Indica a posição onde a etiqueta de {{ MathMLElement("mlabeledtr") }} deve ser posta. Os valores acietes são: <code>left</code>, <code>right</code> (pré-definido), <code>leftoverlap</code> e <code>rightoverlap</code>.</dd> + <dt id="attr-width">width</dt> + <dd>Indica a largura desejada da tabela. Ver <a href="/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos" title="/en-US/docs/MathML/Attributes/Values#Lengths">comprimentos</a> para valores possíveis.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<h3 id="Alinhamento_com_linha_indicada">Alinhamento com linha indicada</h3> + +<p>Renderização: <img alt="" src="/files/3295/mtable-1.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<pre class="brush: html notranslate"><math> + + <mi>X</mi> + <mo>=</mo> + <mtable frame="solid" rowlines="solid" align="axis 3"> + <mtr> + <mtd><mi>A</mi></mtd> + <mtd><mi>B</mi></mtd> + </mtr> + <mtr> + <mtd><mi>C</mi></mtd> + <mtd><mi>D</mi></mtd> + </mtr> + <mtr> + <mtd><mi>E</mi></mtd> + <mtd><mi>F</mi></mtd> + </mtr> + </mtable> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mtable', 'mtable') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mtable', 'mtable') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mtable")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mtd") }} (Célula de tabela)</li> + <li>{{ MathMLElement("mtr") }} (Linha de tablela)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mtd/index.html b/files/pt-pt/web/mathml/element/mtd/index.html new file mode 100644 index 0000000000..e799e7d4c1 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mtd/index.html @@ -0,0 +1,75 @@ +--- +title: <mtd> +slug: Web/MathML/Element/mtd +tags: + - MathML + - 'MathML:Element' + - 'MathML:Tabular Math' + - Referência de MathML +translation_of: Web/MathML/Element/mtd +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento <code><mtd></code> de MathML representa uma célula numa tabela ou matriz. Só pode aparecer dentro do elemento {{ MathMLElement("mtr") }}. Este elemento é semelhante ao elemento {{ HTMLElement("td") }} de <a href="/pt-PT/docs/Web/HTML">HTML</a>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/pt-PT/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-columnalign">columnalign</dt> + <dd>Indica o alinhamento horizontal desta célula e sobrepõe o valor especificado por {{ MathMLElement("mtable") }} ou {{ MathMLElement("mtr") }}.<br> + Os valores possíveis são: <code>left</code>, <code>center</code> e <code>right</code>.</dd> + <dt id="attr-columnspan">columnspan</dt> + <dd>Um integral não negativo que indica qual o numero de colunas sob qual a célula se estende.</dd> + <dt>groupalign</dt> + <dd>{{ unimplemented_inline() }}</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords">nomes de cores HTML</a>.</dd> + <dt id="attr-rowalign">rowalign</dt> + <dd>Indica o alinhamento vertical desta célula e sobrepõe os valores especificados por {{ MathMLElement("mtable") }} ou {{ MathMLElement("mtr") }}.<br> + Os valores possíveis são: <code>axis</code>, <code>baseline</code>, <code>bottom</code>, <code>center</code> e <code>top</code>.</dd> + <dt id="attr-rowspan">rowspan</dt> + <dd>Um integral não negativo que indica qual o número de linhas (<em>rows</em>) sob qual a célula se estende.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mtd', 'mtd') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mtd', 'mtd') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mtd")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mtable") }}</li> + <li>{{ MathMLElement("mtr") }}</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mtext/index.html b/files/pt-pt/web/mathml/element/mtext/index.html new file mode 100644 index 0000000000..79be044f23 --- /dev/null +++ b/files/pt-pt/web/mathml/element/mtext/index.html @@ -0,0 +1,113 @@ +--- +title: <mtext> +slug: Web/MathML/Element/mtext +tags: + - MathML + - 'MathML:Element' + - 'MathML:Token Elements' + - Referência de MathML +translation_of: Web/MathML/Element/mtext +--- +<div>{{MathMLRef}}</div> + +<p><span class="seoSummary">O elemento de MathML <code><mtext></code> é usado para apresentar texto <em>sem</em> significado notacional, como comentários e anotações.</span></p> + +<p>Para apresentar texto <em>com</em> significado notacional, use {{ MathMLElement("mi") }} e {{ MathMLElement("mo") }}.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-dir">dir</dt> + <dd>A direção geral das fórmulas. Valores aceites são <code>ltr</code> (da esquerda para a direita) ou <code>rtl</code> (da direita para a esquerda).</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> + <dt id="attr-mathsize">mathsize</dt> + <dd>O tamanho do conteúdo. Ver <a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Attribute/Valores#Comprimentos">comprimento</a> para os valores aceites.<br> + Valores obsoletos: <code>small</code>, <code>normal</code> e <code>big</code>. Estes serão removidos no futuro.</dd> + <dt id="attr-mathvariant">mathvariant</dt> + <dd>Este atributo especifica a classe lógica do identificador, que varia em tipografia. Ou seja, embora os nomes sugerem o estilo tipográfico da classe, semanticamente, os itens com a mesma classe são tratados "da mesma forma" dentro de uma expressão, o que pode ou não envolver a sua exibição com a tipografia nomeada. São permitidos os seguintes valores: + <ul> + <li><code>normal</code> (Valor padrão) ; <math><mtext mathvariant="normal">Exemplo</mtext></math></li> + <li><code>bold</code> ; <math><mtext mathvariant="bold">Exemplo</mtext></math></li> + <li><code>italic</code> ; <math><mtext mathvariant="italic">Exemplo</mtext></math></li> + <li><code>bold-italic</code> ; <math><mtext mathvariant="bold-italic">Exemplo</mtext></math></li> + </ul> + + <ul> + <li><code>double-struck</code> ; <math><mtext mathvariant="double-struck">Exemplo</mtext></math></li> + <li><code>bold-fraktur</code> ; <math><mtext mathvariant="bold-fraktur">Exemplo</mtext></math></li> + <li><code>script</code> ; <math><mtext mathvariant="script">Exemplo</mtext></math></li> + <li><code>bold-script</code> ; <math><mtext mathvariant="bold-script">Exemplo</mtext></math></li> + <li><code>fraktur</code> ; <math><mtext mathvariant="fraktur">Exemplo</mtext></math></li> + </ul> + + <ul> + <li><code>sans-serif</code> ; <math><mtext mathvariant="sans-serif">Exemplo</mtext></math></li> + <li><code>bold-sans-serif</code> ; <math><mtext mathvariant="bold-sans-serif">Exemplo</mtext></math></li> + <li><code>sans-serif-italic</code> ; <math><mtext mathvariant="sans-serif-italic">Exemplo</mtext></math></li> + <li><code>sans-serif-bold-italic</code> ; <math><mtext mathvariant="sans-serif-bold-italic">Exemplo</mtext></math></li> + <li><code>monospace</code> ; <math><mtext mathvariant="monospace">Exemplo</mtext></math></li> + </ul> + + <ul> + <li><code>normal</code> (Valor padrão) ; <math><mtext>مثال</mtext></math></li> + <li><code>initial</code> ; <math><mtext mathvariant="initial">مثال</mtext></math></li> + <li><code>tailed</code> ; <math><mtext mathvariant="tailed">مثال</mtext></math></li> + <li><code>looped</code> ; <math><mtext mathvariant="looped">مثال</mtext></math></li> + <li><code>stretched</code> ; <math><mtext mathvariant="stretched">مثال</mtext></math></li> + </ul> + </dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<pre class="brush: html notranslate"><math> + + <mtext> Theorem of Pythagoras </mtext> + + <mtext> /* comment here */ </mtext> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mtext', 'mtext') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mtext', 'mtext') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mtext")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>Alguns valores de <code>mathvariant</code> só estão implementados a partir de Gecko 28.0 (Firefox 28.0 / Thunderbird 28.0 / SeaMonkey 2.25) e requerem <a href="https://developer.mozilla.org/en-US/docs/Mozilla/MathML_Project/Fonts">fontes de matemática</a> apropriadas.</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/mtr/index.html b/files/pt-pt/web/mathml/element/mtr/index.html new file mode 100644 index 0000000000..f36748642a --- /dev/null +++ b/files/pt-pt/web/mathml/element/mtr/index.html @@ -0,0 +1,71 @@ +--- +title: <mtr> +slug: Web/MathML/Element/mtr +tags: + - 'Math:Element' + - MathML + - 'MathML:Tabular Math' + - Referência de MathML +translation_of: Web/MathML/Element/mtr +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML, <code><mtr></code>, representa uma linha numa tabela ou matriz. Este elemento só pode aparecer no elemento {{ MathMLElement("mtable") }}. Este elemento é semelhante ao elemento {{ HTMLElement("tr") }} de <a href="/pt-PT/docs/HTML">HTML</a>.</p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="https://wiki.developer.mozilla.org/pt-PT/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-columnalign">columnalign</dt> + <dd>Indica o alinhamento horizontal desta célula e sobrepõe o valor especificado por <code><a class="new" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Element/mtable" rel="nofollow" title="<mtable>"><mtable></a></code>.<br> + Os valores possíveis são: <code>left</code>, <code>center</code> e <code>right</code>.</dd> + <dt>groupalign</dt> + <dd>{{ unimplemented_inline() }}</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> + <dt id="attr-rowalign">rowalign</dt> + <dd>Indica o alinhamento vertical desta célula e sobrepõe o valor especificado por <code><a class="new" href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/MathML/Element/mtable" rel="nofollow" title="<mtable>"><mtable></a></code>.<br> + Os valores possíveis são: <code>axis</code>, <code>baseline</code>, <code>bottom</code>, <code>center</code> e <code>top</code>.</dd> +</dl> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentários</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.mtr', 'mtr') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.mtr', 'mtr') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.mtr")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mtable") }}</li> + <li>{{ MathMLElement("mtd") }}</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/munder/index.html b/files/pt-pt/web/mathml/element/munder/index.html new file mode 100644 index 0000000000..477bbf4601 --- /dev/null +++ b/files/pt-pt/web/mathml/element/munder/index.html @@ -0,0 +1,91 @@ +--- +title: <munder> +slug: Web/MathML/Element/munder +tags: + - MathML + - 'MathML:Element' + - 'MathML:Script and Limit Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/munder +--- +<div>{{MathMLRef}}</div> + +<p class="summary">O elemento de MathML <code><munder></code> é usado para adicionar um acento ou limite abaixo duma expressão. Usa a seguinte sintaxe: <code><munder> <em>base underscript</em> </munder></code></p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-accentunder">accentunder</dt> + <dd>Se <code>true</code>, o elemento é um acento, que então é desenhado mais perto da expressão base.<br> + Se <code>false</code> (valor pré-definido), o elemento é um limite debaixo da expressão base.</dd> + <dt id="attr-align">align {{deprecated_inline}}</dt> + <dd>O alinhamento do <em>underscript</em>. Os valores possíveis são: <code>left</code>, <code>center</code>, and <code>right</code>.<br> + Este atributo está obsoleto e será removido no futuro. Use antes o atributo de CSS <code><a href="/en-US/docs/Web/CSS/text-align">text-align</a></code>.</dd> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="x+y+z" src="/files/3197/munder.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math> <munder accentunder="true"> <mrow> <mi> x </mi> <mo> + </mo> <mi> y </mi> <mo> + </mo> <mi> z </mi> </mrow> <mo> ⏟ </mo> </munder> </math></p> + +<pre class="brush: html notranslate"><math> + +<munder accentunder="true"> + <mrow> + <mi> x </mi> + <mo> + </mo> + <mi> y </mi> + <mo> + </mo> + <mi> z </mi> + </mrow> + <mo> &#x23DF; <!--BOTTOM CURLY BRACKET--> </mo> +</munder> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.munder', 'munder') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.munder', 'munder') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.munder")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("mover") }} (<em>Overscript</em>)</li> + <li>{{ MathMLElement("munderover") }} (Par de <em>underscript-overscript</em>)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/munderover/index.html b/files/pt-pt/web/mathml/element/munderover/index.html new file mode 100644 index 0000000000..5f217a2766 --- /dev/null +++ b/files/pt-pt/web/mathml/element/munderover/index.html @@ -0,0 +1,91 @@ +--- +title: <munderover> +slug: Web/MathML/Element/munderover +tags: + - MathML + - 'MathML:Element' + - 'MathML:Script and Limit Schemata' + - Referência de MathML +translation_of: Web/MathML/Element/munderover +--- +<div>{{MathMLRef}}</div> + +<p><span class="seoSummary">O elemento de MathML <code><munderover></code> é usado para adicionar acentos ou limites acima e abaixo duma expressão.</span></p> + +<p>Usa a sintaxe seguinte: <code><munderover> <em>base underscript overscript</em> </munderover></code></p> + +<h2 id="Atributos">Atributos</h2> + +<dl> + <dt id="attr-accent">accent</dt> + <dd>Se <code>true</code>, o <em>overscript</em> é um acento, que então é desenhado mais perto da expressão base.<br> + Se <code>false</code> (valor pré-definido), o <em>overscript</em> é um limite acima da expressão base.</dd> + <dt id="attr-accentunder">accentunder</dt> + <dd>Se <code>true</code>, o <em>underscript</em> é um acento, que então é desenhado mais perto da expressão base.<br> + Se <code>false</code> (valor pré-definido), o <em>underscript</em> é um limite debaixo da expressão base.</dd> + <dt id="attr-align">align {{deprecated_inline}}</dt> + <dd>O alinhamento do <em>overscript</em> e <em>underscript</em>. Os valores possíveis são: <code>left</code>, <code>center</code>, and <code>right</code>.<br> + Este atributo está obsoleto e será removido no futuro. Use antes o atributo de CSS <code><a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/Web/CSS/text-align" rel="noopener">text-align</a></code>.</dd> + <dt id="attr-class-id-style">class, id, style</dt> + <dd>Para uso com <em><a href="/en-US/docs/CSS">stylesheets</a></em>.</dd> + <dt id="attr-href">href</dt> + <dd>Usado para criar uma hiperligação para um URI.</dd> + <dt id="attr-mathbackground">mathbackground</dt> + <dd>A cor de fundo. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores de HTML</a>.</dd> + <dt id="attr-mathcolor">mathcolor</dt> + <dd>A cor do texto. Pode usar <code>#rgb</code>, <code>#rrggbb</code> e <a class="external external-icon" href="https://wiki.developer.mozilla.org/en-US/docs/CSS/color_value#Color_Keywords" rel="noopener">nomes de cores HTML</a>.</dd> +</dl> + +<h2 id="Exemplos">Exemplos</h2> + +<p>Exemplo: <img alt="integral-0-infinity" src="/files/3198/munderover.png" style="margin-left: 10px; vertical-align: middle;"></p> + +<p>Exemplo renderizado no seu navegador: <math displaystyle="true"> <munderover> <mo> ∫ </mo> <mn> 0 </mn> <mi> ∞ </mi> </munderover> </math></p> + +<pre class="brush: html notranslate"><math displaystyle="true"> + + <munderover > + <mo> &#x222B; <!--INTEGRAL--> </mo> + <mn> 0 </mn> + <mi> &#x221E; <!--INFINITY--> </mi> + </munderover> + +</math> +</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Espicifcação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter3.html#presm.munderover', 'munderover') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter3.html#presm.munderover', 'munderover') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.munderover")}}</p> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li>{{ MathMLElement("munder") }} (<em>Underscript</em>)</li> + <li>{{ MathMLElement("mover") }} (<em>Overscript</em>)</li> +</ul> diff --git a/files/pt-pt/web/mathml/element/semantics/index.html b/files/pt-pt/web/mathml/element/semantics/index.html new file mode 100644 index 0000000000..49db97fb8e --- /dev/null +++ b/files/pt-pt/web/mathml/element/semantics/index.html @@ -0,0 +1,127 @@ +--- +title: <semantics> +slug: Web/MathML/Element/semantics +tags: + - MathML + - 'MathML:Element' + - Referência de MathML +translation_of: Web/MathML/Element/semantics +--- +<div>{{MathMLRef}}</div> + +<div> +<p>Em MathML há duas formas de marcar a matemática: A <em>Presentation MathML</em> (MathML de apresentação) é utilizada para controlar a apresentação das equações, enquanto o <em>Content MathML</em> (MathML de conteúdo) foi concebida para codificar o significado matemático semântico e para tornar as expressões compreensíveis para os sistemas de álgebra computacionais. Os elementos MathML <code><semantics></code>, <code><annotation></code> e <code><annotation-xml></code> são utilizados para combinar a apresentação e a marcação do conteúdo e para fornecer ambas, a informação de disposição e o significado semântico das expressões matemáticas.</p> +</div> + +<p>O elemento <code><semantics></code> atua como um elemento contentor que associa anotações e então deve ter elementos (senão levanta um erro de marcação inválido). O elemento <code><annotation></code> é o elemento contentor que contem informação semântica num formato não XML, enquanto o elemento <code><annotation-xml></code> contém conteúdo num formato XML, por exemplo, <em>Content MathML</em> ou <em>OpenMath</em>.</p> + +<p>As regras para determinar o elemento filho visível no elemento <code><semantics></code> são as seguintes:</p> + +<ul> + <li>Se mais nenhuma regra se aplica: O primeiro elemento filho é apresentado por pré-definição, este é suposto ser notação de apresentação.</li> + <li>Se o primeiro filho é um elemento MathML de apresentação que não é <code><annotation></code> nem <code><annotation-xml></code>, é apresentado o primeiro filho.</li> + <li>Se não existem elementos MathML de apresentação, apresenta o primeiro elemento <code><annotation></code> ou <code><annotation-xml></code> que seja filho do <code><semantics></code>.<br> + Atenção que elementos de <code><annotation-xml></code> só são reconhecidos se o atributo de codificação tem um dos seguintes valores: + <ul> + <li><code><span id="the-code"><span class="s">"application/mathml-presentation+xml</span></span></code>"</li> + <li><code><span id="the-code"><span class="s">"MathML-Presentation</span></span></code>"</li> + <li><span id="the-code"><span class="s"><code>"SVG1.1</code></span></span>"</li> + <li><code>"text/html"</code></li> + <li><code>"image/svg+xml"</code></li> + <li><code><span class="st">"application/xml</span></code>".</li> + </ul> + Note que<span id="the-code"><span class="c"> <code>"application/mathml+xml</code></span></span><code>"</code> não é mencionado aqui, já que não distingue entre MathML de apresentação ou MathML de conteúdo.</li> +</ul> + +<h2 id="Atributos">Atributos</h2> + +<p>Os seguintes atributos podem ser adicionados aos elementos <code><annotation></code> e <code><annotation-xml></code>:</p> + +<dl> + <dt id="attr-definitionurl">definitionURL</dt> + <dd>A localização do símbolo da chave da anotação.</dd> + <dt id="attr-encoding">encoding</dt> + <dd>A codificação da informação semântica na anotação (e.g. "<code>MathML-Content</code>", "<code>MathML-Presentation</code>", "<code>application/openmath+xml</code>", "<code>image/png</code>")</dd> + <dt id="attr-cd">cd</dt> + <dd>O dicionário que ontem o símbolo da chave da anotação.</dd> + <dt id="attr-name">name</dt> + <dd>O nome do símbolo da chave da anotação.</dd> + <dt id="attr-src">src</dt> + <dd>A localização de uma fonte externa de informação semântica.</dd> +</dl> + +<h2 id="Exemplo">Exemplo</h2> + +<pre class="brush: html notranslate"><math> + <semantics> + + <!-- Presentation MathML --> + <mrow> + <msup> + <mi>x</mi> + <mn>2</mn> + </msup> + <mo>+</mo> + <mi>y</mi> + </mrow> + + <!-- Content MathML --> + <annotation-xml encoding="MathML-Content"> + <apply> + <plus/> + <apply> + <power/> + <ci>x</ci> + <cn type="integer">2</cn> + </apply> + <ci>y</ci> + </apply> + </annotation-xml> + + <!-- anotar uma imagem --> + <annotation encoding="image/png" src="some/path/formula.png"/> + + <!-- anotar TeX --> + <annotation encoding="application/x-tex"> + x^{2} + y + </annotation> + + </semantics> +</math></pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Especificação</th> + <th scope="col">Estado</th> + <th scope="col">Comentário</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ SpecName('MathML3', 'chapter5.html', 'Mixing Markup Languages for Mathematical Expressions') }}</td> + <td>{{ Spec2('MathML3') }}</td> + <td>Especificação atual</td> + </tr> + <tr> + <td>{{ SpecName('MathML2', 'chapter5.html', 'Combining Presentation and Content Markup ') }}</td> + <td>{{ Spec2('MathML2') }}</td> + <td>Especificação inicial</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade">Compatibilidade</h2> + + + +<p>{{Compat("mathml.elements.semantics")}}</p> + +<h2 id="Notas_para_Gecko">Notas para Gecko</h2> + +<ul> + <li>O algoritmo para determinar o elemento visível em <code><semantics></code> foi corrigido em {{geckoRelease("23")}} para ser conforme a especificação de MathML. Em versões anteriores o primeiro elemento era apresentado.</li> + <li>No Gecko, os elementos <code><annotation></code> e <code><annotation-xml></code> são ignorados se têm o atributo <code>src</code>.</li> +</ul> diff --git a/files/pt-pt/web/mathml/examples/derivar_a_formula_resolvente/index.html b/files/pt-pt/web/mathml/examples/derivar_a_formula_resolvente/index.html new file mode 100644 index 0000000000..08f847fbb3 --- /dev/null +++ b/files/pt-pt/web/mathml/examples/derivar_a_formula_resolvente/index.html @@ -0,0 +1,17 @@ +--- +title: 'MathML: Derivar a Formula Resolvente' +slug: Web/MathML/Examples/Derivar_a_Formula_Resolvente +tags: + - Beginner + - Educação + - Exemplo + - Guía + - HTML5 + - MathML +translation_of: Web/MathML/Examples/Deriving_the_Quadratic_Formula +--- +<p><span class="seoSummary">Esta página descreve a derivação da Fórmula Resultante.</span></p> + +<p><math><mtable columnalign="left"><mtr><mtd><mrow><mrow><mrow><mrow>Pegamos na equação quadrática na sua forma geral, resolvemos em busca de x:<mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace></mrow></mrow></mrow></mrow></mtd></mtr></mtable></math></p> + +<p><math><mtable columnalign="left"><mtr><mtd><mrow><mrow><mrow><mrow> <mi>a</mi> <mo></mo> <msup> <mi>x</mi> <mn>2</mn> </msup></mrow> <mo> + </mo> <mi>b</mi> <mo></mo> <mi>x</mi> </mrow> <mo> + </mo> <mi>c</mi> </mrow> <mo>=</mo> <mn>0</mn> </mrow> </mtd> </mtr> <mtr> <mtd> <mrow> <mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <mi>a</mi> <mo></mo> <msup> <mi>x</mi> <mn>2</mn> </msup></mrow> <mo> + </mo> <mi>b</mi> <mo></mo> <mi>x</mi> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> </mrow> <mo>=</mo> <mo>-</mo><mi> c</mi><mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> </mtd> </mtr> <mtr> <mtd> <mrow> <mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <msup> <mi>x</mi> <mn>2</mn> </msup></mrow> <mo> + </mo> <mfrac> <mrow> <mi>b</mi> </mrow> <mi>a</mi> </mfrac> <mo></mo> <mi>x</mi> </mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <mo>=</mo> <mfrac> <mrow> <mo>-</mo><mi>c</mi> </mrow> <mi>a</mi> </mfrac> <mspace depth="1ex" height="0.5ex" width="2ex"></mspace><mrow><mtext mathcolor="red" mathsize="10pt">Dividir o coeficiente principal.</mtext> </mrow> </mtd> </mtr> <mtr> <mtd> <mrow> <mrow> <mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <msup> <mi>x</mi> <mn>2</mn> </msup></mrow> <mo> + </mo> <mfrac> <mrow> <mi>b</mi> </mrow> <mi>a</mi> </mfrac> <mo></mo> <mi>x</mi> <mo> + </mo> <msup> <mfenced> <mfrac> <mrow> <mi>b</mi> </mrow> <mrow> <mn>2</mn> <mi>a</mi> </mrow> </mfrac> </mfenced> <mn>2</mn> </msup> </mrow> <mo>=</mo> <mfrac> <mrow> <mo>-</mo> <mi>c</mi> <mo>(</mo> <mn>4</mn> <mi>a</mi> <mo>)</mo> </mrow> <mrow> <mi>a</mi> <mo>(</mo> <mn>4</mn> <mi>a</mi> <mo>)</mo> </mrow></mfrac> </mrow> <mo> + </mo> <mfrac> <mrow> <msup> <mi>b</mi> <mn>2</mn> </msup> </mrow> <mrow> <mn>4</mn> <msup> <mi>a</mi> <mn>2</mn> </msup> </mrow></mfrac> <mspace depth="1ex" height="0.5ex" width="2ex"></mspace><mrow><mtext mathcolor="red" mathsize="10pt">Completar o quadrado.</mtext> </mrow> </mtd> </mtr> <mtr> <mtd> <mrow> <mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <mo>(</mo> <mi>x</mi> <mo> + </mo> <mfrac> <mrow> <mi>b</mi> </mrow> <mrow> <mn>2</mn> <mi>a</mi> </mrow></mfrac> <mo>)</mo> <mo>(</mo> <mi>x</mi> <mo> + </mo> <mfrac> <mrow> <mi>b</mi> </mrow> <mrow> <mn>2</mn> <mi>a</mi> </mrow></mfrac> <mo>)</mo> <mo>=</mo> <mfrac> <mrow> <msup> <mi>b</mi> <mn>2</mn> </msup> <mo> - </mo> <mn>4</mn> <mi>a</mi> <mi>c</mi> </mrow> <mrow> <mn>4</mn> <msup> <mi>a</mi> <mn>2</mn> </msup> </mrow></mfrac> </mrow> <mspace depth="1ex" height="0.5ex" width="2ex"></mspace><mrow><mtext mathcolor="red" mathsize="10pt">Encontrar o discriminante.</mtext> </mrow> </mrow> </mtd> </mtr> <mtr> <mtd> <mrow> <mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <msup> <mrow> <mo>(</mo> <mi>x</mi> <mo> + </mo> <mfrac> <mrow> <mi>b</mi> </mrow> <mrow> <mn>2</mn> <mi>a</mi> </mrow></mfrac> <mo>)</mo> </mrow> <mn>2</mn> </msup> <mo>=</mo> <mfrac> <mrow> <msup> <mi>b</mi> <mn>2</mn> </msup> <mo> - </mo> <mn>4</mn> <mi>a</mi> <mi>c</mi> </mrow> <mrow> <mn>4</mn> <msup> <mi>a</mi> <mn>2</mn> </msup> </mrow></mfrac> </mrow> <mspace depth="1ex" height="0.5ex" width="2ex"></mspace><mrow><mtext mathcolor="red" mathsize="10pt"></mtext> </mrow> </mrow> </mtd> </mtr> <mtr> <mtd> <mrow> <mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <mrow> <mi>x</mi> <mo> + </mo> <mfrac> <mrow> <mi>b</mi> </mrow> <mrow> <mn>2</mn> <mi>a</mi> </mrow></mfrac> </mrow> <mo>=</mo> <msqrt> <mfrac> <mrow> <msup> <mi>b</mi> <mn>2</mn> </msup> <mo> - </mo> <mn>4</mn> <mi>a</mi> <mi>c</mi> </mrow> <mrow> <mn>4</mn> <msup> <mi>a</mi> <mn>2</mn> </msup> </mrow></mfrac> </msqrt> </mrow> <mspace depth="1ex" height="0.5ex" width="2ex"></mspace><mrow><mtext mathcolor="red" mathsize="10pt"></mtext> </mrow> </mrow> </mtd> </mtr> <mtr> <mtd> <mrow> <mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <mrow> <mi>x</mi> </mrow> <mo>=</mo> <mfrac> <mrow> <mo>-</mo><mi>b</mi> </mrow> <mrow> <mn>2</mn> <mi>a</mi> </mrow></mfrac> <mo>±</mo><mrow><mo>{</mo><mi>C</mi><mo>}</mo></mrow> <msqrt> <mfrac> <mrow> <msup> <mi>b</mi> <mn>2</mn> </msup> <mo> - </mo> <mn>4</mn> <mi>a</mi> <mi>c</mi> </mrow> <mrow> <mn>4</mn> <msup> <mi>a</mi> <mn>2</mn> </msup> </mrow></mfrac> </msqrt> </mrow> <mspace depth="1ex" height="0.5ex" width="2ex"></mspace><mrow><mtext mathcolor="red" mathsize="10pt">A fórmula do vértice.</mtext> </mrow> </mrow> </mtd> </mtr> <mtr> <mtd> <mrow> <mrow> <mspace depth="1ex" height="0.5ex" width="2.5ex"></mspace> <mrow> <mi>x</mi> </mrow> <mo>=</mo> <mfrac> <mrow> <mo>-</mo> <mi> b</mi> <mo>±</mo><mrow><mo>{</mo><mi>C</mi><mo>}</mo></mrow> <msqrt> <msup> <mi>b</mi> <mn>2</mn> </msup> <mo> - </mo> <mn>4</mn> <mi>a</mi> <mi>c</mi> </msqrt></mrow> <mrow> <mn>2</mn> <mi>a</mi> </mrow></mfrac> </mrow> <mspace depth="1ex" height="0.5ex" width="2ex"></mspace> <mrow><mtext mathcolor="red" mathsize="10pt"></mtext> </mrow> </mrow> </mtd> </mtr> </mtable></math></p> diff --git a/files/pt-pt/web/mathml/examples/index.html b/files/pt-pt/web/mathml/examples/index.html new file mode 100644 index 0000000000..8ae4c20e35 --- /dev/null +++ b/files/pt-pt/web/mathml/examples/index.html @@ -0,0 +1,22 @@ +--- +title: Exemplos +slug: Web/MathML/Examples +tags: + - Beginner + - Exemplo + - Guía + - MathML +translation_of: Web/MathML/Examples +--- +<p>Abaixo encontrará alguns exemplos que poderá consultar para o ajudar a compreender como utilizar a MathML para exibir conceitos matemáticos cada vez mais complexos na <em>web</em>.</p> + +<dl> + <dt><a href="/pt-PT/docs/Web/MathML/Examples/MathML_teorema_de_Pitagoras">Teorema de Pitágoras</a></dt> + <dd>Pequeno exemplo mostrando a provar o teorema de Pitágoras.</dd> + <dt><a href="/pt-PT/docs/Web/MathML/Examples/Derivar_a_Formula_Resolvente">Derivar a Fórmula Resolvente</a></dt> + <dd> + <p>Descreve a derivação da Fórmula Resultante.</p> + </dd> + <dt><a href="/en-US/docs/Mozilla/MathML_Project/MathML_Torture_Test">Teste de MathML</a></dt> + <dd>Conjunto de exemplos a testar a notação de MathML.</dd> +</dl> diff --git a/files/pt-pt/web/mathml/examples/mathml_teorema_de_pitagoras/index.html b/files/pt-pt/web/mathml/examples/mathml_teorema_de_pitagoras/index.html new file mode 100644 index 0000000000..d4edbfc4dd --- /dev/null +++ b/files/pt-pt/web/mathml/examples/mathml_teorema_de_pitagoras/index.html @@ -0,0 +1,19 @@ +--- +title: Provar o teorema de Pitágoras +slug: Web/MathML/Examples/MathML_teorema_de_Pitagoras +tags: + - Beginner + - Educação de matemática + - Exemplo + - Guía + - Matemática HTML5 + - MathML +translation_of: Web/MathML/Examples/MathML_Pythagorean_Theorem +--- +<p>Iremos provar o teorema de Pitágoras:</p> + +<p><strong>Declaração:</strong> Num triângulo retângulo, o quadrado da hipotenusa é igual à soma dos quadrados dos outros dois lados.</p> + +<p>Isto é, se <strong>a</strong> e <strong>b</strong> são os catetos, e <strong>c</strong> é a hipotenusa então<math><mrow><msup><mi> a </mi><mn>2</mn></msup> <mo> + </mo> <msup><mi> b </mi><mn>2</mn></msup> <mo> = </mo> <msup><mi> c </mi><mn>2</mn></msup> </mrow> </math>.</p> + +<p><strong>Prova:</strong> Podemos provar o teorema algebricamente mostrando que a área do quadrado grande é igual à área do quadrado interior (hipotenusa ao quadrado) mais a área dos quatro triângulos:<math style="display: block;"><mtable columnalign="right center left"><mtr><mtd><msup><mrow><mo>( </mo> <mi> a </mi> <mo> + </mo> <mi> b </mi> <mo> ) </mo> </mrow> <mn> 2 </mn> </msup> </mtd> <mtd> <mo> = </mo> </mtd> <mtd> <msup><mi> c </mi><mn>2</mn></msup> <mo> + </mo> <mn> 4 </mn> <mo> ⋅ </mo> <mo>(</mo> <mfrac> <mn> 1 </mn> <mn> 2 </mn> </mfrac> <mi> a </mi><mi> b </mi> <mo>)</mo> </mtd> </mtr> <mtr> <mtd> <msup><mi> a </mi><mn>2</mn></msup> <mo> + </mo> <mn> 2 </mn><mi> a </mi><mi> b </mi> <mo> + </mo> <msup><mi> b </mi><mn>2</mn></msup> </mtd> <mtd> <mo> = </mo> </mtd> <mtd> <msup><mi> c </mi><mn>2</mn></msup> <mo> + </mo> <mn> 2 </mn><mi> a </mi><mi> b</mi></mtd></mtr><mtr><mtd></mtd></mtr><mtr><mtd><msup><mi>a </mi><mn>2</mn></msup> <mo> + </mo> <msup><mi> b </mi><mn>2</mn></msup> </mtd> <mtd> <mo> = </mo> </mtd> <mtd> <msup><mi> c </mi><mn>2</mn></msup> </mtd> </mtr> </mtable> </math></p> diff --git a/files/pt-pt/web/mathml/index.html b/files/pt-pt/web/mathml/index.html new file mode 100644 index 0000000000..2a170729a1 --- /dev/null +++ b/files/pt-pt/web/mathml/index.html @@ -0,0 +1,72 @@ +--- +title: MathML +slug: Web/MathML +tags: + - Landing + - MathML + - Referencia + - Web + - XML +translation_of: Web/MathML +--- +<div>{{MathMLRef}}</div> + +<p class="summary"><strong>MathML (Linguagem de Marcação Matemática)</strong> é um dialeto de <a href="/pt-PT/docs/Web/XML">XML</a> para descrever a notação matemática e capturar ambos na sua estrutura e conteúdo.</p> + +<p>Aqui vai encontrar hiperligações para documentação, exemplos, e ferramentas que ajudarão o seu trabalho com esta tecnologia poderosa. Para uma rápida visão geral, veja os <a href="https://fred-wang.github.io/MozSummitMathML/index.html">slides para as feiras de inovação no Mozilla Summit 2013</a>.</p> + +<div class="row topicpage-table"> +<div class="section"> +<h2 id="Referência_de_MathML">Referência de MathML</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/MathML/Element">Referencia de elementos MathML</a></dt> + <dd>Detalhes acerca de cada elemento MathML e informação de compatibilidade para navegadores em computadores e telemóveis.</dd> + <dt><a href="/pt-PT/docs/Web/MathML/Attribute">Referencia de atributos MathML</a></dt> + <dd>Informação sobre atributos MathML que modificam a aparência ou o comportamento de elementos.</dd> + <dt><a href="/pt-PT/docs/Web/MathML/Examples">Exemplos de MathML</a></dt> + <dd>Exemplos e vinhetas de MathML para ajudar a entender como a tecnologia funciona.</dd> + <dt><a href="/pt-PT/docs/Web/MathML/Authoring">Redigir MathML</a></dt> + <dd>Sugestões e dicas para escrever MathML, incluindo editores e como integrar o seu resultado em conteúdo da web.</dd> +</dl> + +<p><a href="/pt-PT/docs/tag/MathML">Ver Tudo...</a></p> +</div> + +<div class="section"> +<h2 id="Obter_ajuda_da_comunidade">Obter ajuda da comunidade</h2> + +<ul> + <li>Ver fóruns da Mozilla...<br> + {{ DiscussionList("dev-tech-mathml", "mozilla.dev.tech.mathml") }}</li> + <li><a href="irc://irc.mozilla.org/%23mathml" rel="external" title="#mathml">Canal de IRC</a></li> + <li><a href="https://wiki.mozilla.org/MathML:Home_Page">Wiki utilizada pelos colaboradores da Mozilla</a></li> + <li><a href="https://www.w3.org/Math/" title="http://www.w3.org">Pagina Inicial da Matemática W3C</a></li> + <li><a href="https://lists.w3.org/Archives/Public/www-math/" title="http://lists.w3.org">www-math w3.org arquivo de correio eletrónico</a></li> +</ul> + +<h2 id="Ferramentas">Ferramentas</h2> + +<ul> + <li><a href="https://validator.w3.org" title="http://validator.w3.org">Validador W3C</a></li> + <li><a href="https://addons.mozilla.org/firefox/collections/fred_wang/mathzilla/">Mathzilla Firefox coleção de Add-Ons</a></li> + <li><a href="https://github.com/fred-wang/TeXZilla">TeXZilla</a> — Convertedor de Javascript LaTeX para MathML (<a href="https://fred-wang.github.io/TeXZilla/" title="http://fred-wang.github.io">live demo</a>, <a href="https://r-gaia-cs.github.io/TeXZilla-webapp/" title="http://r-gaia-cs.github.io">Firefox OS webapp</a>, <a href="https://addons.mozilla.org/en-US/firefox/addon/texzilla/">Firefox add-on</a>, <a href="https://github.com/fred-wang/TeXZilla/wiki/Using-TeXZilla">using in a Web Page, JS program etc</a>)</li> + <li><a href="http://dlmf.nist.gov/LaTeXML/" title="http://dlmf.nist.gov">LaTeXML</a> - Convertedor de documentos LaTeX em páginas HTML+MathML</li> + <li><a href="https://www.mathjax.org/" title="http://www.mathjax.org">MathJax</a> - Motor de visualização de JavaScript cross-browser para matemática. Para forçar o MathJax a utilizar MathML nativo, tente <a href="https://addons.mozilla.org/en-US/firefox/addon/mathjax-native-mathml/">este add-on Mozilla</a>, <a href="https://fred-wang.github.io/mathjax-native-mathml-safari/mathjax-native-mathml.safariextz">esta extensão Safari</a> ou <a href="https://openuserjs.org/scripts/fred.wang/MathJax_Native_MathML/">este script do GreaseMonkey</a>.</li> +</ul> + +<h2 id="Tópicos_relacionados">Tópicos relacionados</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/CSS">CSS</a></li> + <li><a href="/pt-PT/docs/Web/HTML">HTML</a></li> + <li><a href="/pt-PT/docs/Web/SVG">SVG</a></li> +</ul> +</div> +</div> + +<h2 id="Compatibilidade">Compatibilidade</h2> + +<div class="hidden">A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir com os dados, por favor, consulte <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> e envie-nos um pedido de submissão.</div> + +<p>{{Compat("mathml.elements.math", 0)}}</p> diff --git a/files/pt-pt/web/mathml/index/index.html b/files/pt-pt/web/mathml/index/index.html new file mode 100644 index 0000000000..2c4f5fb273 --- /dev/null +++ b/files/pt-pt/web/mathml/index/index.html @@ -0,0 +1,11 @@ +--- +title: Índice de documentação de MathML +slug: Web/MathML/Index +tags: + - MathML + - Índice +translation_of: Web/MathML/Index +--- +<div>{{MathMLRef}}</div> + +<p>{{Index("/pt-PT/docs/Web/MathML")}}</p> diff --git a/files/pt-pt/web/progressive_web_apps/guia_de_programacao/index.html b/files/pt-pt/web/progressive_web_apps/guia_de_programacao/index.html new file mode 100644 index 0000000000..7c63675479 --- /dev/null +++ b/files/pt-pt/web/progressive_web_apps/guia_de_programacao/index.html @@ -0,0 +1,77 @@ +--- +title: PWA - Guia de programação +slug: Web/Progressive_web_apps/Guia_de_programacao +tags: + - Aplicações + - Aplicações da Web progressivas + - Apps + - Guia de Programação + - Landing + - Off-line + - PWA + - Persistente + - Web + - progressivo +translation_of: Web/Progressive_web_apps/Developer_guide +--- +<p>{{draft}}</p> + +<p><span class="seoSummary">Nos artigos listados aaui, irá encontrar guias sobre cada aspeto da programação para a geração de aplicações da Web progressivas (PWAs).</span> For all other documentation about web development, which generally pertains to PWAs as well, see our primary <a href="/en-US/docs/Web">web development documentation</a>.</p> + +<p><strong>--->>> Titles below are just for the list; give articles good SEO names and feel free to tweak those and this as needed... <<<---</strong></p> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Basics" id="Básico_da_aplicação_da_Web">Básico da aplicação da Web</h2> + +<dl> + <dt>Introduction and getting started with PWA development</dt> + <dd>some description</dd> + <dt><a href="/en-US/docs/Web/Progressive_web_apps/Developer_guide/Installing">Installing and uninstalling web apps</a></dt> + <dd>An introductory guide to how a web app can be installed on the user's device...</dd> + <dt>Using service workers to run offline</dt> + <dd>description</dd> + <dt>Alerting the user using notifications</dt> + <dd>description</dd> + <dt>Creating a web app from an existing site</dt> + <dd>description</dd> +</dl> + +<h2 id="Tópicos_avançados">Tópicos avançados</h2> + +<dl> + <dt>Pushing data from the server to your web application</dt> + <dd>some description</dd> + <dt>Resource management</dt> + <dd>description</dd> + <dt>Integration with the host device</dt> + <dd>description</dd> + <dt>Security and privacy</dt> + <dd>description</dd> + <dt>Gaming topics for web app developers</dt> + <dd>description</dd> +</dl> +</div> + +<div class="section"> +<h2 class="Polishing" id="Polishing_web_apps">Polishing web apps</h2> + +<dl> + <dt>Web API equivalents for common native APIs</dt> + <dd>some description</dd> + <dt>Platform-specific tips and issues</dt> + <dd>description</dd> + <dt>Web application performance guide</dt> + <dd>description</dd> + <dt>Ensuring a good user experience</dt> + <dd>description</dd> +</dl> + +<h2 class="landingPageList" id="Tópicos_relacionados">Tópicos relacionados</h2> + +<dl> + <dt>some topic</dt> + <dd>some description</dd> +</dl> +</div> +</div> diff --git a/files/pt-pt/web/progressive_web_apps/identificavel/index.html b/files/pt-pt/web/progressive_web_apps/identificavel/index.html new file mode 100644 index 0000000000..f077bab989 --- /dev/null +++ b/files/pt-pt/web/progressive_web_apps/identificavel/index.html @@ -0,0 +1,61 @@ +--- +title: Identificável +slug: Web/Progressive_web_apps/Identificavel +tags: + - Aplicações + - Aplicações da Web modernas + - Aplicações da Web progressivas + - Manifesto + - identificável + - manifesto da Web +translation_of: Web/Progressive_web_apps +--- +<div class="column-container summary"> +<div class="column-11">As soon as you publish a new web app, you want the world to know about it. Search engines do ok, but often more control is desired over how your apps are exposed in search results. The new W3C Manifest for a web application can help with this, along with other available features.</div> + +<div class="column-1"><img alt="" src="https://mdn.mozillademos.org/files/12654/discoverable.svg" style="height: 43px; width: 34px;"></div> +</div> + +<p>Objetivos eventuais para as aplicações da Web :</p> + +<ul> + <li>To have better representation in search engines</li> + <li>To be easier to expose, catalog and rank</li> + <li>To have metadata useable by browsers to give them special capabilities</li> +</ul> + +<h2 id="Guias_principais">Guias principais</h2> + +<p>None written as yet; contributions appreciated.</p> + +<h2 id="Tecnologias">Tecnologias</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Tecnologia</th> + <th scope="col">Descrição</th> + <th scope="col">Resumo de suporte</th> + <th scope="col">Especificações mais recentes</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/Manifest">Web app manifest</a></td> + <td>Defines features of an app such as name, icon, splash screen, and theme colors, for use in contexts such as app listings and device home screens.</td> + <td>Experimental, Supported in Chrome, limited support in Firefox (<a href="/en-US/docs/Web/Manifest#Browser_compatibility">more detail</a>)</td> + <td>{{SpecName('Manifest')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Ferramentas">Ferramentas</h2> + +<p>Add links to useful tools/libraries.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<dl> + <dt><a href="http://ogp.me/">Open Graph</a></dt> + <dd>A <em>defacto</em> standard providing a format for specifying similar metadata in the HTML <code><head></code> using meta tags. Supported by Facebook and other properties.</dd> +</dl> diff --git a/files/pt-pt/web/progressive_web_apps/index.html b/files/pt-pt/web/progressive_web_apps/index.html new file mode 100644 index 0000000000..8758f24575 --- /dev/null +++ b/files/pt-pt/web/progressive_web_apps/index.html @@ -0,0 +1,107 @@ +--- +title: Aplicações da Web progressivas +slug: Web/Progressive_web_apps +tags: + - Aplicação da Web + - Aplicações + - Aplicações da Web modernas + - Aplicações da Web progressivas + - App + - PWA +translation_of: Web/Progressive_web_apps +--- +<p>{{draft}}</p> + +<p class="summary"><img alt="PWA community logo" src="https://mdn.mozillademos.org/files/16742/pwa.png" style="display: block; float: left; height: 188px; margin: 0px auto; padding-bottom: 1em; padding-right: 2em; width: 350px;"><strong>Aplicações da Web Progressivas</strong> são aplicações da Web que utilizam APIs e funcionaldiades emergentes do navegador da Web, juntamente com a estratégia tradicional de melhoramento progressivo, para trazer uma experiência do utilziador semelhante a uma aplicação nativa para as aplicações da Web de plataforma cruzada. Progressive Web Apps are a useful design pattern, though they aren't a formalized standard. PWA can be thought of as similar to AJAX or other similar patterns that encompass a set of application attributes, including use of specific web technologies and techniques. This set of docs tells you all you need to know about them.</p> + +<p>In order to call a Web App a PWA, technically speaking it should have the following features: <a href="/en-US/docs/Web/Security/Secure_Contexts">Secure contexts</a> (<strong>{{Glossary("HTTPS")}}</strong>), one or more <a href="/en-US/docs/Web/API/Service_Worker_API">Service Workers</a>, and a <a href="/en-US/docs/Web/Manifest">manifest file</a>.</p> + +<dl> + <dt><a href="/en-US/docs/Web/Security/Secure_Contexts">Secure contexts</a> (<a href="/en-US/docs/Glossary/https">HTTPS</a>)</dt> + <dd>The web application must be served over a secure network. Being a secure site is not only a best practice, but it also establishes your web application as a trusted site especially if users need to make secure transactions. Most of the features related to a PWA such as geolocation and even service workers are available only once the app has been loaded using HTTPS.</dd> + <dt><a href="/en-US/docs/Web/API/Service_Worker_API">Service workers</a></dt> + <dd>A service worker is a script that allows intercepting and control of how a web browser handles its network requests and asset caching. With service workers, web developers can create reliably fast web pages and offline experiences.</dd> + <dt><a href="/en-US/docs/Web/Manifest">Manifest file</a></dt> + <dd>A {{Glossary("JSON")}} file that controls how your app appears to the user and ensures that progressive web apps are discoverable. It describes the name of the app, the start URL, icons, and all of the other details necessary to transform the website into an app-like format.</dd> +</dl> + +<h2 id="Vantagens_de_PWA">Vantagens de PWA</h2> + +<p>PWAs should be discoverable, installable, linkable, network independent, progressive, re-engageable, responsive, and safe. To find out more about what these mean, read <a href="/en-US/docs/Web/Progressive_web_apps/Advantages">Progressive web app advantages</a>.</p> + +<p>Para saber como implementar as PWAs, consulte o nosso <a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/Progressive_web_apps/Developer_guide">guia de programação PWA</a>.</p> + +<h2 id="Documentação">Documentação</h2> + +<p><strong><-- The temporary automatic list below will be replaced soon --></strong></p> + +<p>{{LandingPageListSubpages}}</p> + +<div class="blockIndicator warning"> +<p><strong>Everything below this point is left over from the old version of this page and will be revamped as other content is overhauled.</strong></p> +</div> + +<h2 id="Guias_de_PWA_núcleo">Guias de PWA núcleo</h2> + +<p>The following guides show you what need to do to implement a PWA, by examining a simple example and showing you how all the pieces work.</p> + +<ol> + <li><a href="/en-US/docs/Web/Progressive_web_apps/Introduction">Introduction to progressive web apps</a></li> + <li><a href="/en-US/docs/Web/Progressive_web_apps/App_structure">Progressive web app structure</a></li> + <li><a href="/en-US/docs/Web/Progressive_web_apps/Offline_Service_workers">Making PWAs work offline with Service workers</a></li> + <li><a href="/en-US/docs/Web/Progressive_web_apps/Installable_PWAs">How to make PWAs installable</a></li> + <li><a href="/en-US/docs/Web/Progressive_web_apps/Re-engageable_Notifications_Push">How to make PWAs re-engageable using Notifications and Push</a></li> + <li><a href="/en-US/docs/Web/Progressive_web_apps/Loading">Progressive loading</a></li> + <li><a href="https://pwafire.org">Collection of resources, codelabs and tools you need to build PWAs by the team at pwafire.org</a></li> + <li><a href="https://github.com/pwafire/pwadev-tips">Setting up your Progressive Web App Development environment</a></li> +</ol> + +<div class="column-container"> +<div class="column-half"> +<h2 id="Guias_de_tecnologia">Guias de tecnologia</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage">Client-side storage</a> — A lengthy guide showing how and when to use web storage, IndexedDB, and service workers.</li> + <li><a href="/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers">Using service workers</a> — A more in-depth guide covering the Service Worker API.</li> + <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Using IndexedDB</a> — The fundamentals of IndexedDB, explained in detail.</li> + <li><a href="/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API">Using the Web Storage API</a> — The Web storage API made simple.</li> + <li><a class="external external-icon" href="https://developers.google.com/web/updates/2015/11/app-shell" rel="noopener">Instant Loading Web Apps with An Application Shell Architecture</a> — A guide to using the App Shell coding pattern to create apps that load quickly.</li> + <li><a href="/en-US/docs/Web/API/Push_API/Using_the_Push_API">Using the Push API</a> — Learn the essentials behind the Web Push API.</li> + <li><a href="/en-US/docs/Web/API/Notifications_API/Using_the_Notifications_API">Using the Notifications API</a> — Web notifications in a nutshell.</li> + <li><a href="/en-US/docs/Web/Apps/Modern/Responsive/responsive_design_building_blocks">The building blocks of responsive design</a> — Learn the basics of responsive design, an essential topic for modern app layout.</li> + <li><a href="/en-US/docs/Web/Apps/Modern/Responsive/Mobile_first">Mobile first</a> — Often when creating responsive application layouts, it makes sense to create the mobile layout as the default, and build wider layouts on top.</li> + <li><a href="/en-US/docs/Web/Apps/Progressive/Add_to_home_screen">Add to home screen guide</a> — Learn how your apps can take advantage of Add to home screen (A2HS).</li> +</ul> +</div> + +<div class="column-half"> +<h2 id="Ferramentas">Ferramentas</h2> + +<ul> + <li><a class="external external-icon" href="https://localforage.github.io/localForage/" rel="noopener">localForage</a> — A nice simple JavaScript library for making client-side data storage really simple; it uses IndexedDB by default and falls back to Web SQL/Web Storage if necessary.</li> + <li><a class="external external-icon" href="https://github.com/fxos-components/serviceworkerware" rel="noopener">ServiceWorkerWare</a> — An <em>Express-like</em> microframework for easy Service Worker development.</li> + <li><a class="external external-icon" href="https://github.com/mozilla/oghliner" rel="noopener">oghliner</a> — Not only a template but a tool for deploying Offline Web Apps to GitHub Pages.</li> + <li><a class="external external-icon" href="https://github.com/GoogleChrome/sw-precache" rel="noopener">sw-precache</a> — A node module to generate service worker code that will precache specific resources.</li> + <li><a class="external external-icon" href="https://github.com/GoogleChrome/workbox" rel="noopener">workbox</a> — Spiritual successor to sw-precache with more advanced caching strategies and easy precaching.</li> + <li><a class="external external-icon" href="https://www.talater.com/upup/" rel="noopener">upup</a> — A tiny script that makes sure your site is always there for your users.</li> + <li><a class="external external-icon" href="https://serviceworke.rs/" rel="noopener">The service worker cookbook</a> — A series of excellent service worker/push recipes, showing how to implement an offline app, but also much more.</li> + <li><a href="https://marketplace.visualstudio.com/items?itemName=mayeedwin.vscode-pwa">PWA VS Code extension</a> - A collection of all essential code snippets you need to build Progressive Web Apps right there in your VS Code environment.</li> +</ul> +</div> +</div> + +<ul> + <li><a href="https://developers.google.com/web/progressive-web-apps">Progressive web apps</a> on Google Developers.</li> + <li><a href="https://medium.com/@slightlylate/progressive-apps-escaping-tabs-without-losing-our-soul-3b93a8561955#.6czgj0myh">Progressive Web Apps: Escaping Tabs Without Losing Our Soul</a> by Alex Russell.</li> + <li><a href="https://developers.google.com/web/progressive-web-apps/checklist">Progressive Web Apps Check List</a>.</li> + <li><a href="https://developers.google.com/web/tools/lighthouse">The Lighthouse Tool</a> by Google.</li> + <li><a href="https://github.com/angular/mobile-toolkit">Tools for building progressive web apps with Angular</a>.</li> + <li><a href="https://github.com/codebusking/react-pwa-guide-kit">React PWA Guide Kit</a>.</li> + <li><a href="https://pokedex.org/">Offline-capable Pokédex web site</a>.</li> + <li><a href="https://hnpwa.com/">Hacker News readers as Progressive Web Apps</a>.</li> + <li><a href="https://goingmeta.io/dienstleistungen/progressive-web-app/">Progressive Web App: Advantages in a nutshell</a></li> + <li><a href="https://ymedialabs.com/progressive-web-apps">Why Progressive Web Apps Are The Future of Mobile Web (2019 Research)</a>.</li> + <li><a href="https://www.csschopper.com/blog/progressive-web-apps-everything-you-need-to-know/">Progressive Web Apps: Everything You Need To Know</a></li> +</ul> + +<div>{{QuickLinksWithSubpages("/en-US/docs/Web/Progressive_web_apps/")}}</div> diff --git a/files/pt-pt/web/progressive_web_apps/responsivo/elementos_base_desenho_adaptavel/index.html b/files/pt-pt/web/progressive_web_apps/responsivo/elementos_base_desenho_adaptavel/index.html new file mode 100644 index 0000000000..bb101b0350 --- /dev/null +++ b/files/pt-pt/web/progressive_web_apps/responsivo/elementos_base_desenho_adaptavel/index.html @@ -0,0 +1,428 @@ +--- +title: Elementos base do desenho adaptável +slug: Web/Progressive_web_apps/Responsivo/Elementos_base_desenho_adaptavel +tags: + - Aplicações + - CSS + - Design Adaptável + - HTML5 + - Movel +translation_of: Web/Progressive_web_apps/Responsive/responsive_design_building_blocks +--- +<div class="summary"> +<p>Este artigo discute os componentes essenciais de desenho responsivo, com ligações para outros artigos que ajudam a aprofundar, se for necessário.</p> +</div> + +<p>Para os desenvolvedores da Web, hoje em dia é bastante comum serem chamados a criar um site ou aplicação Web que muda a sua interface de acordo com o navegar (<em>browser</em>) ou dispositivo que lhe estiver a aceder, e assim proporcionar uma experiência ótima. Uma possível abordagem a este desafio é criar versões diferentes da aplicação ou site para diferentes plataformas ou navegadores e servi-los de forma apropriada depois de detetar qual o navegador ou plataforma que está a olhar para o site. Mas esta solução seria cada vez mais ineficiente: os métodos para determinar o navegador são intrinsecamente propícios a erros, e manter várias cópias do código pode tornar-se um pesadelo.</p> + +<p>Em geral é muito melhor criar uma única versão do código que não toma decisões com base no navegador ou plataforma, mas que faz testes a fim de saber quais as funcionalidades suportadas pelo navegador, ou quais os parâmetros do mesmo. Depois, este código é ajustado em função das funcionalidades disponíveis. Costuma-se chamar a isto <strong>desenho responsivo </strong>ou <strong>desenho adaptativo </strong>(estes dois termos referem-se a abordagens diferentes ao mesmo problema; para uma discussão sobre as diferentes entre ambos, leia <a href="/en-US/docs/Web/Apps/app_layout/Responsive_design_versus_adaptive_design" title="/en-US/docs/Web/Apps/app_layout/Responsive_design_versus_adaptive_design">Responsive design versus adaptive design</a>).</p> + +<p>Esta solução é muito mais fiável, a sua manutenção é mais fácil, e pensa mais no futuro. Já não traz o problema que é desenvolver mais versões do site à medida que surgem novos navegadores e plataformas, pois o código é ajustado à medida que os navegadores e as funcionalidades existentes mudam.</p> + +<p>Ainda assim tem desvantagens. Se o conteúdo, disposição (<em>layout</em>) e funcionalidade precisam de ser extremamente diferentes para cada dispositivo, pode não ser uma boa abordagem. Além disso, pegar num site que já existe e adicionar-lhe características de desenho responsivo / adaptável, para ser mais amigo dos dispositivos móveis, pode implicar um esforço maior do que simplesmente criar uma site ou aplicação separado, especialmente se for um site empresarial em expansão. Leia mais sobre <a href="/en-US/docs/Web_Development/Mobile/Responsive_design" title="/en-US/docs/Web_Development/Mobile/Responsive_design">vantagens e desvantagens de desenho adaptável</a>.</p> + +<div class="note"> +<p>Pode ler a nossa discussão sobre <a href="/en-US/docs/Web_Development/Mobile/Responsive_design">desenho adaptável</a>, se precisar de peceber melhor o contexto e as bases.</p> +</div> + +<h2 id="Grelhas_fluídas">Grelhas fluídas</h2> + +<p>O melhor sítio para começar é com medições fluídas do layout da aplicação — essencialmente, isto significa utilizar uma combinação de percentagens e <strong>em</strong>/<strong>rem</strong> para dar tamanho ao texto e contentores, em vez de unidades fixas como pixel. Desta forma, o layout adapta-se a diferentes dimensões do viewport, o que traz muitas vantagens. Vejamos um exemplo.</p> + +<p>Escrevemos um protótipo simples-mas-divertido de uma aplicação chamada Snapshot, a qual grava um <em>stream</em> de vídeo da sua webcam (usando {{domxref("navigator.getUserMedia", "getUserMedia()")}}) e depois permite capturar imagens estáticas desse <em>stream</em> (com a {{HTMLElement("canvas")}} do HTML5), e guarda-os numa galeria. Depois pode ver as imagens capturadas e apagá-las. Outros artigos discutem esta funcionalidade mais detalhadamente, mas agora só nos interessa o layout.</p> + +<div class="note"> +<p><strong>Note:</strong> Pode encontar a <a href="https://github.com/chrisdavidmills/snapshot" title="https://github.com/chrisdavidmills/snapshot">aplicação Snapshot no Github</a>; veja o código e ajude a melhorar. Também pode ver o <a href="https://chrisdavidmills.github.io/snapshot/" title="http://people.mozilla.com/~cmills/snapshot/">Snapshot ao vivo</a>. Note que <code>getUserMedia()</code> é uma tecnologia experimental, que de momento apenas funciona no Google Chrome e Firefox desktop. No futuro planeia-se mais funcionalidade e melhor organização do Snapshot.</p> +</div> + +<p>O layout na versão desktop do Snapshot consiste em três colunas, que mostram o <em>stream</em>, imagem de captura e a galeria, respetivamente.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/5917/desktop-layout.png" style="display: block; height: 184px; margin: 0px auto; width: 600px;"></p> + +<p>A marcação é muito simples:</p> + +<pre class="brush: html"><x-deck selected-index="0"> + <x-card> + … + </x-card> + <x-card> + … + </x-card> + <x-card> + … + </x-card> +</x-deck></pre> + +<div class="note"> +<p><strong>Note:</strong> Estes elementos "x-" esquisitos não devem ser familiares; fazem parte do <a href="http://mozbrick.github.io/" title="http://mozilla.github.io/brick/">Brick</a>, a biblioteca da Mozilla de elementos UI para aplicações web móveis. Utilizámos o Brick para criar o layout móvel do Snapshot, sobre o qual irá ler mais em baixo.</p> +</div> + +<p>Para que fiquem lado a lado, usamos estas regras:</p> + +<pre class="brush: css">x-card { + width: 100%; +} + +x-card:nth-child(1), x-card:nth-child(2) { + width: 30%; + float: left; + padding: 2rem; +} + +x-card:nth-child(3) { + width: 40%; + float: left; + height: 100%; + overflow: auto; + padding: 2rem; +}</pre> + +<p>Demos largura ({{cssxref("width")}}) <code>30%</code> às primeiras duas colunas, e à terceira, <code>40%</code> de largura, e deixamos as colunas flutuarem (<font face="consolas, Liberation Mono, courier, monospace"><span style="background-color: #eeeeee; font-size: 17px; white-space: nowrap;">float</span></font>) à esquerda. Assim ficam lado a lado, e mantêm as mesmas proporções à medida que varia o tamanho da janela do navegador. Este é um exemplo muito simples de uma grelha, mas pode aplicar este princípio a grelhas mais complexas, conforme necessário.</p> + +<h3 id="Dimensões_dos_contornos_da_caixa">Dimensões dos contornos da caixa</h3> + +<p>O espaçamento não afeta a largura e altura totais dos contentores porque mudámos a propriedade {{cssxref("box-sizing")}} para <code>border-box</code> em todos os elementos:</p> + +<pre class="brush: css">*, *:before, *:after { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +}</pre> + +<p>Basicamente, isto significa que, agora, {{cssxref("width")}} e {{cssxref("height")}} definem as dimensões de um elemento incluindo os conternos, e não só o conteúdo. Por isso, ao fixar <code>width: 40%</code>, a largura da caixa será <code>40%</code> do pai, e larguras de {{cssxref("padding")}} ou {{cssxref("border")}} serão subtraídas da largura do conteudo, em vez de adicionadas. Isto é muito útil! Leia mais no artigo <a href="http://www.paulirish.com/2012/box-sizing-border-box-ftw/" title="http://www.paulirish.com/2012/box-sizing-border-box-ftw/">* { Box-sizing: Border-box } FTW</a>, escrito pelo Paul Irish.</p> + +<h2 id="Flexible_replaced_elements">Flexible replaced elements</h2> + +<p>Até agora tudo bem, mas há algumas questões à espera de se chegarem à frente. Primeiro, vamos ver o que acontece quando incluímos os elementos {{HTMLElement("video")}} e {{HTMLElement("img")}} nas duas primeiras colunas, nus e sem estilo.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/5913/broken-images.png" style="display: block; height: 316px; margin: 0px auto; width: 480px;"></p> + +<p>Como o tamanho dos elementos substituídos é ditado pelo tamanho dos média inseridos neles, e este média tem tamanho fixo, explodem para fora dos elementos que os contem e fazem uma confusão no layout. É horrível, mas em geral este problema é resolvido com CSS simples:</p> + +<pre class="brush: css">img, video { + max-width: 100%; +}</pre> + +<p>Isto diz aos elementos substituídos para permanecerem dentro da largura do elementos que os contem, em qualquer circunstância. Contudo, se não forem tão largos como os elementos pai, não aumenta para os preencher. No exemplo da fotografia, o código final é um pouco diferente:</p> + +<pre class="brush: css">x-card:nth-child(1) video, x-card:nth-child(2) img { + width: 100%; + … +}</pre> + +<p>Isto porque, no nosso caso, queremos de facto que vídeo e imagem preencham o elemento pai em qualquer circunstância — uma diferença subtil mas importante em relação a {{cssxref("max-width")}} — logo, terão sempre o mesmo tamanho. O vídeo muda de tamanho dinamicamente, mas as capturas de ecrã não, portanto, ao ampliar o ecrã podia obter-se um layout desorganizado, com elementos de dimensões diferentes, quando se utiliza <code>max-width: 100%</code>, por exemplo:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/5915/broken-max-width-layout.png" style="display: block; height: 220px; margin: 0px auto; width: 480px;"></p> + +<h2 id="Consultas_de_média">Consultas de média</h2> + +<p>Grelhas fluídas são um ótimo começo, mas notará que em certos pontos, (conhecidos como <em>breakpoints</em>) o layout começa a desfazer-se. Nestes pontos vai querer retificar o problema no layout, e para o efeito pode usar consultas de média.</p> + +<div class="note"> +<p><strong>Nota:</strong> As consultas de média são uma funcionalidade CSS3 que permite aplicar CSS seletivamente, em função do resultado de testes a funcionalidades do média — para aprofundar as bases, leia <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries">Media queries</a>.</p> +</div> + +<h3 id="Disposição_típica_no_desktop">Disposição típica no desktop</h3> + +<p>Como já vimos, no nosso exemplo temos um layout para computador de secretária (<em>desktop</em>). O mesmo é definido pelas regras CSS no topo da folha de estilos, antes de quaisquer consultas de média.<br> + <br> + <img alt="" src="https://mdn.mozillademos.org/files/5917/desktop-layout.png" style="display: block; height: 184px; margin: 0px auto; width: 600px;"></p> + +<h3 id="Layout_de_largura_média">Layout de largura média</h3> + +<p>Também temos um layout de largura média, o qual pretendemos que funcione bem em tablets e portáteis com ecrã estreito. É definido pelo CSS na primeira consulta:</p> + +<pre class="brush: css">@media all and (max-width: 1024px) { + x-card:nth-child(1), x-card:nth-child(2) { + width: 50%; + } + + x-card:nth-child(3) { + width: 100%; + clear: left; + } + + x-card:nth-child(3) img { + width: 20%; + } +}</pre> + +<p>Aqui estamos a mudar larguras das colunas e a remover <code>float</code> na terceira coluna (e adicionar <code>clear</code> para acautelar comportamentos imprevisíveis de elementos flutuantes). Também alterámos largura das imagens dentro do terceiro contentor, (a galeria, que já não é uma coluna) e agira há 5 em cada linha (dantes eram 3).</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/5919/middle-layout.png" style="display: block; height: 390px; margin: 0px auto; width: 480px;"></p> + +<h3 id="Layout_em_ecrã_estreito_telemóvel">Layout em ecrã estreito / telemóvel</h3> + +<p>Por fim temos layout para ecrãs estreitos, adequado para aplicações móveis ou "open Web apps" (por exemplo, uma aplicação do Firefox OS). Este foi criado em várias partes. Primeiro, como esperado, há uma consulta de média no CSS. Como é bastante comprida, vamos analiśa-la aos poucos:</p> + +<pre class="brush: css">@media all and (max-width: 480px) { + x-card:nth-child(1), x-card:nth-child(2), x-card:nth-child(3) { + width: 100%; + float: none; + padding: 0; + } + + button { + margin-top: 0; + border-radius: 0; + } + + x-card:nth-child(1) video, x-card:nth-child(2) img { + border-radius: 0px; + border: none; + padding: 0; + background-color: 0; + }</pre> + +<p>Este primeiro bloco repõe várias coisas dos layouts mais largos que não eram necessárias para a aplicação móvel.</p> + +<pre class="brush: css"> x-card:nth-child(1) video, x-card:nth-child(2) img, x-card:nth-child(3) { + margin-top: 17.5vw; + } + + x-card:nth-child(1) button, x-card:nth-child(2) button { + position: absolute; + bottom: 0; + } + + x-card:nth-child(2) button:nth-of-type(2) { + bottom: 5.9rem; + } + + x-card:nth-child(1) button { + font-size: 7vw; + } + + x-card:nth-child(2) button { + font-size: 7vw; + }</pre> + +<p>Estas regras estipulam o tamanho dos botões dentro dos dois primeiros cartões, e dão a todo o conteúdo uma margem superior para o conteúdo não se preder debaixo dos botões de navegação (ler em baixo). Isto é necessário porque Mozilla Brick (ler também em baixo) obriga os seus componentes a ter 100% da largura e altura do ecrã. Nestes, usámos unidades <code>vw</code> (<em>viewport width</em>) — <code>1vw</code> equivale a 1% da largura do viewport. Assim as dimensões aumentam e diminuem em conjunto com a largura do viewport.</p> + +<p>Quando se clica numa imagem da galeria, aparece um botão para removê-la e outro para cancelar remoção, e não queremos que os dois botões fiquem um em cima do outro. Na última parte desta secção, damos aos botões posição absoluta na parte de baixo dos cartões em que se encontram, para o layout ser apresentável em diferentes variações no tamanho do viewport. Depois acrescentamos uma regra que desloca o segundo botão de qualquer cartão mais para cima, num comprimento igual ao de um botão.</p> + +<pre class="brush: css">x-card:nth-child(3) img { + width: 50%; +}</pre> + +<p>Esta regra muda a largura das imagens da galeria para aparcerem 2 em cada linha.</p> + +<pre class="brush: css"> nav { + width: 100%; + position: absolute; + z-index: 1000; + + display: -webkit-flex; + display: -moz-flex; + display: -ms-flexbox; + display: flex; + } + + nav button { + font-size: 6.8vw; + + -webkit-flex: 1; + -moz-flex: 1; + -ms-flex: 1; + flex: 1; + + border-left: 1px solid rgba(100,100,100,0.4); + } + + nav button:first-child { + border-left: 0; + } +}</pre> + +<p>Por fim, mudamos o valor de <code>display</code> do elemento {{HTMLElement("nav")}} para <code>flex</code>, de forma a que seja apresentado (estava <code>none</code> no CSS por omissão, no incío da folha de estilos, pois não era necessário nos outros formatos). Depois damos posição absoluta e {{cssxref("z-index")}} para que não ocupe espaço no fluxo do documento, e fique sobre as x-cards (foi por isso que há bocado demos margem superior às x-cards).</p> + +<p>A seguir, o <code>font-size</code> dos botões é <code>6.8vw</code>. Porquê? Porque a margem superior dos x-cards ficou <code>17vw</code> anteriormente. Todos os botões na aplicação têm <code>line-height</code> igual a 2.5 (veja o CSS por omissão no início da folha). E 6.8 x 2.5 = 17.</p> + +<p>Por último, utilizámos <code>flex: 1;</code> para os botões ocuparem sempre a mesma proporção de espaço na mesma linha. Vejamos a imagem em baixo o layout móvel:</p> + +<p><img alt="single column layout for mobile app view, with three buttons to navigate between cards, an image viewer, and a Save Picture button at the button." src="https://mdn.mozillademos.org/files/5939/mobile-layout.png" style="float: left; height: 417px; margin-right: 2rem; width: 304px;">Mas ainda há truques na manga para este layout de aplicação móvel! Como referimos anteriormente, utilizámos <a href="http://mozilla.github.io/brick/" title="http://mozilla.github.io/brick/">Mozilla Brick</a>, uma coleção pré-fabricada de componentes para IU de telemóvel. Em particular, usámos o componente <a href="http://mozilla.github.io/brick/docs.html#deck" title="http://mozilla.github.io/brick/docs.html#deck">deck</a> (baralho de cartas) e o seu simpático efeito de transição entre cartas quando se pressionam os botões. Se quiese saber mais, leia <a href="/en-US/docs/Web/Apps/app_layout/Mozilla_Brick_ready_made_UI_components" title="/en-US/docs/Web/Apps/app_layout/Mozilla_Brick_ready_made_UI_components">Mozilla Brick: ready made UI components</a>.</p> + +<p>O mais relevante neste artigo é uqe não queríamos que o CSS relativo ao Brick e ficheiros JavaScript aplicados à demarcação a não ser que estivéssemos a olhar para a aplicação em aspeto móvel. Para tal, incluímos o CSS do Brick na página com recurso a um elemento {{HTMLElement("link")}} separado e um atributo <code>media</code>:</p> + +<pre class="brush: html"><link href="dist/brick.css" type="text/css" rel="stylesheet" media="all and (max-width: 480px)"></pre> + +<p>Aqui diz que a folha de estilo inteira só será ligada ao HTML se e só se a largura do viewport for 480px ou menos. Passando ao JavaScript, elementos {{HTMLElement("script")}} não aceitam atributoss <code>media</code>, então tem que se usar outra estratégia. Felizmente existe um conceito em JavaScript chamado {{domxref("window.matchMedia()")}}, que executa outros conceitos dependendo do resultado de uma consulta de média. Abrimos o ficheiro <code>brick.js</code> e à volta de todo o código existente, colocámos:</p> + +<pre class="brush: js">if (window.matchMedia("(max-width: 480px)").matches) { + // O código inteiro do ficheiro brick.js está aqui! +}</pre> + +<p>Assim nada dentro do ficheiro <code>brick.js</code> será executado a não ser que a largura do viewport seja 480px ou menos. Problema resolvido.</p> + +<h3 id="Ecrãs_mesmos_grandes">Ecrãs mesmos grandes</h3> + +<p>Podes ter reparado que se o viewport alargar muito (como um ecrã de cinema), o layout pára de crescer, e centra-se no espaço disponível. Isto é relativamente simples de conseguir. Poderias usar uma consulta de média a <code>min-width</code> para fixar a largura do elemento {{HTMLElement("body")}} a determinado momento:</p> + +<pre class="brush: css">@media all and (min-width: 1400px) { + body { + width: 1400px; + margin: 0 auto; + } +}</pre> + +<p>Mas é mais fácil aplicar a regra seguinte e retirar por completo a consulta de média:</p> + +<pre class="brush: css">body { + max-width: 1400px; + margin: 0 auto; +}</pre> + +<h3 id="Falha_na_orientação">Falha na orientação</h3> + +<p>Tabém nos deparámos com problemas de orientação: o layout do tablet foi concebido para orientação em modo retrato, e fica horrível se pusermos o aparelho em modo paisagem. Para consertar isto, acrescentamos uma consulta que só tem efeito em modo paisagem:</p> + +<pre class="brush: css">@media all and (max-width: 480px) and (orientation: landscape) { + nav { + width: auto; + + -webkit-flex-direction: column; + -moz-flex-direction: column; + -ms-flex-direction: column; + flex-direction: column; + } + + nav button { + font-size: 6.8vh; + } + + nav button { + border-left: 0; + } + + x-card:nth-child(1) video, x-card:nth-child(2) img, x-card:nth-child(3) { + margin-top: 0; + } + + x-card:nth-child(1) button, x-card:nth-child(2) button { + font-size: 2rem; + } +}</pre> + +<p>Isto faz o seguinte:</p> + +<ul> + <li>Ajusta os botões <code>nav</code>, mudando a direção da flexbox em que estão dispostos, e mudando tamanho de margens e letra para ficarem na vertical e não horizontal.</li> + <li>Remove a margem superior do conteúdo da x-card para evitar um fosso desagradável no topo do ecrã em modo paisagem.</li> + <li>Muda tamanho dos botões de controlo (como <em>Tirar Foto</em>, <em>Apagar Foto</em>) para não parecerem demasiado grandes e aparecerem corretamente no ecrã.</li> +</ul> + +<p>Assim obtém-se o seguinte layout:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/5923/viewport-fail-fixed.png" style="display: block; height: 320px; margin: 0px auto; width: 479px;"></p> + +<div class="note"> +<p><strong>Nota</strong>: Outra solução no que respeita à orientação pode ser simplesmente fixar a orientação da aplicação, em retrato ou paisagem. Se estiver a desenvolver uma aplicação instalada, ou uma aplicação do Firefox OS, pode fazê-lo facilmente com o <a href="https://developer.mozilla.org/en-US/Apps/Build/Manifest#orientation">campo de oritentação do manifesto</a>. Se quer uma solução que funcione em geral nas aplicações web, pode recorrer à <a href="https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Managing_screen_orientation#Locking_the_screen_orientation">API de orientação do ecrã</a>, e/ou apresentar uma mensagem que peça ao utilizador para rodar o ecrã se estiverem a usar a orientação errada (por exemplo, se <code>window.innerWidth</code> for maior que <code>window.innerHeight</code>, assume-se que o jogo está em modo paisagem e mostra-se uma mensagem "por favor rode o ecrã").</p> +</div> + +<h2 id="Viewport">Viewport</h2> + +<p>Um último problema a mencionar na nossa aplicação de exemplo relaciona-se com consultas de média em navegadores móveis. Se víssemos o meu exemplo num navegador móvel, não iríamos ver o simpático layout móvel. Em vez disso, veríamos a imagem em baixo.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/5925/viewport-fail.png" style="float: left; height: 569px; margin-right: 2rem; width: 320px;">Porque isto acontece? Curto e grosso, os navegadores móveis mentem. Não foto-realizam páginas da internet à largura verdadeira do viewport. Em vez disso, realizam as páginas a uma largura maior que a assumida (próxima da largura de um portátil), e depois encolhem o resultado para caber no ecrã do telemóvel. Isto é um mecanismo de defesa sensato — sites da velha guarda que não fazem consultas de média teriam péssima aparência se fossem realizados numa largura de 320px ou 480px. Mas não ajuda desenvolvedores web responsáveis, que escreveram layouts para ecrãs pequenos no CSS com consultas de média e querem que os dispositivos móveis as utilizem!</p> + +<p>Existe uma maneira de anular este comportamento de fotorrealização — viewport, que está inserido nas páginas HTML sob forma da etiqueta {{HTMLElement("meta")}}. No meu exemplo, vamos adicioná-lo ao {{HTMLElement("head")}}:</p> + +<pre><meta name="viewport" content="width=480"></pre> + +<p>Isto obriga o navegador a realizar corretamente o layout móvel da nossa aplicação — <code>width=480</code> diz-lhe: <em>"realize o HTML a 480 pixels de largura"</em>, e portanto, as consultas de média são devidamente efetuadas. Há muitas mais opções disponíveis na etiqueta <code>meta</code> do <code>viewport</code>, as quais pode aprodundar em <a href="/en-US/docs/Mozilla/Mobile/Viewport_meta_tag" title="/en-US/docs/Mozilla/Mobile/Viewport_meta_tag">Utilizar etiqueta meta do viewport para controlar layout em navegadores móveis</a>.</p> + +<div class="note"> +<p><strong>Nota:</strong> Há uma especificação chamada <a href="http://dev.w3.org/csswg/css-device-adapt/" title="http://dev.w3.org/csswg/css-device-adapt/">adaptação de dispositivos</a>, que define a mesma funcionalidade mas em CSS, usando uma regra "at" <code>@viewport</code>. Provavelmente é um local mais lógica para tal informação, mas as especificação ainda não é tão largamente suportada como a etiqueta meta do viewport, pelo que deve manter essa solução por enquanto.</p> +</div> + +<h2 class="cleared" id="Vídeo_e_imagens_adaptáveis">Vídeo e imagens adaptáveis</h2> + +<p>Outro problema cada vez mais comum é tornar o peso (em KB) de imagens e vídeo adaptáveis tal como as dimensões no ecrã. Sim, quer que as imagens fiquem dentro da IU da aplicação quer esteja num telemóvel ou desktop, mas também deve considerar que aplicações móveis têm viewport muito menores que programas desktop, então deve tentar dar aos dispositivos móveis uma imagem mais pequena para transferir. Em geral (e variando com a região do mundo), telemóveis têm banda mais curta e menos memória que os computadores, então uns KB extra também contam.</p> + +<p>Outro desafio é lidar com ecrãs de elevada resolução — gráficos de varredura (<em>bitmaps</em>) pensados para baixas resoluções correm perigo de ficarem minúsculos se apresentados em ecrãs com alta resolução, pelo que os dispositivos aplicam um fator de ampliação às páginas para evitar tal. Infelizmente, imagens de varredura ampliadas podem ficar muito "pixelizadas".</p> + +<h3 id="Imagens_de_fundo_em_CSS">Imagens de fundo em CSS</h3> + +<p>No caso das imagens de fundo em CSS, isto é fácil de resolver. Segundo a metodologia <a href="/en-US/docs/Web/Apps/app_layout/Mobile_first" title="/en-US/docs/Web/Apps/app_layout/Mobile_first">móvel primeiro</a>, cria-se o layout móvel nas instruções CSS por omissão, ou seja, antes de aplicar quaisquer consultas de média. Depois, as consultas de média disponibilizam CSS que só é aplicado quando o viewport tiver larguar <strong>superior </strong>a um dado limiar. Vejamos um breve exemplo:</p> + +<pre class="brush: css">header { + height: 300px; + width: 100%; + background: url(images/small-header.jpg) center; +} + +@media all and (min-width: 480px) { + header { + background: url(images/large-header.jpg) center; + } +}</pre> + +<p>Isto significa que navegadores móveis só vão descarregar a imagem de fundo peqeuna (small-header.jpg), uma vez que não satisfazem a consulta de média, e ignoram a imagem grande (large-header.jpg). Também é possível servir um elemento gráfico com uma resolução mais elevada recorrendo a consultas de média de resolução, como se segue:</p> + +<pre class="prettyprint prettyprinted"><code><span class="brush: css">button { + background: url(images/low-res-header.jpg) 1rem center ; +} + +@media</span><span class="pln"> only screen </span><span class="kwd">and</span><span class="pln"> </span><span class="pun">(-</span><span class="pln">webkit</span><span class="pun">-</span><span class="pln">min</span><span class="pun">-</span><span class="pln">device</span><span class="pun">-</span><span class="pln">pixel</span><span class="pun">-</span><span class="pln">ratio</span><span class="pun">:</span><span class="pln"> </span><span class="lit">2</span><span class="pun">),</span><span class="pln"> + only screen </span><span class="kwd">and</span><span class="pln"> </span><span>(</span><span class="pln"> min</span><span class="pun">-</span><span class="pln">resolution</span><span class="pun">:</span><span class="pln"> </span><span class="lit">192dpi</span><span class="pun">),</span><span class="pln"> + only screen </span><span class="kwd">and</span><span class="pln"> </span><span class="pun">(</span><span class="pln"> min</span><span class="pun">-</span><span class="pln">resolution</span><span class="pun">:</span><span class="pln"> </span><span class="lit">2dppx</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> +<code><span class="lit"> button { + background: url(images/high-res-header.jpg) 1rem center ; + }</span></code> </span><span class="pln"> +</span><span class="pun">}</span></code></pre> + +<p>Parece complicado mas não é — estamos a utilizar diversas consultas de média, uma vez que, nos dias que correm, diferentes navegadores suportam diferentes consultas de média de resolução (e unidades diferentes — dpi, dppx, sem unidade). Brett Jankord tem uma boa explicação no artigo <a href="http://www.brettjankord.com/2012/11/28/cross-browser-retinahigh-resolution-media-queries/" title="http://www.brettjankord.com/2012/11/28/cross-browser-retinahigh-resolution-media-queries/">Cross Browser Retina/High Resolution Media Queries</a>.</p> + +<h3 id="<video>"><video></h3> + +<p>Vídeo em HTML5 está relativamente bem servido em termos de adaptabilidade. Se desejar, pode referir diversos ficheiros com o elemento {{HTMLElement("source")}}, cada um com o caminho de um ficheiro e <em>MIME type</em>:</p> + +<pre class="brush: html"><video controls> + <source src="videos/720/crystal720.mp4" type="video/mp4"> + <source src="videos/720/crystal720.webm" type="video/webm"> +</video></pre> + +<p>Mas ainda pode ir um passo mais além. Pode incluir atributos <code>media</code> no elemento <code><source></code> com consultas de média — o vídeo carregado no navegador vai depender do formato suportado pelo mesmo e também dos resultados das consultas de média. Por exemplo:</p> + +<pre class="brush: html"><video controls> + <source src="videos/320/crystal320.mp4" type="video/mp4" media="all and (max-width: 480px)"> + <source src="videos/320/crystal320.webm" type="video/webm" media="all and (max-width: 480px)"> + <source src="videos/720/crystal720.mp4" type="video/mp4" media="all and (min-width: 481px)"> + <source src="videos/720/crystal720.webm" type="video/webm" media="all and (min-width: 481px)"> +</video></pre> + +<p>Isto permite ao site servir diferentes ficheiros de vídeo em função no espaço disponível, a fim de otimizar a experiência do utilizador.</p> + +<h3 id="<img>"><img></h3> + +<p>Imagens HTML são uma proposta mais difícil. Não existe mecanismo inerente para servir ficheiros diferentes em função do tamanho do viewport e, devido ao número de comportamentos incómodos dos navegadores, as soluções são mais difíceis de criar do que imagina. Atualmente estão em curso algumas propostas de métodos padrão para realizar esta tarefa — o "W3C <a href="http://www.w3.org/community/respimg/" title="http://www.w3.org/community/respimg/">responsive images community group</a>" discutiu este problema durante séculos até chegar ao elemento <a href="http://www.w3.org/TR/html-picture-element/" title="http://www.w3.org/TR/html-picture-element/"><picture></a>, o qual tem estrutura semelhante ao elemento {{HTMLElement("video")}}<a href="/en-US/docs/Web/HTML/Element/video" title="/en-US/docs/Web/HTML/Element/video">,</a> com alternativas de ficheiro fonte ( {{HTMLElement("source")}} ) selecionáveis através de consultas de média. Outra proposta, <a href="http://www.w3.org/html/wg/drafts/srcset/w3c-srcset/" title="http://www.w3.org/html/wg/drafts/srcset/w3c-srcset/">srcset</a>, foi avançada pela Apple e usa uma abordagem diferente, que consiste em incluir um atributo <code>srcset</code> em cada elemento {{HTMLElement("img")}}, no qual se referem as imagens em conjunto com "dicas" ("hints") que o navegador pode usar para determinar qual é a imagem que mais se adequa ao tamanho do viewport, resolução, etc. Não se pretende que os métodos sejam mutuamente exclusivos.</p> + +<p>Isto é tudo muito bonito, mas nenhuma destas soluções está pronta para produção — ambas estão numa fase muito recuada de padronização e não são compatíveis com a maioria dos navegadores. Atualmente temos que depender de em vários {{glossary("Polyfill")}}s e outras soluções, nenhuma das quais é perfeita em todas as situações, pelo que cada pessoa deve decidir qual é a solução acertada para a sua situação em particular. Seguem-se algumas soluções disponíveis:</p> + +<dl> + <dt><a href="https://github.com/teleject/hisrc" title="https://github.com/teleject/hisrc">HiSRC</a></dt> + <dd>Plugin <a href="http://jquery.com" title="http://jquery.com">jQuery</a> que permite criar versões pequenas, médias e grandes de uma imagem, e depois serve a mais apropriada de acordo com a resolução do navegador e velocidade da ligação à internet.</dd> + <dt><a href="http://www.mobify.com/mobifyjs/v2/docs/capturing/" title="http://www.mobify.com/mobifyjs/v2/docs/capturing/">Mobify.js capturing</a></dt> + <dd>Uma técnica da Mozilla que permite capturar a fonte da página antes de ser analisada (<em>parsed</em>) pelo navegador. Desta forma, pode-se mudar os atributos <code>src</code> da imagem com JavaScript, de acordo com funcionalidades do navegador, e evitar problemas de pré-carregamento do navegador. É primissor mas ainda não funciona bem em navegadores antigos.</dd> + <dt><a href="https://github.com/scottjehl/picturefill" title="https://github.com/scottjehl/picturefill">Picturefill</a></dt> + <dd>Um <em>polyfill</em> baseado em JavaScript para elementos <code><picture></code>, que funciona muito bem, mas necessita de marcação muito especializada.</dd> + <dt><a href="http://adaptive-images.com/" title="http://adaptive-images.com/">Adaptive images</a></dt> + <dd>Uma solução do lado do servidor, que grava o tamanho do viewport num cookie, e redimensiona imagens através de uma combinação de PHP e <code>.htaccess</code> para um tamanho mais apropriado. Não requer demarcações HTML ou programas JavaScript, mas tem diversas limitações.</dd> +</dl> + +<h3 id="SVG_e_outros_gráficos_vetoriais">SVG e outros gráficos vetoriais</h3> + +<p>Para certas imagens (não fotografias, mas sim ícones e outros elementos da interface do utilizador), utilizar gráficos vetoriais é uma boa solução. As mesmas são geradas por algoritmos matemáticos em vez de armazenar informação de cada pixel da imagem, pelo que os ficheiros tendem a ser mais pequenos e podem ser facilmente ampliadas ou visualizadas em dispositivos de alta resolução (pelo menos em teoria). Seguem-se algumas ideias, que também ajudam a diminuir o número de pedidos HTTP — outro fator chave no desempenho de aplicações móveis:</p> + +<ul> + <li>Tente utilizar <a href="/en-US/docs/Web/CSS/CSS3" title="/en-US/docs/Web/CSS/CSS3">CSS3</a> para gerar efeitos gráficos quando for possível, em vez de recorrer a ficheiros de imagem. Efeitos esses que incluem cantos arredondados, gradientes e sombras. Estes mudam de tamanho à medida que muda a resolução ou o navegador é ampliado, e embora não sejam bem suportados em navegadores antigos como Internet Explorer 6-8, isso não é preocupante se a interface for dirigida a dispositivos modernos como o Firefox OS, e tais navegadores estão graciosamente a cair em desuso.</li> + <li>Também pode usar <a href="/en-US/docs/Web/SVG" title="/en-US/docs/Web/SVG">SVG</a> para criar elementos da interface. SVG é um formato de gráficos vetoriais e é bem suportado pelos navegadores modernos, além de que existem <em>polyfills</em> de compatibilidade com navegadores antigos.</li> + <li>Utilizar <a href="/en-US/docs/Web/CSS/@font-face" title="/en-US/docs/Web/CSS/@font-face">Web fonts</a> para mostrar ícones é uma técnica eficaz para reduzir o tamanho do fichiero e número de pedididos HTTP, e é compatível com navegadores modernos e antigos.</li> +</ul> + +<h2 id="Ver_também">Ver também</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web_Development" title="https://developer.mozilla.org/en-US/docs/Web_Development">Web development</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Mobile" title="https://developer.mozilla.org/en-US/docs/Web/Guide/Mobile">Mobile Web development</a></li> +</ul> diff --git a/files/pt-pt/web/progressive_web_apps/responsivo/index.html b/files/pt-pt/web/progressive_web_apps/responsivo/index.html new file mode 100644 index 0000000000..52520008ac --- /dev/null +++ b/files/pt-pt/web/progressive_web_apps/responsivo/index.html @@ -0,0 +1,155 @@ +--- +title: Desenho responsivo +slug: Web/Progressive_web_apps/Responsivo +tags: + - Aplicações + - Aplicações da Web progressivas + - Desenvolvimento da Web + - Responsivo +translation_of: Web/Progressive_web_apps/Responsive/responsive_design_building_blocks +--- +<div class="column-container summary"> +<div class="column-11"><span class="seoSummary">As aplicações da <em>Web</em> responsivas utilizam tecnologias, tais como consultas de multimédia e <em>viewport</em> para se certificar que as suas <em>UIs</em> irão enquadrar qualquer fator de forma: pc, telemóvel, tablet, ou que quer que venha a seguir.</span></div> + +<div class="column-1"><img alt="" src="https://mdn.mozillademos.org/files/12650/responsive.svg"></div> +</div> + +<h2 id="Guias_núcleo">Guias núcleo</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Apps/Modern/Responsive/responsive_design_building_blocks">The building blocks of responsive design</a></dt> + <dd>Learn the basics of responsive design, an essential topic for modern app layout.</dd> + <dt><a href="/en-US/docs/Web/Apps/Modern/Responsive/Mobile_first">Mobile first</a></dt> + <dd>Often when creating responsive application layouts, it makes sense to create the mobile layout as the default, and build wider layouts on top.</dd> +</dl> + +<h2 id="Tecnologias">Tecnologias</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Tecnologia</th> + <th scope="col">Descrição</th> + <th scope="col">Resumo de suporte</th> + <th scope="col">Últimas especificações</th> + </tr> + </thead> + <tbody> + <tr> + <td><a href="/en-US/docs/Web/CSS/Media_Queries">Media queries</a></td> + <td>Defines expressions allowing styling to be selectively applied to content depending on viewport size, resolution, orientation, etc.</td> + <td>Widespread across modern browsers (<a href="/en-US/docs/Web/CSS/Media_Queries#Browser_compatibility">more detail</a>)</td> + <td><a href="https://drafts.csswg.org/mediaqueries-4/">Media Queries Level 4</a></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/CSS/@viewport">@viewport</a>/<a href="/en-US/docs/Mozilla/Mobile/Viewport_meta_tag">viewport meta tag</a></td> + <td>Controls viewport settings, primarily on mobile devices.</td> + <td>@viewport: Experimental (<a href="/en-US/docs/Web/CSS/@viewport#Browser_compatibility">more detail</a>)<br> + Viewport meta tag: Widespread across modern mobile devices</td> + <td><a href="https://drafts.csswg.org/css-device-adapt/#the-atviewport-rule">CSS Device Adaptation Module Level 1</a></td> + </tr> + <tr> + <td><a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout">Flexbox</a></td> + <td>A very useful CSS feature for creating flexible, responsive layouts.</td> + <td>Widespread across modern browsers (<a href="/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout#Browser_compatibility">more detail</a>)</td> + <td><a href="https://drafts.csswg.org/css-flexbox-1/">CSS Flexible Box Layout Module Level 1</a></td> + </tr> + </tbody> +</table> + +<h2 id="Ferramentas">Ferramentas</h2> + +<dl> + <dt><a href="https://modernizr.com/">Modernizr</a></dt> + <dd>A feature detection library for applying different CSS and JS to your page depending on whether certain CSS/JS features are supported.</dd> + <dt><a href="https://code.google.com/archive/p/css3-mediaqueries-js/">css3-mediaqueries-js</a></dt> + <dd>A JavaScript polyfill to add Media Query support to old versions of IE (5+.)</dd> +</dl> + +<h2 id="Consulte_também">Consulte também</h2> + +<dl> + <dt><a href="/en-US/docs/Web/Apps/Modern/Responsive/Graphics_for_responsive_sites">Graphics for responsive sites</a></dt> + <dd>Ideas to keep in mind when designing graphics for responsive sites and applications.</dd> + <dt><a href="/en-US/docs/Web/Apps/Modern/Responsive/Responsive_navigation_patterns">Responsive navigation patterns</a></dt> + <dd>How do you make a UI that looks and works as great on a smartphone as it does on the desktop? Learn how to design UIs that change to fit your user's screen.</dd> +</dl> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/progressive_web_apps/seguro/index.html b/files/pt-pt/web/progressive_web_apps/seguro/index.html new file mode 100644 index 0000000000..1866e551ae --- /dev/null +++ b/files/pt-pt/web/progressive_web_apps/seguro/index.html @@ -0,0 +1,34 @@ +--- +title: Segurança +slug: Web/Progressive_web_apps/Seguro +tags: + - Aplicações + - Aplicações da Web modernas + - Aplicações da Web progressivas + - HTTPS + - Segurança + - Seguro + - Web +translation_of: Web/Progressive_web_apps +--- +<div class="column-container summary"> +<div class="column-11">A plataforma da Web fornece um mecanismo de entrega seguro que evita a espionagem e garante que o conteúdo não foi adulterado - desde que aproveite o HTTPS e desenvolva as suas aplicações com a segurança em mente.</div> + +<div class="column-1"><img alt="" src="https://mdn.mozillademos.org/files/12664/safe.svg" style="height: 40px; width: 38px;"></div> +</div> + +<h2 id="Guias_principais">Guias principais</h2> + +<p>Aidna sem guias principais listados. Contribuições são bem-vindas.</p> + +<h2 id="Tecnologias">Tecnologias</h2> + +<p>Não são necessárias novas tecnologias — a Web já funciona como isto!</p> + +<h2 id="Ferramentas">Ferramentas</h2> + +<p>Interligue aqui para quaisquer ferramentas úteis.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<p>Interligue aqui outra informação útil.</p> diff --git a/files/pt-pt/web/reference/api/index.html b/files/pt-pt/web/reference/api/index.html new file mode 100644 index 0000000000..d6102f810b --- /dev/null +++ b/files/pt-pt/web/reference/api/index.html @@ -0,0 +1,57 @@ +--- +title: Referência da API da Web +slug: Web/Reference/API +tags: + - API + - Landing + - Referencia + - Web +translation_of: Web/Reference/API +--- +<p><span class="seoSummary">A Web oferece uma variedade alargada de APIs para realizar várias tarefas úteis. Estas podem ser acedidas, utilizando de código JavaScript, e permitem-lhe fazer qualquer coisa, desde ajustes menores a qualquer {{domxref("janela")}} ou {{domxref("elemento")}}, até à geração de efeitos gráficos e de áudio, utilizando APIs, tais como <a href="/pt-PT/docs/Web/API/WebGL_API">WebGL</a> e <a href="/pt-PT/docs/Web/API/Web_Audio_API">Áudio da Web</a>.</span></p> + +<p>A interface individual de todas as APIs encontra-se listada no <a href="/pt-PT/docs/Web/API">índice.</a></p> + +<p>Há também uma <a href="/pt-PT/docs/Web/Eventos">listagem de todos os eventos disponíveis</a> na referência de eventos</p> + +<div class="cleared topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/DOM">Modelo de Objeto de Documento</a></dt> + <dd>O DOM é uma API que permite o acesso e a modificação do documento atual. Este permite a manipulação do documento {{domxref("Nó")}} e {{domxref("Elemento")}}. HTML, XML e SVG estenderam-no para manipular os seus elementos específicos.</dd> + <dt>APIs de Dispositivo</dt> + <dd>Este conjunto de APIs permite o acesso a várias funcionalidades de hardware disponível para as páginas da Web e aplicações. Por exemplo: <a href="/pt-PT/docs/Web/API/Eventos_de_Luz_Ambiente">API do Sensor de Luz Ambiente</a>, <a href="/pt-PT/docs/Web/API/API_do_Estado_da_Bateria" title="WebAPI/Battery_Status">API do Estado da Bateria</a>, <a href="/en-US/docs/Using_geolocation" title="Using_geolocation">Geolocation API</a>, <a href="/en-US/docs/WebAPI/Pointer_Lock" title="API/Pointer_Lock_API">Pointer Lock API</a>, <a href="/en-US/docs/WebAPI/Proximity" title="WebAPI/Proximity">Proximity API</a>, <a href="/en-US/docs/WebAPI/Detecting_device_orientation" title="WebAPI/Detecting_device_orientation">Device Orientation API</a>, <a href="/en-US/docs/WebAPI/Managing_screen_orientation" title="WebAPI/Detecting_device_orientation">Screen Orientation API</a>, <a href="/en-US/docs/WebAPI/Vibration" title="WebAPI/WebBluetooth">Vibration API</a>.</dd> + <dt>APIs de Comunicação</dt> + <dd>Estas APIs permitem que as páginas da Web e aplicações comuniquem com outras páginas e dispositivos. Por exemplo: <a href="/en-US/docs/WebAPI/Network_Information" title="WebAPI/Network_Information">Network Information API</a>, <a href="/en-US/docs/WebAPI/Using_Web_Notifications" title="/en-US/docs/WebAPI/Using_Web_Notifications">Web Notifications</a>, <a href="/en-US/docs/WebAPI/Simple_Push" title="WebAPI/Push_Notifications">Simple Push API</a>.</dd> + <dt id="Data_management_APIs">APIs de Gestão de Dados</dt> + <dd>Os dados do utilizador podem ser guardados e geridos através da utilização deste conjunto de APIs. Por exempo: <a href="/en-US/docs/WebAPI/FileHandle_API" title="WebAPI/FileHandle_API">FileHandle API</a>, <a href="/en-US/docs/IndexedDB" title="IndexedDB">IndexedDB</a>.</dd> +</dl> + +<p>Para além destas APIs, disponívels para qualquer <em>Site da Web</em> ou aplicação, a Mozilla estendeu este conjunto com APIs mais poderosas, mas apenas disponíveis a aplicações privilegiadas ou, mesmo até, apenas a aplicações certificadas.</p> +</div> + +<div class="section"> +<h2 class="Community" id="Comunidade">Comunidade</h2> + +<p>Junte-se à comunidade de API da Web na nossa lista de discussões ou grupo de discussões:</p> + +<ul> + <li><a class="external" href="https://lists.mozilla.org/listinfo/dev-webapi">através da lista de discussões</a></li> + <li><a href="news://news.mozilla.org/mozilla.dev.webapi">através do grupo de discussões</a></li> + <li><a class="external" href="http://groups.google.com/group/mozilla.dev.webapi">através do Grupo da Google</a></li> + <li><a class="external" href="http://groups.google.com/group/mozilla.dev.webapi/feeds">através da Feed da Web</a></li> +</ul> + +<p>Também, não se esqueça de se juntar na discussão em direto no canal <a href="irc://irc.mozilla.org/webapi">#webapi</a>, no <a class="external" href="https://wiki.mozilla.org/IRC">IRC</a>.</p> + +<h2 class="Related_Topics" id="Tópicos_Relacionados">Tópicos Relacionados</h2> + +<p>Estes tópicos também podem ser interessantes:</p> + +<ul> + <li><a href="/pt-PT/docs/Web/API">Índice de todas as interfaces das APIs da Web</a></li> +</ul> +</div> +</div> + +<p> </p> diff --git a/files/pt-pt/web/reference/index.html b/files/pt-pt/web/reference/index.html new file mode 100644 index 0000000000..a0eec76f94 --- /dev/null +++ b/files/pt-pt/web/reference/index.html @@ -0,0 +1,28 @@ +--- +title: Referência de tecnologia da Web +slug: Web/Reference +tags: + - Landing + - Tecnologias + - Web +translation_of: Web/Reference +--- +<p><span class="seoSummary">A Web aberta é baseada num número de tecnologias que podem ser utilizadas para criar tudo, desde ''sites'' simples até aplicações da web poderosas. Em baixo, irá encontrar hiperligações para uma seleção de documentação chave cada uma delas. </span></p> + +<div id="Web_technologies"> +<p>Se é novo ao desenvolvimento na Web, considere <a href="/en-US/docs/Learn/Getting_started_with_the_web">começar com a nossa área de aprendizagem</a>, que está repleto de tutoriais que o irão guiar de um novato do <em>webdev</em> até ser minimamente proficiente!</p> + +<dl> + <dt><a href="/pt-PT/docs/Glossary/HTML">HTML</a> — Estruturar a Web</dt> + <dd><strong>HyperText Markup Language</strong> é usada para definir e descrever semanticamente o conteúdo (<em><a href="/en-US/docs/Glossary/markup">markup</a></em>) duma página web numa forma bem estruturada. HTML oferece um meio para criar documentos estruturados feitos a partir de blocos chamados <a href="/en-US/docs/Web/HTML/Element">elementos HTML</a> que são delineados por <em><a href="/en-US/docs/Glossary/Tag">tags</a></em>, escritos com <code><</code> e <code>></code>. Alguns introduzem conteudo na página diretamente, enquanto outros oferecem informação acerca do documento e podem incluir outras <em>tags</em> como sub elementos. Como é de esperar, navegadores não os mostram, já que eles são utilizados para interpretar a página.<br> + <br> + <a href="/pt-PT/docs/Learn/HTML/Introducao_ao_HTML">Introdução ao HTML</a> | <a href="/pt-PT/docs/Learn/HTML">Aprender HTML</a> | <a href="/pt-PT/docs/Web/HTML/HTML5">HTML5</a> | <a href="/pt-PT/docs/Learn/HTML">Guia de Desenvolvimento </a>| <a href="/pt-PT/docs/Web/HTML/Element">Referência de elemento</a> | <strong><a href="/pt-PT/docs/Web/HTML/Referencia">Referência</a></strong></dd> + <dt><strong><a href="/pt-PT/docs/Glossary/CSS">CSS</a></strong> — styling the Web</dt> + <dd>As <strong>Cascading Style Sheets</strong> são usadas para descrever a aparencia de conteudos da Web.<br> + <br> + <a href="/pt-PT/docs/Learn/CSS/Introduction_to_CSS">Introdução ao CSS</a> | <a href="/pt-PT/docs/Learn/CSS">Aprender CSS</a> | <a href="/pt-PT/docs/Web/CSS/CSS3">CSS3 </a>| <a href="/pt-PT/docs/Learn/CSS">Guia de Programador</a> | <a href="/pt-PT/docs/Learn/CSS/Howto/FAQ_de_CSS">Perguntas comuns sobre CSS </a>| <strong><a href="/pt-PT/docs/Web/CSS/Refer%C3%AAncia_CSS">Referência</a></strong></dd> + <dt><strong><a href="/pt-PT/docs/Glossary/JavaScript">JavaScript</a></strong> — D<strong>ynamic client-side scripting</strong></dt> + <dd>A linguagem de programação <strong>JavaScript </strong>é usada para dar interatividade e outras funções dinâmicas a sites na Web.</dd> + <dd><a href="/pt-PT/docs/Learn/JavaScript">Aprender JavaScript</a> | <a href="/pt-PT/docs/Web/JavaScript/Guia">Guia do Programador</a> | <a href="/pt-PT/docs/Web/JavaScript/Reference">Referência</a></dd> +</dl> +</div> diff --git a/files/pt-pt/web/security/conteudo_misto/index.html b/files/pt-pt/web/security/conteudo_misto/index.html new file mode 100644 index 0000000000..0f54944fef --- /dev/null +++ b/files/pt-pt/web/security/conteudo_misto/index.html @@ -0,0 +1,80 @@ +--- +title: Conteúdo misto +slug: Web/Security/Conteudo_misto +tags: + - Consola + - HTTP + - HTTPS + - Segurança + - Web +translation_of: Web/Security/Mixed_content +--- +<p>Quando um utilizador visita uma página servida sobre {{Glossary("HTTPS")}}, a sua ligação com o servidor da <em>Web </em>é encriptada com {{Glossary("TLS")}} e é, portanto, salvaguardada da maioria dos <em>sniffers</em> e ataques <em>man-in-the-middle</em>. Uma página HTTPS que inclui conteúdo obtido utilizando texto simples HTTP é chamada de de página de <strong>conteúdo misto</strong>. As páginas como esta são apenas parcialmente encriptadas, deixando o conteúdo não encriptado acessível aos <em>sniffers</em> e atacantes <em>man-in-the-middle</em>. Isso deixa as páginas inseguras.</p> + +<h2 id="Tipos_de_conteúdo_misto">Tipos de conteúdo misto</h2> + +<p>There are two categories for mixed content: <strong>mixed passive/display content</strong> and <strong>mixed active content</strong>. The difference lies in the threat level of the worst case scenario if content is rewritten as part of a man-in-the-middle attack. In the case of passive content, the threat is lower (the page may contain misleading content, or the user's cookies may be stolen). In the case of active content, the threat can lead to phishing, sensitive data disclosure, redirection to malicious sites, etc.</p> + +<h3 id="Conteúdo_misto_passivode_exibição">Conteúdo misto passivo/de exibição</h3> + +<p>Mixed passive/display content is content served over HTTP that is included in an HTTPS webpage, but that cannot alter other portions of the webpage. For example, an attacker could replace an image served over HTTP with an inappropriate image or message to the user. The attacker could also infer information about the user's activities by watching which images are served to the user; often images are only served on a specific page within a website. If the attacker observes HTTP requests to certain images, they could determine which webpage the user is visiting.</p> + +<h4 id="Lista_de_conteúdo_passivo">Lista de conteúdo passivo</h4> + +<p>This section lists all types of HTTP requests which are considered passive content:</p> + +<ul> + <li>{{HTMLElement("img")}} (<code>src</code> attribute)</li> + <li>{{HTMLElement("audio")}} (<code>src</code> attribute)</li> + <li>{{HTMLElement("video")}} (<code>src</code> attribute)</li> + <li>{{HTMLElement("object")}} subresources (when an <code><object></code> performs HTTP requests)</li> +</ul> + +<h3 id="Conteúdo_ativo_misto">Conteúdo ativo misto</h3> + +<p><strong>Mixed active content</strong> is content that has access to all or parts of the Document Object Model of the HTTPS page. This type of mixed content can alter the behavior of the HTTPS page and potentially steal sensitive data from the user. Hence, in addition to the risks described for mixed display content above, mixed active content is vulnerable to a few other attack vectors.</p> + +<p>In the mixed active content case, a man-in-the-middle attacker can intercept the request for the HTTP content. The attacker can also rewrite the response to include malicious JavaScript code. Malicious active content can steal the user's credentials, acquire sensitive data about the user, or attempt to install malware on the user's system (by leveraging vulnerabilities in the browser or its plugins, for example).</p> + +<p>The risk involved with mixed content does depend on the type of website the user is visiting and how sensitive the data exposed to that site may be. The webpage may have public data visible to the world or private data visible only when authenticated. If the webpage is public and has no sensitive data about the user, using mixed active content still provides the attacker with the opportunity to redirect the user to other HTTP pages and steal HTTP cookies from those sites.</p> + +<h4 id="Exemplos_de_conteúdo_ativo">Exemplos de conteúdo ativo</h4> + +<p>This section lists some types of HTTP requests which are considered active content:</p> + +<ul> + <li>{{HTMLElement("script")}} (<code>src</code> attribute)</li> + <li>{{HTMLElement("link")}} (<code>href</code> attribute) (this includes CSS stylesheets)</li> + <li>{{HTMLElement("iframe")}} (<code>src</code> attribute)</li> + <li>{{domxref("XMLHttpRequest")}} requests</li> + <li>{{domxref("GlobalFetch.fetch","fetch()")}} requests</li> + <li>All cases in CSS where a {{cssxref("url")}} value is used ({{cssxref("@font-face")}}, {{cssxref("cursor")}}, {{cssxref("background-image")}}, and so forth).</li> + <li>{{HTMLElement("object")}} (<code>data</code> attribute)</li> +</ul> + +<p>Other resource types like web fonts and workers may be considered active mixed content, <a href="https://code.google.com/p/chromium/codesearch#chromium/src/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp&q=MixedContentChecker::contextTypeFromContext%20f:cpp&sq=package:chromium&type=cs">as they are in Chromium</a>.</p> + +<h2 id="Avisos_na_Consola_da_Web">Avisos na Consola da <em>Web</em></h2> + +<p>The Firefox Web Console displays a mixed content warning message in the Net pane when a page on your website has this issue. The mixed content resource that was loaded via HTTP will show up in red, along with the text "mixed content", which links to this page.</p> + +<p><a class="internal" href="/files/12545/Mixed_content_-_Net_pane.png"><img alt="Screen shot of the web console displaying a mixed content warning." src="https://mdn.mozillademos.org/files/12545/Mixed_content_-_Net_pane.png" style="border-style: solid; border-width: 1px; height: 286px; width: 720px;"></a></p> + +<p>As well as finding these warnings in the Web Console, you could use <a href="/en-US/docs/Web/HTTP/CSP">Content Security Policy (CSP)</a> to report issues or a website crawler to find issues across your site, such as <a href="https://httpschecker.net/guides/https-checker">HTTPS Checker</a> or <a href="https://github.com/bramus/mixed-content-scan">Mixed Content Scan</a>.</p> + +<p>Starting in Firefox 23, mixed active content is blocked by default (and mixed display content can be blocked by setting a preference). To make it easier for web developers to find mixed content errors, all blocked mixed content requests are logged to the Security pane of the Web Console, as seen below:</p> + +<p><a href="/files/5261/blocked-mixed-content-errors.png"><img alt="A screenshot of blocked mixed content errors in the Security Pane of the Web Console" src="https://mdn.mozillademos.org/files/12543/mixed_content_webconsole.png" style="border-style: solid; border-width: 1px; height: 285px; width: 720px;"></a></p> + +<p>To fix this type of error, all requests to HTTP content should be removed and replaced with content served over HTTPS. Some common examples of mixed content include JavaScript files, stylesheets, images, videos, and other media.</p> + +<div class="note"> +<p><strong>Nota</strong>: a partir do Firefox 55, o carregamento de conteúdo misto é permitido em http://127.0.0.1/ (see {{bug(903966)}}). O Chrome permite conteúdo misto em http://127.0.0.1/ e http://localhost/. O Safari não permite conteúdo misto.</p> +</div> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="https://w3c.github.io/webappsec/specs/mixedcontent/" title="https://w3c.github.io/webappsec/specs/mixedcontent/">Conteúdo Misto - W3C Editor's Draft</a></li> + <li><a href="/pt-PT/docs/Web/Security/Mixed_content/Como_corrigir_um_site_da_Web_com_conteudo_misto_bloqueado">Como corrigir um site da Web com conteúdo misto bloqueado</a></li> +</ul> diff --git a/files/pt-pt/web/security/mixed_content/como_corrigir_um_site_da_web_com_conteudo_misto_bloqueado/index.html b/files/pt-pt/web/security/mixed_content/como_corrigir_um_site_da_web_com_conteudo_misto_bloqueado/index.html new file mode 100644 index 0000000000..c10ae3f15d --- /dev/null +++ b/files/pt-pt/web/security/mixed_content/como_corrigir_um_site_da_web_com_conteudo_misto_bloqueado/index.html @@ -0,0 +1,30 @@ +--- +title: Como corrigir um site da Web com conteúdo misto bloqueado +slug: >- + Web/Security/Mixed_content/Como_corrigir_um_site_da_Web_com_conteudo_misto_bloqueado +tags: + - HTTPS + - Segurança +translation_of: Web/Security/Mixed_content/How_to_fix_website_with_mixed_content +--- +<p>A partir do <a href="/en-US/docs/Mozilla/Firefox/Releases/23" title="/en-US/docs/Mozilla/Firefox/Releases/23">Firefox 23</a>, o Firefox bloqueia o <a href="/en-US/docs/Security/MixedContent#Mixed_active_content" title="/en-US/docs/Security/MixedContent#Mixed_active_content">conteúdo misto ativo </a>por predefinição. Isto segue uma prática adotada pelo Internet Explorer (A partir da <a href="http://blogs.msdn.com/b/ie/archive/2011/06/23/internet-explorer-9-security-part-4-protecting-consumers-from-malicious-mixed-content.aspx" title="http://blogs.msdn.com/b/ie/archive/2011/06/23/internet-explorer-9-security-part-4-protecting-consumers-from-malicious-mixed-content.aspx">versão 9</a>) e <a href="http://googleonlinesecurity.blogspot.com/2011/06/trying-to-end-mixed-scripting.html" title="http://googleonlinesecurity.blogspot.com/2011/06/trying-to-end-mixed-scripting.html">Chrome</a>.</p> + +<p>Esta página explica a que deverá prestar atenção, como um programador da Web.</p> + +<h2 id="O_seu_site_da_Web_poderá_crachar">O seu site da Web poderá crachar</h2> + +<p>If your website delivers HTTPS pages, all <a href="/en-US/docs/Security/MixedContent#Mixed_active_content" title="/en-US/docs/Security/MixedContent#Mixed_active_content">active mixed content</a> delivered via HTTP on this pages will be blocked by default. Consequently, your website may appear broken to users (if iframes or plugins don't load, etc.). <a href="/en-US/docs/Security/MixedContent#Mixed_passivedisplay_content" title="/en-US/docs/Security/MixedContent#Mixed_passive.2Fdisplay_content">Passive mixed content</a> is displayed by default, but users can set a preference to block this type of content, as well.</p> + +<p>Note that since mixed content blocking already happens in Chrome and Internet Explorer, it is very likely that if your website works in both of these browsers, it will work equally well in Firefox with mixed content blocking.</p> + +<p>In any case, the best way to know if something is broken in Firefox is to download the <a href="https://www.mozilla.org/en-US/firefox/developer/" title="https://www.mozilla.org/en-US/firefox/developer/">latest Firefox Edition</a>, open different pages on your website with the <a href="/en-US/docs/Tools/Web_Console" title="/en-US/docs/Tools/Web_Console">web console</a> open (enable the "Security" messages) and see if anything related to mixed content is reported. Or use an online crawler like <a href="http://www.jitbit.com/sslcheck/">SSL-check</a>, a desktop crawler like <a href="https://httpschecker.net/how-it-works">HTTPSChecker</a> that will check your website recursively and find links to insecure content, or a CLI tool like <a href="https://github.com/agis/mcdetect">mcdetect</a>. If nothing is said about mixed content, your website is in good shape: Keep making excellent websites!</p> + +<h2 id="Como_corrigir_um_site_da_Web">Como corrigir um site da Web</h2> + +<p>The best strategy to avoid mixed content blocking is to serve all the content as HTTPS instead of HTTP.</p> + +<p><strong>Para o seu próprio domínio,</strong> serve all content as HTTPS and fix your links. Often, the HTTPS version of the content already exists and this just requires adding an "s" to links - http:// to https://.</p> + +<p>However, in some cases, the path may just be incorrect to the media in question. There are online as well as offline tools (depending on your operating system) such as <a href="https://wummel.github.io/linkchecker/">linkchecker</a> to help resolve this.</p> + +<p><strong>Para outros domínios, </strong>use the site's HTTPS version if available. If HTTPS is not available, you can try contacting the domain and asking them if they can make the content available via HTTPS.</p> diff --git a/files/pt-pt/web/security/secure_contexts/index.html b/files/pt-pt/web/security/secure_contexts/index.html new file mode 100644 index 0000000000..d2de69988c --- /dev/null +++ b/files/pt-pt/web/security/secure_contexts/index.html @@ -0,0 +1,202 @@ +--- +title: Contextos seguros +slug: Web/Security/Secure_Contexts +tags: + - Contextos seguros + - Segurança +translation_of: Web/Security/Secure_Contexts +--- +<p><span class="seoSummary">Um <strong>contexto de segurança</strong> é uma <em><code>Window</code></em> ou <em><code>Worker</code> </em></span><em> </em>para o qual há confiança razoável de que o conteúdo foi entregue com segurança <span class="seoSummary">(via HTTPS/TLS), </span> e para o qual o potencial para a comunicação com contextos que <strong>não</strong> são seguros é limitado. Muitas <em>APIs da Web</em> e funcionalidades só são acessíveis num contexto seguro. O principal objetivo de contextos seguros é prevenir {{interwiki("wikipedia", "man-in-the-middle attack", "man-in-the-middle attackers")}} de aceder as <em>APis</em> poderosas que poderiam comprometer ainda mais a vítima de um ataque .</p> + +<h2 id="Porque_é_que_algumas_funcionalidades_deveriam_ser_restritas">Porque é que algumas funcionalidades deveriam ser restritas? </h2> + +<p>Algumas APIs na Web são muito poderosas, dando a um atacante a capacidade para fazer o seguinte e muito mais:</p> + +<ul> + <li>Invadir a privacidade do utilizador.</li> + <li>Obter acesso de baixo nível ao computador do utilizador.</li> + <li>Obter acesso aos dados, tal como as credenciais do utilizador.</li> +</ul> + +<h2 id="Quando_é_que_um_contexto_é_considerado_seguro">Quando é que um contexto é considerado seguro?</h2> + +<p>Um contexto será considerado seguro quando este for entregue com segurança (ou localmente), e quando ele não pode ser utilizado para fornecer acesso às APIs seguras para um contexto que não é seguro. Na prática, isto significa que, para que uma página tenha um contexto seguro, esta e todas as páginas a par dos seus originais e o abridor da cadeia devem ter sido entregues de uma forma segura .</p> + +<p>Por exemplo, uma página entregue de forma segura em TLS <strong>não </strong>é considerada um contexto seguro se tiver um documento original ou antigo que não tenha sido entregue de forma segura, pois, de outra forma, a página poderá expor APIs sensíveis para um antigo não entregue de forma segura via mensagens <a href="/pt-PT/docs/Web/API/Window/postMessage">postMessage</a>. Da mesma forma, se um documento TLS entregue for aberto numa nova janela por um contexto inseguro sem ser especificado <a href="/pt-PT/docs/Web/API/Window/open#noopener">noopener</a>, depois a janela aberta <strong>não </strong>é considerada um contexto seguro (uma vez que o abridor e a janela aberta poderão comunicar via PostMessage). .</p> + +<p>Os ficheiros entregues localmente, tais como os caminhos <em>http://localhost</em> e <em>ficheiro:// </em>são considerados como sendo entregues de forma segura.</p> + +<p>Os contextos que não são locais devem ser servidos sobre <em>https://</em> ou <em>wss://</em> e onde os protocolos utilizados não deverão ser considerados obsoletos. </p> + +<h2 id="Deteção_de_funcionalidade">Deteção de funcionalidade</h2> + +<p>As páginas podem utilizar a deteção de funcionalidade para verificar se elas estão num contexto seguro ou não, utilizando o booleano {{domxref("WindowOrWorkerGlobalScope.isSecureContext", "isSecureContext")}}, que é exposto num âmbito global.</p> + +<pre class="brush: js">if (window.isSecureContext) { + // Page is a secure context so service workers are now available + navigator.serviceWorker.register("/offline-worker.js").then(function () { + ... + }); +}</pre> + +<h2 id="Especificações">Especificações</h2> + +<table class="standard-table"> + <tbody> + <tr> + <td>Especificação</td> + <td>Estado</td> + <td>Comentário</td> + </tr> + <tr> + <td>{{SpecName('Contextos seguros')}}</td> + <td>{{Spec2('Contextos seguros')}}</td> + <td>Editor’s Draft</td> + </tr> + </tbody> +</table> + +<h2 id="Compatibilidade_de_navegador">Compatibilidade de navegador</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Microsoft Edge</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Funcionalidade</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Suporte básico</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + <td>{{CompatVersionUnknown}}<sup>[1]</sup></td> + </tr> + </tbody> +</table> +</div> + +<p>[1] A implementação ainda não está completa.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/Security/Secure_Contexts/Funcionalidades_restringidas_para_contextos_seguros">Funcionalidades da plataforma restringidas para contextos seguros</a> — uma lista de funcionalidades disponíveis apenas nos contextos seguros</li> + <li>{{domxref("Window.isSecureContext")}} ("Contextos seguros")</li> + <li><a href="http://permission.site">http://permission.site</a> — Um site que lhe permite verificar qual a permissão da API que o seu navegador emprega, sobre HTTP e HTTPS.</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result"> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/seguranca/index.html b/files/pt-pt/web/seguranca/index.html new file mode 100644 index 0000000000..4a555a18f6 --- /dev/null +++ b/files/pt-pt/web/seguranca/index.html @@ -0,0 +1,16 @@ +--- +title: Segurança da Web +slug: Web/Seguranca +tags: + - Landing + - Segurança + - Web +translation_of: Web/Security +--- +<div class="summary"> +<p><span class="seoSummary">É crítico assegurar que o seu site da Web ou aplicação da Web aberta é segura. Até erros simples no seu código podem resultar na divulgação de informação privada, e as pessoas más estão por aí a tentar encontrar meios para roubar dados. Estes articgos proporcionam informação que poderá ajudá-lo a proteger o seu código code.</span></p> +</div> + +<p>{{LandingPageListSubpages}}</p> + +<p>{{QuickLinksWithSubpages}}</p> diff --git a/files/pt-pt/web/seguranca/palavras-passe_inseguras/index.html b/files/pt-pt/web/seguranca/palavras-passe_inseguras/index.html new file mode 100644 index 0000000000..239618d225 --- /dev/null +++ b/files/pt-pt/web/seguranca/palavras-passe_inseguras/index.html @@ -0,0 +1,157 @@ +--- +title: Palavras-passe inseguras +slug: Web/Seguranca/Palavras-passe_inseguras +tags: + - Insegura + - Intermediária + - Segurança + - Web + - palavra-passe + - palavras-passe +translation_of: Web/Security/Insecure_passwords +--- +<p class="summary">Apresentar formulários de sessão usando protocolo HTTP é especialmente perigoso por causa da grande variedade de ataques que podem ser utilizados contra os mesmos para extrair a palavra-passe de um utilizador. As escutas ocultas de rede podem roubar a palavra-passe de um utilizador ao "farejar" a rede ou modificar a página servida no tráfego. Esta página detalha os mecanismos de segurança que o Firefox criou para alertar os utilizadores e programadores dos riscos que envolvem as palavras-passe inseguras e o roubo da mesma<span class="seoSummary">.</span></p> + +<p>O protocolo <a href="https://en.wikipedia.org/wiki/HTTP_Secure" title="https://en.wikipedia.org/wiki/HTTP_Secure">HTTPS</a> foi desenhado para proteger os dados dos utilizadores de escutas (confidencialidade) e modificação (integridade) na rede. As páginas que lidam com dados de utilizador, deveriam idealmente usar HTTPS para proteger os utilizadores de ataques. Caso uma página use HTTP em vez de HTTPS, roubar informação acerca do utilizador (como os dados de autenticação) é um processo trivial. Esta técnica ficou famosamente demonstrada por <a href="https://codebutler.github.io/firesheep/" title="http://codebutler.com/firesheep/">Firesheep</a>.</p> + +<p>Para resolver este problema, é necessário instalar e configurar um certificado SSL/TLS no servidor onde está alojada a página. Existem vários emissores deste tipo de certificados sendo que uns são grátis e outros pagos. Se está a usar uma plataforma cloud, é possível que a mesma tenha as suas próprias maneiras de ativar o protocolo HTTPS.</p> + +<h2 id="Indicadores_de_segurança_de_palavra-passe_do_Firefox">Indicadores de segurança de palavra-passe do Firefox</h2> + +<p>Para o informar do perigo descrito acima, o Firefox implementa vários mecanismos de aviso:</p> + +<ol> + <li> + <p>Firefox 51+ mostrará o símbolo de um cadeado com um traço vermelho na barra de endereços sempre que uma página de autenticação não tenha uma ligação segura, como demonstrado abaixo.</p> + + <p style="text-align: center;"><img alt="Lock Icon" src="https://support.cdn.mozilla.net/media/uploads/gallery/images/2015-11-17-12-13-18-2faa61.png" style="height: 25px; width: 25px;"></p> + </li> + <li> + <p>Firefox 52+ mostrará um aviso claro na barra de endereço e mais abaixo, focará o campo de introdução da password em qualquer formulário inseguro:</p> + + <p style="text-align: center;"><img alt="Warning" src="https://support.cdn.mozilla.net/media/uploads/gallery/images/2017-04-21-23-52-53-ba340d.png" style="height: 133px; width: 328px;"></p> + </li> + <li> + <p>Firefox 52+ também desabilita o preenchimento automático em formulários inseguros. No entanto, a partir da caixa de seleção, os utilizadores continuam a poder utilizar o preenchimento automático caso tenham os seus dados de autenticação gravados.</p> + </li> + <li> + <p>Avisos acerca de formulários inseguros também podem ser encontrados no separador "Segurança" da consola de programador em todas as versões distribuídas de Firefox, como demonstrado na próxima secção.</p> + </li> +</ol> + +<h2 id="Mensagens_da_Consola_da_Web"><strong>Mensagens da Consola da Web</strong></h2> + +<p>Esta secção descreve as mensagens de segurança mostradas pela consola de programador das Firefox DevTools (ferramentas de desenvolvimento), acerca de passwords inseguras.</p> + +<h3 id="Apresentando_o_formulário_de_sessão_usando_protocolo_HTTP">Apresentando o formulário de sessão usando protocolo HTTP</h3> + +<p>Mesmo que a acção do formulário seja um endereço HTTPS, a informação introduzida no formulário pelo utilizador não está protegida porque um possível atacante pode modificar a própria página que o utilizador consulta (por exemplo, os atacantes podem mudar o destino do formulário de forma a que os dados sensíveis sejam enviados para um servidor por eles controlados, ou inserir um script de leitura de teclas que desenha a password enquanto o utilizador a escreve). O separador de segurança da consola de programador web avisará os programadores e utilizadores acerca desta preocupação de segurança:</p> + +<p style="text-align: center;"><img alt="Insecure login form shown with the Web Console and contextual warning on the password field." src="https://mdn.mozillademos.org/files/14783/Insecure_Password_Console_Contextual_sm.png" style="height: 566px; width: 790px;"></p> + +<div class="note"> +<p><strong>Nota</strong>: Também não é seguro incluir uma página de autenticação recorrendo a HTTPS numa página HTTP - um atacante pode alterar a frame e respetivo endereço para apontar para um outro endereço, possivelmente malicioso.</p> +</div> + +<h3 id="Utilizar_um_URL_HTTP_na_acção_do_formulário"><strong>Utilizar um URL HTTP na acção do formulário</strong></h3> + +<p>Neste caso, quaisquer dados que o utilizador introduza é enviado pela rede como sendo apenas texto básico. A password do utilizador é claramente visível para qualquer pessoa que "fareje" a rede desde o momento em que deixa o computador do utilizador até ao momento em que chega ao servidor onde se encontra alojado o website de destino.</p> + +<p style="text-align: center;"><img alt="Insecure login form action shown with the Web Console and contextual warning on the password field." src="https://mdn.mozillademos.org/files/14785/Insecure_Action_Password_Console_Contextual_sm.png" style="height: 566px; width: 790px;"></p> + +<h2 id="Nota_sobre_a_reutilização_de_palavra-passe">Nota sobre a reutilização de palavra-passe</h2> + +<p>Por vezes, as páginas requerem nomes de utilizador e palavras-passe, mas não guardam dados que sejam particularmente sensíveis. Por exemplo, uma página de notícias pode gravar quais os anúncios que um utilizador queira voltar a rever e ler, sem guardar quaisquer dados acerca deste utilizador. Os programadores web deste tipo de páginas poderão estar menos preocupados a promover a segurança desta página e dos dados dos seus utilizadores.</p> + +<p>Infelizmente, <a href="https://www.lightbluetouchpaper.org/2011/02/09/measuring-password-re-use-empirically/">a reutilização de palavras-passe é um grande problema</a>. Os utilizadores tendem a utilizar a mesma palavra-passe para aceder a múltiplas páginas (seja de notícias, redes sociais, serviços de email, bancos, etc.). Por essa razão, mesmo que o acesso ao utilizador e palavra-passe do seu site não lhe pareça um enorme risco, é um grande risco para utilizadores que usem esse mesmo nome de utilizador e palavra-passe para aceder, por exemplo, às suas contas bancárias. Os atacantes estão a tornar-se cada vez mais espertos; roubam pares de nomes de utilizador/palavra-passe de um site, e tentam reusá-los em sites mais lucrativos.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li class="entry-title"><a href="https://blog.mozilla.org/tanvi/2016/01/28/no-more-passwords-over-http-please/">Não Utilizar Mais Palavras-passe sobre HTTP, Por favor!</a> (inglês)— artigo de blogue detalhado com mais informação, e perguntas frequentes.</li> +</ul> + +<p class="entry-title">{{QuickLinksWithSubpages("/en-US/docs/Web/Security")}}</p> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: none; opacity: 1; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/seguranca/same-origin_policy/index.html b/files/pt-pt/web/seguranca/same-origin_policy/index.html new file mode 100644 index 0000000000..a6ebc31ad6 --- /dev/null +++ b/files/pt-pt/web/seguranca/same-origin_policy/index.html @@ -0,0 +1,263 @@ +--- +title: Same-origin policy +slug: Web/Seguranca/Same-origin_policy +translation_of: Web/Security/Same-origin_policy +--- +<div>{{QuickLinksWithSubpages("/en-US/docs/Web/Security")}}</div> + +<p><span class="seoSummary">The <strong>same-origin policy</strong> is a critical security mechanism that restricts how a document or script loaded from one {{Glossary("origin")}} can interact with a resource from another origin.</span> It helps isolate potentially malicious documents, reducing possible attack vectors.</p> + +<p>Definição de uma Origem</p> + +<p>Duas URL tem a mesma origem se o {{Glossary("protocol")}}, {{Glossary("port")}} (if specified), and {{Glossary("host")}} are the same for both. You may see this referenced as the "scheme/host/port tuple", or just "tuple". (A "tuple" is a set of items that together comprise a whole — a generic form for double/triple/quadruple/quintuple/etc.)</p> + +<p>The following table gives examples of origin comparisons with the URL <code>http://store.company.com/dir/page.html</code>:</p> + +<table class="standard-table"> + <tbody> + <tr> + <th>URL</th> + <th>Outcome</th> + <th>Reason</th> + </tr> + <tr> + <td><code>http://store.company.com/dir2/other.html</code></td> + <td>Same origin</td> + <td>Only the path differs</td> + </tr> + <tr> + <td><code>http://store.company.com/dir/inner/another.html</code></td> + <td>Same origin</td> + <td>Only the path differs</td> + </tr> + <tr> + <td><code>https://store.company.com/page.html</code></td> + <td>Failure</td> + <td>Different protocol</td> + </tr> + <tr> + <td><code>http://store.company.com:81/dir/page.html</code></td> + <td>Failure</td> + <td>Different port (<code>http://</code> is port 80 by default)</td> + </tr> + <tr> + <td><code>http://news.company.com/dir/page.html</code></td> + <td>Failure</td> + <td>Different host</td> + </tr> + </tbody> +</table> + +<h3 id="Inherited_origins">Inherited origins</h3> + +<p>Scripts executed from pages with an <code>about:blank</code> or <code>javascript:</code> URL inherit the origin of the document containing that URL, since these types of URLs do not contain information about an origin server.</p> + +<div class="note"> +<p>For example, <code>about:blank</code> is often used as a URL of new, empty popup windows into which the parent script writes content (e.g. via the {{domxref("Window.open()")}} mechanism). If this popup also contains JavaScript, that script would inherit the same origin as the script that created it.</p> +</div> + +<div class="warning"> +<p><code>data:</code> URLs get a new, empty, security context.</p> +</div> + +<h3 id="Exceptions_in_Internet_Explorer">Exceptions in Internet Explorer</h3> + +<p>Internet Explorer has two major exceptions to the same-origin policy:</p> + +<dl> + <dt>Trust Zones</dt> + <dd>If both domains are in the <em>highly trusted zone</em> (e.g. corporate intranet domains), then the same-origin limitations are not applied.</dd> + <dt>Port</dt> + <dd>IE doesn't include port into same-origin checks. Therefore, <code>https://company.com:81/index.html</code> and <code>https://company.com/index.html</code> are considered the same origin and no restrictions are applied.</dd> +</dl> + +<p>These exceptions are nonstandard and unsupported in any other browser.</p> + +<h2 id="Changing_origin">Changing origin</h2> + +<p>A page may change its own origin, with some limitations. A script can set the value of {{domxref("document.domain")}} to its current domain or a superdomain of its current domain. If set to a superdomain of the current domain, the shorter superdomain is used for same-origin checks.</p> + +<p>For example, assume a script from the document at <code>http://store.company.com/dir/other.html</code> executes the following:</p> + +<pre class="brush: js notranslate">document.domain = "company.com"; +</pre> + +<p>Afterward, the page can pass the same-origin check with <code>http://company.com/dir/page.html</code> (assuming <code>http://company.com/dir/page.html</code> sets its <code>document.domain</code> to "<code>company.com</code>" to indicate that it wishes to allow that - see {{domxref("document.domain")}} for more). However, <code>company.com</code> could <strong>not</strong> set <code>document.domain</code> to <code>othercompany.com</code>, since that is not a superdomain of <code>company.com</code>.</p> + +<p>The port number is checked separately by the browser. Any call to <code>document.domain</code>, including <code>document.domain = document.domain</code>, causes the port number to be overwritten with <code>null</code>. Therefore, one <strong>cannot</strong> make <code>company.com:8080</code> talk to <code>company.com</code> by only setting <code>document.domain = "company.com"</code> in the first. It has to be set in both so their port numbers are both <code>null</code>.</p> + +<div class="note"> +<p><strong>Note:</strong> When using <code>document.domain</code> to allow a subdomain to access its parent securely, you need to set <code>document.domain</code> to the <em>same value</em> in both the parent domain and the subdomain. This is necessary even if doing so is simply setting the parent domain back to its original value. Failure to do this may result in permission errors.</p> +</div> + +<h2 id="Cross-origin_network_access">Cross-origin network access</h2> + +<p>The same-origin policy controls interactions between two different origins, such as when you use {{domxref("XMLHttpRequest")}} or an {{htmlelement("img")}} element. These interactions are typically placed into three categories:</p> + +<ul> + <li>Cross-origin <em>writes</em> are typically allowed. Examples are links, redirects, and form submissions. Some HTTP requests require <a href="/en-US/docs/Web/HTTP/CORS#Preflighted_requests">preflight</a>.</li> + <li>Cross-origin <em>embedding</em> is typically allowed. (Examples are listed below.)</li> + <li>Cross-origin <em>reads</em> are typically disallowed, but read access is often leaked by embedding. For example, you can read the dimensions of an embedded image, the actions of an embedded script, or the <a class="external" href="https://bugzilla.mozilla.org/show_bug.cgi?id=629094">availability of an embedded resource</a>.</li> +</ul> + +<p>Here are some examples of resources which may be embedded cross-origin:</p> + +<ul> + <li>JavaScript with <code><script src="…"></script></code>. Error details for syntax errors are only available for same-origin scripts.</li> + <li>CSS applied with <code><link rel="stylesheet" href="…"></code>. Due to the <a class="external" href="https://scarybeastsecurity.blogspot.com/2009/12/generic-cross-browser-cross-domain.html">relaxed syntax rules</a> of CSS, cross-origin CSS requires a correct <code>Content-Type</code> header. Restrictions vary by browser: <a class="external" href="https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/gg622939(v=vs.85)?redirectedfrom=MSDN">Internet Explorer</a>, <a class="external" href="https://www.mozilla.org/en-US/security/advisories/mfsa2010-46/">Firefox</a>, <a class="external" href="https://bugs.chromium.org/p/chromium/issues/detail?id=9877">Chrome</a> , <a class="external" href="https://support.apple.com/kb/HT4070">Safari</a> (scroll down to CVE-2010-0051) and <a class="external" href="https://security.opera.com/cross-domain-data-theft-with-css-load-opera-security-advisories/">Opera</a>.</li> + <li>Images displayed by {{htmlelement("img")}}.</li> + <li>Media played by {{htmlelement("video")}} and {{htmlelement("audio")}}.</li> + <li>External resources embedded with {{htmlelement("object")}} and {{htmlelement("embed")}}.</li> + <li>Fonts applied with {{cssxref("@font-face")}}. Some browsers allow cross-origin fonts, others require same-origin.</li> + <li>Anything embedded by {{htmlelement("iframe")}}. Sites can use the {{HTTPHeader("X-Frame-Options")}} header to prevent cross-origin framing.</li> +</ul> + +<h3 id="How_to_allow_cross-origin_access">How to allow cross-origin access</h3> + +<p>Use <a href="/en-US/docs/Web/HTTP/CORS">CORS</a> to allow cross-origin access. CORS is a part of {{Glossary("HTTP")}} that lets servers specify what hosts are permitted to load content from that server.</p> + +<h3 id="How_to_block_cross-origin_access">How to block cross-origin access</h3> + +<ul> + <li>To prevent cross-origin writes, check an unguessable token in the request — known as a <a class="external" href="https://owasp.org/www-community/attacks/csrf">Cross-Site Request Forgery (CSRF)</a> token. You must prevent cross-origin reads of pages that require this token.</li> + <li>To prevent cross-origin reads of a resource, ensure that it is not embeddable. It is often necessary to prevent embedding because embedding a resource always leaks some information about it.</li> + <li>To prevent cross-origin embeds, ensure that your resource cannot be interpreted as one of the embeddable formats listed above. Browsers may not respect the <code>Content-Type</code> header. For example, if you point a <code><script></code> tag at an HTML document, the browser will try to parse the HTML as JavaScript. When your resource is not an entry point to your site, you can also use a CSRF token to prevent embedding.</li> +</ul> + +<h2 id="Cross-origin_script_API_access">Cross-origin script API access</h2> + +<p>JavaScript APIs like {{domxref("HTMLIFrameElement.contentWindow", "iframe.contentWindow")}}, {{domxref("window.parent")}}, {{domxref("window.open")}}, and {{domxref("window.opener")}} allow documents to directly reference each other. When two documents do not have the same origin, these references provide very limited access to {{domxref("Window")}} and {{domxref("Location")}} objects, as described in the next two sections.</p> + +<p>To communicate between documents from different origins, use {{domxref("window.postMessage")}}.</p> + +<p>Specification: <a class="external" href="https://html.spec.whatwg.org/multipage/browsers.html#cross-origin-objects">HTML Living Standard § Cross-origin objects</a>.</p> + +<h3 id="Window">Window</h3> + +<p>The following cross-origin access to these <code>Window</code> properties is allowed:</p> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="col">Methods</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{domxref("window.blur")}}</td> + </tr> + <tr> + <td>{{domxref("window.close")}}</td> + </tr> + <tr> + <td>{{domxref("window.focus")}}</td> + </tr> + <tr> + <td>{{domxref("window.postMessage")}}</td> + </tr> + </tbody> +</table> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="col">Attributes</th> + <th scope="col"></th> + </tr> + </thead> + <tbody> + <tr> + <td>{{domxref("window.closed")}}</td> + <td>Read only.</td> + </tr> + <tr> + <td>{{domxref("window.frames")}}</td> + <td>Read only.</td> + </tr> + <tr> + <td>{{domxref("window.length")}}</td> + <td>Read only.</td> + </tr> + <tr> + <td>{{domxref("window.location")}}</td> + <td>Read/Write.</td> + </tr> + <tr> + <td>{{domxref("window.opener")}}</td> + <td>Read only.</td> + </tr> + <tr> + <td>{{domxref("window.parent")}}</td> + <td>Read only.</td> + </tr> + <tr> + <td>{{domxref("window.self")}}</td> + <td>Read only.</td> + </tr> + <tr> + <td>{{domxref("window.top")}}</td> + <td>Read only.</td> + </tr> + <tr> + <td>{{domxref("window.window")}}</td> + <td>Read only.</td> + </tr> + </tbody> +</table> + +<p>Some browsers allow access to more properties than the above.</p> + +<h3 id="Location">Location</h3> + +<p>The following cross-origin access to <code>Location</code> properties is allowed:</p> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="col">Methods</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{domxref("location.replace")}}</td> + </tr> + </tbody> +</table> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="col">Attributes</th> + <th scope="col"></th> + </tr> + </thead> + <tbody> + <tr> + <td>{{domxref("URLUtils.href")}}</td> + <td>Write-only.</td> + </tr> + </tbody> +</table> + +<p>Some browsers allow access to more properties than the above.</p> + +<h2 id="Cross-origin_data_storage_access">Cross-origin data storage access</h2> + +<p>Access to data stored in the browser such as <a href="/en-US/docs/Web/API/Web_Storage_API">Web Storage</a> and <a href="/en-US/docs/Web/API/IndexedDB_API">IndexedDB</a> are separated by origin. Each origin gets its own separate storage, and JavaScript in one origin cannot read from or write to the storage belonging to another origin.</p> + +<p>{{glossary("Cookie", "Cookies")}} use a separate definition of origins. A page can set a cookie for its own domain or any parent domain, as long as the parent domain is not a public suffix. Firefox and Chrome use the <a class="external" href="https://publicsuffix.org/">Public Suffix List</a> to determine if a domain is a public suffix. Internet Explorer uses its own internal method to determine if a domain is a public suffix. The browser will make a cookie available to the given domain including any sub-domains, no matter which protocol (HTTP/HTTPS) or port is used. When you set a cookie, you can limit its availability using the <code>Domain</code>, <code>Path</code>, <code>Secure</code>, and <code>HttpOnly</code> flags. When you read a cookie, you cannot see from where it was set. Even if you use only secure https connections, any cookie you see may have been set using an insecure connection.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://www.w3.org/Security/wiki/Same_Origin_Policy">Same Origin Policy at W3C</a></li> + <li><a href="https://web.dev/secure/same-origin-policy">Same-origin policy at web.dev</a></li> +</ul> + +<div class="originaldocinfo"> +<h2 id="Original_Document_Information" name="Original_Document_Information">Original Document Information</h2> + +<ul> + <li>Author(s): Jesse Ruderman</li> +</ul> +</div> diff --git a/files/pt-pt/web/svg/aplicar_efeitos_svg_conteudo_html/index.html b/files/pt-pt/web/svg/aplicar_efeitos_svg_conteudo_html/index.html new file mode 100644 index 0000000000..babd7630bb --- /dev/null +++ b/files/pt-pt/web/svg/aplicar_efeitos_svg_conteudo_html/index.html @@ -0,0 +1,301 @@ +--- +title: Aplicar efeitos de SVG ao conteúdo HTML +slug: Web/SVG/Aplicar_efeitos_SVG_conteudo_HTML +translation_of: Web/SVG/Applying_SVG_effects_to_HTML_content +--- +<p>Os navegadores modernos suportam a utilização de <a href="/en-US/docs/SVG">SVG</a> dentro dos estilos de <a href="/en-US/docs/Web/CSS" title="Cascading Style Sheets">CSS</a> para aplicar efeitos gráficos ao conteúdo HTML.</p> + +<p>You may specify SVG in styles either within the same document or an external style sheet. There are 3 properties you can use: <a href="/en-US/docs/Web/CSS/mask"><code>mask</code></a>, <a href="/en-US/docs/Web/CSS/clip-path"><code>clip-path</code></a>, and <a href="/en-US/docs/Web/CSS/filter"><code>filter</code></a>.</p> + +<div class="note"><strong>Nota:</strong> as referências a SVG nos ficheiros externos devem ter a <a href="/pt-PT/docs/Web/Seguranca/politica_de_mesma_origem">mesma origem</a> como o documento de referência.</div> + +<h2 id="Using_embedded_SVG">Using embedded SVG</h2> + +<p>To apply an SVG effect using CSS styles, you first need to create the CSS style that references the SVG to apply.</p> + +<pre class="brush: html"><style>p { mask: url(#my-mask); }</style> +</pre> + +<p>In the above example, all paragraphs are masked by an <a href="/en-US/docs/Web/SVG/Element/mask">SVG <code><mask></code></a> with the <a href="/en-US/docs/Web/HTML/Global_attributes/id">ID</a> <code>my-mask</code>.</p> + +<h3 id="Example_Masking">Example: Masking</h3> + +<p>For example, you can make a gradient mask for HTML content using SVG and CSS code similar to the following, inside your HTML document:</p> + +<pre class="brush: html"><svg height="0"> + <mask id="mask-1"> + <linearGradient id="gradient-1" y2="1"> + <stop stop-color="white" offset="0"/> + <stop stop-opacity="0" offset="1"/> + </linearGradient> + <circle cx="0.25" cy="0.25" r="0.25" id="circle" fill="white"/> + <rect x="0.5" y="0.2" width="300" height="100" fill="url(#gradient-1)"/> + </mask> +</svg> +</pre> + +<pre class="brush: css">.target { + mask: url(#mask-1); +} +p { + width: 300px; + border: 1px solid #000; + display: inline-block; +}</pre> + +<p>Note that in the CSS, the mask is specified using a URL to the ID <code>#mask-1</code>, which is the ID of the SVG mask specified below it. Everything else specifies details about the gradient mask itself.</p> + +<p>Applying the SVG effect to (X)HTML is accomplished by assigning the <code>target</code> class defined above to an element, like this:</p> + +<pre class="brush: html"><p class="target" style="background:lime;"> + Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt + ut labore et dolore magna aliqua. Ut enim ad minim veniam. +</p> +<p> + Lorem ipsum dolor sit amet, consectetur adipisicing + <b class="target">elit, sed do eiusmod tempor incididunt + ut labore et dolore magna aliqua.</b> + Ut enim ad minim veniam. +</p> +</pre> + +<p>The above example would be rendered with the mask applied to it.</p> + +<p>{{EmbedLiveSample('Example_Masking', 650, 200)}}</p> + +<h3 id="Example_Clipping">Example: Clipping</h3> + +<p>This example demonstrates using SVG to clip HTML content. Notice that even the clickable areas for links are clipped.</p> + +<pre class="brush: html"><p class="target" style="background:lime;"> + Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt + ut labore et dolore magna aliqua. Ut enim ad minim veniam. +</p> +<p> + Lorem ipsum dolor sit amet, consectetur adipisicing + <b class="target">elit, sed do eiusmod tempor incididunt + ut labore et dolore magna aliqua.</b> + Ut enim ad minim veniam. +</p> + +<button onclick="toggleRadius()">Toggle radius</button> + +<svg height="0"> + <clipPath id="clipping-path-1" clipPathUnits="objectBoundingBox"> + <circle cx="0.25" cy="0.25" r="0.25" id="circle"/> + <rect x="0.5" y="0.2" width="0.5" height="0.8"/> + </clipPath> +</svg> +</pre> + +<pre class="brush: css">.target { + clip-path: url(#clipping-path-1); +} +p { + width: 300px; + border: 1px solid #000; + display: inline-block; +}</pre> + +<p>This establishes a clipping area made of a circle and rectangle, assigns it the ID <code>#clipping-path-1</code>, then references it in the CSS. The clip path can be assigned to any element with the <code>target</code> class.</p> + +<p>You can make changes to the SVG in real time and see them immediately affect the rendering of the HTML. For example, you can resize the circle in the clip path established above:</p> + +<pre class="brush: js">function toggleRadius() { + var circle = document.getElementById("circle"); + circle.r.baseVal.value = 0.40 - circle.r.baseVal.value; +} +</pre> + +<p>{{EmbedLiveSample('Example_Clipping', 650, 200)}}</p> + +<h3 id="Example_Filtering">Example: Filtering</h3> + +<p>This demonstrates applying a filter to HTML content using SVG. It establishes several filters, which are applied with CSS to three elements in both the normal and mouse <a href="/en-US/docs/Web/CSS/:hover">hover</a> states.</p> + +<pre class="brush: html"><p class="target" style="background: lime;"> + Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt + ut labore et dolore magna aliqua. Ut enim ad minim veniam. +</p> +<pre class="target">lorem</pre> +<p> + Lorem ipsum dolor sit amet, consectetur adipisicing + <b class="target">elit, sed do eiusmod tempor incididunt + ut labore et dolore magna aliqua.</b> + Ut enim ad minim veniam. +</p> +</pre> + +<p>Any SVG filter can be applied this way. For example, to apply a blur effect, you might use:</p> + +<pre class="brush: html"><svg height="0"> + <filter id="f1"> + <feGaussianBlur stdDeviation="3"/> + </filter> +</svg></pre> + +<p>You could also apply a color matrix:</p> + +<pre class="brush: html"><svg height="0"> + <filter id="f2"> + <feColorMatrix values="0.3333 0.3333 0.3333 0 0 + 0.3333 0.3333 0.3333 0 0 + 0.3333 0.3333 0.3333 0 0 + 0 0 0 1 0"/> + </filter> +</svg> +</pre> + +<p>And some more filters:</p> + +<pre class="brush: html"><span><svg height="0"> +</span> <filter id="f3"> + <feConvolveMatrix filterRes="100 100" style="color-interpolation-filters:sRGB" + order="3" kernelMatrix="0 -1 0 -1 4 -1 0 -1 0" preserveAlpha="true"/> + </filter> + <filter id="f4"> + <feSpecularLighting surfaceScale="5" specularConstant="1" + specularExponent="10" lighting-color="white"> + <fePointLight x="-5000" y="-10000" z="20000"/> + </feSpecularLighting> + </filter> + <filter id="f5"> + <feColorMatrix values="1 0 0 0 0 + 0 1 0 0 0 + 0 0 1 0 0 + 0 1 0 0 0" style="color-interpolation-filters:sRGB"/> + </filter> +<span></svg></span></pre> + +<p>The five filters are applied using the following CSS:</p> + +<pre class="brush: css">p.target { filter:url(#f3); } +p.target:hover { filter:url(#f5); } +b.target { filter:url(#f1); } +b.target:hover { filter:url(#f4); } +pre.target { filter:url(#f2); } +pre.target:hover { filter:url(#f3); } +</pre> + +<p>{{EmbedLiveSample('Example_Filtering', 650, 200)}}</p> + +<p style="display: none;"><a class="button liveSample" href="/files/3329/filterdemo.xhtml">View this example live</a></p> + +<h3 id="Example_Blurred_Text">Example: Blurred Text</h3> + +<p>In order to blur text, Webkit based browsers have a (prefixed) CSS filter called blur (see also <a href="/en-US/docs/Web/CSS/filter#blur%28%29_2">CSS filter</a>). You can achieve the same effect using SVG filters.</p> + +<pre class="brush: html"><p class="blur">Time to clean my glasses</p> +<svg height="0"> + <defs> + <filter id="wherearemyglasses" x="0" y="0"> + <feGaussianBlur in="SourceGraphic" stdDeviation="1"/> + </filter> + </defs> +</svg> +</pre> + +<p>You can apply the SVG and the CSS filter in the same class:</p> + +<pre class="brush: css">.blur { filter: url(#wherearemyglasses); }</pre> + +<p>{{ EmbedLiveSample('Example_Blurred_Text', 300, 100) }}</p> + +<p>Blurring is computation heavy, so ensure to use it sparingly, especially in elements that get scrolled or animated.</p> + +<h2 id="Using_external_references">Using external references</h2> + +<p>SVG used for clipping, masking, and filtering can be loaded from an external source, as long as that source comes from the same origin as the HTML document to which it's applied.</p> + +<p>For example, if your CSS is in a file named <code>default.css</code>, it can look like this:</p> + +<pre class="brush: css" id="line1">.target { clip-path: url(resources.svg#c1); }</pre> + +<p>The SVG is then imported from a file named <code>resources.svg</code>, using the clip path with the ID <code>c1</code>.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/SVG" title="SVG">SVG</a></li> + <li><a class="external" href="http://robert.ocallahan.org/2008/06/applying-svg-effects-to-html-content_04.html">SVG Effects for HTML Content</a> (blog post)</li> + <li><del><a class="external" href="/web-tech/2008/10/10/svg-external-document-references">SVG External Document References</a></del> (blog post) (<a href="http://web.archive.org/web/20120512132948/https://developer.mozilla.org/web-tech/2008/10/10/svg-external-document-references/" title="Web Tech Blog » Blog Archive » SVG External Document References">[archive.org] Web Tech Blog » Blog Archive » SVG External Document References</a>)</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result"> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/svg/element/index.html b/files/pt-pt/web/svg/element/index.html new file mode 100644 index 0000000000..27ec9421de --- /dev/null +++ b/files/pt-pt/web/svg/element/index.html @@ -0,0 +1,298 @@ +--- +title: SVG - Referência de elemento +slug: Web/SVG/Element +tags: + - Desenho + - Elementos + - Gráficos Vetoriais + - Referência de SVG + - SVG + - 'l10n:priority' +translation_of: Web/SVG/Element +--- +<p>« <a href="/pt-PT/docs/Web/SVG">SVG</a> / <a href="/pt-PT/docs/Web/SVG/Atributo">SVG - Referência de atributo</a> »</p> + +<p><span class="seoSummary">SVG drawings and images are created using a wide array of elements which are dedicated to the construction, drawing, and layout of vector images and diagrams. Here you'll find reference documentation for each of the SVG elements.</span></p> + +<h2 id="SVG_-_Elementos_de_A_até_Z">SVG - Elementos de A até Z</h2> + +<div class="index"> +<h3 id="A">A</h3> + +<ul> + <li>{{SVGElement("a")}}</li> + <li>{{SVGElement("animate")}}</li> + <li>{{SVGElement("animateMotion")}}</li> + <li>{{SVGElement("animateTransform")}}</li> +</ul> + +<h3 id="C">C</h3> + +<ul> + <li>{{SVGElement("circle")}}</li> + <li>{{SVGElement("clipPath")}}</li> + <li>{{SVGElement("color-profile")}}</li> +</ul> + +<h3 id="D">D</h3> + +<ul> + <li>{{SVGElement("defs")}}</li> + <li>{{SVGElement("desc")}}</li> + <li>{{SVGElement("discard")}}</li> +</ul> + +<h3 id="E">E</h3> + +<ul> + <li>{{SVGElement("ellipse")}}</li> +</ul> + +<h3 id="F">F</h3> + +<ul> + <li>{{SVGElement("feBlend")}}</li> + <li>{{SVGElement("feColorMatrix")}}</li> + <li>{{SVGElement("feComponentTransfer")}}</li> + <li>{{SVGElement("feComposite")}}</li> + <li>{{SVGElement("feConvolveMatrix")}}</li> + <li>{{SVGElement("feDiffuseLighting")}}</li> + <li>{{SVGElement("feDisplacementMap")}}</li> + <li>{{SVGElement("feDistantLight")}}</li> + <li>{{SVGElement("feDropShadow")}}</li> + <li>{{SVGElement("feFlood")}}</li> + <li>{{SVGElement("feFuncA")}}</li> + <li>{{SVGElement("feFuncB")}}</li> + <li>{{SVGElement("feFuncG")}}</li> + <li>{{SVGElement("feFuncR")}}</li> + <li>{{SVGElement("feGaussianBlur")}}</li> + <li>{{SVGElement("feImage")}}</li> + <li>{{SVGElement("feMerge")}}</li> + <li>{{SVGElement("feMergeNode")}}</li> + <li>{{SVGElement("feMorphology")}}</li> + <li>{{SVGElement("feOffset")}}</li> + <li>{{SVGElement("fePointLight")}}</li> + <li>{{SVGElement("feSpecularLighting")}}</li> + <li>{{SVGElement("feSpotLight")}}</li> + <li>{{SVGElement("feTile")}}</li> + <li>{{SVGElement("feTurbulence")}}</li> + <li>{{SVGElement("filter")}}</li> + <li>{{SVGElement("foreignObject")}}</li> +</ul> + +<h3 id="G">G</h3> + +<ul> + <li>{{SVGElement("g")}}</li> +</ul> + +<h3 id="H">H</h3> + +<ul> + <li>{{SVGElement("hatch")}}</li> + <li>{{SVGElement("hatchpath")}}</li> +</ul> + +<h3 id="I">I</h3> + +<ul> + <li>{{SVGElement("image")}}</li> +</ul> + +<h3 id="L">L</h3> + +<ul> + <li>{{SVGElement("line")}}</li> + <li>{{SVGElement("linearGradient")}}</li> +</ul> + +<h3 id="M">M</h3> + +<ul> + <li>{{SVGElement("marker")}}</li> + <li>{{SVGElement("mask")}}</li> + <li>{{SVGElement("mesh")}}</li> + <li>{{SVGElement("meshgradient")}}</li> + <li>{{SVGElement("meshpatch")}}</li> + <li>{{SVGElement("meshrow")}}</li> + <li>{{SVGElement("metadata")}}</li> + <li>{{SVGElement("mpath")}}</li> +</ul> + +<h3 id="P">P</h3> + +<ul> + <li>{{SVGElement("path")}}</li> + <li>{{SVGElement("pattern")}}</li> + <li>{{SVGElement("polygon")}}</li> + <li>{{SVGElement("polyline")}}</li> +</ul> + +<h3 id="R">R</h3> + +<ul> + <li>{{SVGElement("radialGradient")}}</li> + <li>{{SVGElement("rect")}}</li> +</ul> + +<h3 id="S">S</h3> + +<ul> + <li>{{SVGElement("script")}}</li> + <li>{{SVGElement("set")}}</li> + <li>{{SVGElement("solidcolor")}}</li> + <li>{{SVGElement("stop")}}</li> + <li>{{SVGElement("style")}}</li> + <li>{{SVGElement("svg")}}</li> + <li>{{SVGElement("switch")}}</li> + <li>{{SVGElement("symbol")}}</li> +</ul> + +<h3 id="T">T</h3> + +<ul> + <li>{{SVGElement("text")}}</li> + <li>{{SVGElement("textPath")}}</li> + <li>{{SVGElement("title")}}</li> + <li>{{SVGElement("tspan")}}</li> +</ul> + +<h3 id="U">U</h3> + +<ul> + <li>{{SVGElement("unknown")}}</li> + <li>{{SVGElement("use")}}</li> +</ul> + +<h3 id="V">V</h3> + +<ul> + <li>{{SVGElement("view")}}</li> +</ul> +</div> + +<h2 id="SVG_-_Elementos_por_categoria">SVG - Elementos por categoria</h2> + +<h3 id="Elementos_de_animação">Elementos de animação</h3> + +<p>{{SVGElement("animate")}}, {{SVGElement("animateColor")}}, {{SVGElement("animateMotion")}}, {{SVGElement("animateTransform")}}, {{SVGElement("discard")}}, {{SVGElement("mpath")}}, {{SVGElement("set")}}</p> + +<h3 id="Formas_básicas">Formas básicas</h3> + +<p>{{SVGElement("circle")}}, {{SVGElement("ellipse")}}, {{SVGElement("line")}}, {{SVGElement("polygon")}}, {{SVGElement("polyline")}}, {{SVGElement("rect")}}</p> + +<h3 id="Elementos_contentores">Elementos contentores</h3> + +<p>{{SVGElement("a")}}, {{SVGElement("defs")}}, {{SVGElement("g")}}, {{SVGElement("marker")}}, {{SVGElement("mask")}}, {{SVGElement("missing-glyph")}}, {{SVGElement("pattern")}}, {{SVGElement("svg")}}, {{SVGElement("switch")}}, {{SVGElement("symbol")}}, {{SVGElement("unknown")}}</p> + +<h3 id="Elementos_descritivos">Elementos descritivos </h3> + +<p>{{SVGElement("desc")}}, {{SVGElement("metadata")}}, {{SVGElement("title")}}</p> + +<h3 id="Elementos_filtros_primitivos">Elementos filtros primitivos</h3> + +<p>{{SVGElement("feBlend")}}, {{SVGElement("feColorMatrix")}}, {{SVGElement("feComponentTransfer")}}, {{SVGElement("feComposite")}}, {{SVGElement("feConvolveMatrix")}}, {{SVGElement("feDiffuseLighting")}}, {{SVGElement("feDisplacementMap")}}, {{SVGElement("feDropShadow")}}, {{SVGElement("feFlood")}},{{SVGElement("feFuncA")}}, {{SVGElement("feFuncB")}}, {{SVGElement("feFuncG")}}, {{SVGElement("feFuncR")}},{{SVGElement("feGaussianBlur")}}, {{SVGElement("feImage")}}, {{SVGElement("feMerge")}}, {{SVGElement("feMergeNode")}}, {{SVGElement("feMorphology")}}, {{SVGElement("feOffset")}}, {{SVGElement("feSpecularLighting")}}, {{SVGElement("feTile")}}, {{SVGElement("feTurbulence")}}</p> + +<h3 id="Elementos_de_tipo_de_letra">Elementos de tipo de letra</h3> + +<p>{{SVGElement("font")}}, {{SVGElement("font-face")}}, {{SVGElement("font-face-format")}}, {{SVGElement("font-face-name")}}, {{SVGElement("font-face-src")}}, {{SVGElement("font-face-uri")}}, {{SVGElement("hkern")}}, {{SVGElement("vkern")}}</p> + +<h3 id="Elementos_gradientes">Elementos gradientes</h3> + +<p>{{SVGElement("linearGradient")}}, {{SVGElement("meshgradient")}}, {{SVGElement("radialGradient")}}, {{SVGElement("stop")}}</p> + +<h3 id="Elementos_gráficos">Elementos gráficos</h3> + +<p>{{SVGElement("circle")}}, {{SVGElement("ellipse")}}, {{SVGElement("image")}}, {{SVGElement("line")}}, {{SVGElement("mesh")}}, {{SVGElement("path")}}, {{SVGElement("polygon")}}, {{SVGElement("polyline")}}, {{SVGElement("rect")}}, {{SVGElement("text")}}, {{SVGElement("use")}}</p> + +<h3 id="Elementos_referenciadores_de_gráficos">Elementos referenciadores de gráficos</h3> + +<p>{{HTMLElement("audio")}}, {{HTMLElement("iframe")}}, {{SVGElement("image")}}, {{SVGElement("mesh")}}, {{SVGElement("use")}}, {{HTMLElement("video")}}</p> + +<h3 id="Elementos_HTML">Elementos HTML</h3> + +<p>{{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{HTMLElement("iframe")}}, {{HTMLElement("video")}}</p> + +<h3 id="Elementos_fonte_de_luz">Elementos fonte de luz</h3> + +<p>{{SVGElement("feDistantLight")}}, {{SVGElement("fePointLight")}}, {{SVGElement("feSpotLight")}}</p> + +<h3 id="Elementos_nunca_apresentados">Elementos nunca apresentados</h3> + +<p>{{SVGElement("clipPath")}}, {{SVGElement("defs")}}, {{SVGElement("hatch")}}, {{SVGElement("linearGradient")}}, {{SVGElement("marker")}}, {{SVGElement("mask")}}, {{SVGElement("meshgradient")}}, {{SVGElement("metadata")}}, {{SVGElement("pattern")}}, {{SVGElement("radialGradient")}}, {{SVGElement("script")}}, {{SVGElement("style")}}, {{SVGElement("symbol")}}, {{SVGElement("title")}}</p> + +<h3 id="Elementos_servidores_de_tinta">Elementos servidores de tinta</h3> + +<p>{{SVGElement("hatch")}}, {{SVGElement("linearGradient")}}, {{SVGElement("meshgradient")}}, {{SVGElement("pattern")}}, {{SVGElement("radialGradient")}}, {{SVGElement("solidcolor")}}</p> + +<h3 id="Elementos_apresentáveis">Elementos apresentáveis</h3> + +<p>{{SVGElement("a")}}, {{HTMLElement("audio")}}, {{HTMLElement("canvas")}}, {{SVGElement("circle")}}, {{SVGElement("ellipse")}}, {{SVGElement("foreignObject")}}, {{SVGElement("g")}}, {{HTMLElement("iframe")}}, {{SVGElement("image")}}, {{SVGElement("line")}}, {{SVGElement("mesh")}}, {{SVGElement("path")}}, {{SVGElement("polygon")}}, {{SVGElement("polyline")}}, {{SVGElement("rect")}}, {{SVGElement("svg")}}, {{SVGElement("switch")}}, {{SVGElement("symbol")}}, {{SVGElement("text")}}, {{SVGElement("textPath")}}, {{SVGElement("tspan")}}, {{SVGElement("unknown")}}, {{SVGElement("use")}}, {{HTMLElement("video")}}</p> + +<h3 id="Elementos_de_forma">Elementos de forma</h3> + +<p>{{SVGElement("circle")}}, {{SVGElement("ellipse")}}, {{SVGElement("line")}}, {{SVGElement("mesh")}}, {{SVGElement("path")}}, {{SVGElement("polygon")}}, {{SVGElement("polyline")}}, {{SVGElement("rect")}}</p> + +<h3 id="Elementos_estruturais">Elementos estruturais</h3> + +<p>{{SVGElement("defs")}}, {{SVGElement("g")}}, {{SVGElement("svg")}}, {{SVGElement("symbol")}}, {{SVGElement("use")}}</p> + +<h3 id="Elementos_de_conteúdo_textual">Elementos de conteúdo textual</h3> + +<p>{{SVGElement("altGlyph")}}, {{SVGElement("altGlyphDef")}}, {{SVGElement("altGlyphItem")}}, {{SVGElement("glyph")}}, {{SVGElement("glyphRef")}}, {{SVGElement("textPath")}}, {{SVGElement("text")}}, {{SVGElement("tref")}}, {{SVGElement("tspan")}}</p> + +<h3 id="Elementos_filhos_de_conteúdo_textual">Elementos filhos de conteúdo textual</h3> + +<p>{{SVGElement("altGlyph")}}, {{SVGElement("textPath")}}, {{SVGElement("tref")}}, {{SVGElement("tspan")}}</p> + +<h3 id="Elementos_não_categorizados">Elementos não categorizados</h3> + +<p>{{SVGElement("clipPath")}}, {{SVGElement("color-profile")}}, {{SVGElement("cursor")}}, {{SVGElement("filter")}}, {{SVGElement("foreignObject")}}, {{SVGElement("hatchpath")}}, {{SVGElement("meshpatch")}}, {{SVGElement("meshrow")}}, {{SVGElement("script")}}, {{SVGElement("style")}}, {{SVGElement("view")}}</p> + +<h2 id="Obsolete_and_deprecated_elements">Obsolete and deprecated elements</h2> + +<div class="blockIndicator warning"> +<p><strong>Aviso:</strong> These are old SVG elements which are deprecated and should not be used. <strong>You should never use them in new projects, and should replace them in old projects as soon as you can.</strong> They are listed here for informational purposes only.</p> +</div> + +<h3 id="A_2">A</h3> + +<p>{{SVGElement("altGlyph")}}, {{SVGElement("altGlyphDef")}}, {{SVGElement("altGlyphItem")}}, {{SVGElement("animateColor")}}</p> + +<h3 id="C_2">C</h3> + +<p>{{SVGElement("cursor")}}</p> + +<h3 id="F_2">F</h3> + +<p>{{SVGElement("font")}}, {{SVGElement("font-face")}}, {{SVGElement("font-face-format")}}, {{SVGElement("font-face-name")}}, {{SVGElement("font-face-src")}}, {{SVGElement("font-face-uri")}}</p> + +<h3 id="G_2">G</h3> + +<p>{{SVGElement("glyph")}}, {{SVGElement("glyphRef")}}</p> + +<h3 id="H_2">H</h3> + +<p>{{SVGElement("hkern")}}</p> + +<h3 id="M_2">M</h3> + +<p>{{SVGElement("missing-glyph")}}</p> + +<h3 id="T_2">T</h3> + +<p>{{SVGElement("tref")}}</p> + +<h3 id="V_2">V</h3> + +<p>{{SVGElement("vkern")}}</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/SVG/Attribute">SVG + Referência de atributo</a></li> + <li><a href="/pt-PT/docs/Web/SVG/Tutorial">SVG - Tutorial</a></li> + <li><a href="/pt-PT/docs/Web/API/Document_Object_Model#SVG_interfaces">SVG - Referência de interface</a></li> +</ul> + +<p>{{SVGRef}}</p> diff --git a/files/pt-pt/web/svg/index.html b/files/pt-pt/web/svg/index.html new file mode 100644 index 0000000000..8d27ffbb6b --- /dev/null +++ b/files/pt-pt/web/svg/index.html @@ -0,0 +1,95 @@ +--- +title: SVG - Gráficos Vetoriais Escaláveis +slug: Web/SVG +tags: + - Gráficos 2D + - Imagens + - Prioridade l10n + - Referencia + - SVG + - Web + - graficos + - Ícones +translation_of: Web/SVG +--- +<div class="callout-box"><strong><a href="/pt-PT/docs/Web/SVG/Tutorial">Inicação</a></strong><br> +Este tutorial irá ajudá-lo a começar a utilizar SVG.</div> + +<p><span class="seoSummary"><strong>Scalable Vector Graphics (SVG)</strong> é uma linguagem de marcação com base em <a href="/pt-PT/docs/Introducao_a_XML">XML </a>para descrever dois <a class="external" href="https://pt.wikipedia.org/wiki/Desenho_vetorial">gráficos vetoriais</a> dimensionais.</span> Como tal, é um padrão da Web aberta baseado erm texto para descrever imagens que podem ser renderizadas para qualquer tamanho e são criadas especificamente para funcionarem bem com outros padrões da Web, incluindo <a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/CSS">CSS</a>, <a href="https://wiki.developer.mozilla.org/pt-PT/docs/DOM">DOM</a>, <a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/JavaScript">JavaScript</a>, e <a href="https://wiki.developer.mozilla.org/pt-PT/docs/Web/SVG/SVG_animation_with_SMIL">SMIL</a>. SVG é, essencialmente para os gráficos, o que o <a href="/pt-PT/docs/Web/HTML">HTML</a> é para o texto.</p> + +<p>SVG images and their related behaviors are defined in <a href="/pt-PT/docs/Web/XML">XML</a> text files, which means they can be searched, indexed, scripted, and compressed. Additionally, this means they can be created and edited with any text editor or with drawing software.</p> + +<p>Compared to classic bitmapped image formats such as {{Glossary("JPEG")}} or {{Glossary("PNG")}}, SVG-format vector images can be rendered at any size without loss of quality and can be easily localized by updating the text within them, without the need of a graphical editor to do so. With proper libraries, SVG files can even be localized on-the-fly.</p> + +<p>SVG tem sido desenvolvido por <a href="https://www.w3.org/">World Wide Web Consortium (W3C)</a>, desde 1999.</p> + +<div class="cleared row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Documentação">Documentação</h2> + +<dl> + <dt><a href="/pt-PT/docs/Web/SVG/Element">SVG - referência de elemento</a></dt> + <dd>Details about each SVG element.</dd> + <dt><a href="/pt-PT/docs/Web/SVG/Attribute">SVG - referência de atributo</a></dt> + <dd>Details about each SVG attribute.</dd> + <dt><a href="/en-US/docs/DOM/DOM_Reference#SVG_interfaces">SVG DOM interface reference</a></dt> + <dd>Details about the SVG DOM API, for interaction with JavaScript.</dd> + <dt><a href="/en-US/docs/Web/SVG/Applying_SVG_effects_to_HTML_content">Applying SVG effects to HTML content</a></dt> + <dd>SVG works together with {{Glossary("HTML")}}, {{Glossary("CSS")}} and {{Glossary("JavaScript")}}. Use SVG to <a href="/en-US/docs/SVG_In_HTML_Introduction">enhance a regular HTML page or web application</a>.</dd> +</dl> + +<p><span class="alllinks"><a href="/en-US/docs/tag/SVG">View All...</a></span></p> + +<h2 class="Community" id="Comunidade">Comunidade</h2> + +<ul> + <li>Consulte os fóruns da Mozilla... {{DiscussionList("dev-tech-svg", "mozilla.dev.tech.svg")}}</li> +</ul> + +<h2 class="Tools" id="Ferramentas">Ferramentas</h2> + +<ul> + <li><a href="http://www.w3.org/Graphics/SVG/Test/">SVG Test Suite</a></li> + <li><a href="http://jiggles.w3.org/svgvalidator/">Validador de SVG </a>(<strong>Descontinuado</strong>)</li> + <li><a href="/pt-PT/docs/tag/SVG:Tools">Mais Ferramentas...</a></li> + <li>Outros recursos: <a href="/pt-PT/docs/Introducao_a_XML">XML</a>, <a href="/pt-PT/docs/Web/CSS">CSS</a>, <a href="/pt-PT/docs/DOM/DOM_Reference">DOM</a>, <a href="/pt-PT/docs/Web/API/API_de_canvas">Canvas</a></li> +</ul> +</div> + +<div class="section"> +<h2 class="Related_Topics" id="Exemplos">Exemplos</h2> + +<ul> + <li>Google <a href="http://maps.google.com">Maps</a> (route overlay) & <a href="http://docs.google.com">Docs</a> (spreadsheet charting)</li> + <li><a href="http://starkravingfinkle.org/projects/demo/svg-bubblemenu-in-html.xml">SVG bubble menus</a></li> + <li><a href="http://jwatt.org/svg/authoring/">SVG authoring guidelines</a></li> + <li>An overview of the <a href="/en-US/docs/Mozilla_SVG_Project">Mozilla SVG Project</a></li> + <li><a href="/en-US/docs/SVG/FAQ">Frequently asked questions</a> regarding SVG and Mozilla</li> + <li><a href="/en-US/docs/SVG/SVG_as_an_Image">SVG as an image</a></li> + <li><a href="/en-US/docs/SVG/SVG_animation_with_SMIL">SVG animation with SMIL</a></li> + <li><a href="http://plurib.us/1shot/2007/svg_gallery/">SVG art gallery</a></li> +</ul> + +<h3 id="Animação_e_interações">Animação e interações</h3> + +<p>Like HTML, SVG has a document model (DOM) and events, and is accessible from JavaScript. This allows developers to create rich animations and interactive images.</p> + +<ul> + <li>Some real eye-candy SVG at <a href="http://svg-wow.org/">svg-wow.org</a></li> + <li>Firefox extension (<a href="http://schepers.cc/grafox/">Grafox</a>) to add a subset of {{Glossary("SMIL")}} animation support</li> + <li>Interactive <a href="http://people.mozilla.com/~vladimir/demos/photos.svg">photos</a> manipulation</li> + <li><a href="http://starkravingfinkle.org/blog/2007/07/firefox-3-svg-foreignobject/">HTML transformations</a> using SVG's <code>foreignObject</code></li> +</ul> + +<h3 id="Mapeamento_gráficos_jogos_e_experiências_em_3D">Mapeamento, gráficos, jogos e experiências em 3D</h3> + +<p>While a little SVG can go a long way to enhanced web content, here are some examples of heavy SVG usage.</p> + +<ul> + <li><a href="https://web.archive.org/web/20131019072450/http://www.treebuilder.de/svg/connect4.svg" title="Archive link provided because source now requires authentication.">Connect 4</a></li> + <li><a href="http://jvectormap.com/">jVectorMap</a> (interactive maps for data visualization)</li> + <li><a href="http://jointjs.com/">JointJS</a> (JavaScript diagramming library)</li> + <li><a href="https://d3js.org/">D3</a> ( JavaScript library for visualizing data with HTML, SVG, and CSS )</li> +</ul> +</div> +</div> diff --git a/files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html b/files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html new file mode 100644 index 0000000000..a9fa3f8765 --- /dev/null +++ b/files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html @@ -0,0 +1,394 @@ +--- +title: Exemplo +slug: Web/SVG/Namespaces_Crash_Course/Exemplo +tags: + - SVG + - XML +translation_of: Web/SVG/Namespaces_Crash_Course/Example +--- +<p>In this example, we use <a href="/en-US/docs/XHTML">XHTML</a>, <a href="/pt-PT/docs/Web/SVG">SVG</a>, <a href="/pt-PT/docs/Web/JavaScript">JavaScript</a>, and the <a href="/pt-PT/docs/DOM/DOM_Reference">DOM</a> to animate a swarm of "motes". These motes are governed by two simple principles. First, each mote tries to move towards the mouse cursor, and second each mote tries to move away from the average mote position. Combined, we get this very natural-looking behavior.</p> + +<p>This is done completely in W3C Standards–XHTML, SVG, and JavaScript–no Flash or any vendor-specific extensions. This example should work in Firefox 1.5 and above.</p> + +<p><a class="internal button liveSample" href="http://developer.mozilla.org/samples/svg/swarm-of-motes.xhtml">Ver o exemplo</a></p> + +<pre class="brush:xml"><?xml version='1.0'?> +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:svg="http://www.w3.org/2000/svg"> + <head> + <title>A swarm of motes</title> + <style type='text/css'> + <![CDATA[ + label, input + { + width: 150px; + display: block; + float: left; + margin-bottom: 10px; + } + label + { + text-align: right; + width: 75px; + padding-right: 20px; + } + br + { + clear: left; + } + ]]> + </style> + </head> + <body onload='update()'> + <svg:svg id='display' width='400' height='300'> + <svg:circle id='cursor' cx='200' +cy='150' r='7' fill='#0000ff' fill-opacity='0.5'/> + </svg:svg> + + <p>A swarm of motes, governed by two simple principles. + First, each mote tries to move towards the cursor, and + second each mote tries to move away from the average + mote position. Combined, we get this very natural + looking behavior. + </p> + + <p> + This is done completely in W3C Standards–XHTML, + SVG and JavaScript–no flash or any vendor specific + extensions. Currently, this will work in Mozilla Firefox + version 1.5 and above. + </p> + + <div> + (C) 2006 <a id='emailme' href='#'>Nick Johnson</a> + + <script type='text/javascript'> + <![CDATA[ + // foil spam bots + var email = '@riovia.net'; + email ='nick' + email; + document.getElementById('emailme').href = 'mailto:'+email; + ]]> + </script> + This software is free for you to use in any way whatsoever, + and comes with no warranty at all. + </div> + + <form action="" onsubmit="return false;"> + <p> + <label>Number of motes:</label> + <input id='num_motes' value='5'/> + <br/> + + <label>Max. Velocity:</label> + <input id='max_velocity' value='15'/> + <br/> + + <label>Attraction to cursor:</label> + <input id='attract_cursor' value='6'/> + <br/> + + <label>Repulsion from peers:</label> + <input id='repel_peer' value='5'/> + <br/> + </p> + </form> + + <script type='text/javascript'> + <![CDATA[ + + // Array of motes + var motes; + + // Get the display element. + function Display() + { + return document.getElementById('display'); + } + + // Determine dimensions of the display element. + // Return this as a 2-tuple (x,y) in an array + function Dimensions() + { + // Our Rendering Element + var display = Display(); + var width = parseInt( display.getAttributeNS(null,'width') ); + var height = parseInt( display.getAttributeNS(null,'height') ); + + return [width,height]; + } + + // This is called by mouse move events + var mouse_x = 200, mouse_y = 150; + function OnMouseMove(evt) + { + mouse_x = evt.clientX; + mouse_y = evt.clientY; + + var widget = document.getElementById('cursor'); + widget.setAttributeNS(null,'cx',mouse_x); + widget.setAttributeNS(null,'cy',mouse_y); + } + document.onmousemove = OnMouseMove; + + // Determine (x,y) of the cursor + function Cursor() + { + return [mouse_x, mouse_y]; + } + + // Determine average (x,y) of the swarm + function AverageMotePosition() + { + if( !motes ) + return [0,0]; + + if( motes.length == 0 ) + return [0,0]; + + var i; + var sum_x=0, sum_y=0; + for(i=0; i<motes.length; i++) + { + sum_x += motes[i].x; + sum_y += motes[i].y; + } + + return [sum_x/motes.length, sum_y/motes.length]; + } + + // A nicer, integer random + function Rand(modulo) + { + return Math.round( Math.random() * (modulo-1)); + } + + // Class Mote + function Mote() + { + // Dimensions of drawing area. + var dims = Dimensions(); + var width = dims[0], height = dims[1]; + + // Choose a random coordinate to start at. + this.x = Rand( width ); + this.y = Rand( height ); + + // Nil initial velocity. + this.vx = this.vy = 0; + + // A visual element---initially none + this.elt = null; + } + + // Turn this into a class. + new Mote(); + + // Mote::applyForce() -- Adjust velocity + // towards the given position. + // Warning: Pseudo-physics -- not really + // governed by any /real/ physical principles. + Mote.prototype.applyForce = function(pos, mag) + { + if( pos[0] > this.x ) + this.vx += mag; + else if( pos[0] < this.x ) + this.vx -= mag; + + if( pos[1] > this.y ) + this.vy += mag; + else if( pos[1] < this.y ) + this.vy -= mag; + } + + // Mote::capVelocity() -- Apply an upper limit + // on mote velocity. + Mote.prototype.capVelocity = function() + { + var max = parseInt( document.getElementById('max_velocity').value ); + + if( max < this.vx ) + this.vx = max; + else if( -max > this.vx ) + this.vx = -max; + + if( max < this.vy ) + this.vy = max; + else if( -max > this.vy ) + this.vy = -max; + } + + // Mote::capPosition() -- Apply an upper/lower limit + // on mote position. + Mote.prototype.capPosition = function() + { + var dims = Dimensions(); + if( this.x < 0 ) + this.x = 0; + else if( this.x >= dims[0] ) + this.x = dims[0]-1; + + if( this.y < 0 ) + this.y = 0; + else if( this.y >= dims[1] ) + this.y = dims[1]-1; + } + + // Mote::move() -- move a mote, update the screen. + Mote.prototype.move = function() + { + // Apply attraction to cursor. + var attract = parseInt( document.getElementById('attract_cursor').value ); + var cursor = Cursor(); + this.applyForce(cursor, attract); + + // Apply repulsion from average mote position. + var repel = parseInt( document.getElementById('repel_peer').value ); + var average = AverageMotePosition(); + this.applyForce(average, -repel); + + // Add some randomness to the velocity. + this.vx += Rand(3)-1; + this.vy += Rand(3)-1; + + // Put an upper limit on velocity. + this.capVelocity(); + + // Apply velocity. + var old_x = this.x, old_y = this.y; + this.x += this.vx; + this.y += this.vy; + this.capPosition(); + + // Draw it. + + if( this.elt === null ) + { + var svg = 'http://www.w3.org/2000/svg'; + this.elt = document.createElementNS(svg,'line'); + this.elt.setAttributeNS(null,'stroke','green'); + this.elt.setAttributeNS(null,'stroke-width','3'); + this.elt.setAttributeNS(null,'stroke-opacity','0.5'); + Display().appendChild( this.elt ); + } + + this.elt.setAttributeNS(null,'x1',old_x); + this.elt.setAttributeNS(null,'y1',old_y); + + this.elt.setAttributeNS(null,'x2',this.x); + this.elt.setAttributeNS(null,'y2',this.y); + } + + + function update() + { + // First call? + if( !motes ) + motes = []; + + // How many motes should there be? + var num = parseInt( document.getElementById('num_motes').value ); + if( num < 0 ) + num = 0; + + // Make sure we have exactly that many... + // Too few? + while( motes.length < num ) + motes.push( new Mote() ); + // Or too many? + if( num == 0 ) + motes = []; + else if( motes.length > num ) + motes = motes.slice(0,num-1); + + // Move a random mote + if( motes.length > 0 ) + motes[ Rand( motes.length ) ].move(); + + // And do this again in 1/100 sec + setTimeout('update()', 10); + } + ]]> + </script> + </body> +</html> +</pre> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: block; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/svg/namespaces_crash_course/index.html b/files/pt-pt/web/svg/namespaces_crash_course/index.html new file mode 100644 index 0000000000..54a6d077b4 --- /dev/null +++ b/files/pt-pt/web/svg/namespaces_crash_course/index.html @@ -0,0 +1,266 @@ +--- +title: Namespaces Crash Course +slug: Web/SVG/Namespaces_Crash_Course +tags: + - NeedsTranslation + - SVG + - XML +translation_of: Web/SVG/Namespaces_Crash_Course +--- +<p>As an <a href="/en-US/docs/Glossary/XML" title="en-US/docs/Glossary/XML">XML</a> dialect, <a href="/en-US/docs/Web/SVG" title="en-US/docs/Web/SVG">SVG</a> is namespaced. It is important to understand the concept of namespaces and how they are used if you plan to author SVG content. Versions of SVG viewers prior to the release of Firefox 1.5 unfortunately paid scant attention to namespaces, but they are essential to multi-XML dialect supporting user agents such as <a href="/en-US/docs/Mozilla/Gecko" title="en-US/docs/Mozilla/Gecko">Gecko</a>-based browsers which must be very strict. Take some time to understand namespaces now and it will save you all sorts of headaches in the future.</p> + +<h3 id="Background">Background</h3> + +<p>It has been a long standing goal of the W3C to make it possible for different types of XML based content to be mixed together in the same XML file. For example, SVG and <a href="/en-US/docs/Web/MathML" title="en-US/docs/Web/MathML">MathML</a> might be incorporated directly into an XHTML based scientific document. Being able to mix content types like this has many advantages, but it also required a very real problem to be solved.</p> + +<p>Naturally, each XML dialect defines the meaning of the markup tag names described in its specification. The problem with mixing content from different XML dialects in a single XML document is that the tags defined by one dialect may have the same name as tags defined by another. For example, both XHTML and SVG have a <code><title></code> tag. How should the user agent distinguish between the two? In fact how does the user agent tell when XML content is something it knows about, and not just a meaningless XML file containing arbitrary tag names unknown to it?</p> + +<p>Contrary to popular opinion, the answer to this question is not "it can tell from the <code>DOCTYPE</code> declaration". DTDs were never designed with mixed content in mind, and past attempts to create mixed content DTDs are now considered to have failed. XML, and some XML dialects (SVG included), don't require a <code>DOCTYPE</code> declaration, and SVG 1.2 won't even have one. The fact that <code>DOCTYPE</code> declarations (usually) match the content in single content type files is merely coincidental. DTDs are for validation only, not identification of content. User agents that cheat and identify XML content using its DOCTYPE declaration cause harm.</p> + +<p>The real answer to the question is that XML content tells the user agent which dialect the tag names belong to by giving the tags explicit "namespace declarations".</p> + +<h3 id="Declaring_namespaces" name="Declaring_namespaces">Declaring namespaces</h3> + +<p>So what do these namespace declarations look like, and where do they go? Here is a short example.</p> + +<pre><svg xmlns="http://www.w3.org/2000/svg"> + <!-- more tags here --> +</svg> +</pre> + +<p>The namespace declaration is provided by the <code>xmlns</code> attribute. This attribute says that the <code><svg></code> tag and its child tags belong to whichever XML dialect has the namespace name <span class="nowiki">'http://www.w3.org/2000/svg'</span> which is, of course, SVG. Note the namespace declaration only needs to be provided once on a root tag. The declaration defines the <em>default</em> namespace, so the user agent knows that all the <code><svg></code> tag's descendant tags also belong to the same namespace. User agents check to see if they recognize the namespace name to determine if they know how to handle the markup.</p> + +<p>Note that namespace names are just strings, so the fact that the SVG namespace name also looks like a URI isn't important. URIs are commonly used because they are unique, the intention is not to "link" somewhere. (In fact URIs are used so frequently that the term "namespace URI" is commonly used instead of "namespace name".)</p> + +<h4 id="Redeclaring_the_default_namespace" name="Redeclaring_the_default_namespace">Redeclaring the default namespace</h4> + +<p>So if all the descendants of the root tag are also defined to be in the default namespace, how do you mix in content from another namespace? Easy. You just redefine the default namespace. Here's a short example.</p> + +<pre><html xmlns="http://www.w3.org/1999/xhtml"> + <body> + <!-- some XHTML tags here --> + <svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px"> + <!-- some SVG tags here --> + </svg> + <!-- some XHTML tags here --> + </body> +</html> +</pre> + +<p>In this example the <code>xmlns</code> attribute on the root <code><html></code> tag declares the default namespace to be XHTML. As a result it and all its child tags are interpreted by the user agent as belonging to XHTML, except for the <code><svg></code> tag. The <code><svg></code> tag has its own <code>xmlns</code> attribute, and by redeclaring the default namespace, this tells the user agent that the <code><svg></code> tag and its descendants (unless they also redeclare the default namespace) belong to SVG.</p> + +<p>See, namespaces really aren't that hard.</p> + +<h4 id="Declaring_namespace_prefixes" name="Declaring_namespace_prefixes">Declaring namespace prefixes</h4> + +<p>XML dialects not only define their own tags, but also their own attributes. By default, attributes don't have a namespace at all, and are only known to be unique because they appear on an element that itself has a unique name. However, sometimes it is necessary to define attributes so that they can be reused on many different elements and still be considered to be the same attribute, independently of the element with which they are used. A very good example of this is the <code>href</code> attribute defined by the XLink specification. This attribute is commonly used by other XML dialects as a means to link to external resources. But how do you tell the user agent which dialect the attribute belongs to, in this case XLink? Consider the following example.</p> + +<pre><svg xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink"> + <script xlink:href="cool-script.js" type="text/ecmascript"/> +</svg> +</pre> + +<p>This example has the rather unusual looking attribute <code>xmlns:xlink</code>. As you may guess from the first 'xmlns' part, this is another namespace declaration. However, instead of setting the default namespace, this namespace declaration sets the namespace for something called a "namespace prefix". In this case, we have chosen to use the prefix <code>xlink</code> (the second part) since the prefix will be used to tell the user agent about attributes that belong to XLink.</p> + +<p>As their name suggests, namespace prefixes are used to prefix attribute names and tag names. This is done by putting the namespace prefix and a colon before the attribute name as shown on the <code><script></code> tag in the example above. This tells the user agent that that particular attribute belongs to the namespace assigned to the namespace prefix (XLink), and is an attribute that can be used with the same meaning on other tags.</p> + +<p>Note that it is an XML error to use a prefix that hasn't been bound to a namespace name. The binding created by the <code>xmlns:xlink</code> attribute in the example above is absolutely essential if the <code>xlink:href</code> attribute isn't to cause an error. This XLink attribute is also frequently used in SVG on the <code><a></code>, <code><use></code> and <code><image></code> tags among others, so it's a good idea to always include the XLink declaration in your documents.</p> + +<p>As an aside, it's useful to know that namespace prefixes can also be used for tag names. This tells the user agent that that particular tag (but not its children this time!) belongs to the namespace assigned to the prefix. Knowing this will save you some confusion if you come across markup like that in the following example:</p> + +<pre><html xmlns="http://www.w3.org/1999/xhtml" + xmlns:svg="http://www.w3.org/2000/svg"> + <body> + <h1>SVG embedded inline in XHTML</h1> + <svg:svg width="300px" height="200px"> + <svg:circle cx="150" cy="100" r="50" fill="#ff0000"/> + </svg:svg> + </body> +</html> +</pre> + +<p>Note that because a namespace prefix is used for the <code><svg:svg></code> tag and its child <code><svg:circle></code>, it wasn't necessary to redeclare the default namespace. In general though it is better to redeclare the default namespace rather than prefix lots of tags in this way.</p> + +<h3 id="Scripting_in_namespaced_XML" name="Scripting_in_namespaced_XML">Scripting in namespaced XML</h3> + +<p>Namespaces affect not only markup, but also scripting. If you write scripts for namespaced XML such as SVG, read on.</p> + +<p>The <a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/">DOM Level 1</a> recommendation was created before the <a class="external" href="http://www.w3.org/TR/REC-xml-names/">original Namespaces in XML</a> recommendation was released; therefore, DOM1 isn't namespace aware. This causes problems for namespaced XML such as SVG. To resolve these problems, <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/">DOM Level 2 Core</a> added namespace aware equivalents of all the applicable DOM Level 1 methods. When scripting SVG, <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#Namespaces-Considerations">it is important to use the namespace aware methods</a>. The table below lists the DOM1 methods that shouldn't be used in SVG, along with their equivalent DOM2 counterparts that should be used instead.</p> + +<table class="fullwidth-table"> + <tbody> + <tr> + <th>DOM1 (don't use)</th> + <th>DOM2 (use these instead!)</th> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-createAttribute">createAttribute</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrAttrNS">createAttributeNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-createElement">createElement</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-DocCrElNS">createElementNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getAttributeNode">getAttributeNode</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElGetAtNodeNS">getAttributeNodeNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getAttribute">getAttribute</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElGetAttrNS">getAttributeNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getElementsByTagName">getElementsByTagName</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-getElBTNNS">getElementsByTagNameNS</a> (also <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-A6C90942">added to Element</a>)</td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getNamedItem">getNamedItem</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-getNamedItemNS">getNamedItemNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#">hasAttribute</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElHasAttrNS">hasAttributeNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-removeAttribute">removeAttribute</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElRemAtNS">removeAttributeNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-removeNamedItem">removeNamedItem</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-removeNamedItemNS">removeNamedItemNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-setAttribute">setAttribute</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAttrNS">setAttributeNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-setAttributeNode">setAttributeNode</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-ElSetAtNodeNS">setAttributeNodeNS</a></td> + </tr> + <tr> + <td><a class="external" href="http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-setNamedItem">setNamedItem</a></td> + <td><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-setNamedItemNS">setNamedItemNS</a></td> + </tr> + </tbody> +</table> + +<p>The first argument for all the DOM2 namespace aware methods must be the namespace name (also known as the namespace URI) of the element or attribute in question. For SVG <strong>elements</strong> this is <span class="nowiki">'http://www.w3.org/2000/svg'</span>. However, note carefully: the <a class="external" href="http://www.w3.org/TR/xml-names11/#defaulting">Namespaces in XML 1.1</a> recommendation states that the namespace name for attributes without a prefix does not have a value. In other words, although the attributes belong to the namespace of the tag, you do not use the tag's namespace name. Instead, <strong>you must use null as the namespace name for unqualified (prefixless) attributes</strong>. So, to create an SVG <code>rect</code> <em>element</em> using <code>document.createElementNS()</code>, you must write:</p> + +<pre><code class="language-javascript">document.createElementNS('http://www.w3.org/2000/svg', 'rect');</code></pre> + +<p>But to retrieve the value of the <code>x</code> <em>attribute</em> on an SVG <code>rect</code> element, you must write:</p> + +<pre class="eval"><code class="language-javascript">rect.getAttributeNS(<strong>null</strong>, 'x');</code></pre> + +<p>Note that this isn't the case for attributes <em>with</em> a namespace prefix (attributes that don't belong to the same XML dialect as the tag). Attributes such as the <code>xlink:href</code> attribute require the namespace name that was assigned to that prefix (<span class="nowiki">http://www.w3.org/1999/xlink</span> for XLink). Hence to get the value of the <code>xlink:href</code> attribute of an <code><a></code> element in SVG you would write:</p> + +<pre><code class="language-javascript">elt.getAttributeNS('http://www.w3.org/1999/xlink', 'href');</code></pre> + +<p>For setting attributes that have a namespace, it is recommended (but not required) that you also include their prefix in the second argument so that the DOM can later be more easily converted back to XML (if for instance you want to send it back to the server). For example:</p> + +<pre><code class="language-javascript">elt.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', 'otherdoc.svg');</code></pre> + +<p>As a final example, here's a demonstration of how you should dynamically create an <code><image></code> element using script:</p> + +<pre><code class="language-javascript">var SVG_NS = 'http://www.w3.org/2000/svg'; +var XLink_NS = 'http://www.w3.org/1999/xlink'; +var image = document.createElementNS(SVG_NS, 'image'); +image.setAttributeNS(null, 'width', '100'); +image.setAttributeNS(null, 'height', '100'); +image.setAttributeNS(XLink_NS, 'xlink:href', 'flower.png'); +</code></pre> + +<h3 id="Conclusion" name="Conclusion">Conclusão</h3> + +<p>Make sure you always declare the namespaces you use in your XML files. If you don't, user agents such as Firefox won't recognize your content and will simply show the XML markup or inform the user that there's an error in the XML. It's a good idea to use a template that includes all the commonly used namespace declarations when creating new SVG files. If you don't already have one, make one up starting with the following code:</p> + +<pre><svg xmlns="http://www.w3.org/2000/svg" + xmlns:xlink="http://www.w3.org/1999/xlink"> +</svg> +</pre> + +<p>Even if you don't use all those namespaces in a particular document, there's no harm in including the namespace declarations. It may save you from some annoying errors if you end up adding content from one of the unused namespaces at a later date.</p> + +<h3 id="A_full_example" name="A_full_example">Um exemplo completo</h3> + +<p>Para um exemplo completo, consulte <a href="/pt-PT/docs/Web/SVG/Namespaces_Crash_Course/Exemplo">SVG: Namespaces Crash Course: Exemplo</a>.</p> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/svg/svg_animacao_com_smil/index.html b/files/pt-pt/web/svg/svg_animacao_com_smil/index.html new file mode 100644 index 0000000000..be898b1037 --- /dev/null +++ b/files/pt-pt/web/svg/svg_animacao_com_smil/index.html @@ -0,0 +1,125 @@ +--- +title: Animação SVG com SMIL +slug: Web/SVG/SVG_animacao_com_SMIL +tags: + - Animação + - Animação de SVG + - Firefox 4 + - Gecko 2.0 + - SVG +translation_of: Web/SVG/SVG_animation_with_SMIL +--- +<div class="warning"> +<p>Embora o Chrome 45 tenha revogado SMIL em favor das animações CSS e da Web, os programadores do Chrome suspenderam essa revogação.</p> +</div> + +<p>Firefox 4 introduziu suporte para a animação de <a href="/en/SVG" title="en/SVG">SVG</a> utilizando <a class="external" href="http://www.w3.org/TR/REC-smil" title="http://www.w3.org/TR/REC-smil">Synchronized Multimedia Integration Language</a> (SMIL). SMIL permite-lhe:</p> + +<ul> + <li>animate the numeric attributes of an element (x, y, ...)</li> + <li>animate transform attributes (translation or rotation)</li> + <li>animate color attributes</li> + <li>follow a motion path</li> +</ul> + +<p>This is done adding an SVG element like <span class="author-g-shbl2alwmr0wm7ko">{{ SVGElement("animate") }}</span> inside the SVG element to animate. Below are examples for the four different ways.</p> + +<h2 id="Animar_atributos_de_um_elemento">Animar atributos de um elemento</h2> + +<p>The following example animates the <strong>cx</strong> attribute of a circle. To do so, we add an <span class="author-g-shbl2alwmr0wm7ko">{{ SVGElement("animate") }} element inside the </span><span class="author-g-shbl2alwmr0wm7ko">{{ SVGElement("circle") }} element. The important attributes for </span><span class="author-g-shbl2alwmr0wm7ko">{{ SVGElement("animate") }} are:</span></p> + +<dl> + <dt><strong>attributeName</strong></dt> + <dd>The name of the attribute to animate.</dd> + <dt>from</dt> + <dd>The initial value of the attribute.</dd> + <dt>to</dt> + <dd>The final value.</dd> + <dt>dur</dt> + <dd>The duration of the animation (for example, write '5s' for 5 seconds).</dd> +</dl> + +<p>If you want to animate more attributes inside the same element, just add more {{ SVGElement("animate") }} elements.</p> + +<pre class="brush: html"><svg width="300" height="100"> + <title>Attribute Animation with SMIL</title> + <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> + <circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1"> + <animate + attributeName="cx" from="0" to="500" + dur="5s" repeatCount="indefinite" /> + </circle> +</svg></pre> + +<p>{{ EmbedLiveSample('Animating_attributes_of_an_element', '100%', 120) }}</p> + +<h2 id="Animar_os_atributos_transform">Animar os atributos "transform"</h2> + +<p><span class="author-g-shbl2alwmr0wm7ko">The {{ SVGElement("animateTransform") }} element let you animate <strong>transform</strong> attributes. This new element is necessary because we are not animating a simple attribute like <strong>x</strong> which is just a number. Rotation attributes look like this: <code>rotation(theta, x, y)</code>, where <code>theta</code> is the angle in degrees, and <code>x</code> and <code>y</code> are absolute positions. In the example below, we animate the center of the rotation and the angle.</span></p> + +<pre class="brush: html"><svg width="300" height="100"> + <title>SVG SMIL Animate with transform</title> + <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> + <rect x="0" y="50" width="15" height="34" fill="blue" stroke="black" stroke-width="1"> + <animateTransform + attributeName="transform" + begin="0s" + dur="20s" + type="rotate" + from="0 60 60" + to="360 100 60" + repeatCount="indefinite" + /> + </rect> +</svg> +</pre> + +<p>{{ EmbedLiveSample('Animating_the_transform_attributes', '100%', 120) }}</p> + +<h2 id="Animation_following_a_path">Animation following a path</h2> + +<p><span class="author-g-shbl2alwmr0wm7ko">The {{ SVGElement("animateMotion") }} element lets you animate an element position and rotation according to a path. </span>The path is defined the same way as in <span class="author-g-shbl2alwmr0wm7ko">{{ SVGElement("path") }}. You can set the attribute to define whether the object rotates following the tangent of the path. </span></p> + +<h3 id="Example_1_Linear_motion">Example 1: Linear motion</h3> + +<p>In this example, a blue circle bounces between the left and right edges of a black box, over and over again, indefinitely. The animation here is handled by the {{ SVGElement("animateMotion") }} element. In this case, we're establishing a path consisting of a <strong>M</strong>oveTo command to establish the starting point for the animation, then the <strong>H</strong>orizontal-line command to move the circle 300 pixels to the right, followed by the <strong>Z</strong> command, which closes the path, establishing a loop back to the beginning. By setting the value of the <strong>repeatCount</strong> attribute to <code>indefinite</code>, we indicate that the animation should loop forever, as long as the SVG image exists.</p> + +<pre class="brush: html"><svg xmlns="http://www.w3.org/2000/svg" width="300" height="100"> + <title>SVG SMIL Animate with Path</title> + <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> + <circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1"> + <animateMotion + path="M 0 0 H 300 Z" + dur="3s" repeatCount="indefinite" /> + </circle> +</svg> +</pre> + +<p>{{ EmbedLiveSample('Example_1_Linear_motion', '100%', 120) }}</p> + +<p><a href="https://developer.mozilla.org/samples/svg/svganimdemo1.html">View live sample</a></p> + +<h3 id="Example_2_Curved_motion">Example 2: Curved motion</h3> + +<p>Same example as before with a curved path and following the direction of the path.</p> + +<pre class="brush: html"><svg width="300" height="100"> + <title>SVG SMIL Animate with Path</title> + <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> + <rect x="0" y="0" width="20" height="20" fill="blue" stroke="black" stroke-width="1"> + <animateMotion + path="M 250,80 H 50 Q 30,80 30,50 Q 30,20 50,20 H 250 Q 280,20,280,50 Q 280,80,250,80Z" + dur="3s" repeatCount="indefinite" rotate="auto" /> + </rect> +</svg> +</pre> + +<p>{{ EmbedLiveSample('Example_2_Curved_motion', '100%', 120) }}</p> + +<h2 id="Consultar_também">Consultar também</h2> + +<ul> + <li><a href="/pt-PT/docs/Web/SVG" title="en/SVG">SVG</a></li> + <li><a class="external" href="http://www.w3.org/TR/SVG/animate.html" title="http://www.w3.org/TR/SVG/animate.html">Especificação de Animação de SVG</a></li> + <li><a class="external" href="http://www.w3.org/TR/REC-smil" title="http://www.w3.org/TR/REC-smil">Especificação de SMIL</a></li> +</ul> diff --git a/files/pt-pt/web/svg/tutorial/index.html b/files/pt-pt/web/svg/tutorial/index.html new file mode 100644 index 0000000000..9c162f0342 --- /dev/null +++ b/files/pt-pt/web/svg/tutorial/index.html @@ -0,0 +1,32 @@ +--- +title: SGV - Tutorial +slug: Web/SVG/Tutorial +translation_of: Web/SVG/Tutorial +--- +<p>Scalable Vector Graphics, <a href="/pt/SVG" title="pt/SVG">SVG</a>, é uma linguagem baseada em XML para construir gráficos. O SVG foi parcialmente implementado no Firefox, Opera, navegadores WebKit, Internet Explorer e outros navegadores.</p> + +<p>Este tutorial visa explicar como funciona um SVG internamente e tem detalhes técnicos. Se você apenas quer desenhar imagens bonitas, você pode encontrar recursos úteis na <a href="http://inkscape.org/doc/" class="external" title="http://inkscape.org/doc/">Página de documentação do Inkscape</a>. Outra boa introdução ao SVG está disponível em <a href="http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html" class="external" title="http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html">SVG Primer</a>, pela W3C.</p> + +<div class="note">O tutorial está no início de seu desenvolvimento. Se você puder, por favor ajude lapidando e escrevendo um parágrafo ou dois. Pontos extras por escrever a página inteira.</div> + +<h2 id="Introdução_ao_SVG">Introdução ao SVG</h2> + +<ul> + <li><a href="/Introducao" title="Introducao">Introdução</a></li> + <li>Iniciando</li> + <li>Posições</li> + <li>Formas Básicas</li> + <li>Caminhos</li> + <li>Preenchimentos e Linhas</li> + <li>Gradientes</li> + <li>Padrões</li> + <li>Textos</li> + <li>Transformações Básicas</li> + <li>Cortes e Máscaras</li> + <li>Outros Conteúdos em SVG</li> + <li>Efeitos de Filtro</li> + <li>Fontes em SVG</li> + <li>(muitas outras entradas aqui)</li> + <li>Ferramentas para SVG</li> + <li>Outros Tutoriais</li> +</ul> diff --git a/files/pt-pt/web/svg/tutorial/introducao/index.html b/files/pt-pt/web/svg/tutorial/introducao/index.html new file mode 100644 index 0000000000..287de67a14 --- /dev/null +++ b/files/pt-pt/web/svg/tutorial/introducao/index.html @@ -0,0 +1,52 @@ +--- +title: Introdução +slug: Web/SVG/Tutorial/Introducao +tags: + - Guía + - Precisa de Atualização + - Principiante + - SVG + - SVG - Tutorial + - Tutorial +translation_of: Web/SVG/Tutorial/Introduction +--- +<p>{{ PreviousNext("Web/SVG/Tutorial", "Web/SVG/Tutorial/Getting_Started") }}</p> + +<p><img alt="" class="internal" src="/@api/deki/files/348/=SVG_Overview.png" style="float: right;"><a href="/en-US/SVG" title="en-US/SVG">SVG</a> is an <a href="/en-US/XML" title="en-US/XML">XML</a> language, similar to <a href="/en-US/XHTML" title="en-US/XHTML">XHTML</a>, which can be used to draw vector graphics, such as the ones shown to the right. It can be used to create an image either by specifying all the lines and shapes necessary, by modifying already existing raster images, or by a combination of both. The image and its components can also be transformed, composited together, or filtered to change their appearance completely.</p> + +<p>SVG came about in 1999 after several competing formats had been submitted to the <a class="external" href="http://www.w3.org" title="en-US/W3C">W3C</a> and failed to be fully ratified. SVG is supported by all major <a href="https://caniuse.com/#search=svg">browsers</a>. A downside is loading SVG can be slow. SVG does offer benefits, some of which include having a <a href="/en-US/docs/Web/API">DOM interface</a> available for it, and not requiring third-party extensions. Whether or not to use it often depends on your specific use case.</p> + + + + + +<h3 id="Ingredientes_básicos">Ingredientes básicos</h3> + +<p><a href="/en-US/docs/Web/HTML">HTML</a> provides elements for defining headers, paragraphs, tables, and so on. In much the same way SVG provides elements for circles, rectangles, and simple and complex curves. A simple SVG document consists of nothing more than the {{ SVGElement('svg') }} root element and several basic shapes that build a graphic together. In addition there is the {{ SVGElement('g') }} element, which is used to group several basic shapes together.</p> + +<p>Starting from there, the SVG image can become arbitrarily complex. SVG supports gradients, rotations, filter effects, animations, interactivity with JavaScript, and so on. But all these extra features of the language rely on this relatively small set of elements to define the graphics area.</p> + +<h3 id="Before_you_start" name="Before_you_start">Antes de começar</h3> + +<p>There are a number of drawing applications available such as <a class="external" href="http://www.inkscape.org/">Inkscape</a> which are free and use SVG as their native file format. However, this tutorial will rely on the trusty XML or text editor (your choice). The idea is to teach the internals of SVG to those who want to understand it, and that is best done by dirtying your hands with a bit of markup. You should note your final goal though. Not all SVG viewers are equal and so there is a good chance that something written for one app will not display exactly the same in another, simply because they support different levels of the SVG specification or another specification that you are using along with SVG (that is, <a href="/en-US/JavaScript" title="en-US/JavaScript">JavaScript</a> or <a href="/en-US/CSS" title="en-US/CSS">CSS</a>).</p> + +<p>SVG is supported in all modern browsers and even a couple versions back in some cases. A fairly complete browser support table can be found on <a href="http://caniuse.com/svg">Can I use</a>. Firefox has supported some SVG content since version 1.5, and that support level has been growing with each release since. Hopefully, along with the tutorial here, MDN can help developers keep up with the differences between Gecko and some of the other major implementations.</p> + +<p>Before starting you should have a basic understanding of XML or another markup language such as <abbr title="HyperText Markup Language">HTML</abbr>. If you are not too familiar with XML, here are some guidelines to keep in mind:</p> + +<ul> + <li>SVG elements and attributes should all be entered in the case shown here since XML is case-sensitive (unlike HTML).</li> + <li>Attribute values in SVG must be placed inside quotes, even if they are numbers.</li> +</ul> + +<p>SVG is a huge specification. This tutorial attempts to cover the basics. Once you are familiar you should be able to use the <a href="/en-US/SVG/Element" title="en-US/SVG/Element">Element Reference</a> and the <a href="/en-US/docs/DOM/DOM_Reference#SVG_interfaces" title="en-US/SVG/Interface">Interface Reference</a> to find out anything else you need to know.</p> + +<h3 id="Flavors_of_SVG">Flavors of SVG</h3> + +<p>Since becoming a recommendation in 2003, the most recent "full" SVG version is 1.1. It builds on top of SVG 1.0, but adds more modularization to ease implementation. <a href="http://www.w3.org/TR/SVG/">The second edition of SVG 1.1</a> became a Recommendation in 2011. "Full" SVG 1.2 was meant to be the next major release of SVG. It was dropped for the upcoming <a href="http://www.w3.org/TR/SVG2/">SVG 2.0</a>, which is under heavy development right now and follows a similar approach to CSS 3 in that it splits components into several loosely coupled specifications.</p> + +<p>Apart from the full SVG recommendations, the working group at the W3C introduced SVG Tiny and SVG Basic in 2003. These two profiles are aimed mainly at mobile devices. The first, SVG Tiny, should yield graphics primitives for small devices with low capabilities. SVG Basic offers many features of full SVG, but doesn't include the ones which are hard to implement or heavy to render (like animations). In 2008, SVG Tiny 1.2 became a W3C Recommendation.</p> + +<p>There were plans for an SVG Print specification, which would add support for multiple pages and enhanced color management. This work was discontinued.</p> + +<p>{{ PreviousNext("Web/SVG/Tutorial", "Web/SVG/Tutorial/Getting_Started") }}</p> diff --git a/files/pt-pt/web/svg/tutorial/svg_na_introducao_html/index.html b/files/pt-pt/web/svg/tutorial/svg_na_introducao_html/index.html new file mode 100644 index 0000000000..5ca7a4c9e7 --- /dev/null +++ b/files/pt-pt/web/svg/tutorial/svg_na_introducao_html/index.html @@ -0,0 +1,179 @@ +--- +title: Introdução à SVG em HTML +slug: Web/SVG/Tutorial/SVG_na_Introducao_HTML +tags: + - Intermediário + - Precisa de Atualização + - SVG +translation_of: Web/SVG/Tutorial/SVG_In_HTML_Introduction +--- +<h2 id="Overview" name="Overview">Resumo</h2> + +<p>This article and its associated example shows how to use inline <a href="/pt-PT/docs/Web/SVG" title="SVG">SVG</a> to provide a background picture for a form. It shows how <a href="/pt-PT/docs/Web/JavaScript" title="JavaScript">JavaScript</a> and <a href="/pt-PT/docs/Web/CSS" title="CSS">CSS</a> can be used to manipulate the picture in the same way you would script regular XHTML. Note that the example will only work in browsers that support XHTML (not HTML) and SVG integration.</p> + +<h2 id="Source" name="Source">Fonte</h2> + +<p>Aqui tem a fonte para <a class="external" href="/presentations/xtech2005/svg-canvas/SVGDemo.xml" title="presentations/xtech2005/svg-canvas/SVGDemo.xml">o exemplo</a>:</p> + +<pre class="brush: html"><html xmlns="http://www.w3.org/1999/xhtml"> +<head> +<title>XTech SVG Demo</title> +<style> + stop.begin { stop-color:yellow; } + stop.end { stop-color:green; } + body.invalid stop.end { stop-color:red; } + #err { display:none; } + body.invalid #err { display:inline; } +</style> +<script> + function signalError() { + document.getElementById('body').setAttribute("class", "invalid"); + } +</script> +</head> +<body id="body" + style="position:absolute; z-index:0; border:1px solid black; left:5%; top:5%; width:90%; height:90%;"> +<form> + <fieldset> + <legend>HTML Form</legend> + <p><label>Enter something:</label> + <input type="text"/> + <span id="err">Incorrect value!</span></p> + <p><input type="button" value="Activate!" onclick="signalError();" /></p> + </fieldset> +</form> + +<svg xmlns="http://www.w3.org/2000/svg" version="1.1" + viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice" + style="width:100%; height:100%; position:absolute; top:0; left:0; z-index:-1;"> + <linearGradient id="gradient"> + <stop class="begin" offset="0%"/> + <stop class="end" offset="100%"/> + </linearGradient> + <rect x="0" y="0" width="100" height="100" style="fill:url(#gradient)" /> + <circle cx="50" cy="50" r="30" style="fill:url(#gradient)" /> +</svg> +</body> +</html> +</pre> + +<h2 id="Discussion" name="Discussion">Discussão</h2> + +<p>The page is mainly regular XHTML, CSS and JavaScript. The only interesting part is the <svg> element it contains. This element and its children are declared to be in the SVG namespace. The element contains a gradient and two shapes filled with the gradient. The gradient color stops have their colors set by CSS. When the user enters something incorrect into the form, the script sets the <code>invalid</code> attribute on the <body>, and a style rule changes the gradient <code>end-stop</code> color to red. (Another style rule makes an error message appear.)</p> + +<p>This approach has the following points in its favor:</p> + +<ul> + <li>We have taken a regular XHTML form that could have been part of an existing Web site, and added an attractive, interactive background</li> + <li>The approach is backwards compatible to browsers that do not support SVG; simply, no background appears in them</li> + <li>It's very simple and performs very well</li> + <li>The picture dynamically sizes itself to the required size in an intelligent way</li> + <li>We can have declarative style rules applying to both HTML and SVG</li> + <li>The same script manipulates both HTML and SVG</li> + <li>The document is entirely standards-based</li> +</ul> + +<div class="note"> +<p>To add a linked image with DOM methods to an embedded SVG element, one has to use <code>setAttributeNS</code> to set <code>href</code>. Like in the following example:</p> + +<pre class="brush: js"> var img = document.createElementNS("http://www.w3.org/2000/svg", "image"); +img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "move.png"); + + +</pre> +</div> + +<h2 id="Details" name="Details">Detalhes</h2> + +<p>The <code>viewBox</code> attribute establishes a logical coordinate system which the SVG picture's coordinates are relative to. In this case our picture is laid out in a 100 by 100 viewport.</p> + +<p>The <code>preserveAspectRatio</code> attribute specifies that the aspect ratio must be preserved by centering the picture in the available size, sizing to the maximum of the height or width and then cutting off any overflow.</p> + +<p>The <code>style</code> attribute pins the SVG element to the background of the form.</p> + +<h2 id="Related_Links" name="Related_Links">Hiperligações Relacionadas</h2> + +<ul> + <li>Another SVG in XHTML example: <a href="/en-US/docs/SVG/Namespaces_Crash_Course/Example" title="SVG/Namespaces_Crash_Course/Example">A swarm of motes</a></li> + <li><a class="external" href="/pt-PT/docs/Web/SVG/Namespaces_Crash_Course/Exemplo">Working example</a> that works in both Mozilla and in Internet Explorer with Adobe's SVG Viewer installed. (For inline SVG to work in both Firefox and Internet Explorer it is necessary to serve documents with a different Content-Type to each browser. For this reason, if you're behind a proxy server that caches the page, the example wont work in the second browser you load it in because it will receive the wrong Content-Type.)</li> +</ul> + + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: none; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/tutoriais/index.html b/files/pt-pt/web/tutoriais/index.html new file mode 100644 index 0000000000..e0483e1b8a --- /dev/null +++ b/files/pt-pt/web/tutoriais/index.html @@ -0,0 +1,252 @@ +--- +title: Tutoriais +slug: Web/Tutoriais +tags: + - CSS Guia + - Código + - Desenho da Web + - Fundamental da Web + - HTML + - JavaScript + - MDN + - Principiante + - Tutorial +translation_of: Web/Tutorials +--- +<p>As hiperligações nesta página encaminham para uma variedade de tutoriais e materiais de treino. Se está apenas a começar, a aprender o básico, ou é uma mão antiga no desenvolvimento da Web, pode encontrar aqui recursos úteis para as melhores práticas.</p> + +<p>Estes recursos são criados por empresas que pensam no futuro e programadores da <em>Web</em> que abraçaram os padrões abertos e as melhores práticas para o desenvolvimento da <em>Web</em> e que fornecem ou permitem traduções, através de uma licença de conteúdo aberto, tal como Creative Commons. .</p> + +<h2 id="Para_os_principiantes_na_Web">Para os principiantes na Web</h2> + +<dl> + <dt><a href="/pt-PT/docs/Learn/Comecar_com_a_Web">Primeiros passos na Web </a></dt> + <dd><em>Getting started with the Web</em> is a concise series introducing you to the practicalities of web development. You'll set up the tools you need to construct a simple webpage and publish your own simple code.</dd> +</dl> + +<h2 class="Documentation" id="Documentation" name="Documentation">HTML - Tutoriais</h2> + +<h3 id="Nível_introdutório">Nível introdutório</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/HTML/Introduction_to_HTML">Introduction to HTML</a></dt> + <dd>This module sets the stage, getting you used to important concepts and syntax, looking at applying HTML to text, how to create hyperlinks, and how to use HTML to structure a webpage.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/HTML/Element">MDN HTML element reference</a></strong></dt> + <dd>A comprehensive reference for HTML elements, and how the different browsers support them.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><strong><a href="https://www.theblogstarter.com/html-for-beginners">Creating a Simple Web Page with HTML</a> (The Blog Starter)</strong></dt> + <dd>An HTML guide for beginners that includes explanations of common tags, including HTML5 tags. Also includes a step-by-step guide to creating a basic web page with code examples.</dd> + <dt><strong><a href="http://bit.ly/2z9xSS2">Beginner's Guide to HTML</a> (Website Setup)</strong></dt> + <dd>This HTML guide for beginners teaches you how to set up a basic website using HTML and NEW HTML5 tags. Simple step-by-step tutorial with images and resources that you can use to improve your coding skills.</dd> + <dt><strong><a href="http://wikiversity.org/wiki/Web_Design/HTML_Challenges" rel="external">HTML Challenges</a> (Wikiversity)</strong></dt> + <dd>Use these challenges to hone your HTML skills (for example, "Should I use an <h2> element or a <strong> element?"), focusing on meaningful mark-up.</dd> +</dl> +</div> +</div> + +<h3 id="Nível_intermediário">Nível intermediário</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/HTML/Multimedia_and_embedding">Multimedia and embedding</a></dt> + <dd>This module explores how to use HTML to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire other webpages.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt></dt> + <dt><a href="/en-US/docs/Learn/HTML/Tables">HTML tables</a></dt> + <dd>Representing tabular data on a webpage in an understandable, {{glossary("Accessibility", "accessible")}} way can be a challenge. This module covers basic table markup, along with more complex features such as implementing captions and summaries.</dd> +</dl> +</div> +</div> + +<h3 id="Nível_avançado">Nível avançado</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/HTML/Forms">HTML forms</a></dt> + <dd>Forms are a very important part of the Web — these provide much of the functionality you need for interacting with web sites, e.g. registering and logging in, sending feedback, buying products, and more. This module gets you started with creating the client-side parts of forms.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/Tips_for_Authoring_Fast-loading_HTML_Pages">Tips for authoring fast-loading HTML pages</a></strong></dt> + <dd>Optimize web pages to provide a more responsive site for visitors and reduce the load on your web server and Internet connection.</dd> +</dl> +</div> +</div> + +<h2 class="Documentation" id="Documentation" name="Documentation">CSS - Tutoriais</h2> + +<h3 id="Nível_introdutório_2">Nível introdutório</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics">CSS basics</a></dt> + <dd>CSS (Cascading Style Sheets) is the code you use to style your webpage. <em>CSS Basics</em> takes you through what you need to get started. We'll answer questions like: How do I make my text black or red? How do I make my content show up in such-and-such a place on the screen? How do I decorate my webpage with background images and colors?</dd> + <dt><a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introduction to CSS</a></dt> + <dd>This module goes in depth with how CSS works, including selectors and properties, writing CSS rules, applying CSS to HTML, how to specify length, color, and other units in CSS, cascade and inheritance, box model basics, and debugging CSS.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/CSS/Styling_boxes">Styling boxes</a></dt> + <dd>Next up, we look at styling boxes, one of the fundamental steps towards laying out a web page. In this module we recap the box model then look at controlling box layouts by setting padding, borders and margins, setting custom background colors, images and other features, and fancy features such as drop shadows and filters on boxes.</dd> + <dt><a href="/en-US/docs/Learn/CSS/Styling_text">Styling text</a></dt> + <dd>Here we look at text styling fundamentals, including setting font, boldness, and italics, line and letter spacing, and drop shadows and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/Common_CSS_Questions">Common CSS Questions</a></strong></dt> + <dd>Common questions and answers for beginners.</dd> +</dl> +</div> +</div> + +<h3 id="Nível_intermediário_2">Nível intermediário</h3> + +<div class="row topicpage-table" style="width: 100%;"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/CSS/CSS_layout">CSS layout</a></dt> + <dd>At this point we've already looked at CSS fundamentals, how to style text, and how to style and manipulate the boxes that your content sits inside. Now it's time to look at how to place your boxes in the right place in relation to the viewport, and one another. We have covered the necessary prerequisites so can now dive deep into CSS layout, looking at different display settings, traditional layout methods involving float and positioning, and new fangled layout tools like flexbox.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_Reference">CSS reference</a></strong></dt> + <dd>Complete reference to CSS, with details on support by Firefox and other browsers.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><strong><a href="http://www.alistapart.com/articles/fluidgrids/" rel="external">Fluid Grids</a> (A List Apart)</strong></dt> + <dd>Design layouts that fluidly resize with the browser window, while still using a typographic grid.</dd> + <dt><strong><a href="http://en.wikiversity.org/wiki/Web_Design/CSS_challenges" rel="external">CSS Challenges</a> (Wikiversity)</strong></dt> + <dd>Flex your CSS skills, and see where you need more practice.</dd> +</dl> +</div> +</div> + +<h3 id="Nível_avançado_2">Nível avançado</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><strong><a href="/en-US/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms">Using CSS transforms</a></strong></dt> + <dd>Apply rotation, skewing, scaling, and translation using CSS.</dd> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/CSS/CSS_transitions">CSS transitions</a></strong></dt> + <dd>CSS transitions, part of the draft CSS3 specification, provide a way to animate changes to CSS properties, instead of having the changes take effect instantly.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><strong><a href="http://www.html5rocks.com/tutorials/webfonts/quick/" rel="external">Quick Guide to Implement Web Fonts with @font-face</a> (HTML5 Rocks)</strong></dt> + <dd>The @font-face feature from CSS3 allows you to use custom typefaces on the web in an accessible, manipulatable, and scalable way.</dd> + <dt><strong><a href="http://davidwalsh.name/starting-css" rel="external">Starting to Write CSS</a> (David Walsh)</strong></dt> + <dd>An introduction to tools and methodologies to write more succinct, maintainable, and scalable CSS.</dd> +</dl> +</div> +</div> + +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Web/API/Canvas_API/Tutorial">Canvas tutorial</a></dt> + <dd>Learn how to draw graphics using scripting using the canvas element.</dd> + <dt><strong><a href="http://html5doctor.com/" rel="external">HTML5 Doctor</a></strong></dt> + <dd>Articles about using HTML5 right now.</dd> +</dl> +</div> + +<h2 class="Documentation" id="Documentation" name="Documentation">Javascript - Tutoriais</h2> + +<h3 id="Nível_introdutório_3">Nível introdutório</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt></dt> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a></dt> + <dd>In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key JavaScript features in detail, such as variables, strings, numbers and arrays.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks">JavaScript building blocks</a></dt> + <dd>In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly.</dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics">Getting started with JavaScript</a></dt> + <dd>What is JavaScript and how can it help you?</dd> + <dt><strong><a href="http://www.codecademy.com/">Codecademy</a> (Codecademy)</strong></dt> + <dd>Codecademy is a easy way to learn how to code JavaScript. It's interactive and you can do it with your friends.</dd> +</dl> +</div> +</div> + +<h3 id="Nível_intermediário_3">Nível intermediário</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects">Introducing JavaScript objects</a></dt> + <dd>In JavaScript, most things are objects, from core JavaScript features like strings and arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs">Client-side web APIs</a></dt> + <dd>When writing client-side JavaScript for web sites or applications, you won't go very far before you start to use APIs — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other web sites or services. In this module we will explore what APIs are, and how to use some of the most common APIs you'll come across often in your development work. </dd> +</dl> +</div> + +<div class="section"> +<dl> + <dt><strong><a href="https://developer.mozilla.org/en-US/docs/A_re-introduction_to_JavaScript">A re-Introduction to JavaScript</a></strong></dt> + <dd>A recap of the JavaScript programming language aimed at intermediate-level developers.</dd> + <dt><strong><a href="http://eloquentjavascript.net/" rel="external">Eloquent JavaScript</a></strong></dt> + <dd>A comprehensive guide to intermediate and advanced JavaScript methodologies.</dd> + <dt><strong><a href="http://speakingjs.com/es5/" rel="external">Speaking JavaScript</a> (Dr. Axel Rauschmayer)</strong></dt> + <dd>For programmers who want to learn JavaScript quickly and properly, and for JavaScript programmers who want to deepen their skills and/or look up specific topics.</dd> + <dt><strong><a href="http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/" rel="external">Essential JavaScript Design Patterns</a> (Addy Osmani)</strong></dt> + <dd>An introduction to essential JavaScript design patterns.</dd> +</dl> +</div> +</div> + +<h3 id="Nível_avançado_3">Nível avançado</h3> + +<div class="row topicpage-table"> +<div class="section"> +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a></dt> + <dd>A comprehensive, regularly updated guide to JavaScript for all levels of learning from beginner to advanced.</dd> + <dt><strong><a href="https://github.com/getify/You-Dont-Know-JS" rel="external">You Don't Know JS</a> (Kyle Simpson)</strong></dt> + <dd>A series of books diving deep into the core mechanisms of the JavaScript language.</dd> + <dt><strong><a href="http://bonsaiden.github.com/JavaScript-Garden/" rel="external">JavaScript Garden</a></strong></dt> + <dd>Documentation of the most quirky parts of JavaScript.</dd> + <dt><strong><a href="http://exploringjs.com/es6/" rel="external">Exploring ES6</a> (Dr. Axel Rauschmayer)</strong></dt> + <dd>Reliable and in-depth information on ECMAScript 2015.</dd> +</dl> +</div> + +<div class="section"><strong><a href="http://shichuan.github.io/javascript-patterns" rel="external">Javascipt Patterns</a></strong> + +<dl> + <dd>A JavaScript pattern and antipattern collection that covers function patterns, jQuery patterns, jQuery plugin patterns, design patterns, general patterns, literals and constructor patterns, object creation patterns, code reuse patterns, DOM.</dd> + <dt><strong><a href="http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/">How browsers work</a></strong></dt> + <dd>A detailed research article describing different modern browsers, their engines, page rendering etc.</dd> + <dt><a href="https://github.com/bolshchikov/js-must-watch">JavaScript Videos</a> (GitHub)</dt> + <dd>A collection of JavaScript videos to watch.</dd> +</dl> +</div> +</div> + +<h3 id="Desenvolvimento_de_Extensão">Desenvolvimento de Extensão</h3> + +<div class="row topicpage-table" style="width: 100%;"> +<div class="section"> +<dl> + <dt><a href="/pt-PT/Add-ons/WebExtensions">WebExtensions</a></dt> + <dd>WebExtensions is a cross-browser system for developing browser add-ons. To a large extent the system is compatible with the <a class="external-icon external" href="https://developer.chrome.com/extensions">extension API</a> supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/extensions/">Microsoft Edge</a> with <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Porting_from_Google_Chrome">just a few changes</a>. The API is also fully compatible with <a href="https://developer.mozilla.org/en-US/Firefox/Multiprocess_Firefox">multiprocess Firefox</a>.</dd> +</dl> +</div> +</div> diff --git a/files/pt-pt/web/webapi/index.html b/files/pt-pt/web/webapi/index.html new file mode 100644 index 0000000000..948e03e480 --- /dev/null +++ b/files/pt-pt/web/webapi/index.html @@ -0,0 +1,213 @@ +--- +title: WebAPI +slug: Web/WebAPI +tags: + - Aplicações + - Apps + - DOM + - Firefos OS + - Movel +translation_of: Web/API +--- +<p><strong>WebAPI</strong> é um termo utilizado para referir um conjunto de compatibilidade de dispositivo e APIs de acesso que permitem que as aplicações da Web e o conteúdo acedam ao dispositivo de hardware (tais como estado da bateria ou hardware de vibração do dispositivo), bem como aceder aos dados guardados no dispositivo (tais como o calendário ou lista de contactos). Ao adicionarmos estas APIs, nós esperamos que expanda o que a <em>Web</em> pode fazer hoje, para também incluirem o que apenas as plataformas proprietárias podiam fazer no passado.</p> + +<div class="note"> +<p><strong>Nota:</strong> para uma breve explicação de cada distintivo, por favor, consulte a documentação <a href="/pt-PT/docs/Mozilla/Marketplace/Options/Aplicacoes_empacotadas#Tipos_de_aplicações_empacotadas" title="Web/Apps/Packaged_apps#Types_of_packaged_apps">pdas aplicações empacotadas</a>.</p> +</div> + +<div class="row topicpage-table"> +<div class="section"> +<h2 class="Documentation" id="Communication_APIs" name="Communication_APIs">APIs de Comunicação</h2> + +<dl> + <dt><a href="/en-US/docs/WebAPI/Network_Information" title="WebAPI/Network_Information">Network Information API</a></dt> + <dd>Provides basic information about the current network connection, such as connection speed.</dd> + <dt><a href="/en-US/docs/WebAPI/WebBluetooth" title="WebAPI/WebBluetooth">Bluetooth</a> {{NonStandardBadge}}</dt> + <dd>The WebBluetooth API provides low-level access to the device's Bluetooth hardware.</dd> + <dt><a href="/en-US/docs/WebAPI/Mobile_Connection" title="WebAPI/Mobile_Connection">Mobile Connection API</a> {{NonStandardBadge}}</dt> + <dd>Exposes information about the device's cellular connectivity, such as signal strength, operator information, and so forth.</dd> + <dt><a href="/en-US/docs/WebAPI/Network_Stats" title="WebAPI/Network_Stats">Network Stats API</a> {{NonStandardBadge}}</dt> + <dd>Monitors data usage and exposes this data to privileged applications.</dd> + <dt><a href="/en-US/docs/WebAPI/WebTelephony" title="WebAPI/WebTelephony">Telephony</a> {{NonStandardBadge}}</dt> + <dd>Lets apps place and answer phone calls and use the built-in telephony user interface.</dd> + <dt><a href="/en-US/docs/WebAPI/WebSMS" title="WebAPI/WebSMS">WebSMS </a>{{NonStandardBadge}}</dt> + <dd>Lets apps send and receive SMS text messages, as well as to access and manage the messages stored on the device.</dd> + <dt><a href="/en-US/docs/WebAPI/WiFi_Information" title="WebAPI/WiFi_Information">WiFi Information API</a> {{NonStandardBadge}}</dt> + <dd>A privileged API which provides information about signal strength, the name of the current network, available WiFi networks, and so forth.</dd> +</dl> + +<h2 class="Documentation" id="Hardware_access_APIs" name="Hardware_access_APIs">APIs de acesso ao hardware</h2> + +<dl> + <dt><a href="/en-US/docs/WebAPI/Using_Light_Events">Ambient Light Sensor API</a></dt> + <dd>Provides access to the ambient light sensor, which lets your app detect the ambient light level in the vicinity of the device.</dd> + <dt><a href="/en-US/docs/WebAPI/Battery_Status" title="WebAPI/Battery_Status">Battery Status API</a></dt> + <dd>Provides information about the battery's charge level and whether or not the device is currently plugged in and charging.</dd> + <dt><a href="/en-US/docs/Using_geolocation" title="Using_geolocation">Geolocation API</a></dt> + <dd>Provides information about the device's physical location.</dd> + <dt><a href="/en-US/docs/WebAPI/Pointer_Lock" title="API/Pointer_Lock_API">Pointer Lock API</a></dt> + <dd>Lets apps lock access to the mouse and gain access to movement deltas rather than absolute coordinates; this is great for gaming.</dd> + <dt><a href="/en-US/docs/WebAPI/Proximity" title="WebAPI/Proximity">Proximity API</a></dt> + <dd>Lets you detect proximity of the device to a nearby object, such as the user's face.</dd> + <dt><a href="/en-US/docs/WebAPI/Detecting_device_orientation" title="WebAPI/Detecting_device_orientation">Device Orientation API</a></dt> + <dd>Provides notifications when the device's orientation changes.</dd> + <dt><a href="/en-US/docs/WebAPI/Managing_screen_orientation" title="WebAPI/Detecting_device_orientation">Screen Orientation API</a></dt> + <dd>Provides notifications when the screen's orientation changes. You can also use this API to let your app indicate what orientation it prefers.</dd> + <dt><a href="/en-US/docs/WebAPI/Vibration" title="WebAPI/Vibration">Vibration API</a></dt> + <dd>Lets apps control the device's vibration hardware for things such as haptic feedback in games. This is <strong>not</strong> intended for things such as notification vibrations. See the <a href="/en-US/docs/WebAPI/Alarm" title="WebAPI/Alarm">Alarm API</a> for that.</dd> + <dt><a href="/en-US/docs/WebAPI/Camera" title="WebAPI/Camera">Camera API</a> {{NonStandardBadge}}</dt> + <dd>Allows apps to take photographs and/or record video using the device's built-in camera.</dd> + <dt><a href="/en-US/docs/WebAPI/Power_Management" title="WebAPI/Power_Management">Power Management API </a>{{NonStandardBadge}}</dt> + <dd>Lets apps turn on and off the screen, CPU, device power, and so forth. Also provides support for listening for and inspecting resource lock events.</dd> +</dl> + +<p><span class="alllinks"><a href="/en-US/docs/tag/WebAPI" title="tag/CSS">View All...</a></span></p> +</div> + +<div class="section"> +<h2 class="Documentation" id="Data_management_APIs" name="Data_management_APIs">APIs de gestão de dados</h2> + +<dl> + <dt><a href="/en-US/docs/WebAPI/FileHandle_API" title="WebAPI/FileHandle_API">FileHandle API</a> {{NonStandardBadge}}</dt> + <dd>Provides support for writable files with locking support.</dd> + <dt><a href="/en-US/docs/IndexedDB" title="IndexedDB">IndexedDB</a></dt> + <dd>Client-side storage of structured data with support for high-performance searches.</dd> + <dt><a href="/en-US/docs/WebAPI/Settings" title="WebAPI/Settings">Settings API</a> {{NonStandardBadge}}</dt> + <dd>Lets apps examine and change system-wide configuration options that are permanently stored on the device.</dd> +</dl> + +<h2 class="Documentation" id="Other_APIs" name="Other_APIs">Outras APIs</h2> + +<dl> + <dt><a href="/en-US/docs/WebAPI/Alarm" title="WebAPI/Alarm">Alarm API</a></dt> + <dd>Lets apps schedule notifications. Also provides support for automatically launching an app at a specific time.</dd> + <dt><a href="/en-US/docs/WebAPI/Simple_Push" title="WebAPI/Push_Notifications">Simple Push API</a></dt> + <dd>Lets the platform send notification messages to specific applications.</dd> + <dt><a href="/en-US/docs/Web/API/Push_API">Push API</a></dt> + <dd>Gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent.</dd> + <dt><a href="/en-US/docs/WebAPI/Using_Web_Notifications" title="/en-US/docs/WebAPI/Using_Web_Notifications">Web Notifications</a></dt> + <dd>Lets applications send notifications displayed at the system level.</dd> + <dt><a href="/en-US/docs/Web/API/Apps" title="Apps">Apps API</a> {{NonStandardBadge}}</dt> + <dd>The Open WebApps API provides support for installing and managing Web apps. In addition, support is provided to let apps determine payment information.</dd> + <dt><a href="/en-US/docs/WebAPI/Web_Activities" title="WebAPI/Web_Activities">Web Activities</a> {{NonStandardBadge}}</dt> + <dd>Lets an app delegate an activity to another app; for example, an app might ask another app to select (or create) and return a photo. Typically the user is able to configure what apps are used for which activities.</dd> + <dt><a href="/en-US/docs/Apps/Publishing/In-app_payments" title="Apps/Publishing/In-app_payments">WebPayment API</a> {{NonStandardBadge}}</dt> + <dd>Lets Web content initiate payments and refunds for virtual goods.</dd> + <dt><a href="/en-US/docs/DOM/Using_the_Browser_API" title="DOM/Using_the_Browser_API"><strong>Browser API</strong></a> {{NonStandardBadge}}</dt> + <dd>Provides support for building a Web browser completely using Web technologies (in essence, a browser within a browser).</dd> +</dl> + +<dl> + <dt><a href="/en-US/docs/WebAPI/Idle" title="WebAPI/Device_Storage_API">Idle API</a></dt> + <dd>Lets apps receive notifications when the user is not actively using the device.</dd> + <dt><a href="/en-US/docs/WebAPI/Permissions" title="WebAPI/Permissions">Permissions API</a> {{NonStandardBadge}}</dt> + <dd>Manages app permissions in a centralized location. Used by the Settings app.</dd> + <dt><a href="/en-US/docs/WebAPI/Time_and_Clock" title="WebAPI/Time_and_Clock">Time/Clock API</a> {{NonStandardBadge}}</dt> + <dd>Provides support for setting the current time. The time zone is set using the <a href="/en-US/docs/WebAPI/Settings" title="WebAPI/Settings">Settings API</a>.</dd> +</dl> + +<h2 class="Community" id="Community" name="Community">Comunidade de WebAPI</h2> + +<p>If you need help with these APIs, there are several ways you can talk to other developers making use of them.</p> + +<ul> + <li>Consult the WebAPI forum: {{DiscussionList("dev-webapi", "mozilla.dev.webapi")}}</li> + <li>Visit the WebAPI IRC channel: <a href="irc://irc.mozilla.org/webapi" title="irc://irc.mozilla.org/webapi">#webapi</a></li> +</ul> + +<p><span class="alllinks"><a href="http://www.catb.org/~esr/faqs/smart-questions.html" title="http://www.catb.org/~esr/faqs/smart-questions.html">Não se esqueça sobre a <em>netiquette</em>...</a></span></p> + +<h2 class="Related_Topics" id="Related_Topics" name="Related_Topics">Tópicos Relacionados</h2> + +<ul> + <li>O <a href="/pt-PT/docs/DOM/DOM_Reference" title="Document Object Model (DOM)">Modelo de Objeto de Documento (DOM)</a> é a representação de um documento HTML como uma árvore.</li> + <li><a href="/pt-PT/docs/Web/JavaScript" title="JavaScript">JavaScript</a> - Linguagem de <em>scripting para a </em>Web.</li> + <li><a href="/pt-PT/docs/MDN/Doc_status/API" title="WebAPI/Doc_status">Estado do documento</a>: Uma lista dos tópicos de WebAPI e o seu estado da documentação.</li> +</ul> +</div> +</div> + +<p> </p> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: 0% 0% repeat scroll rgba(0, 0, 0, 0); opacity: 1; display: none; left: -8px; top: -25px;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/xml/index.html b/files/pt-pt/web/xml/index.html new file mode 100644 index 0000000000..e8b7c11430 --- /dev/null +++ b/files/pt-pt/web/xml/index.html @@ -0,0 +1,15 @@ +--- +title: 'XML:- Linguagem de Marcação Extensível' +slug: Web/XML +tags: + - Draft + - Landing + - Web + - XML +translation_of: Web/XML +--- +<p>{{QuickLinksWithSubpages("/pt-PT/docs/Web/XML")}}</p> + +<p class="summary">A <strong>Linguagem de Marcação Extensível </strong>é uma a serialização estrita do <a href="pt-PT/docs/DOM/DOM_Reference">Modelo de Objeto de Documento</a>.</p> + +<p>{{LandingPageListSubpages}}</p> diff --git a/files/pt-pt/web/xml/introducao_a_xml/index.html b/files/pt-pt/web/xml/introducao_a_xml/index.html new file mode 100644 index 0000000000..c4820a1245 --- /dev/null +++ b/files/pt-pt/web/xml/introducao_a_xml/index.html @@ -0,0 +1,204 @@ +--- +title: Introdução à XML +slug: Web/XML/Introducao_a_XML +tags: + - Introdução + - Principiante + - XML +translation_of: Web/XML/XML_introduction +--- +<p><span class="seoSummary">XML é uma linguagem de marcação similar à HTML. It stands for Extensible Markup Language and is a <a class="external" href="/web/20150905131205/http://www.w3.org/">W3C recommended</a> specification as a general purpose markup language. This means, unlike other markup languages, XML is not predefined so you must define your own tags. The primary purpose of the language is the sharing of data across different systems, such as the Internet.</span></p> + +<p>There are many languages based on XML; Some examples are <a href="/en-US/docs/Glossary/XHTML" title="en/XHTML">XHTML</a>, <a href="/en-US/docs/Web/MathML" title="en/MathML">MathML</a>, <a href="/en-US/docs/Web/SVG" title="en/SVG">SVG</a>, <a href="/en-US/docs/Mozilla/Tech/XUL" title="en/XUL">XUL</a>, <a href="/en-US/docs/Mozilla/Tech/XBL" title="en/XBL">XBL</a>, <a href="/en-US/docs/Web/RSS" title="en/RSS">RSS</a>, and <a href="/en-US/docs/Web/RDF" title="en/RDF">RDF</a>. You can also create your own.</p> + +<h2 id="Correct_XML_(valid_and_well-formed)">"Correct" XML (valid and well-formed)</h2> + +<p>For an XML document to be correct it must be a well-formed document, conforming to all of XML's syntax rules, and valid, conforming to a specific language's rules. An example of a document that is not well formed is one with an element that has an opening tag with no closing tag and is not self-closing.</p> + +<h3 id="Exemplo">Exemplo</h3> + +<p>In the below example, we see a document in which a tag that isn't self-closing has no closing tag.</p> + +<pre class="brush: xml"><message> + <warning> + Hello World + <!--missing </warning> --> +</message> +</pre> + +<p>Now let's look at a corrected version of that same document:</p> + +<pre class="brush: xml"><message> + <warning> + Hello World + </warning> +</message> +</pre> + +<p>To be valid, an XML document needs to conform to some semantic rules which are usually set in an XML schema or a <strong><a href="/en-US/docs/Glossary/DTD" title="en/DTD">Document Type Definition</a></strong> (DTD). A document that contains an undefined tag is invalid. For example, if we never defined the <code><warning></code> tag, the document above wouldn't be valid.</p> + +<div class="note"> +<p>Most browsers offer a debugger that can identify poorly-formed XML documents.</p> +</div> + +<h2 id="Entities" name="Entities">Entidades</h2> + +<p>Like HTML, XML offers methods (called entities) for referring to some special reserved characters (such as a greater than sign which is used for tags). There are five of these characters that you should know:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Entidade</th> + <th scope="col">Cárater</th> + <th scope="col">Descrição</th> + </tr> + </thead> + <tbody> + <tr> + <td>&lt;</td> + <td><</td> + <td>Less than sign</td> + </tr> + <tr> + <td>&gt;</td> + <td>></td> + <td>Greater than sign</td> + </tr> + <tr> + <td>&amp;</td> + <td>&</td> + <td>Ampersand</td> + </tr> + <tr> + <td>&quot;</td> + <td>"</td> + <td>One double-quotation mark</td> + </tr> + <tr> + <td>&apos;</td> + <td>'</td> + <td>One apostrophe (or single-quotation mark)</td> + </tr> + </tbody> +</table> + +<p>Even though there are only 5 declared entities, more can be added using the document's <a href="/en-US/docs/Glossary/DTD" title="en/DTD">Document Type Definition</a>. For example, to create a new <code>&warning;</code> entity, you can do this:</p> + +<pre><?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE body [ + <!ENTITY warning "Warning: Something bad happened... please refresh and try again."> +]> +<body> + <message> &warning; </message> +</body> +</pre> + +<p>You can also use numeric character references to specify special characters; for example, &#xA9; is the "©" symbol.</p> + +<h2 id="Exibir_XML">Exibir XML</h2> + +<p>XML is usually used for descriptive purposes, but there are ways to display XML data. If you don't define a specific way for the XML to be rendered, the raw XML is displayed in the browser.</p> + +<p>One way to style XML output is to specify <a href="/en-US/docs/Web/CSS" title="en/CSS">CSS</a> to apply to the document using the <code>xml-stylesheet</code> processing instruction.</p> + +<pre><?xml-stylesheet type="text/css" href="stylesheet.css"?></pre> + +<p>There is also another more powerful way to display XML: the <strong>Extensible Stylesheet Language Transformations</strong> (<a href="/en-US/docs/Web/XSLT" title="en/XSLT">XSLT</a>) which can be used to transform XML into other languages such as HTML. This makes XML incredibly versatile.</p> + +<pre><?xml-stylesheet type="text/xsl" href="transform.xsl"?></pre> + +<h2 id="Recommendations" name="Recommendations">Recomendações</h2> + +<p>This article is obviously only a very brief introduction to what XML is, with a few small examples and references to get you started. For more details about XML, you should look around on the Web for more in-depth articles.</p> + +<p>Learning the HyperText Markup Language (<a href="/en-US/docs/Web/HTML" title="en/HTML">HTML</a>) will help you better understand XML.</p> + +<h2 id="Consulte_também">Consulte também</h2> + +<ul> + <li><a class="external" href="http://www.xml.com/">XML.com</a></li> + <li><a class="external" href="https://www.w3.org/XML/">Extensible Markup Language (XML) @ W3.org</a></li> + <li><a class="external" href="http://www.alistapart.com/d/usingxml/xml_uses_a.html">XML Example: A List Apart</a></li> + <li><a class="external" href="http://www.alistapart.com/articles/usingxml/">Using XML: A List Apart</a></li> +</ul> + +<p>O artigo <a href="http://www.alistapart.com/articles/usingxml/"><em>Using</em> XML</a> acima, é um grande recurso de informação para transformar e criar a sua própria linguagem.</p> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; opacity: 0; display: none; left: -8px; top: -25px; transition: visibility 2s ease 0s, opacity 2s linear 0s;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody><tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detectar idioma</option><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Alternar Idiomas"> </div> + </td> + <td class="SL_td"><select><option value="af">Africâner</option><option value="sq">Albanês</option><option value="de">Alemão</option><option value="ar">Arabe</option><option value="hy">Armênio</option><option value="az">Azerbaijano</option><option value="eu">Basco</option><option value="bn">Bengali</option><option value="be">Bielo-russo</option><option value="my">Birmanês</option><option value="bs">Bósnio</option><option value="bg">Búlgaro</option><option value="ca">Catalão</option><option value="kk">Cazaque</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinês (Simp)</option><option value="zh-TW">Chinês (Trad)</option><option value="si">Cingalês</option><option value="ko">Coreano</option><option value="ht">Crioulo haitiano</option><option value="hr">Croata</option><option value="da">Dinamarquês</option><option value="sk">Eslovaco</option><option value="sl">Esloveno</option><option value="es">Espanhol</option><option value="eo">Esperanto</option><option value="et">Estoniano</option><option value="fi">Finlandês</option><option value="fr">Francês</option><option value="gl">Galego</option><option value="cy">Galês</option><option value="ka">Georgiano</option><option value="el">Grego</option><option value="gu">Gujarati</option><option value="ha">Hauça</option><option value="iw">Hebraico</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="nl">Holandês</option><option value="hu">Húngaro</option><option value="ig">Igbo</option><option value="id">Indonésio</option><option selected value="en">Inglês</option><option value="yo">Ioruba</option><option value="ga">Irlandês</option><option value="is">Islandês</option><option value="it">Italiano</option><option value="ja">Japonês</option><option value="jw">Javanês</option><option value="kn">Kannada</option><option value="km">Khmer</option><option value="lo">Laosiano</option><option value="la">Latim</option><option value="lv">Letão</option><option value="lt">Lituano</option><option value="mk">Macedônico</option><option value="ml">Malaiala</option><option value="ms">Malaio</option><option value="mg">Malgaxe</option><option value="mt">Maltês</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongol</option><option value="ne">Nepalês</option><option value="no">Norueguês</option><option value="fa">Persa</option><option value="pl">Polonês</option><option value="pt">Português</option><option value="pa">Punjabi</option><option value="ro">Romeno</option><option value="ru">Russo</option><option value="sr">Sérvio</option><option value="st">Sesotho</option><option value="so">Somália</option><option value="sw">Suaíli</option><option value="su">Sudanês</option><option value="sv">Sueco</option><option value="tg">Tadjique</option><option value="tl">Tagalo</option><option value="th">Tailandês</option><option value="ta">Tâmil</option><option value="cs">Tcheco</option><option value="te">Telugo</option><option value="tr">Turco</option><option value="uk">Ucraniano</option><option value="ur">Urdu</option><option value="uz">Uzbeque</option><option value="vi">Vietnamita</option><option value="yi">Yiddish</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ouça"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Copiar"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Tamanho da fonte"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Ajuda"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Fixar a janela de pop-up"> </div> + </td> + </tr> +</tbody></table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">A função de fala é limitada a 200 caracteres</div> + +<div id="SL_Balloon_options" style="background: rgb(255, 255, 255) repeat scroll 0% 0%;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody><tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%;" title="Mostrar o botão do ImTranslator 3 segundos"> </div> + </td> + <td><a class="SL_options" title="Mostrar opções">Opções</a> : <a class="SL_options" title="Histórico de tradução">Histórico</a> : <a class="SL_options" title="Comentários">Comentários</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Faça sua contribuição">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Encerrar">Encerrar</span></td> + </tr> +</tbody></table> +</div> +</div> +</div> diff --git a/files/pt-pt/web/xslt/comunidade/index.html b/files/pt-pt/web/xslt/comunidade/index.html new file mode 100644 index 0000000000..04308fdeaa --- /dev/null +++ b/files/pt-pt/web/xslt/comunidade/index.html @@ -0,0 +1,8 @@ +--- +title: Comunidade +slug: Web/XSLT/Comunidade +--- +<p>Grupo XSLT Portugal +</p><p>Onde XSLT é discutido em português para os portugueses. Este grupo dispõe de soluções práticas para problemas comums em XSLT e XPath, assim como, auxiliar principiantes ou menos experientes a resolverem problemas. </p><p>Embora o grupo seja dedicado especialmente ao XSLT, não quer dizer que outras tecnologias directamente ligadas não possam ser discutidas, tais como: XML, XPath, XQuery, XML Schema, Schematron, HTML, RSS, CSS, AJAX, etc. </p><p>Claro que seria preferível discutir o uso de tecnologias em que predomine o XSLT. +</p><p><a href="http://groups.google.com/group/xslt-portugal" class=" external" rel="freelink">http://groups.google.com/group/xslt-portugal</a> +</p> diff --git a/files/pt-pt/web/xslt/elementos/index.html b/files/pt-pt/web/xslt/elementos/index.html new file mode 100644 index 0000000000..e47f8bed0b --- /dev/null +++ b/files/pt-pt/web/xslt/elementos/index.html @@ -0,0 +1,59 @@ +--- +title: Elementos +slug: Web/XSLT/Elementos +tags: + - Referência_XSLT +--- +<p> +{{ XsltRef() }} +Existem dois tipos de elementos discutidos aqui: elementos de topo de nível e instruções. Um elemento de topo de nível deve aparecer como filho de qualquer <code><xsl:stylesheet></code> ou <code><xsl:transform></code>. Uma instrução, por outro lado, é associada com o modelo. Uma folha de estilo pode incluir vários modelos. Um terceiro tipo de elemento, não discutido aqui, é o elemento literal do resultado (LRE). Um LRE também aparece em um modelo. Ele consiste em qualquer elemento não-instrução que deva ser copiado como é para o resultado do documento, por exemplo, o elemento <code><hr></code> em uma folha de estilo de conversão HTML. +</p><p>Em uma nota relacionada, qualquer atributo em uma LRE e alguns atributos de um número limitado de elementos XSLT podem também ser incluídos como o valor de um atributo do modelo. Um valor de atributo do modelo é simplesmente uma string que inclui uma expressão XPath encaixada que é usada para especificar o valor de um atributo. Na hora de rodar a expressão é avaliada e o resulta da avaliação é substituido pela expressão XPath. Por exemplo, assumindo que a variável "<tt>image-dir</tt>" é definida pelo seguinte: +</p> +<pre><xsl:variable name="image-dir">/images</xsl:variable></pre> +<p>A expressão para ser avaliada é colocada no interior de chaves: +</p> +<pre><img src="{$image-dir}/mygraphic.jpg"/></pre> +<p>Isto resultaria no seguinte: +</p> +<pre><img src="/images/mygraphic.jpg"/></pre> +<p>As anotações do elemento que seguem incluem uma descrição, uma lista de sintaxe, uma lista de atributos requeridos e opcionais, uma descrição do tipo e posição, seu código na W3C Recommendation e uma explanação dos graus presentes do suporte Gecko. +</p> +<ul><li> <a href="pt/XSLT/apply-imports">xsl:apply-imports</a> +</li><li> <a href="pt/XSLT/apply-templates">xsl:apply-templates</a> +</li><li> <a href="pt/XSLT/attribute">xsl:attribute</a> +</li><li> <a href="pt/XSLT/attribute-set">xsl:attribute-set</a> +</li><li> <a href="pt/XSLT/call-template">xsl:call-template</a> +</li><li> <a href="pt/XSLT/choose">xsl:choose</a> +</li><li> <a href="pt/XSLT/comment">xsl:comment</a> +</li><li> <a href="pt/XSLT/copy">xsl:copy</a> +</li><li> <a href="pt/XSLT/copy-of">xsl:copy-of</a> +</li><li> <a href="pt/XSLT/decimal-format">xsl:decimal-format</a> +</li><li> <a href="pt/XSLT/element">xsl:element</a> +</li><li> <a href="pt/XSLT/fallback">xsl:fallback</a> <i>(não suportado)</i> +</li><li> <a href="pt/XSLT/for-each">xsl:for-each</a> +</li><li> <a href="pt/XSLT/if">xsl:if</a> +</li><li> <a href="pt/XSLT/import">xsl:import</a> <i>(suportado na maior parte)</i> +</li><li> <a href="pt/XSLT/include">xsl:include</a> +</li><li> <a href="pt/XSLT/key">xsl:key</a> +</li><li> <a href="pt/XSLT/message">xsl:message</a> +</li><li> <a href="pt/XSLT/namespace-alias">xsl:namespace-alias</a> <i>(não suportado)</i> +</li><li> <a href="pt/XSLT/number">xsl:number</a> <i>(parcialmente suportado)</i> +</li><li> <a href="pt/XSLT/otherwise">xsl:otherwise</a> +</li><li> <a href="pt/XSLT/output">xsl:output</a> <i>(parcialmente suportado)</i> +</li><li> <a href="pt/XSLT/param">xsl:param</a> +</li><li> <a href="pt/XSLT/preserve-space">xsl:preserve-space</a> +</li><li> <a href="pt/XSLT/processing-instruction">xsl:processing-instruction</a> +</li><li> <a href="pt/XSLT/sort">xsl:sort</a> +</li><li> <a href="pt/XSLT/strip-space">xsl:strip-space</a> +</li><li> <a href="pt/XSLT/stylesheet">xsl:stylesheet</a> <i>(parcialmente suportado)</i> +</li><li> <a href="pt/XSLT/template">xsl:template</a> +</li><li> <a href="pt/XSLT/text">xsl:text</a> <i>(parcialmente suportado)</i> +</li><li> <a href="pt/XSLT/transform">xsl:transform</a> +</li><li> <a href="pt/XSLT/value-of">xsl:value-of</a> <i>(parcialmente suportado)</i> +</li><li> <a href="pt/XSLT/variable">xsl:variable</a> +</li><li> <a href="pt/XSLT/when">xsl:when</a> +</li><li> <a href="pt/XSLT/with-param">xsl:with-param</a> +</li></ul> +<p><span class="comment">Categorias</span> +</p><p><span class="comment">Interwiki Language Links</span> +</p>{{ languages( { "en": "en/XSLT/Elements", "fr": "fr/XSLT/\u00c9l\u00e9ments", "ja": "ja/XSLT/Elements", "pl": "pl/XSLT/Elementy" } ) }} diff --git a/files/pt-pt/web/xslt/index.html b/files/pt-pt/web/xslt/index.html new file mode 100644 index 0000000000..313b05081f --- /dev/null +++ b/files/pt-pt/web/xslt/index.html @@ -0,0 +1,56 @@ +--- +title: XSLT +slug: Web/XSLT +tags: + - XSLT +translation_of: Web/XSLT +--- +<div><strong>Extensible Stylesheet Language Transformations (XSLT)</strong> é uma linguagem utilizada baseada em <a href="/pt/XML" title="pt/XML">XML</a>, em conjunto com software de processamento especializado, para a transformação de documentos XML. Apesar do processo ser referido como "transformação", o documento original não é alterado; em vez disso, é criado um novo documento XML baseado no conteúdo de um documento existente. Depois, o novo documento poderá ser serializado (saída) pelo processador na sintaxe XML padrão ou em outro formato, tais como <a href="/pt/HTML" title="pt/HTML">HTML</a> ou texto simples. XLST é frequentemente utilizado para converter dados entre esquemas XML diferentes ou para converter dados XML em páginas da Web ou documentos PDF. {{ Ref("one") }}</div> + +<table class="topicpage-table"> + <tbody> + <tr> + <td> + <h2 class="Documentation" id="Documentation" name="Documentation">Documentação</h2> + + <dl> + <dt><a href="/en-US/docs/XSLT/Elements" title="XSLT/Elements">XSLT Element Reference</a></dt> + <dd>Reference.</dd> + <dt><a href="/en-US/docs/Web/XSLT/Transforming_XML_with_XSLT" title="Transforming_XML_with_XSLT">Transforming XML with XSLT</a></dt> + <dd>XSLT allows a stylesheet author to transform a primary XML document in two significant ways: manipulating and sorting the content, including a wholesale reordering of it if so desired, and transforming the content into a different format.</dd> + <dt><a href="/en-US/docs/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations" title="Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations">Using the Mozilla JavaScript interface to XSL Transformations</a></dt> + <dd>This document describes the JavaScript interface to the XSLT processing engine in Mozilla 1.2 and up.</dd> + <dt><a href="/en-US/docs/XSLT/PI_Parameters" title="XSLT/PI_Parameters">Specifying parameters using processing instructions</a></dt> + <dd>Firefox allows stylesheet parameters to be specified when using the <code><?xml-stylesheet?></code> processing instruction. This is done using the <code><?xslt-param?></code> PI described in this document.</dd> + <dt><span class="external">XSLT & XPath Tutorial</span></dt> + <dd>The TopXML XSLT tutorial introduces you to the basics of XSLT concepts, syntax, and programming.</dd> + <dt><a class="external" href="http://www.w3schools.com/xml/xsl_intro.asp">XSLT Tutorial</a></dt> + <dd>This <a class="external" href="http://www.w3schools.com">W3Schools</a> tutorial teaches the reader how to use XSLT to transform XML documents into other formats, like XHTML.</dd> + <dt><a class="external" href="http://www.xml.com/pub/a/2000/08/holman/">What is XSLT?</a></dt> + <dd>This extensive introduction to XSLT and XPath assumes no prior knowledge of the technologies, and guides the reader through background, context, structure, concepts and introductory terminology.</dd> + <dt><a href="/en-US/docs/Common_XSLT_Errors" title="Common XSLT Errors">Common XSLT Errors</a></dt> + <dd>This article lists some common problems using XSLT in Firefox.</dd> + <dt><a href="/en-US/docs/XSLT_2.0" title="XSLT_2.0">XSLT 2.0</a> (new)</dt> + </dl> + + <p><span class="alllinks"><a href="/en-US/docs/tag/XSLT" title="en-US/docs/tag/XSLT">View All...</a></span></p> + </td> + <td> + <h2 class="Community" id="Community" name="Community">Comunidade</h2> + + <ul> + <li>View Mozilla forums... {{ DiscussionList("dev-tech-xslt", "mozilla.dev.tech.xslt") }}</li> + </ul> + + <h4 class="Related_Topics" id="Related_Topics" name="Related_Topics">Tópicos Relacionados</h4> + + <ul> + <li><a href="/pt-PT/docs/Introducao_a_XML" title="XML">XML</a>, <a href="/pt-PT/docs/Web/XPath" title="XPath">XPath</a>, <a href="/en-US/docs/XQuery" title="XQuery">XQuery</a></li> + </ul> + </td> + </tr> + </tbody> +</table> + +<hr> +<p><small>{{ endnote("one") }} Esta descrição de XSLT foi obtida do <a class="external" href="https://pt.wikipedia.org/wiki/XSLT">artigo XSLT da Wikipédia</a>. </small></p> |